mirror of
https://github.com/shinyobjectz/raea.git
synced 2026-12-01 06:53:19 -10:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d870159c46 | ||
|
|
4d7fa914cc | ||
|
|
a4bb6e5c1d | ||
|
|
5f65114ce5 | ||
|
|
87bfda4ed2 | ||
|
|
3b61818eb9 | ||
|
|
1680860ff4 | ||
|
|
74ce0ff737 | ||
|
|
90891cc86f | ||
|
|
bb7dc3b79f | ||
|
|
d6d7a520a7 | ||
|
|
c05dfc946e | ||
|
|
c3b2108412 | ||
|
|
2fe9f13908 | ||
|
|
1c93300361 | ||
|
|
ef5761d300 | ||
|
|
37652ae571 | ||
|
|
0ed836095e | ||
|
|
b1b47b7cfa | ||
|
|
c939b27aee | ||
|
|
0ef7287fde | ||
|
|
fce94e630b | ||
|
|
2a38cbc2df | ||
|
|
2ce68890b8 | ||
|
|
4c392f60d6 | ||
|
|
b4e8310f1f | ||
|
|
9cffd0bf0a | ||
|
|
d190585622 | ||
|
|
912c957c9f | ||
|
|
2b9f1ad862 | ||
|
|
b1bfc9ba41 | ||
|
|
d5b8b9ab35 | ||
|
|
a10d64ab75 | ||
|
|
1f3a058ba0 | ||
|
|
c4550ad6ba | ||
|
|
afe2150d19 | ||
|
|
a77d68ef93 | ||
|
|
fad2dbcbf4 | ||
|
|
f9129e758c | ||
|
|
b95a9fab63 | ||
|
|
af752e3a27 | ||
|
|
85d331898f | ||
|
|
8e5f1d449c | ||
|
|
daa81ca944 | ||
|
|
03e3b77578 | ||
|
|
c486a7fe16 | ||
|
|
78cb452725 | ||
|
|
29a3763ecf | ||
|
|
e4a0552663 | ||
|
|
08c70a8318 | ||
|
|
d3762acbf1 | ||
|
|
d0e99b0d46 | ||
|
|
494b395442 | ||
|
|
fa884594a6 | ||
|
|
5b93a70f70 | ||
|
|
a36df13992 | ||
|
|
1190ab6953 | ||
|
|
5ab9285ed3 | ||
|
|
3185fa5adb | ||
|
|
9f553d6ecc | ||
|
|
acb4aa404d | ||
|
|
26d094c341 | ||
|
|
773047de9e | ||
|
|
4a8ad49d60 | ||
|
|
a393b366ac | ||
|
|
dc148cd3f7 | ||
|
|
48c027313d | ||
|
|
b41c609a02 | ||
|
|
90975148a0 | ||
|
|
e658ea89ea | ||
|
|
3fc0c43af0 | ||
|
|
173e397113 | ||
|
|
17fa0e5f31 | ||
|
|
8df1c72a44 | ||
|
|
e3f4c6980e | ||
|
|
7ed8faa7a6 | ||
|
|
283b1ffb87 | ||
|
|
e060c09fe2 | ||
|
|
9a93709831 | ||
|
|
ca0a14e04c | ||
|
|
8fefa2922d | ||
|
|
96f7e64580 | ||
|
|
d79c0b8cef | ||
|
|
81cf2e0386 | ||
|
|
eed69c7bb2 | ||
|
|
271376b898 | ||
|
|
e31056b6ad | ||
|
|
0b7a4203b8 | ||
|
|
95725896a2 | ||
|
|
b476ebb82b | ||
|
|
fd3a75ce72 | ||
|
|
f14232a52e | ||
|
|
43cc233f99 | ||
|
|
31f7961287 | ||
|
|
1918b36f9e | ||
|
|
387f91017c | ||
|
|
d8b51396fa | ||
|
|
0a7c064b05 | ||
|
|
3620aa1def | ||
|
|
b938833097 | ||
|
|
75c3b18c22 | ||
|
|
01076723f4 | ||
|
|
bd670d9040 | ||
|
|
5c7dac41c2 | ||
|
|
f732061d9d | ||
|
|
d7e3d8b2b2 | ||
|
|
c4d3900d68 | ||
|
|
f130f35870 | ||
|
|
2b7574de39 | ||
|
|
bbd658263e | ||
|
|
91731fab14 | ||
|
|
f36ffb903f | ||
|
|
0173108f72 | ||
|
|
bb4402e45a | ||
|
|
661adee396 | ||
|
|
73c5c93e9b | ||
|
|
2427d7c9ee | ||
|
|
e3b048e2d9 | ||
|
|
08f6f621d2 | ||
|
|
7caf1bb596 | ||
|
|
43bfbad61f | ||
|
|
beb4ce1200 | ||
|
|
7bfa7f392c | ||
|
|
47cf338cd6 | ||
|
|
b2a52f6cc1 | ||
|
|
c78ded29e8 | ||
|
|
1c3cb953bd | ||
|
|
53a5cc9ca7 | ||
|
|
3b670e79a5 | ||
|
|
530ff8e3de |
No files matched your search
@@ -307,6 +307,13 @@ jobs:
|
||||
- name: Use the compile cache
|
||||
if: env.RAEA_PROMOTED_FROM == '' && env.AWS_ACCESS_KEY_ID != ''
|
||||
run: bash .workflow/tools/release/compile-cache.sh
|
||||
# openh264-sys2 is built here every time, never taken whole from the cache volume's target/: a build of it whose
|
||||
# assembly didn't make it into the rlib (0.1.3-rc4's Chocolatey nasm) stays fresh to cargo on a restored target/,
|
||||
# and every link after it fails on the same 135 SIMD routines (v0.1.4-rc1, 11-14: only raea-cli compiled, then
|
||||
# WaverageChromaFilter8_sse2 and the rest unresolved). Its C++ comes back from sccache; the assembly is seconds
|
||||
- name: openh264 built here, not restored
|
||||
if: env.RAEA_PROMOTED_FROM == ''
|
||||
run: rm -rf target/dist/build/openh264-sys2-* target/dist/deps/libopenh264_sys2-* target/dist/.fingerprint/openh264-sys2-*
|
||||
- name: Build
|
||||
if: env.RAEA_PROMOTED_FROM == ''
|
||||
run: |
|
||||
|
||||
Generated
+22
-2
@@ -14459,10 +14459,9 @@ name = "raea-io-gen"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"image",
|
||||
"raea-core-facts",
|
||||
"raea-core-meshcheck",
|
||||
"raea-io-gen-comfy",
|
||||
"raea-io-gen-core",
|
||||
"raea-io-gen-fit",
|
||||
"raea-io-home",
|
||||
"serde_json",
|
||||
]
|
||||
@@ -14484,6 +14483,16 @@ dependencies = [
|
||||
"sha2 0.10.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-io-gen-fit"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"raea-core-facts",
|
||||
"raea-core-meshcheck",
|
||||
"raea-io-gen-core",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-io-home"
|
||||
version = "0.1.0"
|
||||
@@ -14677,6 +14686,7 @@ dependencies = [
|
||||
"raea-io-net-calls",
|
||||
"raea-io-os",
|
||||
"raea-page",
|
||||
"raea-page-sound",
|
||||
"raea-page-stage",
|
||||
"raea-page-window",
|
||||
"raea-rune-slots",
|
||||
@@ -14693,6 +14703,16 @@ dependencies = [
|
||||
"tiny_http",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-page-sound"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"raea-runtime-js",
|
||||
"raea-sys-mix",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-page-stage"
|
||||
version = "0.1.0"
|
||||
|
||||
@@ -53,6 +53,7 @@ members = [
|
||||
"engine/rune/js",
|
||||
"engine/rune/layer",
|
||||
"engine/rune/slots",
|
||||
"engine/page/sound",
|
||||
"engine/page/stage",
|
||||
"engine/page/window",
|
||||
"io/trace",
|
||||
@@ -62,6 +63,7 @@ members = [
|
||||
"io/gen",
|
||||
"io/gen-comfy",
|
||||
"io/gen-core",
|
||||
"io/gen-fit",
|
||||
"io/home",
|
||||
"io/soft",
|
||||
"io/av1",
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
//! Grok Bot (xAI's desktop agent, made by Anysphere: /Applications/Grok Bot.app, bundle com.anysphere.sand) as a
|
||||
//! `raea skills install --agent grokbot` target (docs/skills.feature SK13). Read from its app.asar, 1.1.0 (11-14):
|
||||
//! Grok Bot keeps nothing on this Mac that raea could write. Its agent runs on a computer of its own in the cloud (its
|
||||
//! "box"), its skills are held there, and its MCP servers belong to the person's account (Settings → Integrations →
|
||||
//! Add a custom connector), a server's command running on that computer, not here. It has no hooks, no CLI and no ACP.
|
||||
//! What does reach this Mac is its Execution on this computer: the Bot runs a command here, through its local daemon.
|
||||
//! So raea stages its skill in a folder of its own, stamped and with a preface saying where raea runs, and gives the
|
||||
//! grokbot:// links that finish it in Grok Bot: the Execution setting, and a message to the Bot, filled in but not
|
||||
//! sent, asking it to make the skill from the staged file ("Ask your Bot to create one", as Grok Bot itself says).
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
type R<T> = Result<T, String>;
|
||||
|
||||
/// The folder raea stages Grok Bot's copy in: $RAEA_GROKBOT_HOME, else grokbot in raea's own folder in the home.
|
||||
pub fn home() -> R<PathBuf> {
|
||||
match std::env::var_os("RAEA_GROKBOT_HOME").filter(|v| !v.is_empty()) {
|
||||
Some(d) => Ok(PathBuf::from(d)),
|
||||
None => Ok(crate::agent_mcp::user_home()?.join(".raea").join("grokbot")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the staged skills go, one folder per skill holding SKILL.md, as for every agent.
|
||||
pub fn skills_dir() -> R<PathBuf> {
|
||||
Ok(home()?.join("skills"))
|
||||
}
|
||||
|
||||
/// The app, where macOS keeps it (/Applications, or ~/Applications).
|
||||
pub fn app() -> Option<PathBuf> {
|
||||
let home = crate::agent_mcp::user_home().ok();
|
||||
[Some(PathBuf::from("/Applications")), home.map(|h| h.join("Applications"))].into_iter().flatten().map(|d| d.join("Grok Bot.app")).find(|a| a.join("Contents/Info.plist").is_file())
|
||||
}
|
||||
|
||||
/// The largest SKILL.md Grok Bot's Skills → Add new skill → Upload file takes, in bytes (256 KB).
|
||||
pub const MAX_SKILL: usize = 256_000;
|
||||
|
||||
/// After `raea skills install --agent grokbot` has copied raea's skills into `dir` (`said`, what it said doing so): the
|
||||
/// preface in raea's SKILL.md, and the links that finish it. A linked folder is the person's, left as it is. Grok Bot
|
||||
/// gets no hooks (it has none) and no MCP server (its command would run on the Bot's own computer, not this Mac).
|
||||
pub fn stage(dir: &Path, said: String) -> R<String> {
|
||||
let md = dir.join("raea/SKILL.md");
|
||||
if !dir.join("raea").is_symlink() && let Ok(text) = std::fs::read_to_string(&md) {
|
||||
let text = with_preface(&text, dir);
|
||||
if text.len() >= MAX_SKILL {
|
||||
return Err(format!("{}: {} KB, more than the 256 KB Grok Bot's Add new skill takes", md.display(), text.len() / 1000));
|
||||
}
|
||||
std::fs::write(&md, text).map_err(|e| format!("{}: {e}", md.display()))?;
|
||||
}
|
||||
Ok(format!("{said}{}", finish(dir)))
|
||||
}
|
||||
|
||||
/// SKILL.md with the preface after its front matter (or first, when it has none): raea runs on the person's Mac, not on
|
||||
/// the Bot's computer. A copy that has one keeps only one.
|
||||
pub fn with_preface(text: &str, dir: &Path) -> String {
|
||||
if text.contains("> **On Grok Bot.**") {
|
||||
return text.to_string();
|
||||
}
|
||||
let p = format!(
|
||||
"> **On Grok Bot.** raea runs on the person's Mac, not on your computer. Run every `raea` command there, and read\n> every file this skill links (3d.md, reference/cli.md and the rest) from its copy there, in {}, both\n> with Run a command on your local computer (the person turns on Settings → Computer → Execution on this computer).\n> No raea MCP server or hook is set up for you: after saving a composition run `raea check EDIT.tsx --quick` yourself,\n> and `raea show FILE` puts media in front of the person.\n",
|
||||
dir.join("raea").display()
|
||||
);
|
||||
let Some(rest) = text.strip_prefix("---\n") else { return format!("{p}\n{text}") };
|
||||
let Some(end) = rest.find("\n---\n") else { return format!("{p}\n{text}") };
|
||||
let (front, body) = (&rest[..end], rest[end + 5..].trim_start_matches('\n'));
|
||||
format!("---\n{front}\n---\n\n{p}\n{body}")
|
||||
}
|
||||
|
||||
/// A query value as Grok Bot builds its own links (encodeURIComponent): every byte but A-Z a-z 0-9 - _ . ! ~ * ' ( ).
|
||||
fn encode(v: &str) -> String {
|
||||
v.bytes().map(|b| if b.is_ascii_alphanumeric() || b"-_.!~*'()".contains(&b) { (b as char).to_string() } else { format!("%{b:02X}") }).collect()
|
||||
}
|
||||
|
||||
/// One of Grok Bot's deep links (its route table: grokbot://app/v1/ROUTE?KEY=VALUE).
|
||||
pub fn link(route: &str, key: &str, value: &str) -> String {
|
||||
format!("grokbot://app/v1/{route}?{key}={}", encode(value))
|
||||
}
|
||||
|
||||
/// The message to the Bot that makes the skill from the copy staged in `dir`: at most 1000 characters, as its prompt
|
||||
/// link takes.
|
||||
fn ask(dir: &Path) -> String {
|
||||
let md = dir.join("raea/SKILL.md");
|
||||
format!("Please make a private skill named raea from the file {} on my Mac: read it with Run a command on your local computer and keep its text as it is. raea runs on my Mac, so run every raea command there.", md.display())
|
||||
}
|
||||
|
||||
/// What `raea skills install --agent grokbot` says once the copy is staged: where it is, and the links that finish it.
|
||||
pub fn finish(dir: &Path) -> String {
|
||||
let md = dir.join("raea/SKILL.md");
|
||||
let here = match app() {
|
||||
Some(a) => format!("Grok Bot is at {}.", a.display()),
|
||||
None => "Grok Bot isn't installed on this Mac (cursor.com/download/bot); the copy is ready for when it is.".into(),
|
||||
};
|
||||
format!(
|
||||
"{here} It keeps its skills on its own computer and its MCP servers on your account, so the copy waits here: {}. No hooks, and no MCP server: Grok Bot runs a server's command on its computer, where the blender server can't reach this Mac's Blender.\nTo finish, in Grok Bot, signed in:\n 1. turn on Execution on this computer: {}\n 2. send the message this fills in, and the Bot makes the skill from the copy: {}\n or by hand: Skills → Add new skill → Upload file → {}\n`open LINK` opens a link in Grok Bot",
|
||||
dir.display(),
|
||||
link("settings", "id", "local-execution"),
|
||||
link("prompt", "text", &ask(dir)),
|
||||
md.display()
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_preface_goes_after_the_front_matter_once() {
|
||||
let d = Path::new("/h/.raea/grokbot/skills");
|
||||
let md = "---\nname: raea\ndescription: d\nversion: 1\n---\n\n# raea\n";
|
||||
let out = with_preface(md, d);
|
||||
assert!(out.starts_with("---\nname: raea\ndescription: d\nversion: 1\n---\n\n> **On Grok Bot.** raea runs on the person's Mac"), "{out}");
|
||||
assert!(out.contains("in /h/.raea/grokbot/skills/raea, both") && out.ends_with("\n\n# raea\n"), "{out}");
|
||||
assert_eq!(with_preface(&out, d), out);
|
||||
assert!(with_preface("# no front matter\n", d).starts_with("> **On Grok Bot.**"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn links_are_built_as_grok_bot_builds_its_own() {
|
||||
assert_eq!(link("settings", "id", "local-execution"), "grokbot://app/v1/settings?id=local-execution");
|
||||
assert_eq!(link("prompt", "text", "a b/ü&+=?#'()"), "grokbot://app/v1/prompt?text=a%20b%2F%C3%BC%26%2B%3D%3F%23'()");
|
||||
// its prompt route takes at most 1000 characters of text in a link of at most 2048, with no format characters
|
||||
let a = ask(Path::new("/h/a-home-folder-with-a-rather-long-name/.raea/grokbot/skills"));
|
||||
assert!(a.chars().count() <= 1000 && link("prompt", "text", &a).len() <= 2048, "{a}");
|
||||
assert!(a.chars().all(|c| !c.is_control() && !('\u{200B}'..='\u{200F}').contains(&c) && !('\u{202A}'..='\u{202E}').contains(&c)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stage_prefaces_the_copy_once_and_refuses_one_too_big_to_upload() {
|
||||
let d = std::env::temp_dir().join(format!("raea-grokbot-stage-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
std::fs::create_dir_all(d.join("raea")).unwrap();
|
||||
std::fs::write(d.join("raea/SKILL.md"), "---\nname: raea\nversion: 1\n---\n\n# raea\n").unwrap();
|
||||
let out = stage(&d, "copied\n".into()).unwrap();
|
||||
assert!(out.starts_with("copied\n") && out.contains("grokbot://app/v1/prompt?text="), "{out}");
|
||||
stage(&d, String::new()).unwrap();
|
||||
let md = std::fs::read_to_string(d.join("raea/SKILL.md")).unwrap();
|
||||
assert_eq!(md.matches("> **On Grok Bot.**").count(), 1, "{md}");
|
||||
std::fs::write(d.join("raea/SKILL.md"), "x".repeat(MAX_SKILL)).unwrap();
|
||||
assert!(stage(&d, String::new()).unwrap_err().contains("256 KB"));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finish_says_where_the_copy_is_and_both_links() {
|
||||
let f = finish(Path::new("/h/.raea/grokbot/skills"));
|
||||
assert!(f.contains("the copy waits here: /h/.raea/grokbot/skills."), "{f}");
|
||||
assert!(f.contains("grokbot://app/v1/settings?id=local-execution") && f.contains("grokbot://app/v1/prompt?text=Please%20make%20a%20private%20skill"), "{f}");
|
||||
assert!(f.contains("Upload file → /h/.raea/grokbot/skills/raea/SKILL.md"), "{f}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
//! Where each agent `raea skills install` knows reads a person's skills, one folder per skill holding SKILL.md. Checked
|
||||
//! by hand on 11-05: claude: ~/.claude/skills (Claude Code's docs); codex: ~/.agents/skills
|
||||
//! (developers.openai.com/codex/skills, the user scope; older builds read ~/.codex/skills); kimi: $KIMI_CODE_HOME/skills,
|
||||
//! else ~/.kimi-code/skills (kimi 2.3.3's own binary; it also reads ~/.agents/skills and ~/.claude/skills); gemini:
|
||||
//! ~/.gemini/skills (geminicli.com/docs/cli/skills). grokbot (11-14): Grok Bot reads no folder here, so its copy is
|
||||
//! staged in raea's own (agent_grokbot.rs).
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// The agents, in the order `raea doctor` and the usage name them.
|
||||
pub const AGENTS: [&str; 5] = ["claude", "codex", "kimi", "gemini", "grokbot"];
|
||||
|
||||
/// The folder `agent` reads skills from.
|
||||
pub fn folder(agent: &str) -> Result<PathBuf, String> {
|
||||
let home = crate::agent_mcp::user_home()?;
|
||||
Ok(match agent {
|
||||
"claude" => home.join(".claude/skills"),
|
||||
"codex" => home.join(".agents/skills"),
|
||||
"kimi" => std::env::var_os("KIMI_CODE_HOME").filter(|v| !v.is_empty()).map(PathBuf::from).unwrap_or_else(|| home.join(".kimi-code")).join("skills"),
|
||||
"gemini" => home.join(".gemini/skills"),
|
||||
"grokbot" => crate::agent_grokbot::skills_dir()?,
|
||||
a => return Err(format!("no agent {a:?}: claude, codex, kimi, gemini or grokbot")),
|
||||
})
|
||||
}
|
||||
|
||||
/// Each agent and the folder it reads skills from, for `raea doctor` (an agent with no folder is skipped).
|
||||
pub fn agents() -> Vec<(&'static str, PathBuf)> {
|
||||
AGENTS.into_iter().filter_map(|a| folder(a).ok().map(|t| (a, t))).collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn each_agent_has_its_folder() {
|
||||
assert!(folder("claude").unwrap().ends_with(".claude/skills"));
|
||||
assert!(folder("codex").unwrap().ends_with(".agents/skills"));
|
||||
assert!(folder("gemini").unwrap().ends_with(".gemini/skills"));
|
||||
assert_eq!(folder("grokbot").unwrap(), crate::agent_grokbot::skills_dir().unwrap());
|
||||
assert!(folder("cursor").is_err());
|
||||
assert_eq!(agents().len(), AGENTS.len());
|
||||
}
|
||||
}
|
||||
@@ -11,5 +11,9 @@ pub mod splat;
|
||||
/// the MCP servers `raea skills install` offers an agent (blender, for a running Blender)
|
||||
pub mod agent_mcp;
|
||||
pub mod agent_hooks;
|
||||
/// Grok Bot as a `raea skills install` target: its copy staged on this Mac, and the links that finish it in Grok Bot
|
||||
pub mod agent_grokbot;
|
||||
/// where each agent reads a person's skills
|
||||
pub mod agent_skills;
|
||||
/// `raea setup blender` and `raea blender run`
|
||||
pub mod blender;
|
||||
@@ -129,12 +129,10 @@ fn doctor_finds_old_briefs_and_old_skills() {
|
||||
fn the_root_with_none_set() {
|
||||
let home = scratch("home-root");
|
||||
assert_eq!(default_root(&home), home.join("Documents/raea"));
|
||||
// an empty ~/Studio isn't one; one with a workspace stays the root
|
||||
std::fs::create_dir_all(home.join("Studio/notes")).unwrap();
|
||||
assert_eq!(default_root(&home), home.join("Documents/raea"));
|
||||
// never ~/Studio, even with a workspace in it (Shane 11-14: "no internal no studio"; raea.root says otherwise)
|
||||
std::fs::create_dir_all(home.join("Studio/acme/.raea")).unwrap();
|
||||
std::fs::write(home.join("Studio/acme/.raea/workspace"), "").unwrap();
|
||||
assert_eq!(default_root(&home), home.join("Studio"));
|
||||
assert_eq!(default_root(&home), home.join("Documents/raea"));
|
||||
// iCloud keeping Documents: ~/raea
|
||||
let synced = scratch("home-icloud");
|
||||
std::fs::create_dir_all(synced.join("Library/Mobile Documents/com~apple~CloudDocs/Documents")).unwrap();
|
||||
|
||||
@@ -100,31 +100,19 @@ pub fn root() -> PathBuf {
|
||||
}
|
||||
}
|
||||
|
||||
/// Where workspaces go with no raea.root set: ~/Studio where workspaces are already (the root before 11-10), else
|
||||
/// ~/Documents/raea, or ~/raea when iCloud keeps the Documents folder (a workspace's git history and footage don't
|
||||
/// belong in a synced folder). The feed's host says the same (raea-feed host/workspace.ts defaultRoot).
|
||||
/// Where a workspace someone names goes with no raea.root set: ~/Documents/raea, or ~/raea when iCloud keeps the
|
||||
/// Documents folder (a workspace's git history and footage don't belong in a synced folder). Nothing is made there
|
||||
/// until the person or an agent sets a workspace up (`raea workspace init NAME`); ~/Studio, the root on raea's own Mac
|
||||
/// before 11-10, is no one else's (Shane 11-14: "no internal no studio"). The feed's host says the same (raea-feed
|
||||
/// host/workspace.ts defaultRoot).
|
||||
pub fn default_root(home: &Path) -> PathBuf {
|
||||
let studio = home.join("Studio");
|
||||
if holds_workspace(&studio) {
|
||||
studio
|
||||
} else if home.join("Library/Mobile Documents/com~apple~CloudDocs/Documents").is_dir() {
|
||||
if home.join("Library/Mobile Documents/com~apple~CloudDocs/Documents").is_dir() {
|
||||
home.join("raea")
|
||||
} else {
|
||||
home.join("Documents/raea")
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a folder in `dir` is a workspace (it has .raea/workspace).
|
||||
fn holds_workspace(dir: &Path) -> bool {
|
||||
let Ok(entries) = std::fs::read_dir(dir) else { return false };
|
||||
for e in entries.flatten() {
|
||||
if e.path().join(".raea/workspace").exists() {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// The include in a repo's own config that makes `git config` read a committed file. Idempotent; the path is relative
|
||||
/// to the config file, which for a submodule lives under the workspace's .git/modules.
|
||||
pub(crate) fn include(repo: &Path, file: &Path) -> R<()> {
|
||||
|
||||
Executable
+38
@@ -0,0 +1,38 @@
|
||||
#!/bin/bash
|
||||
# text-overflow: ellipsis cuts only text that doesn't fit. A label shrink-wrapped by its box (a grid of picker cells,
|
||||
# each name centred under a dot) drew "Fr…" and "Mou…" for words that fit: the ellipsis was measured against the box's
|
||||
# rounded width, up to a pixel narrower than the text it wraps (each edge rounds on its own), and blitz-paint now
|
||||
# measures against the unrounded width the text was laid out in. Checked, each page rendered twice, once with
|
||||
# `text-overflow: ellipsis` and once with `clip`:
|
||||
# fit shrink-wrapped labels at many x offsets: the two renders are byte-identical (no ellipsis drawn)
|
||||
# over a word wider than its 40 px box: the two renders differ (the ellipsis is drawn)
|
||||
# Exits 1 on a failure.
|
||||
# bench/ellipsis-fit/check.sh (RAEA_BIN: the raea to run, default target/release/raea)
|
||||
cd "$(dirname "$0")/../.." || exit 2
|
||||
BIN=${RAEA_BIN:-$PWD/target/release/raea}
|
||||
export RAEA_SIGN=0 RAEA_MARK=0 RAEA_EXPORT_CACHE=0
|
||||
OUT=$(mktemp -d "${TMPDIR:-/tmp}/raea-ellipsis-fit.XXXXXX")
|
||||
trap 'rm -rf "$OUT"' EXIT
|
||||
status=0
|
||||
page() { # NAME OVERFLOW BODY
|
||||
cat > "$OUT/$1-$2.html" <<HTML
|
||||
<!doctype html><html><head><meta charset="utf-8"><style>
|
||||
html,body{margin:0;width:640px;height:200px;background:#0a0a0a;font:11px/16px system-ui,sans-serif;color:#aaa}
|
||||
.grid{display:grid;grid-template-columns:repeat(7,minmax(0,1fr));gap:3px;width:617px;padding:9px 11.5px}
|
||||
.cell{display:flex;min-width:0;flex-direction:column;align-items:center;gap:4px;padding:8px 4px 6px}
|
||||
.dot{width:30px;height:30px;border-radius:15px;background:#6c6}
|
||||
.t{max-width:100%;overflow:hidden;white-space:nowrap;text-overflow:$2}
|
||||
.narrow{width:40px;margin:20px}
|
||||
</style></head><body><div id="root" data-composition-id="main" data-start="0" data-width="640" data-height="200" data-duration="1">$3</div></body></html>
|
||||
HTML
|
||||
"$BIN" render "$OUT/$1-$2.html" -o "$OUT/$1-$2.png" > "$OUT/$1-$2.log" 2>&1 || { echo "FAIL $1 ($2) didn't render"; cat "$OUT/$1-$2.log"; status=1; }
|
||||
}
|
||||
cells=""
|
||||
for w in Owl Frog Dog Mouse Bunny Bear Fox Cat Tabby Snow Rose Sky Mint Slate; do cells+="<div class=\"cell\"><span class=\"dot\"></span><span class=\"t\">$w</span></div>"; done
|
||||
for ov in ellipsis clip; do
|
||||
page fit "$ov" "<div class=\"grid\">$cells</div>"
|
||||
page over "$ov" "<div class=\"narrow t\">Mousetrap</div>"
|
||||
done
|
||||
cmp -s "$OUT/fit-ellipsis.png" "$OUT/fit-clip.png" && echo "PASS fit: shrink-wrapped labels draw no ellipsis" || { echo "FAIL fit: an ellipsis was drawn on a label that fits"; status=1; }
|
||||
cmp -s "$OUT/over-ellipsis.png" "$OUT/over-clip.png" && { echo "FAIL over: a word wider than its box drew no ellipsis"; status=1; } || echo "PASS over: a word wider than its box ends in an ellipsis"
|
||||
exit $status
|
||||
@@ -201,3 +201,11 @@ Feature: raea's plugin ecosystem: extending the engine and the app, made, shared
|
||||
And may an extension restyle the app itself (a theme), or only draw inside its own frames?
|
||||
And packages install per person, in every project (Shane 11-09: answered)
|
||||
And will packages ever be sold through raea, or stay free with raea taking no part?
|
||||
|
||||
Scenario: EC13. A package that imports raea shares the composition's SDK (#151)
|
||||
Given a package in the project's node_modules (or the person's plugins) that imports "raea", "raea/<module>" or
|
||||
"@raea/<package>", its entry .tsx or plain ESM .js
|
||||
Then the import is the SDK copy the composition's own files import (engine/bundle edit.rs sdk_copy): one SDK, so
|
||||
its hooks read the Clock the engine drives, exactly as the same file imported by a relative path does
|
||||
And never an outside global the bundle leaves unresolved ("Can't find variable: raea" before the first frame)
|
||||
And engine/bundle/tests/bundle.rs a_package_importing_the_sdk_gets_the_work_folders_copy holds it
|
||||
@@ -127,3 +127,31 @@ Feature: Feed tasks: the graph view's layering, the to-do list, and sessions sta
|
||||
Scenario: FT3d. It ties to the to-do list
|
||||
Then a brief's task that @names the session, and an edit on an item it posted, are its tasks
|
||||
And the bubble names them, and the to-do list shows the session on them with what it last did
|
||||
|
||||
# Status 11-13 (FT3e, FT3f): built for 0.1.4 in raea-feed #25, stacked on #24; neither merged, both wait for Shane.
|
||||
# Shane 11-13, on the cards: "even if i started the chat or session out of raea app i can open up the chat in a
|
||||
# raea chat ui ... show what agent is working on what or any subagents and feel more like i can click to see more
|
||||
# and less rows of info". Checked: e2e/outside.spec.ts 3 of 3 in Chrome, with the host's answers given by the
|
||||
# spec; host/outside-chat.test.ts and host/outside.test.ts on files written as Claude Code writes them;
|
||||
# bridge-resume.test.ts on a test agent that offers fork. Not checked: a fork through the real claude-agent-acp.
|
||||
# Left: other harnesses' transcripts (only Claude Code's is read), and an image a prompt carried.
|
||||
Scenario: FT3e. Open chat opens it as a chat in raea
|
||||
When I press Open chat on its bubble
|
||||
Then its conversation so far opens as one of the workspace's chats: my prompts, its replies and thinking, its
|
||||
tool calls with their results and diffs, and its plan, read from its transcript (the newest 6 MB, saying so
|
||||
when older messages were left out)
|
||||
And a line at the top says where it was started and what writing there does
|
||||
And while it is still open where it runs, what it says next shows in the chat as it says it
|
||||
And opening it starts no agent
|
||||
When I write in that chat
|
||||
Then the agent carries it on in the folder it ran in: a copy of it (forked) while it is still open there, so the
|
||||
one there goes on by itself, or the session itself (resumed) when it has ended
|
||||
And from then on it is raea's chat, and following stops
|
||||
|
||||
Scenario: FT3f. Its bubble says who is on what, folded until I open it
|
||||
Then folded, the bubble says what the session is on (its own title, or the name it was given), what it is
|
||||
doing now, and the subagents it has running
|
||||
When I click the bubble or More, which names what more there is
|
||||
Then it opens to its last message, its plan, its subagents (the running ones with the call each is on, then
|
||||
the latest done, with how many more are done) and the notes of mine it has
|
||||
And Less, or another click, folds it again
|
||||
@@ -19,6 +19,12 @@ about a piece, such as a soft picture, dead motion, noise under the voice or a c
|
||||
device**. On top of the axes sit the person's **weighting** across them, an optional **profile** (ranges taken from
|
||||
work they admire) and the **evidence ledger** that every head was trained from.
|
||||
|
||||
The frozen encoders together are the **Edit Embedding Zoo** (Shane, 11-13: the standard name, in the docs, the app
|
||||
and anything we publish): SigLIP 2 for pictures, CLAP for how it sounds, YAMNet for sound events and their timing,
|
||||
EmbeddingGemma 2 for text and Depth Anything 3 for depth. They are pinned, run on the person's device and are the same
|
||||
for every fingerprint. A fingerprint is what a person trains over the zoo: its axes' heads. The zoo itself never
|
||||
changes.
|
||||
|
||||
On day one, an axis's words already give it a zero-shot score. Each label the person adds retrains its head in
|
||||
milliseconds. Whatever can be measured exactly, such as loudness, silence gaps, frozen frames or one thing passing
|
||||
through another, is a check rather than a learned head. A team shares evidence, never media, and each machine
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
@spec
|
||||
Feature: Hardware: controls that feel like instruments, heard on raea's own mixer
|
||||
Shane, 2026-11-14, pointing at SPEC-01 (spec-01.vercel.app, a shadcn registry of controls drawn as hardware, its
|
||||
sounds made with the browser's Web Audio): "i want to have this ui kit installed across the app where relevant with
|
||||
sounds especially for controllers ... wrap the app in <Hardware> ... and have a sound off button in settings. this
|
||||
could be used for so many things and feels aligned with our vibe and brand." Then, on how its sounds would play in
|
||||
raea's window: "why web audio isnt it in a raea engine its rendering wouldnt we use raea tone.js/firewheel?" And:
|
||||
"we would make our own version of it no need to use theirs for real unless it makes sense. we keep dark mode."
|
||||
|
||||
So: raea's own kit, dark, in the idiom SPEC-01 shows (keys that go down and come back, latches, detents, knobs,
|
||||
faders, readouts), with its sounds written in raea/tone and played by raea's mixer on Firewheel. None of SPEC-01's
|
||||
code is taken; it is credited as the inspiration (Apache-2.0, Vercel Labs' ui-sdk).
|
||||
|
||||
What there is to build on (read 11-14):
|
||||
- raea's window has no Web Audio graph on purpose (sdk/ui/src/platform/audio.ts: decodeAudioData only, AudioContext
|
||||
not installed, "so a page that looks for it finds it missing rather than half there"). A web kit's sounds are
|
||||
silent there.
|
||||
- raea/tone (sdk/audio/src/tone) is Tone.js's API on raea's one mixer core: instruments, effects and buses (one of
|
||||
them `ui`) as a graph (`<audio data-tone-graph>`) and events (`<audio data-tone-evs>`). Today only a composition
|
||||
reaches the mixer: a render bounces it (systems/mix offline.rs) and the stage plays it live (systems/mix live.rs,
|
||||
`Live::sync` a frame at a time). A page's own interactions have no way in.
|
||||
- The page's host calls (raea-runtime-js HostCalls; the stage's in engine/page/stage calls.rs), reached from a page
|
||||
as `__raea_engine.call(name, args)`.
|
||||
|
||||
Status, 11-14: HW0 to HW4 built (engine lane `hardware`; the app's raea-feed branch `hardware`, src/hardware). HW0b
|
||||
measured: 200 presses 15 ms apart through Live::fire, 0 late, 200 in the tap (systems/mix tests/fire.rs, ignored as
|
||||
it opens a device); in raea's window, 40 presses on the kit's sheet fired 40 on the page's mixer, 0 late (raea-feed
|
||||
blitz/kit.sh, headless and muted). HW1b: the loudest voice, the primary key, peaks at -22 dB (raea-feed
|
||||
bench/kit-voices.sh). HW2b: the sheet (#/kit, ui-parity screen 27-kit) drawn by raea's window matches Chrome's by eye,
|
||||
and the switches' thumbs measure centred, 2 px all round, in both (Shane 11-14: "slightly off center": a thumb has no
|
||||
skirt, and its groove is shaded evenly, as a well's lit lip read a pixel low); the ui-parity run is still to do (it
|
||||
reads the app while it still shows its loading shapes). Shane 11-14: into 0.1.4. HW5 open.
|
||||
|
||||
Background:
|
||||
Given the engine's part is systems/mix (the mixer) and engine/page/sound (the page's call), the SDK's is
|
||||
sdk/audio/src/tone (fire), and the app's is raea-feed src/hardware
|
||||
|
||||
Rule: HW0. A page plays a sound now, on raea's mixer
|
||||
# Plan (crate or package | file | lines | job)
|
||||
# raea-sys-mix | src/live/fire.rs | 80 | Live::fire: a graph built when it changes, events at the clock's now
|
||||
# raea-page-sound | src/lib.rs | 120 | the page's `sound.fire` call: a mixer of its own on a thread, resting when idle
|
||||
# @raea/audio | src/tone/fire.ts | 80 | fire(play): a page's one-shot, as <Sfx> is a game's, sent to the call
|
||||
|
||||
Scenario: HW0a. sound.fire
|
||||
Given a page in raea's window (the app, a plugin's page, any page the page host shows)
|
||||
When it calls sound.fire with a raea/tone graph and a list of events
|
||||
Then the graph is built on the page's own mixer when it is new or changed, and each event plays at the clock's
|
||||
now plus the mixer's head plus the event's own time: no frame and no timeline stand in between
|
||||
And the call answers at once; it never waits for the sound
|
||||
And RAEA_AUDIO_MUTE=1 silences it as it silences every mixer
|
||||
|
||||
Scenario: HW0b. Heard within a frame of the press
|
||||
Then a fired event reaches the speaker within the mixer's head (two 256-sample blocks and 5 ms: 15.7 ms at
|
||||
48 kHz) of the call, measured on the mixer's own clock (the late-event count stays 0 over 200 fires)
|
||||
|
||||
Scenario: HW0c. Nothing runs while nothing sounds
|
||||
Then the page's mixer opens the device on its first fire, and stops its stream after 10 s with nothing fired
|
||||
(the stage's rest, lightspeed R6); the next fire starts it again
|
||||
|
||||
Scenario: HW0d. fire() in raea/tone
|
||||
Then `fire(play)` runs `play(time)` the way <Sfx> runs a game's one-shot: its triggers become events, keyed so
|
||||
no two fires share one, sent with the graph (only when the graph changed since the last fire) to sound.fire
|
||||
And with no raea engine under the page (a browser) it returns without a sound, and says so once in the console
|
||||
|
||||
Rule: HW1. The kit's voices, in raea/tone
|
||||
Scenario: HW1a. A voice for each kind of touch
|
||||
Then a key going down thocks and coming up clicks lighter, a primary key deeper; a latch catches going down and
|
||||
springs going up; a detent (a knob's step, a switch's position, a wheel's row) ticks; anything on a screen (a
|
||||
readout, a list row) blips; a popup opens with a soft pop; typing clicks, deeper for space and heavier for
|
||||
Enter and Backspace; an outcome chimes (done, warning, error)
|
||||
And each is written with raea/tone's instruments and effects on the `ui` bus, never an audio file
|
||||
And no two presses sound quite alike: each varies its pitch and level a little, by raea/tone's seeded variation
|
||||
|
||||
Scenario: HW1b. Quiet by default
|
||||
Then the kit's loudest voice peaks at least 18 dB under full scale on the ui bus, under any music or voice a
|
||||
stage plays at the same time
|
||||
|
||||
Rule: HW2. The kit, dark, drawn by raea's window
|
||||
Scenario: HW2a. The controls
|
||||
Then the kit has a key (a button), a latch (a key that stays down), a switch and a slide switch, a knob with
|
||||
detents, a fader, a segmented selector, a stepper with its readout, a readout (an LCD-like screen), and a lamp
|
||||
And each is drawn on the app's dark palette (its ground, its raised greys, its ink and its accent), as anodised
|
||||
panels, keycaps and screens; there is no light skin
|
||||
And each works by pointer and by keyboard (arrows step a knob, a fader, a selector; Space and Enter press a key),
|
||||
with a focus ring shown only for the keyboard
|
||||
And each plays its HW1 voice as it moves, and nothing when sound is off (HW4)
|
||||
|
||||
Scenario: HW2b. Drawn the same in raea's window and in Chrome
|
||||
Then every control is drawn with what raea's window paints (no `<input type=range>`, whose thumb the window doesn't
|
||||
move; no SVG for anything a pointer presses; a drag followed by window pointer listeners), and a screenshot of
|
||||
the kit's sheet in a headless raea window matches Chrome's within the ui-parity bar
|
||||
|
||||
Scenario: HW2c. <Hardware>
|
||||
Then the app sits in one <Hardware> root, which installs the kit's sounds and keyboard-only focus once and changes
|
||||
nothing else about how the app looks
|
||||
|
||||
Rule: HW3. Where the kit is used
|
||||
Scenario: HW3a. Controllers
|
||||
Then a controller's fields are the kit's: a toggle is a switch, a choice a segmented selector (a dial past five
|
||||
options), a number a knob or a fader with its readout, and each change sounds as it is made
|
||||
|
||||
Scenario: HW3b. Settings
|
||||
Then Settings' toggles and choices are the kit's switches and selectors
|
||||
|
||||
Scenario: HW3c. The rest of the app, where a control is a control
|
||||
Then the Send keycap, the timeline's sliders and the player's transport use the kit's keys, faders and their
|
||||
voices; lists, menus and text stay the app's own
|
||||
|
||||
Rule: HW4. Sound off
|
||||
Scenario: HW4a. Settings › General › Interface sounds
|
||||
Then one switch turns every interface sound off and on, at once, remembered on this Mac
|
||||
And it is on by default
|
||||
And it never silences a film, a sound or a game: only the interface
|
||||
|
||||
Rule: HW5. Open
|
||||
Scenario: HW5a. Felt on a Mac's trackpad
|
||||
Then a knob's detent, a switch's catch and a fader's end are felt on a Force Touch trackpad (the system's haptic
|
||||
feedback, through a host call), as they are heard
|
||||
|
||||
Scenario: HW5b. A browser hears them too
|
||||
Then the kit's voices are bounced by raea once into small files a browser plays, so the app's page in Chrome (the
|
||||
tutorials' stage on raea.io) clicks as raea's window does
|
||||
+35
-6
@@ -84,6 +84,26 @@ Feature: Lightspeed: raea as fast as anything could be, with the best quality, m
|
||||
each frame two to three times slower: the GPU is one, and the window and every other render wait on it, so
|
||||
it is not a default. Two to three times on ray-traced frames is a cheaper trace (fewer pixels or samples
|
||||
traced, then upscaled), which changes the picture and is a rendering decision, not plumbing
|
||||
And measured 11-13 for drafts, where a smaller picture would change nothing that ships: `raea render` has no
|
||||
way to draw a composition smaller than it says it is (--w and --h only fill in a size a composition leaves
|
||||
out: the same 61-frame ray-traced shot with --w 960 --h 540 came out 1920 by 1080 in 4.1 s, against 4.7 s),
|
||||
so a draft (the composition editor's, a 3D scene's kept frames in docs/timeline.feature TL10f) pays for
|
||||
every pixel of the final. A render asked for again with nothing changed is the export cache's: 0.3 s
|
||||
And done 11-13 for drafts, in the SDK and not the engine: `<Composition edit={{ scale }}>` lays the composition
|
||||
out at its own size (useVideoConfig still says it) in a box drawn at that fraction, and registers the smaller
|
||||
size, so a 3D view, a whole-frame camera's or one in a page element's box, traces fewer pixels and a 2D layout
|
||||
written in px keeps every place (a title, a caption bar, a badge and a boxed 3D view drawn at 0.5 match the
|
||||
full-size frame but for softer type). The same 61-frame ray-traced 1080p shot, warm, three passes each: 2.75 s
|
||||
at full size, 1.6 to 1.7 s at 0.5 (1.7 times end to end, about twice on the frames once the start is taken
|
||||
out); the shot frames the same. The app's composition drafts and a scene's kept frames write it in their
|
||||
throwaway source (raea-feed host/edit.ts withDraftScale: the long side at 960 px, never larger, never under a
|
||||
quarter; RAEA_DRAFT_SCALE=1 draws them at full size). What ships is never scaled. It pays where the GPU
|
||||
does the work: the feed's sample room, a light scene, redraws two 3 s ranges in a headless raea window in
|
||||
8.9 s scaled against 9.4 s, since there the time is each render's start and its JavaScript, not pixels
|
||||
And open: the full-size render itself. Two to three times there is the cheaper trace upscaled (Solari at a
|
||||
lower main-pass resolution, Bevy's MainPassResolutionOverride, with MetalFX's denoised scaler taking it to
|
||||
full size: its input is the output's size today and it runs before the forward meshes), a rendering decision
|
||||
with its own picture checks
|
||||
|
||||
Scenario: PF5. What agents lose time on
|
||||
Then fixed in the lane check (tools/agents/check, on this Mac): the CLI surface step tests the raea it rebuilds
|
||||
@@ -110,15 +130,24 @@ Feature: Lightspeed: raea as fast as anything could be, with the best quality, m
|
||||
And the app's player (raea-feed #13, not merged): the detail view's clock is outside React state, so a playing
|
||||
video's ticks render only what shows the time: the seconds of 60 fps play with a wait of 26 ms or more
|
||||
between frames go from nearly all to about half
|
||||
And open: frames still go through the CPU; the scene inspector's frame rate while orbiting is not measured
|
||||
And a scene looked around (11-13, the feed's sample room live in a headless window, its counter read over
|
||||
5 s): 57 frames a second standing still, 58 while an orbit is dragged without pause (the headless window
|
||||
draws 60 at most)
|
||||
And open: frames still go through the CPU; a heavy or ray-traced scene's rate while orbiting is not measured
|
||||
|
||||
Scenario: PF8. Pages and assets from this Mac open at once
|
||||
Then covered so far by PF1 (a feed) and PF2 (stills)
|
||||
And a project's Source view (50 compositions, 71 components): its list is there 0.18 s after the click when
|
||||
its thumbnails are in the proxy store, and 2.4 to 3.8 s when the store is empty and the feed's own are still
|
||||
being made. Not explained: the host answers in 0.25 to 0.33 s, the window draws 47 to 91 frames a second
|
||||
throughout, holding still-drawing at the click changes nothing, and so does asking for no row thumbnails
|
||||
And open: that first visit; an asset's preview, a model's, and the library on a real library
|
||||
And a project's Source view (Stay: 159 rows), first visit with an empty proxy store, by wall-clock marks in
|
||||
the page: its rows committed 0.59 s after the click; 0.29 s with its views loaded ahead (raea-feed #17: a
|
||||
lazily loaded view waited out React's 300 ms hold on every first open). The 2.4 to 3.8 s written here before
|
||||
was the measuring script: the window's `ui` tool hands out its last 240 frames in order, and a slow poller
|
||||
reads frames seconds old
|
||||
And the host found a project's folder by starting git and `raea workspace --json` (0.1 s) on nearly every
|
||||
request (raea-feed #16 keeps both answers while their files stand): with 54 projects, 52 briefs read at page
|
||||
open went from 4,831 ms for the slowest to 68, a library's files from 1,710 ms to 3
|
||||
And a library's tiles have pictures before its files are indexed, and draw in raea's window (raea-feed #15):
|
||||
60 pictures (463 MB) 3.6 s to make the first time, 0.02 s after
|
||||
And open: an asset's preview and a model's; cold start after a reboot
|
||||
|
||||
Rule: Lightspeed's goals (set 2026-10-19, after the four multi-day levers; the user: "just focus on lightspeed work")
|
||||
Scenario: Who owns what now
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
// check: frames 0,45,89
|
||||
import { AbsoluteFill, Composition, registerRoot, useCurrentFrame } from "raea";
|
||||
import { applyAll, empty, end, length, valueAt, type Clip, type Op, type Timeline } from "raea/editor";
|
||||
|
||||
// A timeline made in code and edited by operations, as the feed's editor and an agent's script both edit one: two
|
||||
// shots on the main track and a title over them.
|
||||
const before: Timeline = {
|
||||
...empty(30),
|
||||
tracks: [
|
||||
{ id: "text", kind: "text", clips: [{ id: "title", kind: "text", name: "Title", start: 0, length: 60 }] },
|
||||
{
|
||||
id: "main",
|
||||
kind: "main",
|
||||
clips: [
|
||||
{ id: "a", kind: "video", name: "Shot A", start: 0, length: 90, in: 0, source: 300 },
|
||||
{ id: "b", kind: "video", name: "Shot B", start: 90, length: 90, in: 0, source: 300 },
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
// Shot A split at one second, and the title faded in by two keys on its opacity.
|
||||
const first: Op[] = [
|
||||
{ op: "split", at: 30, ids: ["a"] },
|
||||
{ op: "key", id: "title", prop: "opacity", at: 0, value: 0, ease: [0.42, 0, 0.58, 1] },
|
||||
{ op: "key", id: "title", prop: "opacity", at: 20, value: 1 },
|
||||
];
|
||||
const cut = applyAll(before, first);
|
||||
// The half the split made is found where it starts, and played twice as fast: the main track's magnet closes the
|
||||
// gap, so Shot B comes in earlier.
|
||||
const half = cut.timeline.tracks[1].clips.find((c) => c.start === 30)!;
|
||||
const after = applyAll(cut.timeline, [{ op: "set", id: half.id, set: { speed: 2 } }]);
|
||||
// Every operation gives back its inverse: applied last first, they put the timeline back as it was.
|
||||
const undone = applyAll(after.timeline, [...after.inverse, ...cut.inverse]).timeline;
|
||||
|
||||
const SCALE = 5; // px a frame
|
||||
const COLOR: Record<string, string> = { video: "#3d7bd9", text: "#c9853d" };
|
||||
|
||||
function Row({ clips, top, frame }: { clips: Clip[]; top: number; frame: number }) {
|
||||
return (
|
||||
<>
|
||||
{clips.map((c) => {
|
||||
const on = frame >= c.start && frame < end(c);
|
||||
const opacity = typeof valueAt(c.keys?.opacity, frame - c.start) === "number" ? (valueAt(c.keys?.opacity, frame - c.start) as number) : 1;
|
||||
return (
|
||||
<div
|
||||
key={c.id}
|
||||
style={{ position: "absolute", left: 80 + c.start * SCALE, top, width: c.length * SCALE - 4, height: 64, borderRadius: 8, background: COLOR[c.kind] ?? "#777", opacity: on ? Math.max(0.35, opacity) : 0.35, color: "#fff", fontSize: 26, padding: "16px 14px", boxSizing: "border-box", overflow: "hidden", whiteSpace: "nowrap" }}
|
||||
>
|
||||
{c.name}
|
||||
{c.speed && c.speed !== 1 ? ` · ${c.speed}x` : ""}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function Edits() {
|
||||
const frame = useCurrentFrame();
|
||||
const label = (y: number, text: string) => <div style={{ position: "absolute", left: 80, top: y, color: "#aaa", fontSize: 28 }}>{text}</div>;
|
||||
return (
|
||||
<AbsoluteFill style={{ background: "#16181c", fontFamily: "sans-serif" }}>
|
||||
{label(100, `Before: ${length(before)} frames`)}
|
||||
<Row clips={before.tracks[0].clips} top={144} frame={frame} />
|
||||
<Row clips={before.tracks[1].clips} top={218} frame={frame} />
|
||||
{label(330, `After ${first.length + 1} edits: ${length(after.timeline)} frames`)}
|
||||
<Row clips={after.timeline.tracks[0].clips} top={374} frame={frame} />
|
||||
<Row clips={after.timeline.tracks[1].clips} top={448} frame={frame} />
|
||||
{label(560, `Undone: ${JSON.stringify(undone) === JSON.stringify(before) ? "as it was" : "changed"}`)}
|
||||
<div style={{ position: "absolute", left: 80 + frame * SCALE, top: 134, width: 3, height: 392, background: "#ff4d4d" }} />
|
||||
</AbsoluteFill>
|
||||
);
|
||||
}
|
||||
|
||||
registerRoot(() => <Composition id="edits" component={Edits} width={1280} height={720} fps={30} durationInFrames={90} />);
|
||||
@@ -1,15 +1,16 @@
|
||||
---
|
||||
title: "Fingerprint: teach raea your eye"
|
||||
summary: "What raea learns about good work from your notes, marks and approvals, on your Mac: the axes it judges, the Fingerprint page, and what it can't judge yet."
|
||||
summary: "What raea learns about good work from your notes, marks and approvals, on your own computer: the axes it judges, the Fingerprint page, and what it can't judge yet."
|
||||
order: 0
|
||||
sources: ["docs/fingerprint.feature", "docs/fingerprint.md", "apps/fingerprint/src", "systems/fingerprint/src", "systems/fingerprint-use/src", "apps/app/src/fingerprint"]
|
||||
---
|
||||
|
||||
A fingerprint is your sense of good work, as raea has learned it on your Mac. It's a list of axes, the things you
|
||||
A fingerprint is your sense of good work, as raea has learned it on your own computer. It's a list of axes, the things you
|
||||
notice: blur, a black frame, hiss, clipping, a glow over everything, a frozen picture, and taste axes such as fake,
|
||||
barren or unreadable text. Each axis has a small model over encoders that run on your Mac (SigLIP 2 for pictures, CLAP
|
||||
for sound, YAMNet for sound events, EmbeddingGemma 2 for scripts and other text), so nothing leaves the machine unless
|
||||
you share it.
|
||||
barren or unreadable text. Each axis has a small model trained over the **Edit Embedding Zoo**: the encoders that run
|
||||
on your computer (SigLIP 2 for pictures, CLAP for sound, YAMNet for sound events, EmbeddingGemma 2 for scripts and other
|
||||
text, Depth Anything 3 for depth), so nothing leaves the machine unless you share it. The zoo is the same for everyone
|
||||
and never changes; what you train over it is yours.
|
||||
|
||||
Your agents use it before they post a cut: `raea fingerprint score` lists the moments your fingerprint expects a note
|
||||
on, each named in your words, and the agent fixes them or tells you why it didn't. It tells you the axis and the
|
||||
|
||||
@@ -14,8 +14,8 @@ the same calls.
|
||||
Anyone on **Pro** or **Team** can, a person on their own included: there's no separate developer plan and no
|
||||
per-call price. The API reaches what lives in raea's cloud, so it comes with the plans that have cloud storage.
|
||||
|
||||
On **Free**, libraries stay on your Mac, and so does their search. Search them from the app, or from a terminal or an
|
||||
agent on the same Mac with [`raea library`](../reference/cli/library.md), which needs no key. Asking for an agent key
|
||||
On **Free**, libraries stay on your computer, and so does their search. Search them from the app, or from a terminal or an
|
||||
agent on the same computer with [`raea library`](../reference/cli/library.md), which needs no key. Asking for an agent key
|
||||
on Free answers `402 agent_keys_paid`.
|
||||
|
||||
## Make an agent key
|
||||
@@ -92,7 +92,7 @@ Each hit is a moment: the file's `sha256`, the segment's `t0` and `t1` in second
|
||||
your words as keywords too: `"by": "meaning"`. Without one, it searches by keywords alone: `"by": "words"`. The vector
|
||||
is EmbeddingGemma 2's (`onnx-community/embeddinggemma-2-ONNX`, 768 numbers) for the text
|
||||
`task: search result | query: ` followed by your words. raea never runs a model in its cloud for you: the app embeds
|
||||
your words on your Mac, which is what `raea library search` and the app's Search do, and raea.io's Storage page
|
||||
your words on your computer, which is what `raea library search` and the app's Search do, and raea.io's Storage page
|
||||
borrows one of your computers that's online.
|
||||
|
||||
## Get a file
|
||||
|
||||
@@ -46,7 +46,7 @@ The raea skill (`raea skill` prints it) is the short version of the same loop; t
|
||||
|
||||
## Fingerprint
|
||||
|
||||
- [Fingerprint: teach raea your eye](fingerprint/index.md): what raea learns about good work from your notes, on your Mac.
|
||||
- [Fingerprint: teach raea your eye](fingerprint/index.md): what raea learns about good work from your notes, on your own computer.
|
||||
- [Train your fingerprint](fingerprint/train.md): your renders, notes and marks, and a box on the part of a sound you mean.
|
||||
- [Check a cut with it](fingerprint/check.md): score a cut before it's posted, and check that a fix really fixed it.
|
||||
- [Projects and teams](fingerprint/projects.md): which fingerprint judges a project, and keeping one with it for the team.
|
||||
|
||||
@@ -23,7 +23,7 @@ raea skill --reference sdk
|
||||
## Usage
|
||||
|
||||
```sh
|
||||
raea skill [NAME] [--reference cli|feed|files|sdk] | raea skills install --agent claude|codex|kimi|gemini [--pin MOVE]... [--no-mcp] [--no-hooks] (the agent skill this raea ships, for its version, which raea --version prints: an agent whose copy names another version reads this; install puts raea's skills where that agent reads skills, adds the blender MCP server unless --no-mcp, makes each --pin MOVE a /MOVE of its own, and adds raea's hooks to that agent unless --no-hooks (raea hook AGENT: media opened in the Mac's viewer goes to raea show, and the quick check after a composition is saved); a skill folder that's a link is left as it is)
|
||||
raea skill [NAME] [--reference cli|feed|files|sdk] | raea skills install --agent claude|codex|kimi|gemini|grokbot [--pin MOVE]... [--no-mcp] [--no-hooks] (the agent skill this raea ships, for its version, which raea --version prints: an agent whose copy names another version reads this; install puts raea's skills where that agent reads skills, adds the blender MCP server unless --no-mcp, makes each --pin MOVE a /MOVE of its own, and adds raea's hooks to that agent unless --no-hooks (raea hook AGENT: media opened in the Mac's viewer goes to raea show, and the quick check after a composition is saved); a skill folder that's a link is left as it is; grokbot, the Grok Bot app, keeps its skills on its own computer, so its copy is staged on this Mac (RAEA_GROKBOT_HOME moves it) with the grokbot:// links that finish it in Grok Bot, and gets no hooks or MCP server)
|
||||
```
|
||||
|
||||
Headless: it needs nothing running and opens no window. Takes up to 1 argument besides its flags.
|
||||
@@ -32,7 +32,7 @@ Headless: it needs nothing running and opens no window. Takes up to 1 argument b
|
||||
|
||||
| Flag | Takes | What it does |
|
||||
| --- | --- | --- |
|
||||
| `--agent` | `claude\|codex\|kimi\|gemini` | Used by `skills install`; see [`raea skills`](skills.md). |
|
||||
| `--agent` | `claude\|codex\|kimi\|gemini\|grokbot` | Used by `skills install`; see [`raea skills`](skills.md). |
|
||||
| `--no-hooks` | – | Used by `skills install`; see [`raea skills`](skills.md). |
|
||||
| `--no-mcp` | – | Used by `skills install`; see [`raea skills`](skills.md). |
|
||||
| `--pin` | `MOVE` | Used by `skills install`; see [`raea skills`](skills.md). |
|
||||
|
||||
@@ -26,7 +26,7 @@ raea skills install --agent claude --pin quieter --pin bolder # /quieter and
|
||||
## Usage
|
||||
|
||||
```sh
|
||||
raea skill [NAME] [--reference cli|feed|files|sdk] | raea skills install --agent claude|codex|kimi|gemini [--pin MOVE]... [--no-mcp] [--no-hooks] (the agent skill this raea ships, for its version, which raea --version prints: an agent whose copy names another version reads this; install puts raea's skills where that agent reads skills, adds the blender MCP server unless --no-mcp, makes each --pin MOVE a /MOVE of its own, and adds raea's hooks to that agent unless --no-hooks (raea hook AGENT: media opened in the Mac's viewer goes to raea show, and the quick check after a composition is saved); a skill folder that's a link is left as it is)
|
||||
raea skill [NAME] [--reference cli|feed|files|sdk] | raea skills install --agent claude|codex|kimi|gemini|grokbot [--pin MOVE]... [--no-mcp] [--no-hooks] (the agent skill this raea ships, for its version, which raea --version prints: an agent whose copy names another version reads this; install puts raea's skills where that agent reads skills, adds the blender MCP server unless --no-mcp, makes each --pin MOVE a /MOVE of its own, and adds raea's hooks to that agent unless --no-hooks (raea hook AGENT: media opened in the Mac's viewer goes to raea show, and the quick check after a composition is saved); a skill folder that's a link is left as it is; grokbot, the Grok Bot app, keeps its skills on its own computer, so its copy is staged on this Mac (RAEA_GROKBOT_HOME moves it) with the grokbot:// links that finish it in Grok Bot, and gets no hooks or MCP server)
|
||||
```
|
||||
|
||||
Headless: it needs nothing running and opens no window. Takes up to 1 argument besides its flags.
|
||||
@@ -35,7 +35,7 @@ Headless: it needs nothing running and opens no window. Takes up to 1 argument b
|
||||
|
||||
| Flag | Takes | What it does |
|
||||
| --- | --- | --- |
|
||||
| `--agent` | `claude\|codex\|kimi\|gemini` | Which agent to install for. |
|
||||
| `--agent` | `claude\|codex\|kimi\|gemini\|grokbot` | Which agent to install for. |
|
||||
| `--no-hooks` | – | Leave Claude Code's settings alone: don't add the quick-check hook. |
|
||||
| `--no-mcp` | – | Don't add the Blender MCP server to the agent. |
|
||||
| `--pin` | `MOVE` | Install a note's guide as a skill of its own, so `/MOVE` loads just it (`quieter`, `bolder`, `layout`, `adapt` and the rest). Repeatable. |
|
||||
|
||||
@@ -247,6 +247,7 @@ a split, a cut word or a moved span is a change to this list; the length becomes
|
||||
| Field | Type | What it is |
|
||||
| --- | --- | --- |
|
||||
| `segments` | `readonly (readonly [number, number])[]` | the composition's own frame ranges, [from, to), played one after another |
|
||||
| `scale` | `number` | the composition drawn at this fraction of its size (above 0, at most 1), what is where kept: it is laid out at its width and height (useVideoConfig still says them) and the whole drawn smaller, so a 3D view traces fewer pixels. A draft's, where a smaller picture changes nothing that ships: the app's composition drafts and a scene's kept frames draw at 0.5 |
|
||||
|
||||
### `OpenOptions`
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -31,7 +31,7 @@ The composition, the app, and the specs and notes an agent writes.
|
||||
|
||||
| Import | What it's for | Exports |
|
||||
| --- | --- | --- |
|
||||
| [`raea`](raea.md) | The main entry: compositions, sequences, time, interpolation, springs, footage, sound and words. | 18 components, 8 hooks, 55 functions, 9 values, 91 types |
|
||||
| [`raea`](raea.md) | The main entry: compositions, sequences, time, interpolation, springs, footage, sound and words. | 20 components, 8 hooks, 62 functions, 11 values, 98 types |
|
||||
| [`raea/app`](app.md) | The App, its plugins and schedules, and the registry a video's compositions are kept in. | 1 component, 4 functions, 3 classes, 17 values, 8 types |
|
||||
| [`raea/brief`](brief.md) | The specs an agent writes as data: brief, script, taste, plan and controller, checked against raea's schemas. | 6 functions, 32 types |
|
||||
| [`raea/note`](note.md) | A person's note as a file in the project: their words kept as written, and the asks the agent restates it as. | 1 function, 4 types |
|
||||
@@ -51,16 +51,17 @@ Frames, animation, springs, states and input, and holding a frame until it's rea
|
||||
|
||||
## Video, sound and text
|
||||
|
||||
Footage, pictures, sound, words and colour.
|
||||
Footage, pictures, sound, words and colour, and the timeline they are edited on.
|
||||
|
||||
| Import | What it's for | Exports |
|
||||
| --- | --- | --- |
|
||||
| [`raea/video`](video.md) | Footage and time-shifted sequences: Video, Sequence, Series, Loop and Freeze. | 5 components, 7 types |
|
||||
| [`raea/video`](video.md) | Footage and time-shifted sequences: Video, Sequence, Series, Loop and Freeze. | 5 components, 8 types |
|
||||
| [`raea/audio`](audio.md) | Sound: Audio, the master Mix, speech, sound in 3D space, and a song's energy map. | 6 components, 1 hook, 7 functions, 1 value, 25 types |
|
||||
| [`raea/text`](text.md) | Text in the 3D world, fonts, and time anchored to the words said. | 3 components, 1 hook, 3 functions, 6 types |
|
||||
| [`raea/image`](image.md) | Pictures on the page and in the world, and texture atlases packed from them. | 3 components, 1 class, 5 types |
|
||||
| [`raea/asset`](asset.md) | Files the project holds and assets made for it: staticFile, generated sound and music, and glTF bytes. | 9 functions, 1 value, 8 types |
|
||||
| [`raea/color`](color.md) | Bevy's colour types: Srgba, LinearRgba, Hsla, Oklab, Oklch and the rest, with their conversions. | 2 functions, 7 classes |
|
||||
| [`raea/editor`](editor.md) | The timeline the feed edits a film, a scene or a sound on, as data: tracks, clips, keys and markers, every edit an operation with its inverse, a film's scenes read in (fromRender) and its cut read back out as segments (segmentsOf). No React and no DOM: an agent's script, the app's host and a test use the same model the app's timeline does. | 63 functions, 28 values, 45 types |
|
||||
|
||||
## 3D
|
||||
|
||||
|
||||
@@ -423,8 +423,8 @@ copy together). Rotation in radians, XYZ order, as everywhere.
|
||||
| `onPointerOver` | `(e: Event3d) => void` | the pointer came over the part (bubbles, as the DOM's) |
|
||||
| `onPointerOut` | `(e: Event3d) => void` | the pointer left the part (bubbles) |
|
||||
| `onWheel` | `(e: Event3d) => void` | the wheel turned over the part (`deltaX`, `deltaY`) |
|
||||
| `quat` | `Quat` | Bevy's rotation as it is, a quaternion [x, y, z, w] in Bevy's axes (y up, z toward the viewer), in place of `rotation`: a turn out of the frame's plane too, as a Sprite's Transform takes it (camera/2d_on_ui) |
|
||||
| `opacity` | `number` | 0 to 1 (1 by default) |
|
||||
| `quat` | `Quat` | Bevy's rotation as it is, a quaternion [x, y, z, w] in Bevy's axes (y up, z toward the viewer), in place of `rotation`: a turn out of the frame's plane too, as a Sprite's Transform takes it (camera/2d_on_ui) |
|
||||
|
||||
### `Mesh3dProps`
|
||||
|
||||
|
||||
@@ -38,7 +38,7 @@ See [Your first video](../../start/first-video.md) for the whole loop, and
|
||||
import { AbsoluteFill, ACTION_KEY, actionsIn, Animate } from "raea"
|
||||
```
|
||||
|
||||
`raea` exports 18 components, 8 hooks, 55 functions, 9 values, 91 types. Source: [sdk/raea/src/index.tsx](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/src/index.tsx).
|
||||
`raea` exports 20 components, 8 hooks, 62 functions, 11 values, 98 types. Source: [sdk/raea/src/index.tsx](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/src/index.tsx).
|
||||
|
||||
## Components
|
||||
|
||||
@@ -52,7 +52,7 @@ A box over the whole of its parent, laid out as a flex column; `style` is merged
|
||||
| `className` | `string` | Tailwind or CSS classes |
|
||||
| `children` | `ReactNode` | what fills it |
|
||||
|
||||
Used in: [ui/images/image_node](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/ui/images/image_node.tsx), [ui/images/ui_texture_slice_flip_and_tile](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/ui/images/ui_texture_slice_flip_and_tile.tsx), [ui/images/image_node_resizing](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/ui/images/image_node_resizing.tsx), [ui/images/ui_texture_atlas_slice](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/ui/images/ui_texture_atlas_slice.tsx), [ui/images/ui_texture_slice](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/ui/images/ui_texture_slice.tsx), [ui/images/ui_texture_atlas](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/ui/images/ui_texture_atlas.tsx), [ui/layout/grid](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/ui/layout/grid.tsx), [ui/layout/ghost_nodes](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/ui/layout/ghost_nodes.tsx), and 98 more.
|
||||
Used in: [ui/images/image_node](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/ui/images/image_node.tsx), [ui/images/ui_texture_slice_flip_and_tile](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/ui/images/ui_texture_slice_flip_and_tile.tsx), [ui/images/image_node_resizing](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/ui/images/image_node_resizing.tsx), [ui/images/ui_texture_atlas_slice](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/ui/images/ui_texture_atlas_slice.tsx), [ui/images/ui_texture_slice](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/ui/images/ui_texture_slice.tsx), [ui/images/ui_texture_atlas](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/ui/images/ui_texture_atlas.tsx), [ui/layout/grid](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/ui/layout/grid.tsx), [ui/layout/ghost_nodes](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/ui/layout/ghost_nodes.tsx), and 99 more.
|
||||
|
||||
### `Animate`
|
||||
|
||||
@@ -108,7 +108,19 @@ Declares a composition inside the root. It draws nothing itself; a renderer find
|
||||
| `defaultProps` | `P` | the props it's rendered with (JSON-like values only) |
|
||||
| `edit` | `Edit` | a hand edit laid over the composition (docs/craft-system.md, L): written back by the app's timeline |
|
||||
|
||||
Used in: [ui/images/image_node](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/ui/images/image_node.tsx), [ui/images/ui_texture_slice_flip_and_tile](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/ui/images/ui_texture_slice_flip_and_tile.tsx), [ui/images/image_node_resizing](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/ui/images/image_node_resizing.tsx), [ui/images/ui_texture_atlas_slice](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/ui/images/ui_texture_atlas_slice.tsx), [ui/images/ui_texture_slice](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/ui/images/ui_texture_slice.tsx), [ui/images/ui_texture_atlas](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/ui/images/ui_texture_atlas.tsx), [ui/layout/grid](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/ui/layout/grid.tsx), [ui/layout/ghost_nodes](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/ui/layout/ghost_nodes.tsx), and 152 more.
|
||||
Used in: [ui/images/image_node](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/ui/images/image_node.tsx), [ui/images/ui_texture_slice_flip_and_tile](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/ui/images/ui_texture_slice_flip_and_tile.tsx), [ui/images/image_node_resizing](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/ui/images/image_node_resizing.tsx), [ui/images/ui_texture_atlas_slice](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/ui/images/ui_texture_atlas_slice.tsx), [ui/images/ui_texture_slice](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/ui/images/ui_texture_slice.tsx), [ui/images/ui_texture_atlas](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/ui/images/ui_texture_atlas.tsx), [ui/layout/grid](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/ui/layout/grid.tsx), [ui/layout/ghost_nodes](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/ui/layout/ghost_nodes.tsx), and 153 more.
|
||||
|
||||
### `Effect`
|
||||
|
||||
The picture under it, through the effect, for as long as its <Sequence> runs.
|
||||
|
||||
| Prop | Type | What it does |
|
||||
| --- | --- | --- |
|
||||
| `kind` (required) | `string` | which effect: blur, mono, sepia, vivid, faded, contrast, bright, dark, invert or hue; with `parts`, its own name |
|
||||
| `parts` | `EffectPart[]` | an effect of its own, as CSS filter functions (a plugin's): each [function, value at amount 0, value at amount 1, unit], such as [["blur", 0, 6, "px"], ["saturate", 1, 1.6]] |
|
||||
| `amount` | `number` | how much of it, from 0 (none) to 1 (all, the default) |
|
||||
| `in` | `number` | frames it takes to come on at its part's start (0: on at once) |
|
||||
| `out` | `number` | frames it takes to go off by its part's end (0: off at once) |
|
||||
|
||||
### `Freeze`
|
||||
|
||||
@@ -168,7 +180,7 @@ The master: every sound in the composition brought to `lufs` integrated loudness
|
||||
### `Nudge`
|
||||
|
||||
Places its child: an element gets the move in front of its own transform and the fade times its own opacity; a
|
||||
component, whose box it can't reach, is placed inside a full-frame layer.
|
||||
component, whose box it can't reach, or a part with a mask, is placed inside a full-frame layer.
|
||||
|
||||
| Prop | Type | What it does |
|
||||
| --- | --- | --- |
|
||||
@@ -177,6 +189,13 @@ component, whose box it can't reach, is placed inside a full-frame layer.
|
||||
| `scale` | `number` | how much bigger (2) or smaller (0.5), about its centre |
|
||||
| `rotate` | `number` | a turn, in degrees, about its centre |
|
||||
| `opacity` | `number` | 0 (gone) to 1 (as it was), times its own opacity |
|
||||
| `mirror` | `boolean` | flipped left to right |
|
||||
| `crop` | `[left: number, top: number, right: number, bottom: number]` | how much is cut off its left, top, right and bottom, each a share of that side from 0 to 0.9 |
|
||||
| `mask` | `Mask` | what of it is seen: a shape in shares of the frame (line, mirror, circle, rect, heart, star), turned, feathered or inverted (sdk/video cutout.ts, TL7f) |
|
||||
| `blend` | `Blend` | how it is drawn over what is under it: screen, multiply, overlay and the rest of CSS's blend modes |
|
||||
| `chroma` | `ChromaKey` | a colour taken out of it, as a green screen is: { color, strength, shadow } |
|
||||
| `adjust` | `Adjust` | its brightness, contrast, saturation, exposure, sharpen, highlights, shadows, temperature, tint, fade, vignette and grain, each 0 as shot (sdk/video adjust.ts, TL7g) |
|
||||
| `keys` | `Partial<Record<NudgeProp, NudgeKey[]>>` | any of the above over time: its keys, each [frame, value, ease?], in frames from where this part's time starts (its <Sequence>'s first frame), by the names in NUDGE_KEYED ("mask.x", "chroma.strength", "crop.left" for what is inside a mask, a key or a crop). A keyed property's still value is ignored. |
|
||||
| `children` | `ReactNode` | the part it places: an element, or a component, which moves inside a full-frame layer |
|
||||
|
||||
### `Overlay`
|
||||
@@ -245,6 +264,17 @@ render gives the same element back.
|
||||
|
||||
Also takes the props of [`StaggerProps`](animation.md#staggerprops) (`each`, `grid`, `exitEach`); [`AnimateOwnProps`](animation.md#animateownprops).
|
||||
|
||||
### `Transition`
|
||||
|
||||
Its children, coming in over the part's first frames, going out over its last, and moving by a Combo throughout.
|
||||
|
||||
| Prop | Type | What it does |
|
||||
| --- | --- | --- |
|
||||
| `in` | `TransitionEdge` | over the part's first frames |
|
||||
| `out` | `TransitionEdge` | over the part's last frames |
|
||||
| `combo` | `ComboLoop` | a Combo over the whole part: a cycle every `frames`, from its first frame |
|
||||
| `children` | `ReactNode` | the part it brings in and takes out: what the <Sequence> holds |
|
||||
|
||||
### `Video`
|
||||
|
||||
A video clip in step with the frame; `data-source-time` is the source time (seconds) to show.
|
||||
@@ -253,6 +283,7 @@ A video clip in step with the frame; `data-source-time` is the source time (seco
|
||||
| --- | --- | --- |
|
||||
| `framing` | `"face"` | ours: frame the take on the largest face |
|
||||
| `punchIn` | `number` | ours: multiplies the framing's scale (1.15 is the usual) |
|
||||
| `matte` | `VideoMatte` | ours: its cutout: the mattes made of its file, which it wears as its mask, so what is cut out shows what is under it |
|
||||
|
||||
Also takes the props of [`MediaProps`](video.md#mediaprops).
|
||||
|
||||
@@ -266,7 +297,7 @@ The frame being rendered, counted from the start of the nearest enclosing Sequen
|
||||
function useCurrentFrame(): number
|
||||
```
|
||||
|
||||
Used in: [ui/scroll_and_overflow/overflow_transform](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/ui/scroll_and_overflow/overflow_transform.tsx), [ui/render_ui_to_texture](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/ui/render_ui_to_texture.tsx), [ui/ui_material](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/ui/ui_material.tsx), [ui/styling/gradients](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/ui/styling/gradients.tsx), [ui/text/text_debug](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/ui/text/text_debug.tsx), [ui/text/text](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/ui/text/text.tsx), [ui/text/font_atlas_debug](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/ui/text/font_atlas_debug.tsx), [3d/fog_volumes](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/3d/fog_volumes.tsx), and 46 more.
|
||||
Used in: [ui/scroll_and_overflow/overflow_transform](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/ui/scroll_and_overflow/overflow_transform.tsx), [ui/render_ui_to_texture](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/ui/render_ui_to_texture.tsx), [ui/ui_material](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/ui/ui_material.tsx), [ui/styling/gradients](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/ui/styling/gradients.tsx), [ui/text/text_debug](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/ui/text/text_debug.tsx), [ui/text/text](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/ui/text/text.tsx), [ui/text/font_atlas_debug](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/ui/text/font_atlas_debug.tsx), [3d/fog_volumes](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/3d/fog_volumes.tsx), and 47 more.
|
||||
|
||||
### `useGameEvents`
|
||||
|
||||
@@ -397,6 +428,30 @@ Hold the frame until `continueRender(handle)`. `label` names it if it's still op
|
||||
function delayRender(label?: string, options?: { timeoutInMilliseconds?: number; } | undefined): number
|
||||
```
|
||||
|
||||
### `effectAt`
|
||||
|
||||
How much of the effect is on at `frame` of a part `duration` frames long, coming on over `enter` and off over `exit`.
|
||||
|
||||
```ts
|
||||
function effectAt(frame: number, duration: number, enter?: number, exit?: number): number
|
||||
```
|
||||
|
||||
### `effectFilter`
|
||||
|
||||
The CSS filter of `kind` at `amount` (0 to 1, clamped); undefined for a kind raea doesn't draw.
|
||||
|
||||
```ts
|
||||
function effectFilter(kind: string, amount?: number): string | undefined
|
||||
```
|
||||
|
||||
### `effectPartsError`
|
||||
|
||||
Why `parts` isn't an effect's parts, or undefined when it is.
|
||||
|
||||
```ts
|
||||
function effectPartsError(parts: unknown): string | undefined
|
||||
```
|
||||
|
||||
### `fade`
|
||||
|
||||
opacity 0 to 1 over `frames` (6).
|
||||
@@ -545,6 +600,14 @@ Every step at once.
|
||||
function parallel(...steps: Step[]): Group
|
||||
```
|
||||
|
||||
### `partsFilter`
|
||||
|
||||
The CSS filter of an effect given as parts, at `amount` (0 to 1, clamped).
|
||||
|
||||
```ts
|
||||
function partsFilter(parts: EffectPart[], amount?: number): string
|
||||
```
|
||||
|
||||
### `pop`
|
||||
|
||||
scale `from` (0.6), `peak` (1.08) at `frames`/2, 1 at `frames` (8); in over 3 frames.
|
||||
@@ -594,7 +657,7 @@ Names the root component the renderer starts from, and records its compositions.
|
||||
function registerRoot(given: ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentType): void
|
||||
```
|
||||
|
||||
Used in: [ui/images/image_node](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/ui/images/image_node.tsx), [ui/images/ui_texture_slice_flip_and_tile](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/ui/images/ui_texture_slice_flip_and_tile.tsx), [ui/images/image_node_resizing](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/ui/images/image_node_resizing.tsx), [ui/images/ui_texture_atlas_slice](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/ui/images/ui_texture_atlas_slice.tsx), [ui/images/ui_texture_slice](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/ui/images/ui_texture_slice.tsx), [ui/images/ui_texture_atlas](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/ui/images/ui_texture_atlas.tsx), [ui/layout/grid](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/ui/layout/grid.tsx), [ui/layout/ghost_nodes](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/ui/layout/ghost_nodes.tsx), and 152 more.
|
||||
Used in: [ui/images/image_node](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/ui/images/image_node.tsx), [ui/images/ui_texture_slice_flip_and_tile](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/ui/images/ui_texture_slice_flip_and_tile.tsx), [ui/images/image_node_resizing](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/ui/images/image_node_resizing.tsx), [ui/images/ui_texture_atlas_slice](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/ui/images/ui_texture_atlas_slice.tsx), [ui/images/ui_texture_slice](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/ui/images/ui_texture_slice.tsx), [ui/images/ui_texture_atlas](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/ui/images/ui_texture_atlas.tsx), [ui/layout/grid](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/ui/layout/grid.tsx), [ui/layout/ghost_nodes](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/ui/layout/ghost_nodes.tsx), and 153 more.
|
||||
|
||||
### `replayDecider`
|
||||
|
||||
@@ -687,6 +750,30 @@ Where the song is at `t` seconds: a pure function of the map.
|
||||
function songAt(map: SongMap, t: number): SongMoment
|
||||
```
|
||||
|
||||
### `speedLength`
|
||||
|
||||
How many frames `span` source frames take under the curve (points from speedPoints).
|
||||
|
||||
```ts
|
||||
function speedLength(ps: SpeedPoint[], span: number): number
|
||||
```
|
||||
|
||||
### `speedPoints`
|
||||
|
||||
The points checked and in order, one at each end.
|
||||
|
||||
```ts
|
||||
function speedPoints(owner: string, curve: SpeedPoint[]): SpeedPoint[]
|
||||
```
|
||||
|
||||
### `speedSource`
|
||||
|
||||
The source frame, counted from the curve's start, showing `frame` frames in; `span` once the curve has run out.
|
||||
|
||||
```ts
|
||||
function speedSource(ps: SpeedPoint[], span: number, frame: number): number
|
||||
```
|
||||
|
||||
### `spring`
|
||||
|
||||
A damped spring's value at `frame`: from `from` (0) to `to` (1), started `delay` frames late, by its `config`
|
||||
@@ -829,6 +916,12 @@ turn one round. Pass one as `interpolate`'s `easing`.
|
||||
|
||||
Used in: [manual: turntable](https://github.com/shinyobjectz/raea/blob/main/docs/manual/examples/turntable.tsx).
|
||||
|
||||
### `EFFECT_FNS`
|
||||
|
||||
The filter functions a part may name, each with the units it takes.
|
||||
|
||||
### `EFFECTS`
|
||||
|
||||
### `FEED_KEY`
|
||||
|
||||
The prefix of the keys the app hands every panel for what it knows: `feed:transcript` (the conversation's last lines,
|
||||
@@ -1073,6 +1166,28 @@ a split, a cut word or a moved span is a change to this list; the length becomes
|
||||
| Field | Type | What it is |
|
||||
| --- | --- | --- |
|
||||
| `segments` | `readonly (readonly [number, number])[]` | the composition's own frame ranges, [from, to), played one after another |
|
||||
| `scale` | `number` | the composition drawn at this fraction of its size (above 0, at most 1), what is where kept: it is laid out at its width and height (useVideoConfig still says them) and the whole drawn smaller, so a 3D view traces fewer pixels. A draft's, where a smaller picture changes nothing that ships: the app's composition drafts and a scene's kept frames draw at 0.5 |
|
||||
|
||||
### `EffectKind`
|
||||
|
||||
| Field | Type | What it is |
|
||||
| --- | --- | --- |
|
||||
| `kind` (required) | `string` | its name in the composition's code: <Effect kind> |
|
||||
| `title` (required) | `string` | what the person sees |
|
||||
| `filter` (required) | `(amount: number) => string` | the CSS filter at `amount` |
|
||||
|
||||
### `EffectPart`
|
||||
|
||||
An effect as data: each part one CSS filter function, its value going
|
||||
from `from` (amount 0, where it changes nothing) to `to` (amount 1), with its unit: ["blur", 0, 6, "px"].
|
||||
|
||||
```ts
|
||||
type EffectPart = [fn: string, from: number, to: number, unit?: string]
|
||||
```
|
||||
|
||||
### `EffectProps`
|
||||
|
||||
The props of [`Effect`](#effect), tabled there.
|
||||
|
||||
### `ExtrapolateMode`
|
||||
|
||||
@@ -1212,6 +1327,7 @@ The props of [`Loop`](#loop), tabled there.
|
||||
| `fadeIn` | `number` | ours: seconds to ramp the sound in from silence at its start (applied by the renderer at the audio's rate) |
|
||||
| `fadeOut` | `number` | ours: seconds to ramp the sound out to silence by its end: the end of its Sequence or Loop pass, or endAt, whichever comes first (one removed some other way fades out after it's gone) |
|
||||
| `playbackRate` | `number` | how fast it plays (1): 2 is double speed |
|
||||
| `speedCurve` | `SpeedPoint[]` | ours: its speed as a curve over its source, [place, speed] points: the place from 0 (startFrom) to 1 (endAt, which it needs), the speed from 0.1 to 10 and changing in a straight line between two points. Wins over playbackRate; its Sequence is as long as the curve takes (`speedLength`) |
|
||||
| `muted` | `boolean` | play no sound |
|
||||
| `loop` | `boolean` | start again from `startFrom` when it reaches `endAt` |
|
||||
| `bus` | `string` | the bus it plays into: a named channel of the edit's Tone graph (music, sfx, voice, ambience, ui), so it takes that bus's volume, effects and ducking (raea/tone `buses`) |
|
||||
@@ -1569,6 +1685,12 @@ The props of [`SongPlot`](#songplot), tabled there.
|
||||
| `energy` (required) | `number` | its mean energy, 0..1 |
|
||||
| `cuts` (required) | `number` | suggested cuts per bar: 0.25, 0.5, 1, 2 or 4 |
|
||||
|
||||
### `SpeedPoint`
|
||||
|
||||
```ts
|
||||
type SpeedPoint = [place: number, speed: number]
|
||||
```
|
||||
|
||||
### `SpringConfig`
|
||||
|
||||
| Field | Type | What it is |
|
||||
@@ -1686,6 +1808,27 @@ many steps in the state at least (`after`), and what to do on the way (`actions`
|
||||
type TransitionConfig = Target<N> & When<C, E> & { /** steps in the state before this transition may fire (0) */ after?: number; actions?: Actions<C, E>; /** what the transition means: a decider reads it (a model's option description), reports show it */ description?: string; }
|
||||
```
|
||||
|
||||
### `TransitionEdge`
|
||||
|
||||
| Field | Type | What it is |
|
||||
| --- | --- | --- |
|
||||
| `kind` (required) | `TransitionKind` | which transition: fade, slide, wipe or zoom |
|
||||
| `frames` (required) | `number` | how many of the part's frames it takes |
|
||||
|
||||
### `TransitionKind`
|
||||
|
||||
fade: through black. slide: in from the right, out to the left. wipe: uncovered from the left, covered from the
|
||||
left. zoom: grows in from 85%, shrinks out to 85%, fading. A dissolve between two parts that only touch has no
|
||||
frames of the other to mix with, so it is written as a fade.
|
||||
|
||||
```ts
|
||||
type TransitionKind = "fade" | "slide" | "wipe" | "zoom"
|
||||
```
|
||||
|
||||
### `TransitionProps`
|
||||
|
||||
The props of [`Transition`](#transition), tabled there.
|
||||
|
||||
### `TransitionRecord`
|
||||
|
||||
One transition as a row: what a trace keeps and rdb loads (step, machine, from, to, edge, decider, evidence). `from` is
|
||||
|
||||
@@ -320,8 +320,8 @@ The props of [`Ellipse`](#ellipse), tabled there.
|
||||
| `onPointerOver` | `(e: Event3d) => void` | the pointer came over the part (bubbles, as the DOM's) |
|
||||
| `onPointerOut` | `(e: Event3d) => void` | the pointer left the part (bubbles) |
|
||||
| `onWheel` | `(e: Event3d) => void` | the wheel turned over the part (`deltaX`, `deltaY`) |
|
||||
| `quat` | `Quat` | Bevy's rotation as it is, a quaternion [x, y, z, w] in Bevy's axes (y up, z toward the viewer), in place of `rotation`: a turn out of the frame's plane too, as a Sprite's Transform takes it (camera/2d_on_ui) |
|
||||
| `opacity` | `number` | 0 to 1 (1 by default) |
|
||||
| `quat` | `Quat` | Bevy's rotation as it is, a quaternion [x, y, z, w] in Bevy's axes (y up, z toward the viewer), in place of `rotation`: a turn out of the frame's plane too, as a Sprite's Transform takes it (camera/2d_on_ui) |
|
||||
|
||||
### `MeshAttributes`
|
||||
|
||||
|
||||
@@ -34,7 +34,7 @@ function Cut() {
|
||||
import { Freeze, Loop, Sequence, Series } from "raea/video"
|
||||
```
|
||||
|
||||
`raea/video` exports 5 components, 7 types. Bevy's counterpart: `raea's own; Bevy has no video crate`. Source: [sdk/raea/src/video.ts](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/src/video.ts).
|
||||
`raea/video` exports 5 components, 8 types. Bevy's counterpart: `raea's own; Bevy has no video crate`. Source: [sdk/raea/src/video.ts](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/src/video.ts).
|
||||
|
||||
## Components
|
||||
|
||||
@@ -93,6 +93,7 @@ A video clip in step with the frame; `data-source-time` is the source time (seco
|
||||
| --- | --- | --- |
|
||||
| `framing` | `"face"` | ours: frame the take on the largest face |
|
||||
| `punchIn` | `number` | ours: multiplies the framing's scale (1.15 is the usual) |
|
||||
| `matte` | `VideoMatte` | ours: its cutout: the mattes made of its file, which it wears as its mask, so what is cut out shows what is under it |
|
||||
|
||||
Also takes the props of [`MediaProps`](#mediaprops).
|
||||
|
||||
@@ -120,6 +121,7 @@ The props of [`Loop`](#loop), tabled there.
|
||||
| `fadeIn` | `number` | ours: seconds to ramp the sound in from silence at its start (applied by the renderer at the audio's rate) |
|
||||
| `fadeOut` | `number` | ours: seconds to ramp the sound out to silence by its end: the end of its Sequence or Loop pass, or endAt, whichever comes first (one removed some other way fades out after it's gone) |
|
||||
| `playbackRate` | `number` | how fast it plays (1): 2 is double speed |
|
||||
| `speedCurve` | `SpeedPoint[]` | ours: its speed as a curve over its source, [place, speed] points: the place from 0 (startFrom) to 1 (endAt, which it needs), the speed from 0.1 to 10 and changing in a straight line between two points. Wins over playbackRate; its Sequence is as long as the curve takes (`speedLength`) |
|
||||
| `muted` | `boolean` | play no sound |
|
||||
| `loop` | `boolean` | start again from `startFrom` when it reaches `endAt` |
|
||||
| `bus` | `string` | the bus it plays into: a named channel of the edit's Tone graph (music, sfx, voice, ambience, ui), so it takes that bus's volume, effects and ducking (raea/tone `buses`) |
|
||||
@@ -150,6 +152,17 @@ The props of [`Sequence`](#sequence), tabled there.
|
||||
| `width` | `number` | the width its children see, px (the parent's by default) |
|
||||
| `durationInFrames` | `number` | how many frames it shows its children (forever by default) |
|
||||
|
||||
### `VideoMatte`
|
||||
|
||||
A clip's mattes: PNGs whose alpha is what is kept, m00001.png on, in one folder of the media folder.
|
||||
|
||||
| Field | Type | What it is |
|
||||
| --- | --- | --- |
|
||||
| `src` (required) | `string` | the folder, as staticFile gives it: staticFile("matte/take-person") |
|
||||
| `fps` (required) | `number` | the file's frame rate: m00001.png is its frame 0 |
|
||||
| `every` | `number` | one matte each `every` frames of the file, held until the next (1, every frame, when left out) |
|
||||
| `count` (required) | `number` | how many mattes there are: past the last, the last is worn |
|
||||
|
||||
### `VideoProps`
|
||||
|
||||
The props of [`Video`](#video), tabled there.
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
---
|
||||
title: "raea 0.1.3"
|
||||
version: "0.1.3"
|
||||
date: "2026-11-13"
|
||||
summary: "Updates that land, a box on the part of a sound you mean, and a fingerprint kept with the project it judges."
|
||||
sources: ["https://github.com/shinyobjectz/raea/releases/tag/v0.1.3"]
|
||||
---
|
||||
|
||||
raea 0.1.3 makes the app's updates land, puts a 3D scene in the feed for you to walk around in and mark up, gives every feed a to-do list, lets you point at the part of a sound you mean, and keeps a fingerprint with the project it judges.
|
||||
|
||||
**Get the app at [raea.io](https://raea.io)** (a Mac with Apple silicon, Windows 10 or 11, or Linux on x86_64).
|
||||
|
||||
The engine alone:
|
||||
|
||||
```sh
|
||||
curl -fsSL https://raea.io/install | sh
|
||||
```
|
||||
|
||||
On Windows, in PowerShell: `irm https://raea.io/install.ps1 | iex`.
|
||||
|
||||
## What changed since 0.1.2
|
||||
|
||||
**Updates that land.** On a Mac, raea opened straight from Downloads runs from a read-only copy macOS makes, so 0.1.1 couldn't replace itself with 0.1.2 and Restart now did nothing. From 0.1.3 the app replaces the original wherever you opened it, and when an update can't install itself the card says so, with a Download button. The sidebar shows **Update** while one waits, and **Check for updates** is in Settings → General. If you're on 0.1.2 and Restart now did nothing, download 0.1.3 from raea.io once and move it into Applications.
|
||||
|
||||
**A cleaner update card.** It plays a short, silent loop of what's new above its words, with Restart now, What's new beside it, and a close button for later.
|
||||
|
||||
**Scenes in the feed.** Your agent can post a 3D scene, a prop, a character, a model or a splat as a scene, and you look at it from inside: walk around it, scrub its timeline when it moves, and pin a comment to a place in it. Pick a part to move, turn or scale it by hand, change a procedural part's props in its details, draw new parts into the scene, or reshape a part's motion as a path of keys. Every change is written into the scene's own code, with Undo, and your agent reads what you changed and where you pinned. Several files posted together open as a board first.
|
||||
|
||||
**A to-do list in every feed.** The agents button in a feed's header now opens the project's to-do list: its brief's tasks and the edits you've sent on its items, one line each, with who has it and what they last did. Add, check off, reword, drag to reorder and remove, with Undo. The Inbox's list has every project's.
|
||||
|
||||
**Sessions you start outside raea, in the feed.** A Claude Code session you start in a terminal or another app is a bubble in its project's feed while it's open, with its last words, the tool it's on and its plan, and it shows on the tasks it has. Other agents are in the feed by what they post.
|
||||
|
||||
**Point at the part of a sound you mean.** Pick **Spectrogram** on the timeline's sound track (or in Listen) and drag a box around the hiss up high or the hum down low. The note keeps that span of time and that band of pitch, your agent reads both with the note, and `raea fingerprint learn-notes` keeps the band with the label in your fingerprint's evidence. Sound axes still judge the whole sound in each moment, so the band is kept but not yet learned from.
|
||||
|
||||
**Keep a fingerprint with a project.** A project's **judged by** chip is now a menu: it says which fingerprint judges the project and why, and **Keep with this project** or **Keep with the workspace** copies one of yours into that folder and commits it, so your team's raea judges with the same taste.
|
||||
|
||||
**Fingerprint has its own docs.** [raea.io/docs/fingerprint](https://raea.io/docs/fingerprint/) covers training one, checking a cut with it, and keeping one with a project for your team, and the raea skill has a page that teaches your agent the same.
|
||||
|
||||
**Fixes**
|
||||
- Each project's feed shows its own work and nothing else. With more than one workspace on a Mac, a project could show another project's cards, a card could be saved into a project of the same name in another workspace, and a terminal session's bubble could pull in what other sessions posted elsewhere. raea now holds one workspace's projects at a time, saves each card back only to the folder it came from, never makes a project just because something asked for it by name, and fills a session's bubble with its own posts in its own project.
|
||||
- A composition kept beside a `tsconfig.json`, as at a new project's root, plays again: `raea play`, the app's stage and stills drawn by playing stopped before the first frame with "__at is not a function".
|
||||
- A fingerprint judges on every machine. raea now downloads YAMNet, the sound-events model, once like its other models. Before, only some machines had it, so a fingerprint trained on one of them refused a teammate's fresh install.
|
||||
- In raea's window, a graph zoomed past the edge of its canvas no longer takes the clicks meant for the sidebar and header around it.
|
||||
- Inside a `<Sequence>`, `useVideoConfig().durationInFrames` is the Sequence's length (its own, cut where its parent's ends; a Loop's one pass), so an animation scaled to its scene runs over the scene, as in Remotion. If one of your compositions read the composition's length from inside a Sequence, read it outside the Sequence and pass it down. Thanks @Ragulsundaram (#126).
|
||||
- A release's `.sha256` files name their file alone, so `shasum -c` passes on a download (0.1.1's and 0.1.2's named the builder's path; 0.1.2's were re-uploaded).
|
||||
|
||||
**Known**
|
||||
- The Windows app is unsigned, as before: Windows asks once whether to run it.
|
||||
@@ -0,0 +1,200 @@
|
||||
@spec
|
||||
Feature: Plans: a project's plan.org, kept by its agents
|
||||
Shane, 2026-11-14: "create a subagent that can flesh out the skills needed for tasks/plannig to be fully carried out
|
||||
by the agent right now its just blank and even if user doesnt touh it we need to have the againt use and maintain it
|
||||
and actualy use it for project managemtn and make that project managemnt system extensible with the task SDK. as a
|
||||
personal notel i liek or mode for managing projects so id liek to have that eb part of the base layer and make sure
|
||||
it integrates well with typescript/react/jsx correctly and the larger project in a way that is integral to the system"
|
||||
|
||||
"or mode" is Emacs org-mode. A project's plan is one Org file, plan.org. It is the base layer: the app, raea's own
|
||||
agents, agents outside raea (Claude Code in a terminal) and people in Emacs all read and write the same plain text.
|
||||
The to-do list was blank because nothing wrote to it but the composer; now every agent plans in it, marks what it's
|
||||
doing and closes what it made, whether or not the person ever opens it. @raea/task (sdk/task) reads and writes the
|
||||
file without losing a byte, edits it by task id, lets a plugin add keywords, properties, kinds and views, and gives
|
||||
React its hooks and components.
|
||||
|
||||
# Status 11-14: landed for 0.1.4. sdk/task (@raea/task) and this file in raea; the app in raea-feed (tasks-org merged
|
||||
# into integration-014 at 1214a21: vitest 242 files, 1509 tests, e2e todo, outside, messages, primary, heads,
|
||||
# consolidate 36 of 36); the skill in raea-skills #75 (skills/raea/plan.md).
|
||||
# Checked after the review: sdk/task 32 bun tests (org, edit, extend, tools), 35 with its react
|
||||
# tests under the app's vitest; the app's vitest 237 files, 1458 tests (base 229 files, 1403 tests, the same skips),
|
||||
# src/plan/agent.test.ts driving a turn's plan tools end to end on a faked host; tsc -b clean; e2e todo.spec.ts and
|
||||
# outside.spec.ts (7) and messages, primary, heads, consolidate (26) in Chrome; todo.spec.ts (4) and outside.spec.ts
|
||||
# (3) in raea's window (BLITZ_E2E bundle, node blitz/pw-run.mjs). The board (feed/Board.tsx, board/Lanes.tsx,
|
||||
# board/CardSheet.tsx) reads the plan now, but no route mounts it. Not done: `raea project new` writes no plan.org yet
|
||||
# (Rust, engine/cli), so reference/files.md, generated from it, doesn't list one; the page makes it on the first
|
||||
# write. The brief page (BriefView, unmounted) still draws a brief's own ## Tasks. Compositions can't import
|
||||
# @raea/task until sdk/tsconfig.base.json and raea's bundler map it.
|
||||
|
||||
Background:
|
||||
Given the app's code is apps/app (raea-feed), the SDK sdk/task, the skill skills/raea/plan.md in raea-skills
|
||||
And the plan's tests: sdk/task/test/*.test.ts (PL2, PL3, PL5, PL6), apps/app src/plan/plan.test.ts (PL1c, PL4, PL4c,
|
||||
PL5), src/plan/agent.test.ts (PL5a, PL5b), host/plan.test.ts (PL4, PL5), src/feed/todo.test.ts and outside.test.ts
|
||||
(PL4b), e2e/todo.spec.ts (PL4b)
|
||||
|
||||
Rule: PL1. A project's plan is plan.org at the top of its folder
|
||||
# Why there: it's the project's own file, versioned with it in the workspace's repo, found by anyone who opens the
|
||||
# folder (a person, Emacs, an agent in a terminal). Not under .raea/, which is raea's state, not the person's. One
|
||||
# file a project: the Inbox reads each project's in turn.
|
||||
|
||||
@done
|
||||
Scenario: PL1a. The file says its title and raea's keywords
|
||||
Given a project with no plan.org
|
||||
When anything adds a task to it (the to-do list, the composer, an agent's plan_add)
|
||||
Then <project>/plan.org is made, starting "#+TITLE: <project's name>" and "#+TODO: TODO MAKING REVIEW | DONE DROPPED"
|
||||
And an Org reader (Emacs) cycles the same keywords: TODO, MAKING and REVIEW are open, DONE and DROPPED closed
|
||||
And a keyword written into a plan whose #+TODO: lines don't name it (MAKING in a file written by hand, a plugin's
|
||||
SHOT) adds its sequence's #+TODO: line to the head, so Emacs cycles it too; Org's own TODO and DONE need none
|
||||
|
||||
@done
|
||||
Scenario: PL1b. The Org it uses
|
||||
Given a plan.org
|
||||
Then a headline with a keyword is a task; a headline with none is a heading: a stage that groups the tasks under it
|
||||
And a task may carry a priority ([#A]), tags (:look:sound:; a dash is written _), a planning line (SCHEDULED,
|
||||
DEADLINE, CLOSED), a PROPERTIES drawer, checkboxes (- [ ], - [X]), a progress cookie ([2/5] or [40%]) and links
|
||||
And its properties are :ID: (t- and eight letters and digits), :ITEM: (the feed item it stands on), :AGENT: (who
|
||||
has it), :FROM: (what asked for it), :KIND: and :VERB:; any other property is kept as written
|
||||
And links name feed items and tasks by id: [[item:i-door-2]], [[id:t-ab12cd34]]
|
||||
And a subtask is a task under a task; its parent's cookie counts its subtasks, or with none its checkboxes
|
||||
|
||||
@done
|
||||
Scenario: PL1c. Everything is linked by id, never by name
|
||||
Given a task typed with "@grade #look due 11-20 → i-hall" (the to-do list, the composer)
|
||||
Then :AGENT: holds the agent's id; an @name no agent has yet is kept as @name, and shows that name
|
||||
And :ITEM: holds the item's id, the tags are the task's tags, and DEADLINE is that day this year
|
||||
And a task the composer writes for a message has :FROM: the message's id; one for a comment, ITEM#COMMENT
|
||||
|
||||
Rule: PL2. @raea/task reads a plan without losing a byte
|
||||
@done
|
||||
Scenario: PL2a. A round trip changes nothing
|
||||
Given any text, Org or not: drawers it doesn't know, #+BEGIN blocks, tables, CRLF endings, tabs, no final newline
|
||||
When it's read and printed with no edits
|
||||
Then the text is the same, byte for byte
|
||||
And a planning line with a stamp it can't wholly read (a range of days, a habit's .+2d/3d) is still the planning
|
||||
line: the drawer under it, and its :ID:, are read, and the part it couldn't read is written back as it was
|
||||
|
||||
@done
|
||||
Scenario: PL2b. A plan as values
|
||||
Given a plan.org
|
||||
Then readPlan gives every headline as an entry and the ones with a keyword as tasks, each with its state (todo,
|
||||
making, review, done, dropped, whatever its keyword is called), priority, tags and inherited tags, dates,
|
||||
properties, item, agents, from, parent and children, its stage, checkboxes, progress, links and body
|
||||
And a plan's own #+TODO: lines add keywords; a word a plugin defined keeps its plugin's state
|
||||
|
||||
@done
|
||||
Scenario: PL2c. A changed entry is written again part by part
|
||||
Given an edit that changes one task's keyword
|
||||
Then only its headline line is written again; its drawer, body and every other entry are as they were
|
||||
And the headline keeps its own spacing and its tags end where they ended, as Org's org-todo leaves them; a
|
||||
planning line written again keeps its parts' order, with a new CLOSED first
|
||||
|
||||
Rule: PL3. Every change is an edit by task id
|
||||
@done
|
||||
Scenario: PL3a. The edits
|
||||
Then applyEdits(text, edits) makes add, set, state, move, remove and check, in order, each naming its task by
|
||||
:ID: (or #N, its place among the headlines, for one that has no id yet)
|
||||
And add goes under a heading by its words (made when there's none), under a task (a subtask), or before or
|
||||
after a task; with none of them, at the end
|
||||
And every task is given an :ID: it lacks, and every progress cookie counts again
|
||||
|
||||
@done
|
||||
Scenario: PL3b. Closing stamps CLOSED; reopening takes it off
|
||||
When a task's state becomes done or dropped
|
||||
Then its planning line gets CLOSED: [YYYY-MM-DD Day HH:MM], as Org's org-log-done does
|
||||
And opening it again removes CLOSED
|
||||
|
||||
@done
|
||||
Scenario: PL3c. A wrong edit changes nothing
|
||||
When an edit names a task that isn't there (under: a task id included, which never becomes a stage heading), a
|
||||
day that isn't one, a keyword the plan doesn't know or a move into the task's own subtree
|
||||
Then applyEdits throws, saying what's wrong and how to find the right id, and the text is as it was
|
||||
|
||||
Rule: PL4. The app keeps its tasks in the plan
|
||||
@done
|
||||
Scenario: PL4a. The host reads and writes plan.org whole
|
||||
Given POST /host/plan {op: read | apply | put, workspace, project}
|
||||
Then read answers the text and a stamp (same: true when the page's stamp still holds); a read for an agent
|
||||
(name: true: its turn, its plan_read) first gives each task written without an :ID: one, and writes it
|
||||
And apply makes the edits on the file (or on a new plan) and writes it through a temporary file, renamed over,
|
||||
answering with the text they were made on; edits naming a task by its place (#N) carry the text that place
|
||||
was counted in, and are refused when the file has changed since
|
||||
And put writes an older text back for Undo only while the file is still the text the page last saw
|
||||
And the e2e host (RAEA_FEED_KEEP=0) keeps nothing: the page's plan is the plan
|
||||
|
||||
@done
|
||||
Scenario: PL4b. The to-do list, the composer and raea's own work write plan edits
|
||||
Given the to-do list (feed/TodoPanel.tsx) open on a project or the Inbox
|
||||
Then its rows are the plan's tasks as written (subtasks too) and the edits sent on the project's items
|
||||
And a task linked to an item stands where the item does (the work is the truth)
|
||||
And add, check off, reword, reorder and remove are plan edits made at once in the page and then on the file
|
||||
And Undo puts the text back only while the plan hasn't changed since ("The plan has changed since: nothing
|
||||
undone"), and puts back the file as the edit found it, so a task another writer added before the edit stays
|
||||
And the list reads the plan again every few seconds and on focus, so an edit in Emacs or a terminal shows; an
|
||||
agent's turn and its plan_read read it again first
|
||||
And a message sent in the composer is a task in the plan: after the last task carrying the view's tags, held by the
|
||||
agent it went to, :FROM: the message's id
|
||||
And raea's shaping, storyboards, directions and renders are its tasks under Plan and Make, each :ITEM: the card it
|
||||
waits on; a critique's gate is "<title> passes check and critique" with :ITEM: the newest critique
|
||||
And an item carries the tags of the tasks linked to it, a workflow field places a channel by its plan's tasks, and
|
||||
a session outside raea holds the tasks whose :AGENT: is @its-name or its inbox
|
||||
And the board (feed/Board.tsx, board/Lanes.tsx, board/CardSheet.tsx) reads and edits the plan the same way, by
|
||||
task id; no route mounts it yet
|
||||
|
||||
@done
|
||||
Scenario: PL4c. A brief's tasks move into the plan once
|
||||
Given a project whose brief.md still has ## Tasks (every brief before this, and the starter brief's "Write the plan")
|
||||
When the page has read its kept brief
|
||||
Then each task is added to the plan with its mark as its keyword, its ### stage as its heading, its @agents by id,
|
||||
its #tags, its due day as DEADLINE, its → item as :ITEM: and its craft verb as :VERB:
|
||||
And the task lines, the stages and an emptied ## Tasks leave the brief; everything else in it stays
|
||||
And a brief the plan can't take (the host refused the write) keeps its tasks, and is tried again next load
|
||||
And each task's id comes from its stage, its words and which of the same words it is, so a brief moved twice (two
|
||||
pages open on it, a reload before the brief was saved) adds nothing the second time
|
||||
|
||||
@done
|
||||
Scenario: PL4d. Comment tasks stay where they are
|
||||
Given an edit sent on an item (model/tasks.ts, raea show --working/--done)
|
||||
Then it is not copied into the plan; it shows in the same to-do list, under the plan's tasks, as it did
|
||||
|
||||
Rule: PL5. Agents use and maintain the plan, whether the person opens it or not
|
||||
@done
|
||||
Scenario: PL5a. The plan tools
|
||||
Given an agent the raea app launches (the feed MCP server, apps/app host/acp/feed-mcp.ts)
|
||||
Then it has plan_read (the open tasks by id; full: the whole file), plan_add (tasks under a stage or a task,
|
||||
held by the agent unless it names others), plan_update (mark, tick or add a checkbox, change fields, move,
|
||||
remove) and plan_close (DONE with CLOSED and the item it made, or dropped)
|
||||
And the page answers them through its plans (@raea/task answerPlanTool), a headless run (host/acp/memory.ts) on
|
||||
the folder's plan.org; a session with no project has no plan, and says so
|
||||
|
||||
@done
|
||||
Scenario: PL5b. Every turn carries the plan
|
||||
Given an agent's turn in a project (src/acp/session.ts prompt)
|
||||
Then the prompt carries raea://plan/<project>: the rule to keep the plan, the task this message is (by :FROM:),
|
||||
and the open tasks by id under their stages (planDigest)
|
||||
And the rule: plan work of more than one step first, mark a task MAKING as you start it and REVIEW when it waits
|
||||
on the person, close it as you finish with the item it made, add what's left, drop rather than remove
|
||||
And every task it names has an id: a task written without one is given one before the plan is read for the turn
|
||||
And an agent launched without the plan tools is told to keep plan.org as text; a message whose task is already
|
||||
closed says so, rather than asking for it to be marked
|
||||
|
||||
Scenario: PL5c. An agent outside raea keeps the same file
|
||||
Given Claude Code in a terminal in the project's folder, with the raea skill
|
||||
Then it opens plan.org (skills/raea/plan.md), plans and marks there as plain Org text, keeping each :ID:
|
||||
And the person sees its changes in the to-do list within a few seconds
|
||||
|
||||
Rule: PL6. A plugin extends plans; React and raea's window read them
|
||||
@done
|
||||
Scenario: PL6a. Keywords, properties, kinds and views
|
||||
Then defineKeywords adds a sequence ("SHOT LIT GRADED | APPROVED") with each word's state; defineProperty a
|
||||
property with a check; definePlanKind a kind (its keywords, required properties, a check, defaults an add
|
||||
starts with; a new task of the kind starts at its sequence's first word); defineView a view any page can
|
||||
build (view(plan, name)); createRegistry one of a plugin's own
|
||||
And checkPlan says what's wrong by those rules: ids used twice, failing properties, unknown kinds, missing
|
||||
properties, keywords outside a kind's sequence
|
||||
And board, agenda and outline are the views raea ships
|
||||
|
||||
@done
|
||||
Scenario: PL6b. React
|
||||
Then usePlan(text or source) gives the plan, its text and edit; useView a registered view; TaskLine, PlanOutline,
|
||||
Agenda and BoardLanes draw them, with toggled for a checkbox's edit
|
||||
And none of it uses a dynamic import or dangerouslySetInnerHTML, so raea's window bundle (one IIFE) holds it
|
||||
@@ -247,3 +247,15 @@ Feature: React Three Fiber both ways: an R3F scene drawn by raea, a raea composi
|
||||
facing that light or sideways, as the hemisphere light is), and its constant band is scaled as three's
|
||||
irradiance is (0.886, where 0.282 made it a third as bright)
|
||||
And in-approx: SSIM 0.9848 (Phong's F0 is held at Bevy's highest, 0.16, so its orange highlight glints less)
|
||||
|
||||
Scenario: R3F15. What an R3F scene throws is the composition's error (#131)
|
||||
Given an <R3F> whose scene throws: rendering a component, in an effect, in a ref
|
||||
Then the frame throws it out of the <R3F> drawing it (src/input/session.ts: the scene under raea's own error
|
||||
boundary), so the render is refused naming it, exactly as a throw outside R3F is: "REFUSED the composition threw
|
||||
at frame 0: Error: ...", exit 1
|
||||
And never as R3F's own root reported it (reportError, else a stack without its message), the scene drawing nothing
|
||||
and the render ending with 0 errors
|
||||
And three's PMREMGenerator makes no GPU cube map in raea (src/input/pmrem.ts): fromEquirectangular of a panorama
|
||||
raea loads is that panorama, lighting the scene as scene.environment does; fromScene (RoomEnvironment) and
|
||||
fromCubemap are left out with a warning naming them, the scene drawn without them
|
||||
And test/errors.test.tsx holds it
|
||||
@@ -0,0 +1,875 @@
|
||||
@spec
|
||||
Feature: The timeline SDK (0.1.5): CapCut's timeline, on the composition, in the feed, open to extension
|
||||
Shane, 2026-11-13 (goal, launching alongside the character SDK): "the goal with the timeline sdk is to provide
|
||||
agents pushing feed items or controllers / things we might want to be able to edit directly with timeline based
|
||||
adjustment which includes full on video editing in the feed watch/scene items if any components or compositions are
|
||||
in the sequence, text, effects, transitions etc. the goal should be to actually open and explore every inch and
|
||||
aspect of how capcut timeline works and basically do the exact same thing. we want full editing ability and to
|
||||
remove the timeline 'comments' as we can just do that in the viewer at whatever timecode im at ... the switcher on
|
||||
the left for video/audio and we should basically allow those to expand; we also can add some way of allowing for
|
||||
keyframes, changing the way you make bezier curves and things. the idea is that we provide the framework and parity
|
||||
functionality and feel to capcut while allowing it to be extended. This also means live editing buffering and
|
||||
playback of whole sequences, 3d scenes, etc need to be done to include buffering, caching, smart cache clearing,
|
||||
etc. these changes in the timeline are not suggestions they are actual edits sent to the agent. these should be
|
||||
deeply connected to the watch, listen, and scene feed experiences."
|
||||
|
||||
What there is to build on (read 11-13):
|
||||
- docs/editing.feature E1 to E5: the composition's file is the document, a change is a change to its code made at
|
||||
once, the working version (NAME-vN.tsx), a <Sequence>'s span edited on a strip (host/sequences.ts), the engine's
|
||||
stage playing the working file live (E4a), an agent editing through the same operations (editor_edit, E5a).
|
||||
- raea-feed src/detail: the viewer's strip (blocks/Filmstrip.tsx: two tracks, a kind picker in each track's
|
||||
gutter, plugins' lanes, the comments' pins and a comment card on the strip), the hand editor (timeline/Editor.tsx,
|
||||
Strip.tsx: cuts over the render, parts retimed, undo and redo), the composition editor (src/compositions).
|
||||
- raea-feed PR #18 (11-13): a scrubber that only seeks, the strip collapsed to it, a resize handle on its top edge.
|
||||
- The proxy store (host/preview/proxies.ts: light copies, thumbnails, peaks, a size limit and a sweep), the export
|
||||
and bundle caches (runtime/bundle cache.rs), rr3's shot segments (docs/rerender.feature, behind RAEA_SEGMENTS=1).
|
||||
|
||||
CapCut's desktop timeline, as its own help pages and guides describe it (read 11-13; no CapCut code is read or
|
||||
copied, and no other editor's under a licence that forbids it: docs/editing.feature's note on react-video-editor-pro):
|
||||
- Above the timeline, left: the pointer's mode (Select A, Split B, select everything left [ or right ]), undo and
|
||||
redo, Split (Cmd+B; Cmd+Shift+B every track), Delete left Q and Delete right W (of the playhead, on the picked
|
||||
clip, the gap closed), a marker M, Delete, and for a picked clip Freeze, Reverse, Mirror, Rotate, Crop.
|
||||
Right: record a voice, the main track magnet P, auto snapping N, linkage ~, the preview axis S (the frame under
|
||||
the pointer), fit Shift+Z, and zoom (Cmd +/-, Cmd+scroll; Option+scroll scrolls sideways).
|
||||
- Tracks: one main track that never holds a gap while its magnet is on (a clip dropped between two moves the rest;
|
||||
off, a clip dragged over others becomes an overlay on a track above); overlay picture tracks above it; text,
|
||||
sticker, effect, filter and adjustment tracks above those; sound tracks below. Each track's head locks it, hides
|
||||
it (eye) or mutes it (speaker).
|
||||
- A clip: picked by a click, several by Cmd+click or a box; moved by a drag, trimmed by its edges (back out again
|
||||
to the source's end), split, deleted, duplicated, copied and pasted, its attributes pasted onto another
|
||||
(Cmd+Shift+C/V), disabled (V), grouped (Cmd+G), made a compound clip (Option+G), its sound extracted
|
||||
(Cmd+Shift+S). I and O mark a range.
|
||||
- Moving in time: Space, Left/Right a frame, Shift+Left/Right several, Up/Down the cut before or after, Home/End.
|
||||
- Keyframes: a diamond beside each property in the inspector stores its value at the playhead; a second, later
|
||||
one with another value animates between them; the diamonds show on the clip; a graph shapes the change (linear,
|
||||
ease in, out, both, or a curve dragged by hand). Position, scale, rotation, opacity, colour, volume.
|
||||
- Speed: constant, or a curve of points from 0.1x to 10x with presets (Montage, Hero, Bullet, Jump cut, Flash in,
|
||||
Flash out) and a custom one; the clip's length follows.
|
||||
- A transition sits on the cut between two clips that touch; its length is dragged. Effects, filters and
|
||||
adjustments are clips on their own tracks, over the span they cover.
|
||||
- Sound: the waveform on the clip, a volume line, fade in and fade out as lengths at the clip's ends, beat markers
|
||||
on the waveform that edges snap to.
|
||||
- Playing while editing: lighter copies of heavy media (Proxy, 540 or 720 lines), a lower preview quality, parts
|
||||
that were worked out kept (the cache: its size shown, cleared by hand or on a schedule), all remade when needed;
|
||||
an export always reads the originals.
|
||||
- The inspector beside the player (read 11-14), its tabs by the picked clip's kind. Video: Basic (position, scale,
|
||||
rotation, opacity, blend mode, stabilise), Mask (line, mirror, circle, rectangle, heart, star; position, size,
|
||||
rotation, feather, round corners, invert), Cutout (auto cutout of a person, a custom cutout brushed, chroma key
|
||||
with its colour picked from the picture, strength and shadow), Retouch. Animation: In, Out, Combo. Speed:
|
||||
constant and curve. Adjust: brightness, contrast, saturation, exposure, sharpen, highlights, shadows,
|
||||
temperature, tint, fade, vignette, grain. Audio: volume, fades, noise reduction, voice changer. Text: font,
|
||||
style, effects, bubbles, animation, and its words read aloud.
|
||||
Here 11-14: Basic (TL3h, TL5) with stabilise (TL7k, a film's footage and a composition's <Video>), auto cutout
|
||||
of a person or the subject (TL7l, a film's footage or a composition's <Video>, on a Mac) and a custom one brushed on the picture (TL7m), Retouch (TL7n: smooth, brighten, slim face and bigger eyes, a film's footage, a file from Media or a composition's <Video>, on a Mac), Mask, chroma key and Blend (TL7f) with the key's colour picked from
|
||||
the picture (TL7h) and the mask's handles dragged there (TL7i), Animation (TL7d, TL7e), Speed (TL6), Audio's
|
||||
volume and fades (TL8a) and its noise reduction and voice changer (TL8d, a film's sounds and a composition's
|
||||
<Audio>), Text's words, styles and captions (TL7c) and its words read aloud (TL7j), Adjust as effect clips
|
||||
over a span (TL7b, raea's ten) and as the clip's own twelve sliders (TL7g, on the film and on a file from Media
|
||||
over it), every number of these keyed (TL5a).
|
||||
|
||||
The model this file sets:
|
||||
1. One timeline model, in an SDK (sdk/timeline, TypeScript, no React, no DOM): tracks, clips, keys, markers, and
|
||||
the operations on them, each a pure function from a timeline to the next. The app's strip draws it and the
|
||||
host writes it; an agent reads and writes the same model. It replaces the strip's own cut and parts.
|
||||
2. The composition's file is still the document (docs/editing.feature): a timeline is read from a composition's
|
||||
tree, and each operation is also a code edit to the working version. What the code can't express as written
|
||||
(a span set by an expression) is shown locked, with why.
|
||||
3. An operation made by the person is an edit, applied at once, and sent to the item's agent as the edit that
|
||||
was made, never as a note asking for it.
|
||||
4. Parity first, in function and feel: CapCut's tools, keys, magnet, snapping and gestures, at 60 frames a second
|
||||
under the pointer. Then the points where it is extended: a kind of track, a kind of clip, a property and its
|
||||
editor, an easing, a transition, an effect, a lane, a tool, each a plugin's contribution.
|
||||
5. Comments are the viewer's. The timeline takes no comment and opens no comment card; a comment made on the
|
||||
picture at a moment shows as a marker on the timeline, which opens it.
|
||||
6. The picture under an edit is the engine playing the working file (E4a) where there is a stage, with what was
|
||||
drawn kept: a range's frames are kept by what draws them, an edit drops only the ranges it changed, and the
|
||||
store keeps itself under a size the person sets.
|
||||
|
||||
Status, 11-13 (the first day). On raea main: sdk/timeline (model, ops with inverses, compound clips, keys and
|
||||
bezier easing, speed curves, freeze frames and reversed footage, snapping, the frame store's decisions, live
|
||||
playback's mapping, readers and writers for a composition's sequences (its footage and sound, its text, its
|
||||
effects, a recording, a project's file), a film's scenes and a sound's tracks, the palette a plugin adds to, a clip's cutout and Adjust; 106
|
||||
tests), and in
|
||||
sdk/video <Nudge keys mask blend chroma adjust> (keys for the placement and, by a dotted name, a mask's, a key's, a
|
||||
crop's and an adjustment's numbers; cutout.ts: a mask's six shapes, CSS's blend modes, a chroma key; adjust.ts:
|
||||
CapCut's twelve adjustments as one SVG filter and a vignette layer), <Transition in out combo> (fade, slide, wipe, zoom; a Combo's seven waves), <Effect kind amount in out> (blur, mono,
|
||||
sepia, vivid, faded, contrast, bright, dark, invert, hue: a filter on the picture under it) and a <Video>'s or
|
||||
an <Audio>'s speedCurve (the mixer carries its sound through the changing rate as one voice). In raea-feed, draft
|
||||
PR #19: the new timeline is the timeline (localStorage raea.timeline-sdk = 0 brings the old strip back); 49 browser
|
||||
tests in Chrome, all passing; in a headless raea window 47 of the 49 pass and two skip themselves there with their
|
||||
reason (the voice test, which would ask for this Mac's microphone, and TL10d, whose film the window decodes itself,
|
||||
so no route can hold its data), among them TL9c, an agent's edits, a composition's every edit, freeze and reverse, mirror and
|
||||
crop, effects, groups and compounds, the posted item's, a plugin's effect, text style, tool and snap grid, saved
|
||||
curves, Settings' kept frames, both kinds of sound taken out, the switcher, the export range, media added, the
|
||||
Option keys, captions made from what is said, a clip's In, Out and Combo, and its mask, blend and chroma key (whose
|
||||
sliders are a track of their own, as the volume's is: the window doesn't move a range input), their numbers and the
|
||||
crop's sides keyed (TL5a), its own Adjust (TL7g), its key's colour picked from the picture (TL7h: read from the
|
||||
clip's file by the host, since the window has no canvas to read), its mask's handles dragged there (TL7i), and a file
|
||||
from Media over the film with its own vignette and its key's colour picked from its own file, a text's words
|
||||
read aloud onto a sound track (TL7j), and a sound's noise reduced and its voice changed (TL8d: its menu is made
|
||||
again after each try, since the window keeps a picked option shown when the clip's didn't change), footage held
|
||||
steady (TL7k), footage cut out (TL7l; its pixels are compared in Chrome only, which can screenshot an
|
||||
element) and cut out by what is brushed over it (TL7m: the strokes painted with the window's own pointer), and footage retouched (TL7n: the copy put in the clip's place at the playhead's second and wearing its mask; that it has the frame and the film's picture goes are checked in Chrome only, which plays the copy). The window runner (blitz/pw.mjs) answers routes one at a time in the order asked, keeps a reload's
|
||||
address and each test's storage, and has keyboard down and up, toBeFocused and waitForResponse. The timeline's keys
|
||||
follow the pointer over it, not :hover, which raea's window doesn't match for a script, so there they only worked
|
||||
after a click in the timeline:
|
||||
built TL0a-d, TL1a-b, TL1c (the switcher on the left of each track, picking what its clips show: the
|
||||
frames, the energy, the waveform, the spectrogram, the words said, with Transcribe offered until
|
||||
there are words; only what the film has is offered, each clip draws its own stretch of the film,
|
||||
and the choice is kept by the track's kind for the next film; a sound in Listen the same; a clip
|
||||
of one of the project's files, a sound track's or one added from Media, draws its own file's
|
||||
loudness, read once on the host (/host/asset-peaks); a plugin's lane as a row under the tracks;
|
||||
collapse and the top edge's resize),
|
||||
TL1d (the poster on the main track's head: a click makes the playhead's frame the poster),
|
||||
TL2a-e, TL2f (I and O in either order, Shift+X around the picked clips, its ends dragged on the
|
||||
ruler, Option+X or the × beside Export clearing it; kept with the item; Export says the span and
|
||||
the host cuts only it with raea media trim, raea's encoder signing it as every export: a real
|
||||
render's 1 s to 2.5 s came out 1.5 s, 90 frames and its sound), TL3a-g (and TL3b's Option-drag,
|
||||
leaving the clip and putting a copy down), TL3h (freeze and reverse played live from the film's own
|
||||
frames; mirror,
|
||||
rotate and crop shown on the player at once, as are a clip's keyed scale, place, turn and opacity),
|
||||
TL3i, TL3j (Media in the bar, Cmd+I: the project's footage, stills and sounds, each added at the
|
||||
playhead as long as its file, a still 3 s; on a film cut here footage and stills go over the
|
||||
picture, drawn on the player where they are on, a sound on a sound track), TL4a-b, TL4c (and a clip's own sound taken out with Cmd+Shift+S: the SDK's extract
|
||||
operation, a sound clip over the same span from the same place in the file, the footage marked
|
||||
muted; in a composition the host mutes the <Video> and writes an <Audio> of its file beside it, read
|
||||
back as clips; in a film cut here the player is silent over that footage and the sound plays from
|
||||
its place in the film wherever it is moved), TL5a-b, TL5c (and a curve shaped by hand saved by name for the workspace: kept as
|
||||
timeline/curves.json in its folder, a preset in every timeline there, forgotten by its ×), TL6a-b
|
||||
(and Option on a clip's edge changing its speed, Cmd+R to the speed, Shift+B to its curve),
|
||||
TL7a, TL7b for raea's ten effects (an effect is a clip of its own,
|
||||
shown on the player where it is on), TL7c (text added with T or in a style from the bar, drawn over a
|
||||
film where it is on, renamed by a double-click, a caption split at the caret with Enter; raea's
|
||||
four text styles and a plugin's, as data; and captions made from what is said, CapCut's auto
|
||||
captions: Captions in the bar transcribes the film first when it has no words yet, then puts the
|
||||
words, where the edited cut now says them (sdk/timeline captions.ts heard: a scene taken out takes
|
||||
its words, a duplicated one says them twice, a curved, reversed or frozen clip none), in lines (a
|
||||
sentence's end, a pause of 0.6 s, seven words or 42 characters end one) as text clips in the
|
||||
caption style on a Captions track of their own: one edit (the `captions` operation), undone
|
||||
whole, drawn over the film, told to the agent as one line with every caption's words and
|
||||
timecodes, and in a composition each line a sequence of words), TL7d's In and Out (a picked
|
||||
clip's own animation at each end, CapCut's Animation tab: fade, slide, wipe, zoom or a plugin's,
|
||||
and its frames, in the clip's row; a ramp on the clip; the film's picture and words over it show it
|
||||
at once, drawn by sdk/video edges.ts, the table <Transition> now draws from too; split, each half
|
||||
keeps its own end's; never longer than the clip; in a composition the sequence's <Transition>
|
||||
edge, taken off with no frames, read back as the clip's own where no cut's transition takes it;
|
||||
Send says how it comes in or goes out), TL7e (a Combo: seven of raea's, as waves in sdk/video
|
||||
edges.ts, and a plugin's as data; its cycle starts at the clip's length, playing once, and loops
|
||||
when shorter; with the In and Out at once on the film's picture and words; a line with a tick a
|
||||
cycle on the clip; <Transition combo> in a composition, written and read back), TL7f (a mask, a
|
||||
blend and a chroma key: the row's blend menu, and a mask and a key panel; a mask an SVG mask image
|
||||
laid over the frame, feathered by a blur, inverted by mask-composite; a blend CSS's mix-blend-mode;
|
||||
a key an SVG colour-matrix filter whose alpha falls as a colour's share of the key's hue rises; drawn
|
||||
by sdk/video cutout.ts in the preview and in <Nudge>, and by raea's renderer as Chrome draws them,
|
||||
seen on a render of a keyed green panel, a feathered heart, an inverted turned star and a screen
|
||||
blend; an SVG <mask> to invert overran Vello's buffers, so it isn't used; a clip's cutout is its
|
||||
props, a preset's to set later; Send says all three as they stand), TL7g (the clip's own twelve
|
||||
Adjust sliders, one SVG filter after its key and a vignette layer, by sdk/video adjust.ts in the
|
||||
preview and in <Nudge adjust>; raea's renderer within 0.4% RMSE of Chrome on a probe), TL7h (the
|
||||
key's colour picked from the picture: a press on the film or a file over it, undone through its
|
||||
placement, read by the host from the clip's file where the player is, a small patch's mean), TL7i
|
||||
(the mask's outline and CapCut's handles on the picture through the clip's placement: move, width,
|
||||
height, corner, turn, feather, round; a drag shown as it moves and one edit when let go, keyed
|
||||
numbers keyed), TL7j (a text's words read aloud: raea gen speech on the host, kept under
|
||||
media/speech by the words' hash, a sound clip from the text's start; a real line 8.4 s to make,
|
||||
43 ms read again), a plugin's effects as data (timeline.effects in its manifest: parts
|
||||
of CSS filter functions, drawn by <Effect parts> and by the preview alike), TL8a
|
||||
(waveform, level line, fades; Cmd+. and Cmd+, step the level by 0.1 dB, or key it at the
|
||||
playhead when it is keyed), TL8b's beats as ticks that edges snap to, each turned off by a
|
||||
click, TL8c (Record from the playhead, the picture playing; the recording a clip named by what was
|
||||
said, its file in the project's attachments), TL8d (a sound's noise reduced and its voice
|
||||
changed: host/dsp.ts in TypeScript, an FFT and Hann overlap-add, the noise's floor from the quietest
|
||||
tenth, a phase vocoder for pitch, biquads for the bands, a delay line for the echo; on made sounds hiss
|
||||
down 16 dB with the tone within 0.04 dB, 3 minutes in 2.3 s; on a real voice the chipmunk moves its
|
||||
spectral centroid x1.46 and deep x0.77, each setting 25-73 ms for 1.2 s, kept under media/voice and
|
||||
read again in under 1 ms; each voice's copy as loud as its source short of clipping, where on a line
|
||||
with pauses they had moved it -12.5 dB (robot) to +8.6 dB (megaphone); in a composition, an <Audio>'s
|
||||
copy made from its own file and kept in its media folder's voice/, the <Audio> playing it and saying
|
||||
what it was made from and how (data-voice-of, data-denoise, data-voice), both off its src as it was;
|
||||
raea renders it, a scratch composition's line at 105 Hz voiced, 140 its own), TL7k (footage held steady: host/shake.ts in TypeScript on 320 px
|
||||
grey frames from `raea media still`, eight at a time; the window over a block read again where
|
||||
the first reading put the move, since a fixed window reads big moves short; the path smoothed by
|
||||
a Gaussian-weighted line, so a pan stays a pan to the clip's ends; on a shaky clip made from a real
|
||||
frame along a known path, the shake 21 px down to 0.23 and its turn 0.54 deg to 0.03, a 1 Hz sway
|
||||
12 px kept to 5.4 at Minimal cut and held to 2.9 at Most stable, zoom 1.05 to 1.06, 34 ms a frame
|
||||
read and the kept file read again in 28 ms; in a composition, its <Video>'s whole file read, the moves kept in its
|
||||
media folder's steady/ and a steadied copy rendered by raea beside them (a composition playing the file
|
||||
with each frame's move as the player wears it), which the <Video> plays, saying what it was made from
|
||||
(data-steady-of, data-steady), off its src as it was; a 2 s clip shaken along a known path steadied in
|
||||
3.4 s, its frame-to-frame shake 7.49 px to 2.12 at 320 px, a copy with no moves its file's every frame), TL7l (footage cut out, CapCut's Auto cutout: Apple's
|
||||
Vision on the host through osascript's JavaScript, its person segmentation (macOS 12) or its
|
||||
subject mask (macOS 14), each frame of the part the clip shows as a 512 px matte PNG under
|
||||
media/matte, 120 frames a run, its index written last; the player wears the frame's matte as the
|
||||
top layer of its mask, intersected with the clip's own shape, and fetches the next 12 ahead; on a
|
||||
real clip a person 97 ms a frame and 73 KB, the subject 79 ms and 33 KB, hair kept; in Chrome a
|
||||
matte clear on its left leaves that quarter of the picture flat and the right as it was), TL7m
|
||||
(footage cut out by what is brushed over it, CapCut's Custom cutout: Brushed… in the cutout menu
|
||||
opens a brush on the picture, keep and erase, its width a share of the frame's, a stroke undone or
|
||||
all cleared; a stroke's points undone through the clip's placement and thinned by Ramer-Douglas-Peucker
|
||||
to what it needs; Cut out sends them with the second under the playhead, and the host matted from
|
||||
that frame to the clip's end and back to its start: Vision's subject mask tells the picture's things
|
||||
apart, those under more keep than erase strokes are kept, and on each frame after, those lying 30% or
|
||||
more in the matte before it, or holding 30% of it, a frame Vision sees nothing in holding the matte
|
||||
before for up to 3 frames; overlaps read as CIAreaAverage means undone from sRGB, a 25% square read
|
||||
0.2502; on two subjects side by side a stroke on either kept only it, both kept both, an erase took
|
||||
one out, a stroke on the sky said nothing is under it; a real clip 90 frames in 11.9 s, the cat
|
||||
followed through all of them; the strokes kept in the clip's props as JSON, there to brush again; in a
|
||||
composition, the whole of what its <Video> plays (its file, or its retouched or steadied copy) matted
|
||||
into its media folder's matte/, and the <Video> wears them by raea's new Video matte prop (matte={{ src:
|
||||
staticFile(folder), fps, every, count }}: the matte its source time is on, as its mask-image, sized as
|
||||
its objectFit sizes the picture), saying what they are of (data-matte; brushed, data-brush-at and
|
||||
data-brush-strokes), off its props as they were; while it wears them, Stabilise and Retouch are refused,
|
||||
since what it plays would change under them. A composition's strokes are on its frame, which is the
|
||||
<Video>'s picture only when the <Video> fills it. A real 3 s face clip's person matted in 9.1 s, and
|
||||
raea's render of the edited composition keeps on each frame what that frame's matte keeps (overlap 0.92
|
||||
at least, 0.972 on average; its own matte over the one 15 frames away on 88 of 90 frames), where the
|
||||
uncut composition's overlap is 0.53),
|
||||
TL7n (footage retouched, CapCut's Retouch: four sliders, smooth, brighten, slim face and bigger eyes, set
|
||||
then applied; the host reads each frame of the part the clip shows (`raea media still`, as wide as the
|
||||
picture up to 1280 px), finds its faces and their landmarks with Vision's face landmarks (up to 4 a
|
||||
frame) and retouches them with Core Image through osascript's JavaScript: the skin a mask of the jaw's
|
||||
line closed by an arc over the forehead, less the eyes, brows and lips, feathered; smooth a blur
|
||||
blended in only where the picture differs little from it, so a lash line or a nostril stays sharp;
|
||||
brighten an exposure lift through the mask; bigger eyes a bump at each eye; slim a warp kernel drawing
|
||||
the cheeks and jaw toward the face's middle. Two Core Image traps found on the way: an image read
|
||||
straight from a bitmap comes out blank from a render with a warp kernel in it (the mask is made from
|
||||
its TIFF data), and a blur under a warp whose region callback is JavaScript renders without the
|
||||
blur's branch (what is under the warp is made pixels first). Frames go to `raea media encode` with
|
||||
the part's own sound (`raea media audio`) under them, signed, as media/retouch/<file>-<key>.mp4, in
|
||||
runs of 48 split over two Vision processes; no face in the clip is said and nothing kept. The player
|
||||
shows the copy over a film's picture in its box, wearing the look copied off it as it changes, and
|
||||
hides the film's picture only once the copy has the frame under the playhead (a copy loading shows
|
||||
the film as shot); a clip coming on within a second has its copy loaded ahead; a file from Media plays
|
||||
the copy, which carries its sound, instead of its file. On a 720 x 1280 talking-head clip 90 frames
|
||||
in 10.9 s, a face found on every one; asked again, the kept copy in 24 ms; in a composition, its
|
||||
<Video>'s whole file retouched into its media folder's retouch/ (its steadied copy when it is held
|
||||
steady: the retouch over the steadying, and Stabilise refused while Retouch is on, since what is under
|
||||
it would change), which the <Video> plays, saying what it was made from and by how much
|
||||
(data-retouch-of, data-retouch-smooth, -brighten, -slim and -eyes), off its src as it was; a real 3 s
|
||||
face clip in 4.3 s, a face on all 90 frames, and raea's render of the edited composition is the copy's
|
||||
own frame, 0 apart, where the file's is 1.4 (4.9 over the face). Copies, moves and mattes are read and
|
||||
made at the rate the frames' times sit on (the probe's frame_rate) where it is within 1% of the
|
||||
average: that clip's 30/1 probed 29.97 on average, and a copy made at that drew its frame 44 at the
|
||||
composition's 45; each is named by that rate too, so a copy made at the old one isn't read again),
|
||||
TL11a for easings, speed curves, transitions, effects, text styles, tools (presets put
|
||||
on the picked clips) and snap grids as data (a clip let go 6 px past a plugin grid's mark lands on
|
||||
it, under a browser test with the plugin installed; each e2e run now starts with no plugins
|
||||
installed, since an earlier run's grids had stayed approved and snapped a run whose plugin had none),
|
||||
TL9c (an agent's editor_edit made as raea/editor operations on the open timeline, which
|
||||
editor_selection gives by clip id: one step in the person's history, undo taking it back, Send
|
||||
telling it as the agent's own, the clips it touched ringing and the bar saying what it did), TL9d
|
||||
(an item's own timeline: an edit kept in the item's data, Send telling its agent), TL10d (below),
|
||||
TL10e (a composition's drafts and a scene's ranges kept in the proxy store, <store>/drafts and
|
||||
<store>/scene-frames, under its one limit with the copies: one line by last play across all of
|
||||
them, so a draft played an hour ago goes before a still looked at a minute ago; Settings › Light
|
||||
copies lists drafts of edits and scene ranges with their sizes and Clear takes them; finishing or
|
||||
discarding a sitting forgets its drafts at once, and any ranges of the discarded version; kept
|
||||
frames whose file is gone go at the next sweep, as a copy whose source is gone does. Seen on a real
|
||||
host on its own port: 1 draft and 2 ranges listed as 15,000 bytes, Clear freeing all three), TL11b (the model as raea/editor, with its reference page and an example), TL12a-b, TL14a-c (a
|
||||
scene's timeline as long as the scene, past its last sequence)
|
||||
in code a composition's sequences: move, trim, split, delete (E3), keys on x, y, scale, rotate and opacity
|
||||
(TL5d), its still placement as its <Nudge>'s props, mirror and crop among them (TL3h), and its mask,
|
||||
blend and chroma key (TL7f: mask={{ kind, x, y, w, h, rotate, feather, round, invert }},
|
||||
blend="screen", chroma={{ color, strength, shadow }}, plain values only, any other the code's), a speed or a
|
||||
speed curve for a sequence that holds footage, split in two with it (TL6a-b), a transition on a cut
|
||||
(TL7a), an effect as a sequence holding an <Effect>, its kind and amount (TL7b), a sequence of
|
||||
words as a text clip, its words rewritten, words added as a new sequence (TL7c), a <Video>'s or an
|
||||
<Audio>'s level (TL8a), a recording as a sequence holding an <Audio> of its file (TL8c), a
|
||||
project's file as a sequence holding a <Video>, <Img> or <Audio> of it, named by its path in
|
||||
the composition's media folder (cloned into media/added/ first when it is elsewhere in the
|
||||
project), in at the nearest cut with the main track moving on and the composition growing (TL3j); each
|
||||
written into the working version the moment it is made, its draft played over the picture (TL9a,
|
||||
TL10d), finished and posted on Send with the agent told (TL9b: followed to the wire, a cutout's
|
||||
Send finishes the version on the host and then posts the item's own session, Cutter on Kimi in
|
||||
p-tutorial, a prompt holding the cutout's words, and nothing before Send; with the composition's
|
||||
tell skipped no prompt goes out. Live on Claude over ACP, nothing mocked between page and agent,
|
||||
the agent's first act was a search for "the v2 composition and matte"). A scene's sequences: move, trim,
|
||||
split, delete written into the scene's own file, which the stage opens again (TL14c). A sound's
|
||||
clips: span, place in the file, level (TL14b). An <Audio>'s sound from its copy with its noise
|
||||
reduced or its voice changed: its src the copy, and data-voice-of, data-denoise and data-voice (TL8d).
|
||||
A <Video>'s footage from its steadied copy: its src the copy, and data-steady-of and data-steady (TL7k);
|
||||
from its retouched copy, over the steadied one when both: data-retouch-of and the amounts (TL7n). A
|
||||
<Video> cut out: its matte prop and data-matte, brushed with data-brush-at and data-brush-strokes (TL7l,
|
||||
TL7m)
|
||||
plays TL10a for a film's own frames: cuts, moves, trims, speeds, freezes and reversed footage at once, the
|
||||
player's buffer on the ruler. TL10f: a timed 3D scene's frames are drawn ahead by the host a few
|
||||
seconds at a time at draft quality and kept by range, each range under what it is drawn from (the
|
||||
code outside the scene's sequences and the sequences on in it), so an edit to one sequence draws
|
||||
again only the ranges it is on and an undo plays what it had; the store stays under its one
|
||||
limit (TL10e), the least recently played going first, and beside the switch the
|
||||
scene's kept frames say what they take and are cleared by a click; the scene's timeline
|
||||
shows what is kept, and Play runs it over the stage from the scene's own camera. TL10d: where play
|
||||
reaches a range not kept yet while the frames are being drawn, the picture holds on it saying
|
||||
Buffering until a second from it is kept (with nothing being drawn, the live stage plays on), and
|
||||
a film that runs out of data says Buffering… over the picture. Seen in a headless raea window on
|
||||
the real host: the sample room drawn, kept, and played at its own rate; a 9 s copy of it opened
|
||||
again with every range kept at once (0.5 s); a sequence dragged across two of its three ranges
|
||||
drew those two again (9.4 s) and left every kept file as it was; and with nothing kept and Play
|
||||
pressed at once, Buffering to 7.7 s, the first range played, Buffering again at its end (11.0 s)
|
||||
until the next was kept (13.5 s)
|
||||
decided TL10b, c and e in the SDK (which ranges an edit changes, a range's key, what goes first); a
|
||||
composition's drafts are kept by their source, so an undo plays its draft again at once (and under
|
||||
the store's one limit since TL10e); beside a composition's timeline the
|
||||
kept drafts say what they take and are cleared by a click. Drafts and a scene's kept frames are
|
||||
drawn smaller than they ship and laid out as they ship (raea's <Composition edit={{ scale }}>, the
|
||||
long side at 960 px; docs/lightspeed.feature PF4): a ray-traced 1080p shot's draft 2.75 s at full
|
||||
size, 1.7 s scaled
|
||||
not built TL13a's drag at the window's rate with 400 clips, though close (measured below: Chrome keeps it;
|
||||
raea's window drew 35 frames a second, bound by the page host's frame after a step: Stylo's restyle,
|
||||
which Blitz widened to the changed element's parent's whole subtree, paint, and every element's rect
|
||||
taken each frame). raea-page-host now restyles finely by default (vendor/blitz-dom mutator.rs: what
|
||||
the snapshot's invalidation finds, the changed attribute named in the snapshot even when it was
|
||||
added, and each ancestor itself for `:has()`; RAEA_FINE_RESTYLE=0 for Blitz's own way), and a rect
|
||||
with no transform above it is answered without matrix math. ui-parity with it: 269/271, the same
|
||||
two cases failing as without (p15-media canvas-text, img-downscale); before the snapshot and :has()
|
||||
fixes it was 266. The app's timeline suite in a headless window with it: 53 of 54 pass, TL10d
|
||||
skipping itself there. Measured 11-14 in a headless window, three rounds alternating: the drag 38-41
|
||||
fps without, 48-50 with, against the window's still rate of 52-55, so about 90% of it; a pick
|
||||
42-62 ms and a split 46-63 ms. A sync of the twins that keeps their boxes on each pointer move
|
||||
(RAEA_TWIN_SYNC_LIGHT=1, a trial, off) gained nothing, again in four interleaved rounds with the fine
|
||||
restyle (drag over still 0.62-0.67 with it, 0.65-0.67 without). Under another session's load the
|
||||
drag held the same share of the still rate with the :has() fix as without (0.66-0.72 each, four
|
||||
rounds). Where a drag's frame goes now (a macOS sample of the page host's main thread with the fine
|
||||
restyle, 365 samples): the page's JavaScript for the pointer event 18%, paint 18%, the snapshot of
|
||||
every element's box for the page's JS 11%, the twins' boxes taken again before each event 7% and
|
||||
each frame 5%, Stylo's restyle 2.5% (28% before). The drag adds about 2 ms to a still frame of 18-19
|
||||
ms, so what is left is mostly the still frame: every element's box taken twice a frame and the page
|
||||
painted whole, with nothing changed; an incremental snapshot and paint would be the next step.
|
||||
Drawing only the clips in view would draw none fewer: at its opening fit all 12 tracks and all 400
|
||||
clips are on screen at once.
|
||||
TL13a's stage clause is met (an edit on the scene's stage by 88 ms, median, TL13b). The
|
||||
skills guide's note on an item's `timeline` field waits for PR #19 to merge
|
||||
|
||||
Background:
|
||||
Given the SDK is sdk/timeline in raea, the app's side is raea-feed src/detail (timeline, strip, blocks), the
|
||||
host's is raea-feed host (sequences.ts, edit.ts, preview/proxies.ts) and the engine's stage is engine/page/stage
|
||||
And every scenario below is a task (docs/agents.md "Tasks: rask"); a status line under a rule says what is built
|
||||
|
||||
Rule: TL0. One model: tracks, clips, keys, markers
|
||||
# Plan (crate or package | file | lines | job)
|
||||
# sdk/timeline | src/model.ts | 150 | Timeline, Track, Clip, Key, Marker, Ease; ids; frames as integers
|
||||
# sdk/timeline | src/ops.ts | 300 | every operation as (timeline, op) -> timeline; inverse for undo
|
||||
# sdk/timeline | src/snap.ts | 120 | what an edge snaps to, and the magnet's closing of gaps
|
||||
# sdk/timeline | src/keys.ts | 160 | a property's value at a frame; cubic bezier easing; presets
|
||||
# sdk/timeline | src/speed.ts | 120 | a speed curve's source time at an output time, and its length
|
||||
# sdk/timeline | src/read.ts | 200 | a timeline from a composition's read tree (host/sequences.ts' rows)
|
||||
# sdk/timeline | src/edits.ts | 200 | an operation as code edits to the working version
|
||||
|
||||
Scenario: TL0a. Time is whole frames
|
||||
Given a timeline at 30 frames a second
|
||||
Then every clip's start, length and trim, every key and every marker is a whole number of frames
|
||||
And a timecode is drawn from frames (mm:ss:ff), never the other way
|
||||
|
||||
Scenario: TL0b. An operation is a pure function with an inverse
|
||||
Given any timeline and any operation that applies to it
|
||||
Then applying the operation and then its inverse gives the timeline back, to the frame
|
||||
And an operation that can't apply (a locked track, a clip trimmed past its source) is refused with its reason
|
||||
|
||||
Scenario: TL0c. A timeline is read from a composition
|
||||
Given a composition with sequences, a <Video>, an <Audio>, a component and a <Series>
|
||||
Then each is a clip with its span, on a track by its kind and its depth in the tree, and names its element
|
||||
(file:line:col, docs/editing.feature E2)
|
||||
And a span written as an expression is a clip marked locked, with "set in code"
|
||||
|
||||
Scenario: TL0d. A feed item or a controller declares a timeline
|
||||
Given an agent posts a feed item, or a controller has a field, that carries a timeline (tracks of clips over
|
||||
anything with a time: a film, a song, a scene's animation, a schedule)
|
||||
Then the app draws it with the same strip and tools, and its operations go back to the agent as TL9 says
|
||||
|
||||
Rule: TL1. Tracks: a main track, overlays above, sound below, each with a head
|
||||
Scenario: TL1a. Tracks by kind, in CapCut's order
|
||||
Then from the top: effect and adjustment tracks, text tracks, overlay picture tracks, the main track, sound tracks
|
||||
And a new clip of a kind with no free track makes one in its place in that order
|
||||
|
||||
Scenario: TL1b. A track's head
|
||||
Then each track's head has its kind's icon and name, a lock, an eye (picture) or a speaker (sound)
|
||||
And a locked track's clips can't be picked or changed, a hidden one isn't drawn in the picture, a muted one isn't heard
|
||||
And these are edits like any other (TL9): the composition is drawn that way until they are turned back
|
||||
|
||||
Scenario: TL1c. Tracks expand
|
||||
Given the switcher on the left of a track (what it shows: frames, waveform, spectrogram, words, a plugin's lane)
|
||||
When I drag a track's lower edge, or double-click its head
|
||||
Then that track alone grows or shrinks, from a line to tall, and what it shows gains detail with its height
|
||||
And the whole timeline still resizes from its top edge and collapses to its scrubber (raea-feed PR #18)
|
||||
|
||||
Scenario: TL1d. The main track's cover and the first frame
|
||||
Then the main track's head shows the film's poster, and picking it sets the frame used as the item's poster
|
||||
|
||||
Rule: TL2. Moving through time
|
||||
Scenario: TL2a. The ruler and the playhead
|
||||
Then a ruler over the tracks marks time at the zoom's scale (frames, seconds, tens of seconds)
|
||||
And a press or a drag on the ruler or the scrubber moves the playhead and nothing else
|
||||
|
||||
Scenario: TL2b. Keys, as CapCut's
|
||||
Then Space plays and pauses; Left and Right step a frame; Shift+Left and Shift+Right step ten
|
||||
And Up and Down go to the cut before and after; Home and End to the first and last frame
|
||||
And every key is listed in one place (the app's shortcuts), can be changed there, and shows in its button's tooltip
|
||||
|
||||
Scenario: TL2c. Zoom and scroll
|
||||
Then Cmd+= and Cmd+- zoom about the playhead, Cmd+scroll about the pointer, Shift+Z fits the whole timeline
|
||||
And scroll moves through the tracks, Option+scroll (and a sideways scroll) through time
|
||||
And the zoom goes from the whole film in the strip's width to one frame at 12 px or more
|
||||
|
||||
Scenario: TL2d. The preview axis
|
||||
Given the preview axis is on (S)
|
||||
When the pointer moves over the tracks
|
||||
Then the picture shows the frame under the pointer without moving the playhead, and goes back when it leaves
|
||||
|
||||
Scenario: TL2e. Markers
|
||||
When I press M
|
||||
Then a marker is at the playhead (on the picked clip if one is picked, else on the timeline), which I can name,
|
||||
colour, drag and delete, and which edges snap to
|
||||
|
||||
Scenario: TL2f. A range marked for export
|
||||
When I press I at one place and O at another (in either order), or Shift+X with a clip picked (CapCut's
|
||||
"select an area by clip"; capcut.com/help/export-clip-of-video)
|
||||
Then the span between them is marked on the ruler, its ends dragged, and Option+X clears it
|
||||
And an export of the item renders only that span, all its tracks; with none marked it is the whole timeline
|
||||
And the range is how the timeline is seen, not an edit: it isn't sent, and it is kept with the item's timeline
|
||||
until it is cleared, so a later export isn't cut short without it showing
|
||||
|
||||
Rule: TL3. Clips: pick, move, trim, split, delete
|
||||
Scenario: TL3a. Picking
|
||||
Then a click picks a clip, Cmd+click adds or removes one, a box dragged from empty track picks what it touches
|
||||
And [ and ] pick every clip left or right of the playhead; Cmd+A all; Escape none
|
||||
And what is picked is what the viewer's inspector shows and what editor_selection tells the agent
|
||||
|
||||
Scenario: TL3b. Moving
|
||||
When I drag a clip (or the picked clips together)
|
||||
Then it moves in time on its track, or to another track that takes its kind, snapping as TL4 says
|
||||
And Option held while dragging leaves a copy behind
|
||||
|
||||
Scenario: TL3c. Trimming
|
||||
When I drag a clip's edge
|
||||
Then its start or end moves and, for media, its place in the source with it, never past the source's own ends
|
||||
And a trimmed edge can be dragged back out to what was there
|
||||
|
||||
Scenario: TL3d. Splitting
|
||||
Then Cmd+B splits the picked clips at the playhead (every clip under it when none is picked)
|
||||
And Cmd+Shift+B splits every track; B makes each click a split until A; a split clip's keys stay at their frames
|
||||
|
||||
Scenario: TL3e. Delete, delete left, delete right
|
||||
Then Delete removes the picked clips; on the main track with the magnet on, the gap closes
|
||||
And Q removes what is left of the playhead on the picked clip, W what is right of it, the gap closed
|
||||
And Shift+Delete closes the gap on any track
|
||||
|
||||
Scenario: TL3f. Copy, paste, duplicate, attributes
|
||||
Then Cmd+C, Cmd+X and Cmd+V copy, cut and paste clips at the playhead on their tracks; Cmd+D duplicates after
|
||||
And Cmd+Shift+C and Cmd+Shift+V copy a clip's properties, keys and effects onto the picked ones
|
||||
|
||||
Scenario: TL3g. Disable, group, compound
|
||||
Then V turns the picked clips off and on (drawn dimmed, left out of the picture and the sound)
|
||||
And Cmd+G groups clips so they pick and move as one; Cmd+Shift+G lets them go
|
||||
And Option+G makes the picked clips one compound clip (in code, one component holding them), opened by a
|
||||
double-click to edit inside; Option+Shift+G puts them back
|
||||
|
||||
Scenario: TL3h. Freeze, reverse, mirror, rotate, crop
|
||||
Then with a picture clip picked the bar offers Freeze (a still of the playhead's frame, 3 s, inserted there),
|
||||
Reverse, Mirror, Rotate (90 degrees) and Crop, each an edit to that clip's element
|
||||
|
||||
Scenario: TL3i. Undo and redo
|
||||
Then Cmd+Z and Cmd+Shift+Z step through every operation, the person's and the agent's (E5a), one history
|
||||
And a drag is one step however many frames it crossed
|
||||
|
||||
Scenario: TL3j. The project's media, added at the playhead
|
||||
Given the project's footage, stills and sounds (the files its Source page's Assets tab lists)
|
||||
When I open Media in the bar and press a file's +, as CapCut's media panel adds one
|
||||
Then it is a clip at the playhead as long as its file (a still 3 s, CapCut's default): footage and stills on
|
||||
the main track, a sound on a sound track
|
||||
And in a composition it is a sequence holding a <Video>, an <Img> or an <Audio> of the file, named by its path
|
||||
in the composition's media folder (a file elsewhere in the project copied into media/added/ first, since a
|
||||
render reads that folder alone); on the main track with the magnet on, the clips after it move on by its
|
||||
length and it is drawn under what was over them
|
||||
And in a film cut here it goes over the picture on an overlay track (the film's own cut is its scenes) and
|
||||
plays there, a sound plays where it is placed, and Send tells the agent which file went where
|
||||
|
||||
Rule: TL4. The magnet, snapping and linkage
|
||||
Scenario: TL4a. The main track's magnet (P)
|
||||
Given the magnet is on
|
||||
Then the main track has no gap: a clip removed closes it, a clip dropped between two moves the later ones on
|
||||
And a clip dragged past its neighbour's middle swaps places with it
|
||||
Given it is off
|
||||
Then clips stay where they are, a gap is allowed, and a clip dropped over another goes to a track above
|
||||
|
||||
Scenario: TL4b. Snapping (N)
|
||||
Then a dragged clip's edges, a trimmed edge and the playhead snap within 8 px to clip edges on every track,
|
||||
the playhead, markers, beats and the film's ends, with a line drawn where it snapped
|
||||
And Cmd held while dragging turns snapping off for that drag
|
||||
|
||||
Scenario: TL4c. Linkage (~)
|
||||
Given linkage is on
|
||||
Then what sits over a main-track clip (text, effects, overlays that start inside its span) moves, is split's
|
||||
left or right part, and is deleted with it
|
||||
And a video clip's own sound moves with it until Cmd+Shift+S extracts it to a sound track
|
||||
|
||||
Rule: TL5. Keyframes and curves
|
||||
Scenario: TL5a. A key is a property's value at a frame
|
||||
Given a clip is picked and the playhead is inside it
|
||||
When I press the diamond beside a property (position, scale, rotation, opacity, volume, any prop its element
|
||||
declares as a number, a colour or a point)
|
||||
Then that property has a key there; changing the value at another frame adds a key there
|
||||
And between two keys the value follows the first key's ease; before the first and after the last it holds
|
||||
And the numbers inside a mask (its centre, size, turn, feather, corners), a chroma key (strength, shadow) and a
|
||||
crop (each side) have their keys beside them in their panels, as the placement's are in the row, and the
|
||||
picture follows them as it plays; in a composition they are the <Nudge keys> of a dotted name ("mask.feather",
|
||||
"chroma.strength", "crop.left"), a curve that overshoots held inside what the value can be
|
||||
|
||||
Scenario: TL5b. Keys on the clip
|
||||
Then a clip with keys shows them as diamonds along it (Option+K shows or hides a row a property)
|
||||
And a diamond is dragged in time, copied, deleted; a click on one moves the playhead to it
|
||||
And the diamond beside the property steps to the key before and after
|
||||
|
||||
Scenario: TL5c. Easing is a cubic bezier, edited by hand
|
||||
When I open a span between two keys
|
||||
Then a graph shows its curve with two handles; dragging them changes it; the picture plays it as I drag
|
||||
And presets fill it (linear, ease in, ease out, ease in-out, hold, and those a plugin adds), and a curve I made
|
||||
can be saved by name for the workspace
|
||||
And in code a key's ease is its four numbers ([x1, y1, x2, y2]), "linear" or "hold"
|
||||
|
||||
Scenario: TL5d. Keys in code
|
||||
Then a property with keys is written on its element as one readable prop (keys={{ scale: [[0, 1], [45, 1.15,
|
||||
[0.2, 0, 0, 1]]] }} through one wrapper, as <Nudge> is for a still value), re-written in place on each change
|
||||
And a property animated by the composition's own code (interpolate, spring) is shown as a curve that can be
|
||||
read but not dragged, with "set in code"
|
||||
|
||||
Rule: TL6. Speed
|
||||
Scenario: TL6a. A constant speed
|
||||
When I set a picked clip's speed (Cmd+R) from 0.1x to 100x, or drag its edge with Option held
|
||||
Then its length follows, its sound keeps its pitch unless I say otherwise, and the magnet closes or opens the gap
|
||||
|
||||
Scenario: TL6b. A speed curve
|
||||
When I choose Curve (Shift+B)
|
||||
Then the clip has points from 0.1x to 10x over its source, with the presets Montage, Hero, Bullet, Jump cut,
|
||||
Flash in and Flash out, and a custom one whose points I drag, add and remove
|
||||
And the clip's length is the curve's, and a line over the clip shows where it is fast and slow
|
||||
|
||||
Rule: TL7. Transitions, effects, text
|
||||
Scenario: TL7a. A transition sits on a cut
|
||||
Given two clips that touch on one track
|
||||
When I drop a transition on their cut (or pick one from the cut's own button)
|
||||
Then it is drawn across the cut, its length dragged from either end, within what both clips have beyond the cut
|
||||
And it is a component both clips' elements are wrapped by in code, one a plugin can add
|
||||
|
||||
Scenario: TL7b. Effects, filters and adjustments are clips
|
||||
Then each is a clip on a track above the picture, covering the span it applies to, trimmed and keyed like any other
|
||||
And with linkage on it follows the main-track clip under its start
|
||||
|
||||
Scenario: TL7c. Text and captions
|
||||
Then a text is a clip on a text track; double-click edits its words in the picture; Enter splits a caption in two
|
||||
And captions made from the words (the transcript) are clips on a caption track, each moved, trimmed and edited
|
||||
|
||||
Scenario: TL7d. A clip's own In and Out animations
|
||||
Given a clip of footage, a still or text picked
|
||||
When I give it an In animation or an Out animation (CapCut's Animation tab: fade, slide, wipe, zoom, or a
|
||||
plugin's transition) and how many frames it takes
|
||||
Then it plays over the clip's own first or last frames, drawn as a ramp at that end of the clip, and the picture
|
||||
shows it at once
|
||||
And split, the first part keeps the In and the second the Out; it is never longer than the clip
|
||||
And in a composition it is the sequence's own <Transition in out>, the same component a cut's transition writes,
|
||||
and read back from it as the clip's own wherever no cut's transition takes it
|
||||
|
||||
Scenario: TL7e. A clip's Combo animation
|
||||
Given a clip of footage, a still or text picked
|
||||
When I give it a Combo (CapCut's third kind: pulse, sway, float, shake, swing, spin, flicker, or a plugin's)
|
||||
Then it moves over the clip's whole length, a cycle every so many frames: the clip's own length (what it starts
|
||||
at) plays it once, as CapCut's Combo does, and fewer loop it, as CapCut's text Loop does
|
||||
And it plays with the clip's In and Out at once, drawn as a line along the clip with a tick at each cycle
|
||||
And a Combo is data, a wave of the clip's x, y, scale, rotate and opacity over one cycle, so a plugin adds one in
|
||||
its manifest and the preview draws it
|
||||
And in a composition it is the sequence's <Transition combo>, written and read back
|
||||
|
||||
Scenario: TL7f. A clip's mask, blend and chroma key
|
||||
Given a clip of footage or a still picked
|
||||
When I give it a mask (CapCut's Mask tab: a line, a mirror band, a circle, a rectangle, a heart or a star)
|
||||
Then the picture is seen through it at once: a shape that starts round in the middle of the film, moved and
|
||||
sized in shares of the frame, turned, its edge feathered, a rectangle's corners rounded, or inverted to keep
|
||||
what is outside it
|
||||
When I give it a blend (Basic's Blend: darken, screen, overlay, multiply, lighten, hard and soft light, colour
|
||||
burn and dodge, add, difference, exclusion)
|
||||
Then it is drawn onto what is under it by that mode
|
||||
When I key a colour out of it (Cutout's Chroma key: a green or blue screen, or a colour typed, its strength and
|
||||
its shadow)
|
||||
Then that colour's hue goes from the picture, the screen's shadows let through half seen as far as the shadow
|
||||
says; a grey, which has no hue to key by, is refused in words
|
||||
And in a composition each is a prop of the sequence's <Nudge> (mask, blend, chroma), written and read back,
|
||||
and raea's renderer draws them as the preview does
|
||||
|
||||
Scenario: TL7g. A clip's own Adjust
|
||||
Given a clip of footage or a still picked
|
||||
When I adjust it (CapCut's Adjust tab: brightness, contrast, saturation, exposure, sharpen, highlights, shadows,
|
||||
temperature, tint, fade, vignette, grain), each a slider from as shot, keyed as any number is (TL5a)
|
||||
Then the picture shows it at once, under the effects over it, after its chroma key; a file from Media over the
|
||||
film shows its own, its vignette over its own picture where that sits in the frame
|
||||
And in a composition it is the sequence's <Nudge adjust>, written and read back: its tone one curve read through
|
||||
a table, its colour two colour matrices, sharpen a convolution, grain a noise whose seed is the frame, and a
|
||||
vignette a darkening laid over the part's frame; raea's renderer draws them as Chrome does (11-14 probe: tone,
|
||||
colour, sharpen and vignette within 0.4% RMSE of Chrome, grain the same strength, its noise its own)
|
||||
And Send tells the agent the adjustments as they now stand
|
||||
|
||||
Scenario: TL7h. The key's colour picked from the picture
|
||||
Given a clip of footage or a still picked, its chroma key open
|
||||
When I press pick and then press on the picture (CapCut's picker: a crosshair, a ring under the pointer)
|
||||
Then the key's colour is the clip's own at that point: read from its file where the player is in it, before its
|
||||
key, the mean of a small round patch so one noisy pixel doesn't set it, wherever the clip is placed, turned,
|
||||
scaled or mirrored on the film; a press off its picture is said, not read
|
||||
And the key takes it at once as a typed colour would, and the press leaves no comment and doesn't play
|
||||
And Esc, or pick again, stops picking and keeps the clip picked
|
||||
And the picture is read by the host from the file, not from the screen (raea's window has no canvas to read),
|
||||
so it is the same colour in raea's window and in Chrome
|
||||
|
||||
Scenario: TL7i. A mask's handles dragged on the picture
|
||||
Given a clip with a mask picked, its mask panel open and the playhead on it
|
||||
Then the mask's outline is drawn on the picture where it is, through the clip's placement, with CapCut's
|
||||
handles at a constant size: the shape itself to move it, an edge's for its width or its height, a corner's for
|
||||
both in proportion, a turn handle under it, a feather handle over it that runs out as the edge softens, and a
|
||||
rectangle's corner rounding along its top edge (a line has its turn and feather; a mirror's band its height)
|
||||
When I drag one
|
||||
Then the picture's mask follows as it moves and it is one edit when let go, the panel's numbers with it: a number
|
||||
keyed (TL5a) takes a key at the playhead, the rest a still value
|
||||
And a press on them leaves no comment and doesn't play
|
||||
|
||||
Scenario: TL7j. A text's words read aloud
|
||||
Given a text clip picked, in a film or a composition with a project
|
||||
When I press read aloud (CapCut's text to speech)
|
||||
Then its words are made into a voice on the host (raea gen speech: narration through raea's API, about a cent a
|
||||
line) and kept as a sound file of the project's, media/speech/ by the words and their hash, so the same words
|
||||
read again are the kept file and cost nothing
|
||||
And the voice is a sound clip on a sound track from where the text starts, as long as the voice, named by the
|
||||
words, as a file from Media is (TL3j); in a composition it is the host's edit, as that is
|
||||
And what goes wrong (no words, too many, no credit) is said beside the button, and nothing is added
|
||||
|
||||
Scenario: TL7k. Footage held steady
|
||||
Given a footage clip picked in a film cut here (one of the film's scenes, or footage of the project's over it)
|
||||
When I pick a level in Stabilise (CapCut's: Minimal cut, Recommended, Most stable)
|
||||
Then the host reads the part of its file the clip shows, small and grey, and finds each frame's move from the
|
||||
one before (a grid of blocks by phase correlation, fitted as one shift and turn, a thing moving across the
|
||||
picture left out); the moves add up to the camera's path, smoothed by the level (a slow sway kept at Minimal
|
||||
cut, held at Most stable), and the difference is the move for each frame with one zoom that keeps the frame's
|
||||
edges out of sight, kept as a file of the project's under media/stabilise by its file, frames and level
|
||||
And the player wears the moves under the clip's own placement, so its position, scale, turn and keys move the
|
||||
steadied picture, and the zoom is said in the row
|
||||
And not stabilised, it is as shot; what goes wrong is said beside the level, and nothing changes
|
||||
And the agent is told the level, the file of moves and what is in it, and the zoom (TL9b)
|
||||
|
||||
Scenario: TL7l. Footage cut out
|
||||
Given a footage clip picked in a film cut here (one of the film's scenes, or footage of the project's over it)
|
||||
When I pick what to keep in Auto cutout (CapCut's: a person, or the picture's subject, whatever it is)
|
||||
Then the host has the Mac's own vision models matte each frame of the part of its file the clip shows (no
|
||||
model downloaded, nothing sent anywhere), each a PNG whose alpha is what is kept, kept under media/matte by
|
||||
its file, frames and kind, so the same cutout asked again is read, not made
|
||||
And the player wears each frame's matte as it plays, cut into the clip's own mask (TL7f) and never adding to
|
||||
it, the next mattes fetched before they are worn; a part cut out shows what is under the clip
|
||||
And a long clip is matted every second or third frame, at most 900 mattes, each worn until the next
|
||||
And off, the picture is whole; what goes wrong (not a Mac, a subject cutout before macOS 14, a file with no
|
||||
moving picture) is said beside the menu, and nothing changes
|
||||
And the agent is told what is kept, by what, and where the mattes are and which frame each is (TL9b)
|
||||
|
||||
Scenario: TL7m. Footage cut out by what is brushed over it
|
||||
Given a footage clip picked in a film cut here, at a frame where what I want shows well
|
||||
When I pick Brushed in its cutout menu (CapCut's Custom cutout)
|
||||
Then a brush is on the picture, through the clip's placement: I brush over what to keep, and with the eraser
|
||||
over what to take out, at a width I set; a stroke can be taken back, or all of them, and brushing neither
|
||||
plays nor leaves a note
|
||||
And Cut out has the host find, on that frame, the things in the picture my strokes are over (the Mac's own
|
||||
vision models telling them apart), and follow them to the clip's end and back to its start, each frame's
|
||||
kept as TL7l keeps its mattes; nothing under what I kept is said, and the strokes stay to brush again
|
||||
And the player wears them as TL7l says, and Brushed opened again shows the strokes it was cut out by
|
||||
And the agent is told when it was brushed, its strokes, and where the mattes are (TL9b)
|
||||
|
||||
Scenario: TL7n. Footage retouched
|
||||
Given a footage clip picked in a film cut here, a person's face in it
|
||||
When I open its Retouch (CapCut's Retouch) and set smooth, brighten, slim face and bigger eyes, and apply
|
||||
Then the host finds the faces on each frame of the part of its file the clip shows and retouches them (the
|
||||
skin smoothed with its edges kept, brightened, the cheeks and jaw drawn in, the eyes made bigger), and keeps
|
||||
the frames, with that part's own sound under them, as one copy of the project's, named by its source, part
|
||||
and amounts, so the same retouch asked again is read, not made
|
||||
And the player shows the copy in the clip's place, in step with the playhead and wearing everything the clip's
|
||||
picture wears (its placement, mask, cutout, Adjust); the clip's picture goes only once the copy has the frame
|
||||
under the playhead, and a clip coming on next has its copy loaded before it does
|
||||
And applied again with other amounts it is a new copy; off, the picture as shot; what goes wrong (not a Mac, no
|
||||
face in it, longer than a minute) is said beside the sliders, and nothing changes
|
||||
And the agent is told the amounts, and where the copy is and the part of the file it holds (TL9b)
|
||||
|
||||
Rule: TL8. Sound
|
||||
Scenario: TL8a. The waveform, the volume line and fades
|
||||
Then a sound clip draws its waveform; a line across it is its volume, dragged up and down (Cmd+. and Cmd+,
|
||||
0.1 dB); a handle at each top corner drags a fade in and a fade out, drawn as the waveform's slope
|
||||
And volume takes keys as TL5 says
|
||||
|
||||
Scenario: TL8b. Beats
|
||||
When I ask for a sound clip's beats
|
||||
Then they are marked along it (the bed's beat map where raea made the music, else found from the sound), each
|
||||
can be turned off, and edges snap to them (TL4b)
|
||||
|
||||
Scenario: TL8c. A voice recorded onto the timeline
|
||||
When I press record and speak
|
||||
Then the take is a sound clip from the playhead on a sound track, and a file in the project
|
||||
|
||||
Scenario: TL8d. A sound's noise reduced and its voice changed
|
||||
Given a sound clip picked in a film cut here (a recording, a sound file of the project's, or the film's own
|
||||
sound taken out of its footage)
|
||||
When I press reduce noise, or pick a voice (CapCut's voice changer: chipmunk, deep, robot, telephone,
|
||||
megaphone, echo), or both
|
||||
Then the host makes a copy of the clip's own sound, never of a copy, with that done to it (its steady noise
|
||||
found in its quietest tenth and turned down per frequency; the voice by a phase vocoder, a filter or a delay),
|
||||
mono and as long as its own, kept under the project's media/voice by its file, size, time and settings, so
|
||||
asking again is the kept file
|
||||
And the clip plays the copy from where it played its own, and says so with a mark on it
|
||||
And both turned off, it plays its own sound again
|
||||
And what goes wrong (no sound here, longer than 20 minutes) is said beside the controls, and nothing changes
|
||||
And the agent is told what was done and the file it now plays (TL9b)
|
||||
|
||||
Rule: TL9. An edit is an edit, and the agent gets it as one
|
||||
Scenario: TL9a. Applied at once, to the working version
|
||||
When I make any operation above
|
||||
Then the working version's code is changed by it (docs/editing.feature E1a) and the picture shows it (TL10)
|
||||
And nothing asks me to confirm, and nothing is held as a suggestion
|
||||
|
||||
Scenario: TL9b. Sent to the agent as what was done
|
||||
Given the item's agent has a session (or is started for it, as a note's send does)
|
||||
When my sitting's edits are sent (when I leave the editor, press Send, or pause a while)
|
||||
Then the agent receives them as edits already made: the operations in order, each with the clip's element, the
|
||||
frames before and after, and the file and lines changed, with the version they made
|
||||
And its prompt says they are done and not to be redone or undone, and what is its to do next (render, check,
|
||||
carry the change to what depends on it)
|
||||
|
||||
Scenario: TL9c. The agent's edits are operations too
|
||||
When an agent changes the timeline (editor_edit, or the SDK's operations from its own code)
|
||||
Then they land in the open sitting's history as mine do, and I see each one happen
|
||||
|
||||
Scenario: TL9d. A timeline with no composition behind it
|
||||
Given a feed item or a controller whose timeline is its own data (TL0d)
|
||||
Then an operation changes that data where it is kept and is sent to its agent the same way
|
||||
|
||||
Rule: TL10. Playing while editing: buffer, cache, and clearing it
|
||||
Scenario: TL10a. The engine plays the working file
|
||||
Given a stage (the raea app)
|
||||
Then the picture is the engine drawing the working version at the playhead, for 2D, 3D and ray-traced scenes
|
||||
And a change shows on the next frame; no render stands between an edit and the picture (E4a)
|
||||
|
||||
Scenario: TL10b. Frames drawn are kept, by what draws them
|
||||
Then a range of frames the stage has drawn is kept (in memory near the playhead, on disk beyond it) under a key
|
||||
of everything that draws it: the clips over it, their props and keys, the media's own fingerprints
|
||||
And playing a kept range shows its frames without drawing them again, at the film's own rate
|
||||
And a bar over the ruler shows which ranges are kept and which are being drawn
|
||||
|
||||
Scenario: TL10c. An edit drops only what it changed
|
||||
When I move a clip from 2:00-2:05 to 2:10-2:15
|
||||
Then the kept frames of 2:00-2:05 and 2:10-2:15 are dropped and every other range plays from the store
|
||||
|
||||
Scenario: TL10d. Buffering ahead
|
||||
Given a part of the film that can't be drawn at its rate (a ray-traced scene, a 4K clip)
|
||||
Then while paused, and while playing ahead of the playhead, the stage draws and keeps what comes next
|
||||
And heavy media plays from its light copy while editing (the proxy store), and an export reads the originals
|
||||
And when playing reaches a frame that isn't ready, the picture holds and says "Buffering" until 1 s is ready
|
||||
|
||||
Scenario: TL10e. The store keeps itself small
|
||||
Then the kept frames live in the proxy store, under its one size limit, shown in Settings with what holds it
|
||||
And the least recently played ranges go first; a version that was closed or discarded goes at once; nothing a
|
||||
person made by hand is ever in it
|
||||
And clearing it by hand costs only time: everything in it is made again when needed
|
||||
|
||||
Scenario: TL10f. Whole sequences and scenes
|
||||
Then a Scene item's animation and a film's 3D shots play, scrub and cache the same way
|
||||
And a sequence of several compositions plays through its cuts without a gap or a reload
|
||||
|
||||
Rule: TL11. The framework: every part can be added to
|
||||
Scenario: TL11a. Contribution points
|
||||
Then a plugin (plugins/manifest.ts) can add: a kind of track, a kind of clip and how it draws on the strip, a
|
||||
property and its editor in the inspector, an easing preset, a speed preset, a transition, an effect, a lane,
|
||||
a tool in the bar with its key, and a snapping target
|
||||
And raea's own tracks, clips, easings and transitions are registered through the same points
|
||||
|
||||
@done
|
||||
Scenario: TL11b. The SDK alone
|
||||
# Status 11-13: built. The model is one import, `raea/editor` (sdk/raea/src/editor.ts re-exports sdk/timeline;
|
||||
# raea/timeline was already the video Sequence module), resolved by a bundle as @raea/timeline. Its reference page
|
||||
# is docs/manual/reference/sdk/editor.md, every type and field documented (the manual-ref gate fails on one
|
||||
# without), with docs/manual/examples/edits.tsx as its example: a timeline built in code, split, keyed, sped up
|
||||
# and undone by the inverses, rendered (180 frames to 150, then "as it was"). The skills' SDK reference lists it
|
||||
# (tools/skills.sh now follows export *, raea-skills #65) and motion/footage teaches it (raea-skills #64)
|
||||
Then sdk/timeline has no React and no DOM: an agent's script, the host and a test use it as the app does
|
||||
And its reference page lists every type and operation with an example, in the skills reference
|
||||
|
||||
Rule: TL12. Comments leave the timeline
|
||||
Scenario: TL12a. No comment is made on the timeline
|
||||
Then a press on the tracks never opens a comment card, with any tool on, and the strip's menu has no Comment item
|
||||
And Comment in the viewer pins a comment on the picture at the playhead's time, as it does now
|
||||
|
||||
Scenario: TL12b. A comment shows as a marker
|
||||
Then each comment with a time shows as a marker on the ruler in its author's hue; a click opens it in the viewer
|
||||
|
||||
Rule: TL13. Feel
|
||||
Scenario: TL13a. Under the pointer
|
||||
Then a drag, a trim and a scrub draw at the window's rate with 400 clips on 12 tracks, the dragged clip never
|
||||
more than a frame behind the pointer
|
||||
And a pick shows within 50 ms, a split within 100 ms, and the picture follows an edit within 100 ms where the
|
||||
stage plays it
|
||||
|
||||
Scenario: TL13b. Measured, as 0.1.4's were
|
||||
Then each number above has a harness and a before and after in this file, in a headless window
|
||||
# 11-13, raea-feed e2e/timeline-perf.spec.ts (PERF=1), headless Chrome on the M5 Pro, an item's own timeline
|
||||
# of 400 clips on 12 tracks, three runs:
|
||||
# a pick drawn 9, 10, 13 ms (the bar: 50 ms)
|
||||
# a split drawn 24, 26, 27 ms (the bar: 100 ms; 12 clips cut at once)
|
||||
# a 2 s drag 63 to 65 frames a second; a frame's median 14.2 to 14.8 ms, its 95th centile 27 ms,
|
||||
# its worst 34 to 49 ms: one frame in twenty is a frame late
|
||||
# The same in a headless raea window (blitz/pw-run.mjs, RAEA_PAGE_FPS=120), after each clip's and each
|
||||
# track's drawing was kept while nothing it shows changes (Chrome's drag went to 68 to 71 frames a second):
|
||||
# a pick drawn 45 to 59 ms (at the bar, not under it)
|
||||
# a split drawn 59 to 64 ms
|
||||
# a 2 s drag 27 to 31 frames a second, a frame's median 31 to 36 ms: not the window's rate
|
||||
# nothing moving 63 frames a second; the pointer moving over it, 61
|
||||
# and with 48 clips in place of 400: nothing moving 106 frames a second, a drag 56, a pick 39 ms. So in the
|
||||
# window both scale with the clips on screen: what the window draws each frame (16 ms for 400 clips, 9 for
|
||||
# 48) and what a drag step adds to it (about 18 ms, 8 with 48). Keeping the clips' drawings did not move the
|
||||
# window's numbers, so the step's cost there is not React's work on the clips: it is not yet told apart
|
||||
# between the operation itself (snapping and settling 400 clips) and the window laying the moved clips out.
|
||||
# Told apart since (the measurement times a step's operation and React's commit of it): a drag step asked
|
||||
# the page what was under the pointer (document.elementFromPoint, for the track a clip is carried to), which
|
||||
# in raea's window took 7.7 ms a step (0.2 ms in Chrome). The tracks' places are now read once when a clip
|
||||
# is first carried: the operation is 0.1 ms a step, its commit 2.5 ms, and the window's drag 35 to 37 frames
|
||||
# a second (a frame's median 24 to 26 ms), with nothing moving 80. What is left is the window's: a frame
|
||||
# after any change to the page costs about twice a still one with 400 clips on screen (a clip placed by a
|
||||
# transform instead of its left edge made no difference), so the rest is the engine's layout, not the app's.
|
||||
# 11-14, told apart further (PERF_LISTENERS times the window's host calls and splits a pointermove at the
|
||||
# handler and React's commit; a copy of sdk/ui timed inside built the bundle; PERF_SAMPLE takes a macOS sample
|
||||
# of raea-page-host): of a move's 10 ms in the page, 9.5 went to finding its target, every element hit-tested
|
||||
# in JavaScript, since the clip held no capture. A clip carried over its neighbour is shown on a track with
|
||||
# room for the step, its element made again there, and the capture went with the old one (in Chrome too: a
|
||||
# release over an empty stretch of track never lifted the drag). The clip's new element takes it back now: a
|
||||
# move costs the page 2.3 ms (React's commit 1.8), every move makes a step (67 of 68, against 31 of 62), and
|
||||
# the drag still draws 33 to 35 frames a second, with nothing moving 71 to 77. The host's main thread through
|
||||
# the drag: Stylo's restyle 28%, paint 15%, the page's JavaScript 14%, layout_out 11% (each element's rect
|
||||
# with its ancestors' transforms, every frame, to send the snapshot when it changed), waiting on the render
|
||||
# world 11%. Blitz's set_attribute adds restyle_subtree() to the element and its parent (an upstream TODO)
|
||||
# on top of the snapshot Stylo already diffs, so a clip's left restyled every clip on its track;
|
||||
# RAEA_FINE_RESTYLE=1 leaves it to the snapshot's invalidation (vendor/blitz-dom, off by default), waiting on
|
||||
# a release build of raea-page-host, which the disk had no room for, to be measured and run against ui-parity.
|
||||
# The picture following an edit, 11-14 (raea-feed b7e1514, blitz/scene-timeline.sh: the feed's sample room with
|
||||
# its crate in a sequence, the playhead in the crate's span, the crate's sequence carried off it and back, in a
|
||||
# headless 960x620 window). Before, the stage showed an edit only when the file written with it opened again,
|
||||
# about 1,050 ms after the release. Now the edit goes to the stage as props as it is let go (__raeaSequences:
|
||||
# each named sequence's start and length, which a Sequence takes over its own until that file has opened),
|
||||
# and a paused stage seeks its frame again so it draws them. Captures run back to back through each edit; the
|
||||
# first with the change came back within, over 16 edits:
|
||||
# 81 to 113 ms, median 88 (each counts the capture's own read back, about 78 ms, so the change is sooner)
|
||||
# and 15 of the 16 within 100 ms. The playhead kept its frame through every reopening (one pixel, 678, in all
|
||||
# 16), where it used to jump back to frame 0 and then to its frame; a clip cut where the composition ends kept
|
||||
# the length its code says when carried back (54 frames before, 60 now). Left to the engine: a paused stage
|
||||
# doesn't draw props set on it until something steps it (Live::set_props; the app seeks to work around it),
|
||||
# and the file opened again holds the stage's thread about a second, a hitch when it is playing.
|
||||
# Not yet: RAEA_FINE_RESTYLE measured, and layout_out and paint skipping what didn't change.
|
||||
|
||||
Rule: TL14. Watch, Listen and Scene are one timeline
|
||||
Scenario: TL14a. Watch
|
||||
Then a film in the feed opens with the timeline under it: the render's own reference (frames, waveform,
|
||||
words) when it has no composition, the composition's tracks when it has, edited in place (no separate editor)
|
||||
|
||||
Scenario: TL14b. Listen
|
||||
Then a sound in the feed has the same timeline: its stems as sound tracks, notes and parts as clips where
|
||||
raea made the music, with TL8's tools
|
||||
|
||||
Scenario: TL14c. Scene
|
||||
Then a 3D scene in the feed has the same timeline: its animation clips, cameras' cuts and keyed props as
|
||||
tracks, the stage as its picture, with TL5's keys on any animatable prop
|
||||
@@ -43,6 +43,26 @@ impl EditResolve {
|
||||
let imp = named.canonicalize().map(raea_io_home::plain).unwrap_or_else(|_| named.to_path_buf());
|
||||
imp.starts_with(&self.0.work) && !imp.components().any(|c| c.as_os_str() == "node_modules")
|
||||
}
|
||||
|
||||
/// A package's import of the SDK by its names ("raea", "raea/<module>", "@raea/<package>"): the work folder's copy
|
||||
/// of that module, where the edit's own imports of it were pointed (runtime/bundle's rewrite_into: sdk/raea/src's
|
||||
/// files at motion/, a package's at <package>/ beside it), so a package and the composition share one SDK and its
|
||||
/// hooks read the Clock the engine drives. A package isn't rewritten, so its import resolved nothing from its own
|
||||
/// folder and Rolldown left `raea` an outside global: "Can't find variable: raea" before the first frame (#151)
|
||||
fn sdk_copy(&self, spec: &str) -> Option<PathBuf> {
|
||||
if !(spec == "raea" || spec.starts_with("raea/") || spec.starts_with("@raea/")) {
|
||||
return None;
|
||||
}
|
||||
// sdk/react/js's grandparent
|
||||
let sdk = self.0.js.ancestors().nth(2)?;
|
||||
let f = raea_io_home::sdk::resolve(sdk, spec)?;
|
||||
let mut parts = f.strip_prefix(sdk).ok()?.components();
|
||||
let pkg = parts.next()?.as_os_str().to_string_lossy().into_owned();
|
||||
// its src/
|
||||
parts.next()?;
|
||||
let copy = self.0.work.join(if pkg == "raea" { "motion" } else { pkg.as_str() }).join(parts.as_path());
|
||||
copy.is_file().then_some(copy)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -128,6 +148,12 @@ impl Plugin for EditResolve {
|
||||
}
|
||||
}
|
||||
}
|
||||
// a package importing the SDK: the copy the edit's own sources use (the edit's own were pointed at it already)
|
||||
if !self.from_edit(imp) {
|
||||
if let Some(f) = self.sdk_copy(spec) {
|
||||
return Ok(Some(HookResolveIdOutput::from_id(f.to_string_lossy().as_ref())));
|
||||
}
|
||||
}
|
||||
let bare = spec.starts_with('@') || spec.starts_with(|c: char| c.is_ascii_lowercase());
|
||||
if !bare || spec.starts_with("@raea/") || spec.contains(':') {
|
||||
return Ok(None);
|
||||
|
||||
@@ -212,3 +212,44 @@ fn bundles_a_composition_with_the_persons_plugins() {
|
||||
assert!(b.js.contains("EDIT_BOTH") && !b.js.contains("PLUGIN_BOTH"), "the edit's own copy first");
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
/// A package that imports the SDK ("raea", "raea/<module>") gets the work folder's copy of it, the one the edit's own
|
||||
/// sources were pointed at, so the package's hooks read the same Clock (#151: a package in the project's node_modules
|
||||
/// importing `raea` was refused, "Can't find variable: raea", while the same file imported by a relative path drew).
|
||||
#[test]
|
||||
fn a_package_importing_the_sdk_gets_the_work_folders_copy() {
|
||||
let d = std::env::temp_dir().join(format!("raea-bundle-pkg-sdk-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
let w = |p: &str, s: &str| {
|
||||
let f = d.join(p);
|
||||
std::fs::create_dir_all(f.parent().unwrap()).unwrap();
|
||||
std::fs::write(f, s).unwrap();
|
||||
};
|
||||
// raea's home: the SDK's sources and their names, the engine's node_modules under sdk/react/js
|
||||
w("home/sdk/tsconfig.base.json", r#"{ "compilerOptions": { "paths": { "raea": ["./raea/src/prelude.ts"], "raea/clock": ["./app/src/clock.tsx"], "raea/*": ["./raea/src/*"], "@raea/app": ["./app/src/index.ts"], "@raea/app/*": ["./app/src/*"] } } }"#);
|
||||
w("home/sdk/raea/src/prelude.ts", "export const prelude = 'SDK_ORIGINAL_PRELUDE';\n");
|
||||
w("home/sdk/raea/src/easing.ts", "export const easing = 'SDK_ORIGINAL_EASING';\n");
|
||||
w("home/sdk/app/src/clock.tsx", "export const clock = 'SDK_ORIGINAL_CLOCK';\n");
|
||||
w("home/sdk/react/js/node_modules/react/package.json", r#"{ "name": "react", "main": "index.js" }"#);
|
||||
w("home/sdk/react/js/node_modules/react/index.js", "export const version = 'ENGINE_REACT';\n");
|
||||
// the work folder raea makes: the SDK copied (motion/ and app/), the edit's source copied with its imports pointed
|
||||
w("work/motion/prelude.ts", "export const prelude = 'WORK_PRELUDE';\n");
|
||||
w("work/motion/easing.ts", "export const easing = 'WORK_EASING';\n");
|
||||
w("work/app/clock.tsx", "export const clock = 'WORK_CLOCK';\n");
|
||||
w("work/src/edit.tsx", "import { prelude } from '../motion/prelude';\nimport { bar } from 'vk-parts';\n(globalThis as any).out = [prelude, bar];\n");
|
||||
w("work/entry.ts", "import './src/edit.tsx';\n");
|
||||
// the edit's own package, importing the SDK by its names
|
||||
w("edit/node_modules/vk-parts/package.json", r#"{ "name": "vk-parts", "version": "0.0.1", "main": "index.tsx", "peerDependencies": { "raea": "*" } }"#);
|
||||
w("edit/node_modules/vk-parts/index.tsx", "import { prelude } from 'raea';\nimport { clock } from 'raea/clock';\nimport { easing } from 'raea/easing';\nexport const bar = [prelude, clock, easing].join(' ');\n");
|
||||
#[cfg(unix)]
|
||||
std::os::unix::fs::symlink(d.join("home/sdk/react/js/node_modules"), d.join("work/node_modules")).unwrap();
|
||||
let edit = raea_bundle::edit::Edit { dir: d.join("edit"), js: d.join("home/sdk/react/js"), work: d.join("work") };
|
||||
let b = raea_bundle::bundle_with(&d.join("work/entry.ts"), raea_bundle::Options { edit: Some(edit), ..Default::default() }).expect("bundles");
|
||||
for want in ["WORK_PRELUDE", "WORK_CLOCK", "WORK_EASING"] {
|
||||
assert!(b.js.contains(want), "{want}: the package's SDK import is the work folder's copy: {}", b.js);
|
||||
}
|
||||
assert!(!b.js.contains("SDK_ORIGINAL"), "one SDK, the copy, not its sources: {}", b.js);
|
||||
// one copy of each module for the edit and the package alike
|
||||
assert_eq!(b.js.matches("WORK_PRELUDE").count(), 1, "{}", b.js);
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
@@ -64,7 +64,7 @@ pub fn context(project: Option<&str>) -> R<String> {
|
||||
let dir = brief_path.parent().unwrap_or(Path::new(".")).to_path_buf();
|
||||
let taste_dir = raea_app_direction::check::taste_dir();
|
||||
// a cheap doctor (file reads and git config): CONTEXT_STALE when this project or the agent's skill is from another raea
|
||||
let stale = raea_app_workspace::doctor::findings(&dir, &skill::agents(), &skill::version());
|
||||
let stale = raea_app_workspace::doctor::findings(&dir, &tools::agent_skills::agents(), &skill::version());
|
||||
let stale = match stale.first() {
|
||||
Some(f) => format!("CONTEXT_STALE raea doctor finds {} thing(s), first: {} (raea doctor --fix)\n\n", stale.len(), f.says),
|
||||
None => String::new(),
|
||||
@@ -82,7 +82,7 @@ pub fn next(args: &[String]) -> R<String> {
|
||||
let brief_path = brief_at(args.first().map(String::as_str).unwrap_or("."))?;
|
||||
let l = spec::load_brief_ts(&brief_path)?;
|
||||
let dir = brief_path.parent().unwrap_or(Path::new(".")).to_path_buf();
|
||||
let stale = raea_app_workspace::doctor::findings(&dir, &skill::agents(), &skill::version()).len();
|
||||
let stale = raea_app_workspace::doctor::findings(&dir, &tools::agent_skills::agents(), &skill::version()).len();
|
||||
Ok(raea_app_workspace::next::text(&dir, &raea_app_workspace::next::Brief { needs: l.missing, modes: l.modes }, stale))
|
||||
}
|
||||
|
||||
|
||||
@@ -22,8 +22,10 @@ raea show [--title T] --question Q1 [--preview FILE] --choice A [--preview FILE]
|
||||
It lands in the person's feed with a notice and the window stays where they are; --open brings the window up on it
|
||||
(only when they're waiting on it).
|
||||
FILE: stills (several make a storyboard), a video, a sound, a NAME.script.ts or .md, or a .tsx (an interactive
|
||||
artifact; one of the project's compositions opens in its editor). P: the project's id, title or Workspace/project;
|
||||
else the one this folder is in. Who's showing it: --as NAME [--role ROLE] [--inbox NAME], else your harness's.
|
||||
artifact; one of the project's compositions opens in its editor). P: Workspace/id (ids as raea workspace --json
|
||||
lists them), a folder in the project, or a Copy reference from the app; a title only when it's the only one and
|
||||
this folder isn't in another project. Else the one this folder is in. Who's showing it: --as NAME [--role ROLE]
|
||||
[--inbox NAME], else your harness's.
|
||||
raea show --on ITEM --working ID... [--ask TEXT]... [--status S [--states S1,S2...]] | --done ID... [--note LINE] [--sub NAME]
|
||||
raea show --on ITEM --working ID --sign N --clip FILE --render HASH
|
||||
raea show FILE... --replaces ITEM --done ID...
|
||||
|
||||
+10
-34
@@ -4,32 +4,12 @@
|
||||
//! `raea --version` the agent reads `raea skill` instead.
|
||||
use super::*;
|
||||
|
||||
pub const USAGE: &str = "raea skill [NAME] [--reference cli|feed|files|sdk] | raea skills install --agent claude|codex|kimi|gemini [--pin MOVE]... [--no-mcp] [--no-hooks] (the agent skill this raea ships, for its version, which raea --version prints: an agent whose copy names another version reads this; install puts raea's skills where that agent reads skills, adds the blender MCP server unless --no-mcp, makes each --pin MOVE a /MOVE of its own, and adds raea's hooks to that agent unless --no-hooks (raea hook AGENT: media opened in the Mac's viewer goes to raea show, and the quick check after a composition is saved); a skill folder that's a link is left as it is)";
|
||||
|
||||
/// Where each agent reads a person's skills, one folder per skill holding SKILL.md. Checked by hand on 11-05:
|
||||
/// claude: ~/.claude/skills (Claude Code's docs); codex: ~/.agents/skills (developers.openai.com/codex/skills, the user
|
||||
/// scope; older builds read ~/.codex/skills); kimi: $KIMI_CODE_HOME/skills, else ~/.kimi-code/skills (kimi 2.3.3's own
|
||||
/// binary; it also reads ~/.agents/skills and ~/.claude/skills); gemini: ~/.gemini/skills (geminicli.com/docs/cli/skills).
|
||||
fn target(agent: &str) -> R<PathBuf> {
|
||||
let home = tools::agent_mcp::user_home()?;
|
||||
Ok(match agent {
|
||||
"claude" => home.join(".claude/skills"),
|
||||
"codex" => home.join(".agents/skills"),
|
||||
"kimi" => std::env::var_os("KIMI_CODE_HOME").filter(|v| !v.is_empty()).map(PathBuf::from).unwrap_or_else(|| home.join(".kimi-code")).join("skills"),
|
||||
"gemini" => home.join(".gemini/skills"),
|
||||
a => return Err(format!("no agent {a:?}: claude, codex, kimi or gemini")),
|
||||
})
|
||||
}
|
||||
|
||||
/// Each agent and the folder it reads skills from, for `raea doctor` (an agent with no folder is skipped).
|
||||
pub fn agents() -> Vec<(&'static str, PathBuf)> {
|
||||
["claude", "codex", "kimi", "gemini"].into_iter().filter_map(|a| target(a).ok().map(|t| (a, t))).collect()
|
||||
}
|
||||
pub const USAGE: &str = "raea skill [NAME] [--reference cli|feed|files|sdk] | raea skills install --agent claude|codex|kimi|gemini|grokbot [--pin MOVE]... [--no-mcp] [--no-hooks] (the agent skill this raea ships, for its version, which raea --version prints: an agent whose copy names another version reads this; install puts raea's skills where that agent reads skills, adds the blender MCP server unless --no-mcp, makes each --pin MOVE a /MOVE of its own, and adds raea's hooks to that agent unless --no-hooks (raea hook AGENT: media opened in the Mac's viewer goes to raea show, and the quick check after a composition is saved); a skill folder that's a link is left as it is; grokbot, the Grok Bot app, keeps its skills on its own computer, so its copy is staged on this Mac (RAEA_GROKBOT_HOME moves it) with the grokbot:// links that finish it in Grok Bot, and gets no hooks or MCP server)";
|
||||
|
||||
/// `raea doctor [--fix] [DIR]` (SK10): what doesn't match this raea, an agent's skill reinstalled by --fix.
|
||||
pub fn doctor(args: &[String]) -> R<String> {
|
||||
let again = |agent: &str| install(&["install".into(), "--agent".into(), agent.into(), "--no-mcp".into()]);
|
||||
raea_app_workspace::doctor::doctor(args, &agents(), &version(), &again)
|
||||
raea_app_workspace::doctor::doctor(args, &tools::agent_skills::agents(), &version(), &again)
|
||||
}
|
||||
|
||||
/// This raea's version: the release's (share/raea/VERSION), or the crate's for a build from a checkout.
|
||||
@@ -102,14 +82,14 @@ fn copy(from: &Path, to: &Path) -> R<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `raea skills install --agent claude|codex|kimi|gemini`: raea's skills, stamped with this version, where that agent
|
||||
/// reads them; each replaces the copy that was there, but a link (a checkout of raea-skills) is the person's to keep.
|
||||
/// `raea skills install --agent claude|codex|kimi|gemini|grokbot`: raea's skills, stamped with this version, where that
|
||||
/// agent reads them; each replaces the copy that was there, but a link (a checkout of raea-skills) is the person's to keep.
|
||||
pub fn install(args: &[String]) -> R<String> {
|
||||
if args.first().map(String::as_str) != Some("install") {
|
||||
return Err(format!("usage: {USAGE}"));
|
||||
}
|
||||
let agent = args.iter().position(|a| a == "--agent").and_then(|i| args.get(i + 1)).ok_or("which agent: --agent claude|codex|kimi|gemini")?;
|
||||
let to = target(agent)?;
|
||||
let agent = args.iter().position(|a| a == "--agent").and_then(|i| args.get(i + 1)).ok_or("which agent: --agent claude|codex|kimi|gemini|grokbot")?;
|
||||
let to = tools::agent_skills::folder(agent)?;
|
||||
let (from, v) = (shipped()?, version());
|
||||
let mut out = String::new();
|
||||
for name in installed_names()? {
|
||||
@@ -133,6 +113,8 @@ pub fn install(args: &[String]) -> R<String> {
|
||||
out += &tools::agent_mcp::pin(&to, m, &v)?;
|
||||
}
|
||||
}
|
||||
// Grok Bot (SK13): no hooks or MCP server; its copy gets a preface and the links that finish it (agent_grokbot.rs)
|
||||
if agent == "grokbot" { return tools::agent_grokbot::stage(&to, out); }
|
||||
// every agent's hooks (A5d, SK10), in its own config: --no-hooks leaves it alone
|
||||
if !args.iter().any(|a| a == "--no-hooks") { out += &tools::agent_hooks::install(agent)?; }
|
||||
// the MCP servers raea offers (SK11): blender, for a running Blender; --no-mcp leaves the agent's servers alone
|
||||
@@ -162,13 +144,7 @@ mod tests {
|
||||
assert!(skill(&["raea-bevy".into()]).unwrap_err().contains("3d.md") && installed_names().unwrap() == ["raea"]);
|
||||
assert!(skill(&["../x".into()]).is_err());
|
||||
assert!(skill(&["--reference".into(), "../../x".into()]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn install_targets_each_agents_folder() {
|
||||
assert!(target("claude").unwrap().ends_with(".claude/skills"));
|
||||
assert!(target("codex").unwrap().ends_with(".agents/skills"));
|
||||
assert!(target("gemini").unwrap().ends_with(".gemini/skills"));
|
||||
assert!(target("cursor").is_err());
|
||||
// Grok Bot's Add new skill takes a file of at most 256 KB: the shipped SKILL.md with its preface fits
|
||||
assert!(tools::agent_grokbot::with_preface(&core, Path::new("/h")).len() < tools::agent_grokbot::MAX_SKILL);
|
||||
}
|
||||
}
|
||||
@@ -46,6 +46,8 @@ image = { version = "0.25", default-features = false, features = ["png"] }
|
||||
serde_json = "1"
|
||||
# the live stage: <img data-raea-stage> (raea-page-stage)
|
||||
raea-page-stage = { path = "../stage" }
|
||||
# a page's interaction sounds: sound.fire (raea-page-sound, docs/hardware.feature HW0)
|
||||
raea-page-sound = { path = "../sound" }
|
||||
# Rune layers in the page: what's under a data-raea-renderer="rune" element drawn by Rune on this device (T6c)
|
||||
raea-rune-slots = { path = "../../rune/slots" }
|
||||
# the window build turns bevy_winit on for every Bevy app in the process; the stage's engine is told to leave it out (main.rs)
|
||||
|
||||
@@ -6,7 +6,9 @@
|
||||
//! it, bevy_ui's kinds. --root: where the page's own-origin fetches are read from (RAEA_PAGE_ROOT). --size: the
|
||||
//! window, default 1440x900. RAEA_PAGE_BRP_PORT (default: a free one), RAEA_PAGE_MCP_PORT (default 7477; 0: none),
|
||||
//! RAEA_PAGE_PICK=0: the page's pointers and keys dispatched by the host (page::input) instead of through raea-page's
|
||||
//! picking route, the default. The page's `<img data-raea-stage>` plays a composition live (raea-page-stage).
|
||||
//! picking route, the default. RAEA_FINE_RESTYLE=0: an attribute change restyles its element's parent's whole subtree
|
||||
//! (Blitz's own way; the host's default is the fine restyle, docs/timeline.feature TL13a). The page's
|
||||
//! `<img data-raea-stage>` plays a composition live (raea-page-stage).
|
||||
//! --chrome inset: the page under a transparent title bar, its title area moving the window (raea-page-window).
|
||||
//! --window (built with the `window` feature): on screen, a window of its own that closes the app (raea's desktop app;
|
||||
//! RAEA_PAGE_HOST sends the page's /host/* to the feed's host: raea-page-net).
|
||||
@@ -63,6 +65,14 @@ fn main() {
|
||||
eprintln!("raea-page-host: {e}");
|
||||
std::process::exit(2);
|
||||
});
|
||||
// a page's attribute set or cleared restyles what Stylo's invalidation finds, and each ancestor itself, not the
|
||||
// element's parent's whole subtree (vendor/blitz-dom mutator.rs): ui-parity's 271 cases come out the same case by
|
||||
// case, and a 400-clip timeline drag in raea feed's window went from 38-41 to 48-50 frames a second
|
||||
// (docs/timeline.feature TL13a). RAEA_FINE_RESTYLE=0 restyles the parent's whole subtree, as before. Set here,
|
||||
// before any thread starts, as --root's RAEA_PAGE_ROOT is.
|
||||
if std::env::var_os("RAEA_FINE_RESTYLE").is_none() {
|
||||
unsafe { std::env::set_var("RAEA_FINE_RESTYLE", "1") }
|
||||
}
|
||||
// headless (the benches, raea app check): the system's clipboard, files, dialogs and browser stay untouched (T2d)
|
||||
if !a.window {
|
||||
raea_io_os::set_headless();
|
||||
@@ -105,6 +115,8 @@ fn main() {
|
||||
app.add_plugins(HostPlugin { size: a.size, double_click: Duration::from_millis(500), picking })
|
||||
.add_plugins(brp::plugins(brp::port(), |r| r))
|
||||
.add_plugins(stage::StagePlugin)
|
||||
// a page's interaction sounds, fired on a mixer of its own (docs/hardware.feature HW0)
|
||||
.add_plugins(raea_page_sound::PageSoundPlugin)
|
||||
// the clipboard, links, notifications, the dock badge, raea:// links and the chrome (raea-page-window)
|
||||
.add_plugins(raea_page_window::DesktopPlugin { chrome: a.chrome, live: a.window });
|
||||
raea_page_host::page_plugins(&mut app, picking);
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
[package]
|
||||
name = "raea-page-sound"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "FSL-1.1-ALv2"
|
||||
publish = false
|
||||
description = "A page's interaction sounds: the sound.fire host call, raea/tone events played now on a mixer of the page's own (docs/hardware.feature HW0)"
|
||||
|
||||
[dependencies]
|
||||
bevy = { version = "=0.20.0", default-features = false, features = ["std"] }
|
||||
raea-runtime-js = { path = "../../../runtime/js" }
|
||||
raea-sys-mix = { path = "../../../systems/mix" }
|
||||
serde_json = "1"
|
||||
@@ -0,0 +1,111 @@
|
||||
//! A page's interaction sounds (docs/hardware.feature HW0): raea/tone events a page fires, played now on a mixer of
|
||||
//! the page's own, the same mixer core (Firewheel) a render bounces and the stage plays. raea's window has no Web Audio
|
||||
//! graph (sdk/ui/src/platform/audio.ts), so this is how a page in it is heard:
|
||||
//!
|
||||
//! sound.fire {graph?: string, evs: [..]} -> null
|
||||
//! sound.report {} -> {fired, late}
|
||||
//!
|
||||
//! `graph` is raea/tone's graph JSON (as `<audio data-tone-graph>` holds it), sent when it changed; `evs` are its events,
|
||||
//! each at its own time ("t", seconds) after now. The call answers at once; the mixer runs on a thread of its own,
|
||||
//! opens the device on the first fire and stops its stream after IDLE with nothing fired (the stage's rest).
|
||||
|
||||
use std::sync::mpsc::{Receiver, RecvTimeoutError, Sender, channel};
|
||||
use std::sync::{Mutex, OnceLock};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use bevy::prelude::*;
|
||||
use raea_runtime_js::calls::HostCalls;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// How long the mixer runs with nothing fired before its stream stops.
|
||||
const IDLE: Duration = Duration::from_secs(10);
|
||||
|
||||
enum Msg {
|
||||
Fire(Option<String>, Vec<Value>),
|
||||
Report(Sender<Value>),
|
||||
}
|
||||
|
||||
/// The mixer's thread, started by the first call.
|
||||
fn mixer() -> &'static Mutex<Sender<Msg>> {
|
||||
static TX: OnceLock<Mutex<Sender<Msg>>> = OnceLock::new();
|
||||
TX.get_or_init(|| {
|
||||
let (tx, rx) = channel();
|
||||
let _ = std::thread::Builder::new().name("raea page sound".into()).spawn(move || run(rx));
|
||||
Mutex::new(tx)
|
||||
})
|
||||
}
|
||||
|
||||
fn run(rx: Receiver<Msg>) {
|
||||
let mut live: Option<raea_sys_mix::live::Live> = None;
|
||||
let mut failed = false;
|
||||
let (mut fired, mut last) = (0u64, Instant::now());
|
||||
loop {
|
||||
match rx.recv_timeout(Duration::from_millis(100)) {
|
||||
Ok(Msg::Fire(graph, evs)) => {
|
||||
if live.is_none() && !failed {
|
||||
match raea_sys_mix::live::Live::open() {
|
||||
Ok(l) => live = Some(l),
|
||||
Err(e) => {
|
||||
failed = true;
|
||||
eprintln!("raea page sound: no output device, the page's sounds stay silent ({e})");
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(l) = live.as_mut() {
|
||||
l.fire(graph.as_deref(), &evs);
|
||||
fired += 1;
|
||||
last = Instant::now();
|
||||
}
|
||||
}
|
||||
Ok(Msg::Report(back)) => {
|
||||
let late = live.as_ref().map_or(0, |l| l.late_events());
|
||||
let _ = back.send(json!({ "fired": fired, "late": late }));
|
||||
}
|
||||
Err(RecvTimeoutError::Timeout) => {
|
||||
if let Some(l) = live.as_mut() {
|
||||
l.tend();
|
||||
if last.elapsed() > IDLE {
|
||||
l.rest();
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(RecvTimeoutError::Disconnected) => return,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn send(m: Msg) -> Result<(), String> {
|
||||
mixer().lock().map_err(|_| "the page's mixer stopped".to_string())?.send(m).map_err(|_| "the page's mixer stopped".to_string())
|
||||
}
|
||||
|
||||
/// The calls, onto the page's HostCalls.
|
||||
fn calls(mut calls: ResMut<HostCalls>) {
|
||||
calls
|
||||
.on("sound.fire", |_w, a, answer| {
|
||||
let graph = a.get("graph").and_then(Value::as_str).map(str::to_string);
|
||||
let evs = a.get("evs").and_then(Value::as_array).cloned().unwrap_or_default();
|
||||
match send(Msg::Fire(graph, evs)) {
|
||||
Ok(()) => answer.ok(Value::Null),
|
||||
Err(e) => answer.err(e),
|
||||
}
|
||||
})
|
||||
.on("sound.report", |_w, _a, answer| {
|
||||
let (tx, rx) = channel();
|
||||
if let Err(e) = send(Msg::Report(tx)) {
|
||||
return answer.err(e);
|
||||
}
|
||||
std::thread::spawn(move || match rx.recv_timeout(Duration::from_secs(2)) {
|
||||
Ok(v) => answer.ok(v),
|
||||
Err(_) => answer.err("the page's mixer didn't answer"),
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/// The page's sound calls (HW0a).
|
||||
pub struct PageSoundPlugin;
|
||||
|
||||
impl Plugin for PageSoundPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.init_resource::<HostCalls>().add_systems(Startup, calls);
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@
|
||||
//! notify.permission -> bool macOS's prompt, or its answer if already given
|
||||
//! dock.badge {text} the Dock icon's badge, on Windows the taskbar button's overlay ("" clears it)
|
||||
//! app.urls -> string[] raea:// links opened since the last ask, the app brought to the front for each
|
||||
//! app.drops -> {over, dropped} files dragged from the Finder: whether some are over the window, the paths dropped since the last ask
|
||||
//! native.log -> {...} what was done, for tests
|
||||
//!
|
||||
//! Live only on screen (--window) and without RAEA_NO_OPEN=1: otherwise every call is recorded and answered as if done,
|
||||
@@ -39,6 +40,8 @@ struct Log {
|
||||
static LOG: Mutex<Option<Log>> = Mutex::new(None);
|
||||
/// raea:// links that arrived and the page hasn't read yet (filled by the Apple event handler, on the main thread).
|
||||
static URLS: Mutex<Vec<String>> = Mutex::new(Vec::new());
|
||||
/// Files dragged onto the window: whether some are over it now, and the paths dropped the page hasn't read yet (drops).
|
||||
static DROPS: Mutex<(bool, Vec<String>)> = Mutex::new((false, Vec::new()));
|
||||
|
||||
fn log<T>(f: impl FnOnce(&mut Log) -> T) -> T {
|
||||
f(LOG.lock().unwrap().get_or_insert_with(Log::default))
|
||||
@@ -58,12 +61,12 @@ pub struct NativePlugin {
|
||||
impl Plugin for NativePlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
let live = self.live && std::env::var("RAEA_NO_OPEN").as_deref() != Ok("1");
|
||||
app.insert_resource(Live(live)).init_resource::<Queue>().init_resource::<HostCalls>().add_systems(Startup, (calls, start)).add_systems(Update, drain);
|
||||
app.insert_resource(Live(live)).init_resource::<Queue>().init_resource::<HostCalls>().add_systems(Startup, (calls, start)).add_systems(Update, (drops, drain).chain());
|
||||
}
|
||||
}
|
||||
|
||||
fn calls(mut calls: ResMut<HostCalls>) {
|
||||
for name in ["clipboard.write", "clipboard.read", "app.open", "notify", "notify.permission", "dock.badge", "app.urls", "native.log"] {
|
||||
for name in ["clipboard.write", "clipboard.read", "app.open", "notify", "notify.permission", "dock.badge", "app.urls", "app.drops", "native.log"] {
|
||||
calls.on(name, move |w, args, answer| w.resource::<Queue>().0.lock().unwrap().push(Job(name.to_string(), args, answer)));
|
||||
}
|
||||
}
|
||||
@@ -75,6 +78,23 @@ fn start(live: Res<Live>, _main: NonSendMarker) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Bevy's drag-and-drop messages (winit's), kept for app.drops: live or not, a file dropped on the window is the
|
||||
/// person's own act, never something a call does to them.
|
||||
fn drops(mut evs: MessageReader<bevy::window::FileDragAndDrop>) {
|
||||
use bevy::window::FileDragAndDrop as D;
|
||||
for e in evs.read() {
|
||||
let mut d = DROPS.lock().unwrap();
|
||||
match e {
|
||||
D::HoveredFile { .. } => d.0 = true,
|
||||
D::HoveredFileCanceled { .. } => d.0 = false,
|
||||
D::DroppedFile { path_buf, .. } => {
|
||||
d.0 = false;
|
||||
d.1.push(path_buf.to_string_lossy().into_owned());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn drain(world: &mut World) {
|
||||
let jobs = std::mem::take(&mut *world.resource::<Queue>().0.lock().unwrap());
|
||||
if jobs.is_empty() {
|
||||
@@ -150,6 +170,11 @@ fn run(live: bool, name: &str, a: &Value, answer: Answer) {
|
||||
log(|l| l.urls.extend(urls.iter().cloned()));
|
||||
answer.ok(json!(urls))
|
||||
}
|
||||
"app.drops" => {
|
||||
let mut d = DROPS.lock().unwrap();
|
||||
let dropped = std::mem::take(&mut d.1);
|
||||
answer.ok(json!({"over": d.0, "dropped": dropped}))
|
||||
}
|
||||
"native.log" => answer.ok(log(|l| json!({"live": live, "clipboard": l.clipboard, "opened": l.opened, "notified": l.notified, "badge": l.badge, "urls": l.urls}))),
|
||||
_ => answer.err(format!("no native call {name}")),
|
||||
}
|
||||
@@ -379,3 +404,30 @@ mod tests {
|
||||
assert!(e.contains("raea.app"), "{e}");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod drop_tests {
|
||||
use super::{DROPS, drops};
|
||||
use bevy::prelude::*;
|
||||
use bevy::window::FileDragAndDrop as D;
|
||||
|
||||
/// What app.drops answers: files over the window while they're dragged, then the paths once, as they're dropped.
|
||||
#[test]
|
||||
fn a_finder_drag_says_over_then_hands_its_paths_once() {
|
||||
let mut app = App::new();
|
||||
app.add_message::<D>().add_systems(Update, drops);
|
||||
let window = Entity::PLACEHOLDER;
|
||||
app.world_mut().write_message(D::HoveredFile { window, path_buf: "/tmp/a.mov".into() });
|
||||
app.update();
|
||||
assert!(DROPS.lock().unwrap().0, "over while dragged");
|
||||
app.world_mut().write_message(D::HoveredFileCanceled { window });
|
||||
app.update();
|
||||
assert!(!DROPS.lock().unwrap().0, "not over once it leaves");
|
||||
app.world_mut().write_message(D::DroppedFile { window, path_buf: "/tmp/a.mov".into() });
|
||||
app.world_mut().write_message(D::DroppedFile { window, path_buf: "/tmp/b c.png".into() });
|
||||
app.update();
|
||||
let mut d = DROPS.lock().unwrap();
|
||||
assert!(!d.0);
|
||||
assert_eq!(std::mem::take(&mut d.1), vec!["/tmp/a.mov".to_string(), "/tmp/b c.png".to_string()]);
|
||||
}
|
||||
}
|
||||
@@ -45,7 +45,7 @@ fn meshes(
|
||||
q: Query<(Entity, &Mesh3d, &MeshMaterial3d<StandardMaterial>, Has<bevy::mesh::skinning::SkinnedMesh>, Has<bevy::mesh::morph::MeshMorphWeights>), Pending>,
|
||||
mats: Res<Assets<StandardMaterial>>,
|
||||
mut assets: ResMut<Assets<Mesh>>,
|
||||
mut copies: Local<HashMap<AssetId<Mesh>, Option<Handle<Mesh>>>>,
|
||||
mut copies: Local<HashMap<(AssetId<Mesh>, bool), Option<Handle<Mesh>>>>,
|
||||
mut said: Local<bool>,
|
||||
) {
|
||||
if on.is_empty() {
|
||||
@@ -73,16 +73,18 @@ fn meshes(
|
||||
}
|
||||
// each mesh's traceable form, made once: itself when it's in Solari's layout, else a copy; None when it can't
|
||||
// be traced (not triangles, no normals, or its data only on the GPU)
|
||||
let h = match copies.get(&m.0.id()) {
|
||||
// (a copy by whether its material has a normal map: only that reads the tangents)
|
||||
let mapped = mats.get(&mat.0).is_some_and(|m| m.normal_map_texture.is_some());
|
||||
let h = match copies.get(&(m.0.id(), mapped)) {
|
||||
Some(h) => h.clone(),
|
||||
None => {
|
||||
let Some(t) = assets.get(&m.0).map(traceable) else { continue };
|
||||
let Some(t) = assets.get(&m.0).map(|src| traceable(src, mapped)) else { continue };
|
||||
let h = match t {
|
||||
Some(Traceable::Same) => Some(m.0.clone()),
|
||||
Some(Traceable::Copy(mesh)) => Some(assets.add(mesh)),
|
||||
None => None,
|
||||
};
|
||||
copies.insert(m.0.id(), h.clone());
|
||||
copies.insert((m.0.id(), mapped), h.clone());
|
||||
h
|
||||
}
|
||||
};
|
||||
@@ -104,7 +106,11 @@ enum Traceable {
|
||||
Copy(Mesh),
|
||||
}
|
||||
|
||||
fn traceable(src: &Mesh) -> Option<Traceable> {
|
||||
/// `src` in Solari's layout. A mesh with no tangents of its own gets MikkTSpace's only when `mapped` (its material has
|
||||
/// a normal map: the one thing Solari reads a tangent for, scene/bindings.wesl); else any unit vector across each
|
||||
/// normal does, as the layout needs the attribute. MikkTSpace on every traced mesh was most of a ray-traced render's
|
||||
/// wait for its models (one thread, 0.36 s of a 3.8 s render of a 2.5 s shot).
|
||||
fn traceable(src: &Mesh, mapped: bool) -> Option<Traceable> {
|
||||
if src.primitive_topology() != PrimitiveTopology::TriangleList {
|
||||
return None;
|
||||
}
|
||||
@@ -133,7 +139,12 @@ fn traceable(src: &Mesh) -> Option<Traceable> {
|
||||
out.insert_indices(Indices::U32(idx));
|
||||
match src.attribute(Mesh::ATTRIBUTE_TANGENT) {
|
||||
Some(t) => out.insert_attribute(Mesh::ATTRIBUTE_TANGENT, t.clone()),
|
||||
None => out.generate_tangents().ok()?,
|
||||
None if mapped => out.generate_tangents().ok()?,
|
||||
None => {
|
||||
let VertexAttributeValues::Float32x3(normals) = out.attribute(Mesh::ATTRIBUTE_NORMAL)? else { return None };
|
||||
let across: Vec<[f32; 4]> = normals.iter().map(|n| Vec3::from(*n).any_orthonormal_vector().extend(1.0).to_array()).collect();
|
||||
out.insert_attribute(Mesh::ATTRIBUTE_TANGENT, across);
|
||||
}
|
||||
}
|
||||
Some(Traceable::Copy(out))
|
||||
}
|
||||
@@ -151,6 +162,24 @@ mod tests {
|
||||
m
|
||||
}
|
||||
|
||||
/// A mesh with no tangents and no normal map gets a unit tangent across each normal without MikkTSpace (which
|
||||
/// needs UVs' derivatives and was most of a render's wait for its models); with a normal map, MikkTSpace's.
|
||||
#[test]
|
||||
fn a_mesh_without_a_normal_map_gets_tangents_across_its_normals() {
|
||||
let tangents = |mapped| match traceable(&quad(RenderAssetUsages::default()), mapped) {
|
||||
Some(Traceable::Copy(m)) => match m.attribute(Mesh::ATTRIBUTE_TANGENT) {
|
||||
Some(VertexAttributeValues::Float32x4(t)) => t.clone(),
|
||||
_ => panic!("no tangents"),
|
||||
},
|
||||
_ => panic!("not a copy"),
|
||||
};
|
||||
for t in tangents(false) {
|
||||
let v = Vec3::new(t[0], t[1], t[2]);
|
||||
assert!((v.length() - 1.0).abs() < 1e-5 && v.dot(Vec3::Z).abs() < 1e-5 && t[3] == 1.0, "{t:?}");
|
||||
}
|
||||
assert_eq!(tangents(true).len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_additive_or_multiplying_surface_is_not_traced() {
|
||||
// additive dust cards traced as opaque shaded a sunlit wall; opaque, masked and blended surfaces stay traced
|
||||
@@ -163,9 +192,9 @@ mod tests {
|
||||
// raea-sys-grass's blades: RENDER_WORLD only, their data taken when Bevy extracts them (RR0's film panicked on them)
|
||||
let mut grass = quad(RenderAssetUsages::RENDER_WORLD);
|
||||
let _ = grass.take_gpu_data().expect("a fresh mesh's data can be taken");
|
||||
assert!(traceable(&grass).is_none());
|
||||
assert!(traceable(&grass, true).is_none());
|
||||
// a mesh still in the main world is copied into Solari's layout, its u16 indices widened
|
||||
match traceable(&quad(RenderAssetUsages::default())) {
|
||||
match traceable(&quad(RenderAssetUsages::default()), true) {
|
||||
Some(Traceable::Copy(m)) => assert!(matches!(m.indices(), Some(Indices::U32(v)) if v == &vec![0, 1, 2])),
|
||||
_ => panic!("a readable triangle mesh is traceable"),
|
||||
}
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
[package]
|
||||
name = "raea-io-gen-fit"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "FSL-1.1-ALv2"
|
||||
publish = false
|
||||
description = "A generated model measured and fitted before a scene uses it: raea gen check, and every mesh.generate output of a run fitted by its step's size"
|
||||
|
||||
[dependencies]
|
||||
raea-io-gen-core = { path = "../gen-core" }
|
||||
# the measuring and fitting (raea-core-meshcheck)
|
||||
raea-core-meshcheck = { path = "../../core/meshcheck" }
|
||||
# what gen check finds, as raea's one Finding (docs/direction.feature DR3)
|
||||
raea-core-facts = { path = "../../core/facts" }
|
||||
serde_json = "1"
|
||||
@@ -10,7 +10,7 @@ use raea_core_facts::{Finding, finding};
|
||||
use raea_core_meshcheck::{Glb, Want, check, fix};
|
||||
use serde_json::{Value as J, json};
|
||||
|
||||
use crate::flow::Flow;
|
||||
use raea_io_gen_core::flow::Flow;
|
||||
|
||||
pub const USAGE: &str = "raea gen check MODEL.glb [--h METRES] [--dims W,D,H] [--turn DEG] [--faces N | --seen METRES] [--parts a,b] [--rig] [--solid] [-o FIXED.glb] [--json] (a model measured: size, pivot, facing, triangles, loose pieces, holes, textures, and the Blender script each fault needs; -o writes it fitted)";
|
||||
|
||||
+2
-4
@@ -10,10 +10,8 @@ description = "Generation flows: made.app's models at provider cost, ComfyUI wor
|
||||
raea-io-gen-comfy = { path = "../gen-comfy" }
|
||||
raea-io-gen-core = { path = "../gen-core" }
|
||||
raea-io-home = { path = "../home" }
|
||||
# a generated model measured and fitted after its step (raea gen check; fit.rs)
|
||||
raea-core-meshcheck = { path = "../../core/meshcheck" }
|
||||
# what gen check finds, as raea's one Finding (docs/direction.feature DR3)
|
||||
raea-core-facts = { path = "../../core/facts" }
|
||||
# a generated model measured and fitted after its step (raea gen check)
|
||||
raea-io-gen-fit = { path = "../gen-fit" }
|
||||
serde_json = "1"
|
||||
# image.crop, image.scale, image.stitch, run here (native.rs)
|
||||
image = { version = "0.25", default-features = false, features = ["png", "jpeg", "webp"] }
|
||||
@@ -58,6 +58,7 @@ fn runner<'a>(args: &[String], base: &Path, local: Option<&'a dyn Local>) -> Run
|
||||
r.policy.exact = args.iter().any(|a| a == "--exact");
|
||||
r.policy.comfy_on_replicate = args.iter().any(|a| a == "--comfy-on-replicate") || crate::setting("RAEA_COMFY_ON") .as_deref() == Some("replicate");
|
||||
r.policy.tripo = !args.iter().any(|a| a == "--no-tripo") && crate::tripo::available();
|
||||
r.policy.keys = crate::route::Keys::here();
|
||||
if let Some(l) = local.filter(|_| !args.iter().any(|a| a == "--no-local")) {
|
||||
r.policy.local = l.names();
|
||||
r.local = Some(l);
|
||||
|
||||
+4
-2
@@ -1,10 +1,9 @@
|
||||
//! Generation flows run: route.rs sends each step of a flow to a backend (made.app, fal, Replicate, OpenRouter, a Modal
|
||||
//! endpoint, Fish Audio, a ComfyUI server, or a model the host runs locally) and run.rs makes them, cached by content; cli.rs is
|
||||
//! `raea gen`. The flow format and hosted backends are raea-io-gen-core, ComfyUI import and export raea-io-gen-comfy,
|
||||
//! both re-exported here under their old paths.
|
||||
//! both re-exported here under their old paths, as is fit (raea-io-gen-fit, a generated model measured and fitted).
|
||||
|
||||
pub mod cli;
|
||||
pub mod fit;
|
||||
mod hosted;
|
||||
pub mod native;
|
||||
pub mod route;
|
||||
@@ -13,6 +12,9 @@ pub mod run;
|
||||
mod tests;
|
||||
#[cfg(test)]
|
||||
mod tests_tripo;
|
||||
#[cfg(test)]
|
||||
mod tests_keys;
|
||||
|
||||
pub use raea_io_gen_comfy as comfy;
|
||||
pub use raea_io_gen_fit as fit;
|
||||
pub use raea_io_gen_core::{direct, fal, fish, flow, http, made, modal, openrouter, replicate, setting, tripo, tsflow, types};
|
||||
+53
-1
@@ -3,7 +3,8 @@
|
||||
//! Tripo 3D: through the tripo CLI on the user's own key when this host has both (tripo.rs), else the same Tripo model on fal. text.generate goes to
|
||||
//! OpenRouter (RAEA_GEN_TEXT_MODEL, else Kimi). Otherwise: a `comfy` step on the ComfyUI server; a step with ComfyUI weights on the server too when
|
||||
//! the flow asks for the exact weights (`--exact`), else made's model for that op, which is noted as standing in for
|
||||
//! them; a local model when the host has one for the op (sao for effects); made for the rest.
|
||||
//! them; a local model when the host has one for the op (sao for effects); made for the rest. A picture step on a host
|
||||
//! with no made.app key goes to fal (nano-banana-2), else OpenRouter (Gemini's image model), when it has their key.
|
||||
|
||||
use serde_json::{Map, Value as J, json};
|
||||
|
||||
@@ -86,6 +87,52 @@ pub struct Policy {
|
||||
pub comfy_on_replicate: bool,
|
||||
/// the tripo CLI and a key are on this host (tripo::available), so mesh steps run on Tripo itself
|
||||
pub tripo: bool,
|
||||
/// which picture services this host has a key for
|
||||
pub keys: Keys,
|
||||
}
|
||||
|
||||
/// The picture services this host has a key for (MADE_API_KEY, FAL_KEY, OPENROUTER_API_KEY). With no made.app key, a
|
||||
/// picture step that names no model goes to fal, then OpenRouter (the app's Images and video offers all three; Shane
|
||||
/// 11-14: "maybe add openrouter and fal as other image options"). Default: made's, as before.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Keys {
|
||||
pub made: bool,
|
||||
pub fal: bool,
|
||||
pub openrouter: bool,
|
||||
}
|
||||
|
||||
impl Default for Keys {
|
||||
fn default() -> Self {
|
||||
Keys { made: true, fal: false, openrouter: false }
|
||||
}
|
||||
}
|
||||
|
||||
impl Keys {
|
||||
/// what this host has, from the environment and raea's env file
|
||||
pub fn here() -> Keys {
|
||||
let has = |k: &str| crate::setting(k).is_some_and(|v| !v.trim().is_empty());
|
||||
Keys { made: has("MADE_API_KEY"), fal: has("FAL_KEY"), openrouter: has("OPENROUTER_API_KEY") }
|
||||
}
|
||||
}
|
||||
|
||||
/// fal's and OpenRouter's picture models, for a picture step on a host with no made.app key
|
||||
pub const FAL_IMAGE: &str = "fal-ai/nano-banana-2";
|
||||
pub const FAL_IMAGE_EDIT: &str = "fal-ai/nano-banana-2/edit";
|
||||
pub const OPENROUTER_IMAGE: &str = "google/gemini-3.1-flash-image";
|
||||
|
||||
/// A picture step where made.app has no key here: fal's nano-banana-2 (made's own default for pictures), else
|
||||
/// OpenRouter's Gemini image model; None for any other step, or with neither key.
|
||||
fn without_made(s: &Step, k: &Keys) -> Option<(Backend, Option<String>)> {
|
||||
let edit = match s.op.as_str() {
|
||||
"image.generate" => false,
|
||||
"image.edit" => true,
|
||||
_ => return None,
|
||||
};
|
||||
if k.fal {
|
||||
let e = if edit { FAL_IMAGE_EDIT } else { FAL_IMAGE };
|
||||
return Some((Backend::Fal(e.into()), Some(format!("no made.app key here: fal's {e}"))));
|
||||
}
|
||||
k.openrouter.then(|| (Backend::OpenRouter(OPENROUTER_IMAGE.into()), Some(format!("no made.app or fal key here: OpenRouter's {OPENROUTER_IMAGE}"))))
|
||||
}
|
||||
|
||||
/// Where a step runs, and a note when it stands in for something it was asked for.
|
||||
@@ -132,6 +179,11 @@ pub fn route(s: &Step, p: &Policy) -> Result<(Backend, Option<String>), String>
|
||||
if let Some(l) = local_default(s).filter(|l| p.local.iter().any(|x| x.as_str() == *l)) {
|
||||
return Ok((Backend::Local(l.into()), None));
|
||||
}
|
||||
if !p.keys.made {
|
||||
if let Some(r) = without_made(s, &p.keys) {
|
||||
return Ok(r);
|
||||
}
|
||||
}
|
||||
let m = made_default(s).ok_or(format!("nothing runs {} yet: give it a model (made:<id>, fal:<endpoint>, comfy)", s.op))?;
|
||||
Ok((Backend::Made(m.into()), None))
|
||||
}
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
//! raea gen's picture steps on a host without a made.app key: fal, then OpenRouter (route.rs Keys).
|
||||
use serde_json::json;
|
||||
|
||||
use crate::flow::Step;
|
||||
use crate::route::{Backend, Keys, Policy, route};
|
||||
|
||||
fn on(made: bool, fal: bool, openrouter: bool) -> Policy {
|
||||
Policy { keys: Keys { made, fal, openrouter }, ..Default::default() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pictures_go_to_fal_then_openrouter_without_a_made_key() {
|
||||
let make = Step::new("image.generate", json!({"prompt": "a lighthouse in fog"}));
|
||||
let edit = Step::new("image.edit", json!({"prompt": "make it night", "image": "https://example.com/a.png"}));
|
||||
// made's key here: made, as before (and with no keys known at all, the default)
|
||||
assert!(matches!(route(&make, &on(true, true, true)).unwrap().0, Backend::Made(_)));
|
||||
assert!(matches!(route(&make, &Policy::default()).unwrap().0, Backend::Made(_)));
|
||||
// no made key: fal's nano-banana-2, its edit endpoint for an edit, said in the note
|
||||
let (b, note) = route(&make, &on(false, true, true)).unwrap();
|
||||
assert_eq!(b, Backend::Fal("fal-ai/nano-banana-2".into()));
|
||||
assert!(note.unwrap().contains("no made.app key"));
|
||||
assert_eq!(route(&edit, &on(false, true, false)).unwrap().0, Backend::Fal("fal-ai/nano-banana-2/edit".into()));
|
||||
// no made or fal key: OpenRouter's Gemini image model, for both
|
||||
assert_eq!(route(&make, &on(false, false, true)).unwrap().0, Backend::OpenRouter("google/gemini-3.1-flash-image".into()));
|
||||
assert_eq!(route(&edit, &on(false, false, true)).unwrap().0, Backend::OpenRouter("google/gemini-3.1-flash-image".into()));
|
||||
// none of the three: made, which then asks for its key when it runs
|
||||
assert!(matches!(route(&make, &on(false, false, false)).unwrap().0, Backend::Made(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_picture_steps_and_unnamed_models_fall_back() {
|
||||
let none = on(false, true, true);
|
||||
// a video step stays on made (fal and OpenRouter take its key only when the step names them)
|
||||
let video = Step::new("video.generate", json!({"prompt": "waves"}));
|
||||
assert!(matches!(route(&video, &none).unwrap().0, Backend::Made(_)));
|
||||
// a step that names its model goes there whatever keys are here
|
||||
let mut named = Step::new("image.generate", json!({"prompt": "x"}));
|
||||
named.model = Some("made:nano_banana_2".into());
|
||||
assert_eq!(route(&named, &none).unwrap().0, Backend::Made("nano_banana_2".into()));
|
||||
}
|
||||
@@ -198,7 +198,7 @@ impl<R: OpIds> Plugin for BridgePlugin<R> {
|
||||
.add_message::<PageConflict>()
|
||||
.configure_sets(PreUpdate, PageSystems::Step.after(PageSystems::Events).after(bevy::picking::PickingSystems::Last))
|
||||
.configure_sets(PostUpdate, (PageSystems::Commands, PageSystems::Restyle, PageSystems::Layout, PageSystems::Twins, PageSystems::Paint).chain())
|
||||
.add_systems(PostUpdate, (apply_commands.in_set(PageSystems::Commands), twins::<R>.in_set(PageSystems::Twins)));
|
||||
.add_systems(PostUpdate, (apply_commands.in_set(PageSystems::Commands), twins::<R, true>.in_set(PageSystems::Twins)));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -221,8 +221,9 @@ fn elements(doc: &BaseDocument, ops: Option<&HashMap<u64, NodeId>>, out: &mut Ve
|
||||
}
|
||||
|
||||
/// Twins spawned for new elements and despawned with theirs (and with their page), and each one's box written when it
|
||||
/// changed (H1). A twin's components are the page's (H9): one a system wrote is put back, named.
|
||||
fn twins<R: OpIds>(
|
||||
/// changed (H1). A twin's components are the page's (H9): one a system wrote is put back, named. Without `BOXES` (an
|
||||
/// event's sync, under RAEA_TWIN_SYNC_LIGHT) a kept twin keeps the box it has: only a new one takes its box now.
|
||||
fn twins<R: OpIds, const BOXES: bool>(
|
||||
mut commands: Commands,
|
||||
docs: NonSend<Docs>,
|
||||
roots: Option<NonSend<R>>,
|
||||
@@ -237,6 +238,11 @@ fn twins<R: OpIds>(
|
||||
error!("raea-page: a system wrote {property} on {twin}, which is the page's; the page's value stays (docs/blitz-bevy.feature B3 H9)");
|
||||
conflicts.write(PageConflict { twin, property: property.into(), owner: Owner::Page });
|
||||
};
|
||||
// RAEA_TWIN_SYNC_LIGHT=1 (a trial, off by default): an event's sync spawns and despawns twins and sets their
|
||||
// hierarchy, but leaves a kept twin's box as it is. Layout hasn't run since the frame's own pass took every box, and
|
||||
// that pass takes them again after this frame's layout; taking each element's rect on every pointer move was most of
|
||||
// a 400-clip timeline drag's twin work (docs/timeline.feature TL13a)
|
||||
let keep_boxes = !BOXES && std::env::var_os("RAEA_TWIN_SYNC_LIGHT").is_some_and(|v| v == "1");
|
||||
let index = &mut *index;
|
||||
// pages gone: their twins with them
|
||||
index.pages.retain(|page, t| {
|
||||
@@ -260,11 +266,12 @@ fn twins<R: OpIds>(
|
||||
by_key.clear();
|
||||
t.by_node.clear();
|
||||
for (key, node) in now.drain(..) {
|
||||
let at = doc.get_client_bounding_rect(node).map(|b| ElementBox(Rect::new(b.x as f32, b.y as f32, (b.x + b.width) as f32, (b.y + b.height) as f32))).unwrap_or_default();
|
||||
let rect = || doc.get_client_bounding_rect(node).map(|b| ElementBox(Rect::new(b.x as f32, b.y as f32, (b.x + b.width) as f32, (b.y + b.height) as f32))).unwrap_or_default();
|
||||
let op = if let Key::Op(id) = key { Some(id) } else { plain.0.get(page).and_then(|m| m.get(&node)).copied() };
|
||||
let el_now = PageElement { page: *page, node, op };
|
||||
let e = match t.by_key.remove(&key) {
|
||||
let (e, at) = match t.by_key.remove(&key) {
|
||||
Some(e) => {
|
||||
let mut kept = None;
|
||||
if let Ok((mut el, mut b)) = twins.get_mut(e) {
|
||||
if let Some((was_el, was_b)) = t.written.get(&e) {
|
||||
if *el != *was_el {
|
||||
@@ -275,11 +282,17 @@ fn twins<R: OpIds>(
|
||||
}
|
||||
}
|
||||
el.set_if_neq(el_now);
|
||||
// an event's sync leaves the box to the frame's own pass, which takes it after layout
|
||||
let at = if keep_boxes { *b } else { rect() };
|
||||
b.set_if_neq(at);
|
||||
kept = Some(at);
|
||||
}
|
||||
e
|
||||
(e, kept.unwrap_or_else(rect))
|
||||
}
|
||||
None => {
|
||||
let at = rect();
|
||||
(commands.spawn((el_now, at)).id(), at)
|
||||
}
|
||||
None => commands.spawn((el_now, at)).id(),
|
||||
};
|
||||
t.written.insert(e, (el_now, at));
|
||||
by_key.insert(key, e);
|
||||
@@ -445,7 +458,7 @@ impl<H: EventHandler> EventHandler for Forward<'_, H> {
|
||||
/// for the event's path and for whatever runs in the frame after it (its box comes at [`PageSystems::Twins`]).
|
||||
/// The twins brought to the pages now, outside their set: before an event's delivery, after a host step's commits.
|
||||
pub fn sync_twins<R: OpIds>(world: &mut World) {
|
||||
if let Err(e) = world.run_system_cached(twins::<R>) {
|
||||
if let Err(e) = world.run_system_cached(twins::<R, false>) {
|
||||
warn!("raea-page: twins: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,4 +15,5 @@
|
||||
import { fish, lyria, sao } from "@raea/asset/assets";
|
||||
export { getContext, context, setContext, start, loaded, now, immediate, version, mtof, ftom, dbToGain, gainToDb, intervalToFrequencyRatio, Frequency, Midi, Time, TransportTime, Ticks, Param, Signal, ToneAudioNode, getDestination, Destination, Master, Instrument, Synth, MonoSynth, FMSynth, AMSynth, DuoSynth, MembraneSynth, NoiseSynth, MetalSynth, PluckSynth, PolySynth, Sampler, Player, GrainPlayer, Players, Oscillator, OmniOscillator, FatOscillator, PulseOscillator, Noise, Effect, Reverb, Freeverb, JCReverb, FeedbackDelay, PingPongDelay, Filter, AutoFilter, Compressor, Limiter, EQ3, Distortion, Chorus, BitCrusher, Tremolo, Vibrato, Phaser, AutoPanner, Gain, Volume, Panner, Channel, PanVol, Solo, Meter, FFT, Waveform, Analyser, LFO, Convolver, PitchShift, Offline, bus, buses, tokensynth, getTransport, Transport, Draw, Loop, Part, Sequence, Pattern, ToneOut, Sfx, vary, snapshot, reset } from "./tone/all";
|
||||
|
||||
export { fire } from "./tone/fire";
|
||||
export { sao, lyria, fish };
|
||||
@@ -176,7 +176,8 @@ export class Meter extends ToneAudioNode {
|
||||
constructor(_o?: unknown) {
|
||||
super("Gain", { gain: 1 });
|
||||
}
|
||||
getValue() {
|
||||
// a level, or an FFT's or a Waveform's bins (as Tone's getValue is number | number[])
|
||||
getValue(): number | Float32Array {
|
||||
return -Infinity;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
// raea/tone in a page: a sound fired now (docs/hardware.feature HW0d), as <Sfx> is a game's one-shot on a frame.
|
||||
import { type Ev, ctx } from "./all";
|
||||
|
||||
type Engine = { call: <T>(name: string, args?: unknown) => Promise<T> };
|
||||
|
||||
/** the graph the page's mixer has, as last sent */
|
||||
let sent = "";
|
||||
let fires = 0;
|
||||
let said = false;
|
||||
|
||||
/**
|
||||
* raea: a page's one-shot, heard now. `play(time)` runs the way an <Sfx>'s does, its triggers become events, and the
|
||||
* page's mixer in raea's window plays them at once (the host call sound.fire, on raea's mixer core). Make the
|
||||
* instruments and effects once, at the top level of a module, as a composition does; `play` only triggers them.
|
||||
* const click = new Tone.NoiseSynth({ envelope: { attack: 0.001, decay: 0.03, sustain: 0 } }).connect(Tone.buses.ui);
|
||||
* button.onpointerdown = () => Tone.fire((t) => click.triggerAttackRelease("32n", t));
|
||||
* Returns false, with no sound, where no raea engine is under the page (a browser).
|
||||
*/
|
||||
export function fire(play: (time: number) => void): boolean {
|
||||
const engine = (globalThis as { __raea_engine?: Engine }).__raea_engine;
|
||||
const evs: Ev[] = [];
|
||||
const prev = [ctx.sink, ctx.sinkKey, ctx.seq, ctx.now] as const;
|
||||
ctx.sink = evs;
|
||||
// each fire's own keys: the mixer hears a key once
|
||||
ctx.sinkKey = `fire${++fires}`;
|
||||
ctx.seq = 0;
|
||||
ctx.now = 0;
|
||||
try {
|
||||
play(0);
|
||||
} finally {
|
||||
[ctx.sink, ctx.sinkKey, ctx.seq, ctx.now] = prev;
|
||||
}
|
||||
if (!engine) {
|
||||
if (!said) console.info("raea/tone fire: no raea engine under this page, so its sounds are silent");
|
||||
said = true;
|
||||
return false;
|
||||
}
|
||||
if (evs.length === 0) return true;
|
||||
const graph = ctx.graphJson();
|
||||
const args = graph === sent ? { evs } : { graph, evs };
|
||||
sent = graph;
|
||||
// a call that failed sends the graph again with the next
|
||||
engine.call("sound.fire", args).catch(() => void (sent = ""));
|
||||
return true;
|
||||
}
|
||||
@@ -26,6 +26,25 @@
|
||||
audio's own rate, so they can be shorter than a frame.
|
||||
- Use `muted` for picture-only clips, `playbackRate` for speed changes (the sound follows) and `loop` with `endAt` to
|
||||
repeat a short source from `startFrom` each time it reaches `endAt` (without `endAt`, nothing loops).
|
||||
- For a speed ramp, give `speedCurve` instead of `playbackRate`: `[place, speed]` points over the source from
|
||||
`startFrom` (place 0) to `endAt` (place 1, so it needs `endAt`), each speed from 0.1 to 10, changing in a straight
|
||||
line between points: `speedCurve={[[0, 1], [0.5, 4], [1, 1]]}` speeds up to 4x at the middle and back. The sound
|
||||
follows it. The clip then takes `speedLength(speedPoints("clip", curve), endAt - startFrom)` frames, so give its
|
||||
`<Sequence>` that `durationInFrames` (rounded).
|
||||
- For a look over a stretch of time, put an `<Effect kind="mono" />` in a `<Sequence>` of its own, written after
|
||||
the parts it covers: it filters everything drawn before it for that sequence's frames, and draws nothing itself.
|
||||
Kinds: `blur`, `mono` (black and white), `sepia`, `vivid`, `faded`, `contrast`, `bright`, `dark`, `invert`, `hue`.
|
||||
`amount` (0 to 1) says how much; `in` and `out` are the frames it takes to come on and go off. The feed's timeline
|
||||
shows such a sequence as an effect clip, so the person can move, trim or retune it there.
|
||||
An effect of your own is its `parts`, CSS filter functions from amount 0 to amount 1:
|
||||
`<Effect kind="dream" parts={[["blur", 0, 6, "px"], ["saturate", 1, 1.6]]} />` (blur, brightness, contrast,
|
||||
grayscale, hue-rotate, invert, saturate, sepia).
|
||||
- To recut a composition as data rather than by hand, use `raea/editor`, the model behind the feed's timeline.
|
||||
`fromRender({ frames, fps, cuts })` makes its scenes clips of a main track, `applyAll(t, ops)` makes the edits
|
||||
(`split`, `move`, `trim`, `remove`) and hands back each one's inverse, so a change can be undone, and
|
||||
`segmentsOf(t)` is the cut as `<Composition edit={{ segments }}>` takes it. The main track's magnet closes every
|
||||
gap, as the feed's does. Segments say only which source frames play in which order: a speed or a freeze on a clip
|
||||
is not in them. docs/manual/examples/edits.tsx builds a timeline, edits it and undoes it.
|
||||
- Use `<Img src>` for stills. The frame waits until the image has loaded. An image whose file isn't there fails the
|
||||
render with "missing image: PATH"; a plain App prints that line and draws nothing.
|
||||
|
||||
|
||||
@@ -46,16 +46,26 @@ A video's bitrate follows its size and frame rate (about 20 Mbit/s at 1080p30, 8
|
||||
flat pictures), and `--kbps N` sets it. `--quality draft|high|master` (or 0..1: 0.6, 0.85, 0.95) asks for constant
|
||||
quality instead, each frame getting the bits it needs: `master` keeps thin type and hard vector edges clean at 4K
|
||||
(about 31 Mbit/s on flat motion graphics). Blotching in dark areas is the encoder, not the composition: export dark
|
||||
material as PNG frames (`RAEA_READBACK=rgba raea render piece.tsx -o frames/`) and encode them with more bits for the
|
||||
darks.
|
||||
material as PNG frames (`RAEA_READBACK=rgba raea render piece.tsx -o piece.frames/`) and encode them with more bits for
|
||||
the darks. A `NAME.frames/` folder is never committed, and raea's storage dry run lists it a day after
|
||||
the render unless something names it.
|
||||
|
||||
Which to ask for. A version made for notes (a cut to review, a shot that will be joined, a preview) takes no
|
||||
`--quality` flag: the default is already close to the picture `master` gives, in a fraction of the file. Measured on
|
||||
1080p24 film footage: the default 16 Mbit/s, `high` 30, `master` 87; against the `master` encode the default scores
|
||||
VMAF 99.5 (its worst frame 95.8) and `high` 99.7. So `master` on every review version is five times the disk for
|
||||
nothing a person sees, and a film reviewed ten times is ten gigabytes. Keep `master` for the one file that is
|
||||
delivered when it is motion graphics or type (thin edges at 4K are where it shows); deliver a film at `high`. When a
|
||||
version is replaced, delete the one before the last, and delete a shot's file once the joined film has it.
|
||||
delivered when it is motion graphics or type (thin edges at 4K are where it shows); deliver a film at `high`. A notes
|
||||
version takes no `--quality draft` either: constant quality has no ceiling, so on grain or noise `draft` can come
|
||||
out larger than the default.
|
||||
|
||||
When a version is replaced, keep it, and never `rm` a render yourself: a person may want the earlier cut back, and an
|
||||
item, a note or a composition may still name it. Name versions `-vN` (`cut-v3.mp4`, not `cut3.mp4`) so raea can
|
||||
tell a version from a shot number, and put "final" in the name of a delivered file. When space is short, call
|
||||
`storage_plan`: it lists only versions with a newer one beside them, unused feed renders, frames and broken copies,
|
||||
never a file anything names, and it says why each is listed. Show the person that list, and only on their yes call
|
||||
`storage_trash` with it: the list waits in Settings › Storage for the person to move, and what they move goes to the
|
||||
Trash, where they can put it back.
|
||||
|
||||
## A person's hand edits
|
||||
|
||||
|
||||
@@ -13,9 +13,11 @@ import { Held, useWake } from "./hold";
|
||||
import { stepTo, type Config } from "./session";
|
||||
import { convert } from "./scene";
|
||||
import { standInImages } from "./texture";
|
||||
import { standInPMREM } from "./pmrem";
|
||||
import { elementsOf } from "../parts";
|
||||
|
||||
standInImages();
|
||||
standInPMREM();
|
||||
|
||||
export interface R3FProps extends Config {
|
||||
children?: ReactNode;
|
||||
|
||||
@@ -5,6 +5,7 @@ import * as THREE from "three";
|
||||
import { toRaea, stopsOf } from "../units";
|
||||
import type { Part, Props } from "./material";
|
||||
import { srcOf } from "./texture";
|
||||
import { LEFT_OUT } from "./pmrem";
|
||||
|
||||
const hex = (c: THREE.Color) => "#" + c.getHexString();
|
||||
const at = (o: THREE.Object3D) => o.getWorldPosition(new THREE.Vector3()).toArray() as [number, number, number];
|
||||
@@ -164,7 +165,10 @@ export function skyOf(scene: THREE.Scene, gl?: THREE.WebGLRenderer, webgpu = fal
|
||||
}
|
||||
const env = srcOf(scene.environment);
|
||||
const sky = bg instanceof THREE.Texture ? srcOf(bg) : undefined;
|
||||
if (scene.environment && !(env && PANORAMA.test(env))) warnOnce("scene.environment", "isn't a panorama file raea can load (.hdr, .exr, .png, .jpg): left out");
|
||||
// three's PMREMGenerator making one from a scene or a cube map (pmrem.ts): said as that, not as a missing file
|
||||
const by = scene.environment?.userData?.[LEFT_OUT];
|
||||
if (scene.environment && typeof by === "string" && !env) warnOnce("scene.environment", `made by three's ${by}, which renders on the GPU and raea doesn't make yet: the scene is drawn without it (use a panorama: <Environment preset> or PMREMGenerator.fromEquirectangular of an .hdr)`);
|
||||
else if (scene.environment && !(env && PANORAMA.test(env))) warnOnce("scene.environment", "isn't a panorama file raea can load (.hdr, .exr, .png, .jpg): left out");
|
||||
if (bg instanceof THREE.Texture && !(sky && PANORAMA.test(sky))) warnOnce("scene.background", "texture isn't a panorama file raea can load: left out");
|
||||
const rotation = scene.environmentRotation?.y ?? 0;
|
||||
if (env && PANORAMA.test(env)) {
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
// three's PMREMGenerator filters an environment on the GPU: it renders a scene (RoomEnvironment, three's own recipe for
|
||||
// soft studio light) or a panorama into a cube map with the renderer, which in raea is a stand-in that never draws
|
||||
// (session.ts). raea filters an environment itself, from a panorama (lights.ts skyOf, raea's <Environment>), so the
|
||||
// generator hands back what raea can read: fromEquirectangular of a panorama raea loads is that panorama, lighting the
|
||||
// scene as scene.environment; fromScene and fromCubemap are left out, the scene drawn without them and a warning saying
|
||||
// so (skyOf). fromScene threw inside the stand-in renderer and took the whole <R3F> scene with it (#131).
|
||||
import * as THREE from "three";
|
||||
import { srcOf } from "./texture";
|
||||
|
||||
/** what a stand-in environment was made by, when raea can't light by it: skyOf names it in its warning */
|
||||
export const LEFT_OUT = "raeaLeftOut";
|
||||
|
||||
function standIn(src: string | undefined, by: string): THREE.WebGLRenderTarget {
|
||||
const t = new THREE.WebGLRenderTarget(1, 1);
|
||||
t.texture.mapping = THREE.CubeUVReflectionMapping;
|
||||
if (src) t.texture.userData.src = src;
|
||||
else t.texture.userData[LEFT_OUT] = by;
|
||||
return t;
|
||||
}
|
||||
|
||||
let done = false;
|
||||
|
||||
/** PMREMGenerator's makers as stand-ins, once */
|
||||
export function standInPMREM() {
|
||||
if (done) return;
|
||||
done = true;
|
||||
const pm = THREE.PMREMGenerator.prototype as unknown as Record<string, unknown>;
|
||||
pm.fromScene = () => standIn(undefined, "PMREMGenerator.fromScene");
|
||||
pm.fromSceneAsync = async () => standIn(undefined, "PMREMGenerator.fromScene");
|
||||
pm.fromEquirectangular = (texture: THREE.Texture) => standIn(srcOf(texture), "PMREMGenerator.fromEquirectangular");
|
||||
pm.fromEquirectangularAsync = async (texture: THREE.Texture) => standIn(srcOf(texture), "PMREMGenerator.fromEquirectangular");
|
||||
pm.fromCubemap = () => standIn(undefined, "PMREMGenerator.fromCubemap");
|
||||
pm.fromCubemapAsync = async () => standIn(undefined, "PMREMGenerator.fromCubemap");
|
||||
pm.compileCubemapShader = () => {};
|
||||
pm.compileEquirectangularShader = () => {};
|
||||
}
|
||||
@@ -5,7 +5,7 @@
|
||||
// a frame's scene is the same whichever frame came before it: a render equals its play (raea's first rule).
|
||||
import * as THREE from "three";
|
||||
import { advance, createRoot, extend, flushSync, type ReconcilerRoot, type RenderProps, type RootState } from "@react-three/fiber";
|
||||
import type { ReactNode } from "react";
|
||||
import { Component, createElement, type ReactNode } from "react";
|
||||
import { renderInto } from "./targets";
|
||||
|
||||
extend(THREE as unknown as Parameters<typeof extend>[0]);
|
||||
@@ -92,6 +92,21 @@ const seedOf = (key: string) => [...key].reduce((h, c) => Math.imul(h ^ c.charCo
|
||||
|
||||
const sessions = new Map<string, Session>();
|
||||
|
||||
/** The scene under an error boundary of raea's: what it throws (rendering, in an effect, in a ref) is handed to `on`,
|
||||
* and it draws nothing after. A promise thrown (a load suspending) isn't an error and passes by it, as before. */
|
||||
class Caught extends Component<{ on: (error: unknown) => void; children?: ReactNode }, { failed: boolean }> {
|
||||
state = { failed: false };
|
||||
static getDerivedStateFromError() {
|
||||
return { failed: true };
|
||||
}
|
||||
componentDidCatch(error: unknown) {
|
||||
this.props.on(error);
|
||||
}
|
||||
render() {
|
||||
return this.state.failed ? null : this.props.children;
|
||||
}
|
||||
}
|
||||
|
||||
export type Config = Omit<RenderProps<HTMLCanvasElement>, "gl" | "frameloop" | "size" | "events" | "dpr">;
|
||||
|
||||
function start(key: string, width: number, height: number, config: Config, json: string): Session {
|
||||
@@ -115,8 +130,16 @@ export function stepTo(key: string, frame: number, fps: number, width: number, h
|
||||
const live = s;
|
||||
const render = (i: number) => {
|
||||
let store: ReturnType<typeof live.root.render> | undefined;
|
||||
seeded(live, () => flushSync(() => { store = live.root.render(scene(i)); }));
|
||||
let failed: { error: unknown } | undefined;
|
||||
seeded(live, () => flushSync(() => { store = live.root.render(createElement(Caught, { on: (error: unknown) => void (failed ??= { error }) }, scene(i))); }));
|
||||
if (store) live.state = store.getState();
|
||||
// thrown out of the <R3F> that's drawing it, so the composition throws as it would outside R3F: the render is
|
||||
// refused, naming the error. R3F's own root only reports it (reportError, else console.error: a stack without its
|
||||
// message) and draws nothing, and the render ended with 0 errors (#131). The root starts again next time
|
||||
if (failed) {
|
||||
end(key);
|
||||
throw failed.error;
|
||||
}
|
||||
};
|
||||
// the same frame drawn again (a live replay): its children may have changed, its clock hasn't. When parts of it
|
||||
// mounted only now (a model, a font: what suspended while the frames were stepped, loaded since), their useFrame
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
// What an R3F scene throws is the composition's error, and three's PMREMGenerator doesn't take the scene with it
|
||||
// (#131: any error inside <R3F> was swallowed, the scene drew nothing and the render ended with 0 errors).
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { useThree } from "@react-three/fiber";
|
||||
import { useEffect, useMemo, type ReactNode } from "react";
|
||||
import * as THREE from "three";
|
||||
import { RoomEnvironment } from "three/examples/jsm/environments/RoomEnvironment.js";
|
||||
import { convert } from "../src/input/scene";
|
||||
import { end, stepTo } from "../src/input/session";
|
||||
import { standInPMREM } from "../src/input/pmrem";
|
||||
import type { Part } from "../src/parts";
|
||||
|
||||
standInPMREM();
|
||||
|
||||
const flat = (parts: Part[]): Part[] => parts.flatMap((p) => [p, ...flat(p.children ?? [])]);
|
||||
let n = 0;
|
||||
function partsOf(scene: (i: number) => ReactNode, key = `e${n++}`) {
|
||||
const s = stepTo(key, 0, 30, 400, 400, {}, scene);
|
||||
const st = s.state as unknown as { scene: THREE.Scene; camera: THREE.Camera; gl: THREE.WebGLRenderer };
|
||||
return flat(convert(st.scene, st.camera, st.gl, 400).parts);
|
||||
}
|
||||
const Box = () => (
|
||||
<mesh>
|
||||
<boxGeometry />
|
||||
<meshBasicMaterial color="red" />
|
||||
</mesh>
|
||||
);
|
||||
|
||||
describe("an error inside the scene", () => {
|
||||
test("thrown while rendering, it's thrown out of the frame with its message, and the next frame starts again", () => {
|
||||
const Boom = (): null => {
|
||||
throw new Error("mesh threw");
|
||||
};
|
||||
expect(() => partsOf(() => (<><Box /><Boom /></>), "boom")).toThrow("mesh threw");
|
||||
// the same key without the throw draws: the failed root was ended, not kept
|
||||
expect(partsOf(() => <Box />, "boom").some((p) => p.type === "Mesh")).toBe(true);
|
||||
end("boom");
|
||||
});
|
||||
|
||||
test("thrown in an effect, it's thrown out too", () => {
|
||||
const Late = () => {
|
||||
useEffect(() => {
|
||||
throw new Error("effect threw");
|
||||
}, []);
|
||||
return null;
|
||||
};
|
||||
expect(() => partsOf(() => (<><Box /><Late /></>))).toThrow("effect threw");
|
||||
});
|
||||
});
|
||||
|
||||
describe("three's PMREMGenerator", () => {
|
||||
test("fromScene (RoomEnvironment) leaves the environment out with a warning and the scene draws", () => {
|
||||
const warned: string[] = [];
|
||||
const warn = console.warn;
|
||||
console.warn = (m: string) => void warned.push(String(m));
|
||||
try {
|
||||
const Studio = () => {
|
||||
const { gl, scene } = useThree();
|
||||
useMemo(() => {
|
||||
const pm = new THREE.PMREMGenerator(gl);
|
||||
scene.environment = pm.fromScene(new RoomEnvironment(), 0.04).texture;
|
||||
}, [gl, scene]);
|
||||
return null;
|
||||
};
|
||||
const parts = partsOf(() => (<><Studio /><Box /></>));
|
||||
expect(parts.some((p) => p.type === "Mesh")).toBe(true);
|
||||
expect(parts.some((p) => p.type === "Environment")).toBe(false);
|
||||
} finally {
|
||||
console.warn = warn;
|
||||
}
|
||||
expect(warned.some((w) => w.includes("PMREMGenerator.fromScene"))).toBe(true);
|
||||
});
|
||||
|
||||
test("fromEquirectangular of a panorama lights the scene by that panorama", () => {
|
||||
const Sky = () => {
|
||||
const { gl, scene } = useThree();
|
||||
useMemo(() => {
|
||||
const hdr = new THREE.Texture();
|
||||
hdr.userData.src = "media/studio.hdr";
|
||||
scene.environment = new THREE.PMREMGenerator(gl).fromEquirectangular(hdr).texture;
|
||||
}, [gl, scene]);
|
||||
return null;
|
||||
};
|
||||
const env = partsOf(() => (<><Sky /><Box /></>)).find((p) => p.type === "Environment");
|
||||
expect(env?.props.src).toBe("media/studio.hdr");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,103 @@
|
||||
// <Nudge adjust>: a part's brightness, contrast, saturation, exposure, sharpen, highlights, shadows, temperature, tint,
|
||||
// fade, vignette and grain (docs/timeline.feature TL7g; sdk/video adjust.ts).
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { adjustError, adjustId, adjustSteps, toneAt, vignetteStyle } from "@raea/video/adjust";
|
||||
import { Nudge } from "@raea/video/nudge";
|
||||
import { renderFrame } from "../src/test";
|
||||
|
||||
const opts = { fps: 30, width: 1920, height: 1080, durationInFrames: 300 };
|
||||
const at = (el: JSX.Element, frame = 0) => renderFrame(el, { ...opts, frame });
|
||||
|
||||
describe("the tone curve", () => {
|
||||
test("as shot it is the picture as it was", () => {
|
||||
for (const v of [0, 0.25, 0.5, 0.75, 1]) expect(toneAt({}, v)).toBeCloseTo(v, 6);
|
||||
expect(adjustSteps({})).toEqual([]);
|
||||
});
|
||||
|
||||
test("exposure is a stop either way, brightness lifts the mids and holds the ends", () => {
|
||||
expect(toneAt({ exposure: 1 }, 0.25)).toBeCloseTo(0.5, 6);
|
||||
expect(toneAt({ exposure: -1 }, 0.5)).toBeCloseTo(0.25, 6);
|
||||
expect(toneAt({ brightness: 1 }, 0.25)).toBeCloseTo(0.5, 6);
|
||||
expect([toneAt({ brightness: 1 }, 0), toneAt({ brightness: 1 }, 1)]).toEqual([0, 1]);
|
||||
});
|
||||
|
||||
test("contrast turns about the middle grey; highlights and shadows each move their own end", () => {
|
||||
expect(toneAt({ contrast: 1 }, 0.5)).toBeCloseTo(0.5, 6);
|
||||
expect(toneAt({ contrast: 1 }, 0.75)).toBeCloseTo(1, 6);
|
||||
expect(toneAt({ contrast: -1 }, 1)).toBeLessThan(0.7);
|
||||
// highlights moves the bright more than the dark, shadows the dark more than the bright
|
||||
expect(toneAt({ highlights: 1 }, 0.75) - 0.75).toBeGreaterThan(toneAt({ highlights: 1 }, 0.25) - 0.25);
|
||||
expect(toneAt({ shadows: 1 }, 0.25) - 0.25).toBeGreaterThan(toneAt({ shadows: 1 }, 0.75) - 0.75);
|
||||
expect(toneAt({ highlights: -1 }, 0.8)).toBeLessThan(0.8);
|
||||
});
|
||||
|
||||
test("fade lifts the blacks and lowers the whites", () => {
|
||||
expect(toneAt({ fade: 1 }, 0)).toBeCloseTo(0.22, 6);
|
||||
expect(toneAt({ fade: 1 }, 1)).toBeCloseTo(0.9, 6);
|
||||
});
|
||||
});
|
||||
|
||||
describe("the filter's steps", () => {
|
||||
test("only what is changed: a tone table, a saturation, a warmth, a sharpen, a grain", () => {
|
||||
expect(adjustSteps({ contrast: 0.3 }).map((s) => s.tag)).toEqual(["feComponentTransfer"]);
|
||||
expect(adjustSteps({ saturation: -1 })).toEqual([{ tag: "feColorMatrix", attrs: { type: "saturate", values: "0" } }]);
|
||||
expect(adjustSteps({ temperature: 1 })[0].attrs.values).toBe("1.12 0 0 0 0 0 1 0 0 0 0 0 0.88 0 0 0 0 0 1 0");
|
||||
expect(adjustSteps({ sharpen: 1 })[0].attrs.kernelMatrix).toBe("0 -0.4 0 -0.4 2.6 -0.4 0 -0.4 0");
|
||||
// the tone table: 17 levels each for red, green and blue, alpha left as it is
|
||||
const table = adjustSteps({ exposure: 1 })[0];
|
||||
expect(table.children?.map((c) => c.tag)).toEqual(["feFuncR", "feFuncG", "feFuncB"]);
|
||||
expect(table.children?.[0].attrs.tableValues.split(" ")).toHaveLength(17);
|
||||
});
|
||||
|
||||
test("grain is a noise added about its middle, kept to where the part is, its seed the frame", () => {
|
||||
const steps = adjustSteps({ contrast: 0.2, grain: 0.5 }, 42);
|
||||
expect(steps.map((s) => s.tag)).toEqual(["feComponentTransfer", "feTurbulence", "feColorMatrix", "feComposite", "feComposite"]);
|
||||
expect(steps[0].attrs.result).toBe("toned");
|
||||
expect(steps[1].attrs.seed).toBe("42");
|
||||
expect(steps[3].attrs).toMatchObject({ in: "toned", in2: "grey", operator: "arithmetic", k3: "0.15", k4: "-0.075" });
|
||||
expect(steps[4].attrs).toEqual({ in: "grained", in2: "SourceGraphic", operator: "in" });
|
||||
expect(adjustId({ grain: 0.5 }, 7)).not.toBe(adjustId({ grain: 0.5 }, 8));
|
||||
expect(adjustId({ contrast: 0.5 }, 7)).toBe(adjustId({ contrast: 0.5 }, 8));
|
||||
});
|
||||
|
||||
test("a vignette is a darkening over the frame, none at 0", () => {
|
||||
expect(vignetteStyle(0)).toBeUndefined();
|
||||
expect(vignetteStyle(1)?.background).toBe("radial-gradient(ellipse at center, rgba(0, 0, 0, 0) 35%, rgba(0, 0, 0, 0.85) 100%)");
|
||||
});
|
||||
|
||||
test("what is wrong is said", () => {
|
||||
expect(adjustError({ glow: 1 } as never)).toMatch(/"glow" isn't one/);
|
||||
expect(adjustError({ sharpen: -0.5 })).toMatch(/sharpen is from 0 to 1/);
|
||||
expect(adjustError({ contrast: 2 })).toMatch(/contrast is from -1 to 1/);
|
||||
expect(adjustError({ contrast: -1, vignette: 1 })).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("<Nudge adjust>", () => {
|
||||
test("the part wears the adjustment's filter, after its key, with the filter beside it", () => {
|
||||
const html = at(<Nudge adjust={{ contrast: 0.4, saturation: 0.2 }} chroma={{ color: "#00ff00" }}><div>hi</div></Nudge>);
|
||||
const id = adjustId({ contrast: 0.4, saturation: 0.2 });
|
||||
expect(html).toContain(`filter:url(#raea-key-00ff00-50-20) url(#${id})`);
|
||||
expect(html).toContain(`<filter id="${id}"`);
|
||||
expect(html).toContain('type="table"');
|
||||
expect(html).toContain('type="saturate" values="1.2"');
|
||||
});
|
||||
|
||||
test("a vignette is a layer over the part's frame", () => {
|
||||
const html = at(<Nudge adjust={{ vignette: 0.5 }}><div>hi</div></Nudge>);
|
||||
expect(html).toContain("radial-gradient(ellipse at center, rgba(0, 0, 0, 0) 50%, rgba(0, 0, 0, 0.425) 100%)");
|
||||
// a vignette alone needs no filter
|
||||
expect(html).not.toContain("<filter");
|
||||
});
|
||||
|
||||
test("keyed: an adjustment's number over time, from as shot, without a still adjust", () => {
|
||||
const el = (frame: number) => at(<Nudge keys={{ "adjust.saturation": [[0, 0], [10, -1]] }}><div>hi</div></Nudge>, frame);
|
||||
expect(el(0)).not.toContain("<filter");
|
||||
expect(el(5)).toContain('type="saturate" values="0.5"');
|
||||
expect(el(10)).toContain('type="saturate" values="0"');
|
||||
});
|
||||
|
||||
test("an adjustment out of range fails", () => {
|
||||
expect(() => at(<Nudge adjust={{ grain: 2 }}><div>hi</div></Nudge>)).toThrow(/grain is from 0 to 1/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,172 @@
|
||||
// A part's mask, blend and chroma key (docs/timeline.feature TL7f): CapCut's Mask, Blend and Chroma key, drawn by
|
||||
// <Nudge> from sdk/video cutout.ts.
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { BLEND_KINDS, chromaError, chromaId, chromaMatrix, maskError, maskPlain, maskStyle, maskSvg } from "@raea/video/cutout";
|
||||
import { Video } from "@raea/video/media";
|
||||
import { Nudge } from "@raea/video/nudge";
|
||||
import { renderFrame } from "../src/test";
|
||||
|
||||
const opts = { fps: 30, width: 1920, height: 1080, durationInFrames: 30, frame: 0 };
|
||||
const attr = (svg: string, name: string) => [...svg.matchAll(new RegExp(` ${name}="([^"]*)"`, "g"))].map((m) => m[1]);
|
||||
|
||||
describe("a mask keeps a shape of the part (TL7f)", () => {
|
||||
test("a circle chosen is round on any frame: half the shorter side across, in the middle", () => {
|
||||
expect(maskPlain("circle", 1920, 1080)).toMatchObject({ x: 0.5, y: 0.5, w: 0.28125, h: 0.5, feather: 0, invert: false });
|
||||
const svg = maskSvg({ kind: "circle" }, 1920, 1080);
|
||||
expect(attr(svg, "cx")).toEqual(["960"]);
|
||||
expect(attr(svg, "rx")).toEqual(["270"]);
|
||||
expect(attr(svg, "ry")).toEqual(["270"]);
|
||||
expect(svg).not.toContain("<filter");
|
||||
});
|
||||
|
||||
test("each shape: a line keeps what is above it, a mirror a band, a rectangle its corners rounded, a heart and a star in their box", () => {
|
||||
const line = maskSvg({ kind: "line", y: 0.25 }, 1000, 500).split("<rect")[1];
|
||||
// a rect reaching far up, its bottom edge on the line at 125 px
|
||||
expect(Number(attr(line, "y")[0]) + Number(attr(line, "height")[0])).toBe(125);
|
||||
const mirror = maskSvg({ kind: "mirror", h: 0.2 }, 1000, 500).split("<rect")[1];
|
||||
expect(attr(mirror, "height")).toEqual(["100"]);
|
||||
expect(attr(maskSvg({ kind: "rect", w: 0.4, h: 0.4, round: 1 }, 1000, 500), "rx")).toEqual(["100"]);
|
||||
expect(maskSvg({ kind: "heart" }, 1000, 500)).toContain("<path");
|
||||
expect(maskSvg({ kind: "star" }, 1000, 500)).toContain("<polygon");
|
||||
});
|
||||
|
||||
test("turned about its centre, feathered by a blur no larger than the frame and its reach, inverted by excluding it from a solid layer", () => {
|
||||
expect(maskSvg({ kind: "rect", x: 0.25, y: 0.5, rotate: 30 }, 1000, 500)).toContain('transform="rotate(30 250 250)"');
|
||||
const soft = maskSvg({ kind: "circle", feather: 1 }, 1000, 500);
|
||||
expect(attr(soft, "stdDeviation")).toEqual(["25"]);
|
||||
expect(soft).toContain('x="-75" y="-75" width="1150" height="650"');
|
||||
const inverted = maskStyle({ kind: "circle", invert: true }, 1000, 500);
|
||||
expect(inverted.maskImage.startsWith("linear-gradient(#000, #000), url(")).toBe(true);
|
||||
expect(inverted).toMatchObject({ maskComposite: "exclude", WebkitMaskComposite: "xor" });
|
||||
expect(maskStyle({ kind: "circle" }, 1000, 500)).not.toHaveProperty("maskComposite");
|
||||
});
|
||||
|
||||
test("as a mask image the size of the part, its own url()s escaped so they aren't read as the page's", () => {
|
||||
const s = maskStyle({ kind: "circle", feather: 0.5 }, 1920, 1080);
|
||||
expect(s.maskImage.startsWith('url("data:image/svg+xml,')).toBe(true);
|
||||
expect(s.maskImage.slice(5)).not.toMatch(/url\(/);
|
||||
expect(s).toMatchObject({ maskSize: "100% 100%", maskRepeat: "no-repeat" });
|
||||
});
|
||||
|
||||
test("a kind it hasn't got, or a value out of range, is refused", () => {
|
||||
expect(maskError({ kind: "moon" as never })).toMatch(/kind is one of line, mirror, circle, rect, heart, star/);
|
||||
expect(maskError({ kind: "circle", feather: 2 })).toMatch(/feather is from 0 to 1/);
|
||||
expect(maskError({ kind: "circle", w: -1 })).toMatch(/0 or more/);
|
||||
expect(maskError({ kind: "circle", x: 0.2 })).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("a chroma key takes a colour out (TL7f)", () => {
|
||||
// what the matrix gives a colour's alpha, as the filter clamps it
|
||||
const alpha = (values: string, [r, g, b]: number[]) => {
|
||||
const a = values.split(" ").map(Number).slice(15);
|
||||
return Math.min(1, Math.max(0, a[0] * r + a[1] * g + a[2] * b + a[4]));
|
||||
};
|
||||
|
||||
test("a green screen goes, red and white and grey stay, a dark green is half seen", () => {
|
||||
const m = chromaMatrix({ color: "#00ff00" });
|
||||
expect(alpha(m, [0, 1, 0])).toBe(0);
|
||||
expect(alpha(m, [0.1, 0.9, 0.15])).toBe(0);
|
||||
expect(alpha(m, [1, 0, 0])).toBe(1);
|
||||
expect(alpha(m, [1, 1, 1])).toBe(1);
|
||||
expect(alpha(m, [0.4, 0.4, 0.4])).toBe(1);
|
||||
const dark = alpha(m, [0, 0.5, 0]);
|
||||
expect(dark).toBeGreaterThan(0);
|
||||
expect(dark).toBeLessThan(1);
|
||||
// the colour rows are as they were
|
||||
expect(m.split(" ").slice(0, 15).join(" ")).toBe("1 0 0 0 0 0 1 0 0 0 0 0 1 0 0");
|
||||
});
|
||||
|
||||
test("more strength takes more of the hue; more shadow lets the screen's shadows through half seen", () => {
|
||||
const pale = [0.5, 0.8, 0.5];
|
||||
expect(alpha(chromaMatrix({ color: "#0f0", strength: 0.2 }), pale)).toBe(1);
|
||||
expect(alpha(chromaMatrix({ color: "#0f0", strength: 1 }), pale)).toBe(0);
|
||||
// a shadow on the screen: a darker, duller green
|
||||
const shade = [0.05, 0.5, 0.05];
|
||||
expect(alpha(chromaMatrix({ color: "#0f0", shadow: 0 }), shade)).toBe(1);
|
||||
const half = alpha(chromaMatrix({ color: "#0f0", shadow: 1 }), shade);
|
||||
expect(half).toBeGreaterThan(0.1);
|
||||
expect(half).toBeLessThan(0.5);
|
||||
});
|
||||
|
||||
test("a blue screen keys blue, not green", () => {
|
||||
const m = chromaMatrix({ color: "#1040e0" });
|
||||
expect(alpha(m, [0.06, 0.25, 0.88])).toBe(0);
|
||||
expect(alpha(m, [0, 1, 0])).toBe(1);
|
||||
});
|
||||
|
||||
test("a grey has no hue to key by, and a colour must be one", () => {
|
||||
expect(chromaError({ color: "#808080" })).toMatch(/is grey/);
|
||||
expect(chromaError({ color: "green" })).toMatch(/#rrggbb or #rgb/);
|
||||
expect(chromaError({ color: "#0f0", strength: 3 })).toMatch(/strength is from 0 to 1/);
|
||||
expect(chromaId({ color: "#0f0" })).toBe("raea-key-00ff00-50-20");
|
||||
});
|
||||
});
|
||||
|
||||
describe("<Nudge> draws them on the part it places", () => {
|
||||
test("an element gets the blend, and the key as its filter before its own, drawn beside it", () => {
|
||||
const html = renderFrame(<Nudge blend="screen" chroma={{ color: "#00ff00" }}><div style={{ filter: "blur(2px)" }}>hi</div></Nudge>, opts);
|
||||
expect(html).toContain("mix-blend-mode:screen");
|
||||
expect(html).toContain("filter:url(#raea-key-00ff00-50-20) blur(2px)");
|
||||
expect(html).toContain('<filter id="raea-key-00ff00-50-20" color-interpolation-filters="sRGB"');
|
||||
expect(html).toContain("<feColorMatrix");
|
||||
expect(html).toContain('operator="in"');
|
||||
});
|
||||
|
||||
test("a masked element is placed in a full-frame layer, so the mask is laid over the frame and moves with it", () => {
|
||||
const html = renderFrame(<Nudge x={40} mask={{ kind: "circle" }}><div style={{ width: 100 }}>hi</div></Nudge>, opts);
|
||||
expect(html).toMatch(/<div style="[^"]*transform:translate\(40px, 0px\)[^"]*mask-image:url\("data:image\/svg\+xml,[^"]*"><div style="width:100px">hi<\/div><\/div>/);
|
||||
});
|
||||
|
||||
test("a component is placed in a full-frame layer that carries them; normal is no blend", () => {
|
||||
const Part = () => <p>part</p>;
|
||||
const html = renderFrame(<Nudge mask={{ kind: "line", rotate: 10 }} blend="normal"><Part /></Nudge>, opts);
|
||||
expect(html).toContain("mask-image:url(");
|
||||
expect(html).not.toContain("mix-blend-mode");
|
||||
});
|
||||
|
||||
test("a blend it hasn't got, a grey key and a bad mask are refused", () => {
|
||||
expect(BLEND_KINDS).toContain("plus-lighter");
|
||||
expect(() => renderFrame(<Nudge blend={"glow" as never}><div /></Nudge>, opts)).toThrow(/blend is one of normal, darken, screen/);
|
||||
expect(() => renderFrame(<Nudge chroma={{ color: "#777777" }}><div /></Nudge>, opts)).toThrow(/is grey/);
|
||||
expect(() => renderFrame(<Nudge mask={{ kind: "circle", round: 4 }}><div /></Nudge>, opts)).toThrow(/round is from 0 to 1/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("a <Video> wears its cutout's mattes (TL7l in a composition)", () => {
|
||||
const seq = (html: string) => /mask-image:url\(([^)]*)\)/.exec(html)?.[1];
|
||||
const at = (frame: number, more: object = {}) =>
|
||||
renderFrame(<Video src="/media/clips/take.mp4" startFrom={30} matte={{ src: "/media/matte/take-person", fps: 30, count: 90 }} {...more} />, { ...opts, durationInFrames: 120, frame });
|
||||
|
||||
test("the matte its source frame was made from, as its mask over the picture as it is placed", () => {
|
||||
// from its frame 30 on: the composition's frame 10 shows the file's frame 40
|
||||
expect(seq(at(10))).toBe("/media/matte/take-person/m00041.png");
|
||||
expect(at(10)).toContain("mask-size:cover");
|
||||
expect(at(10)).toContain("mask-position:50% 50%");
|
||||
expect(seq(at(0, { playbackRate: 2 }))).toBe("/media/matte/take-person/m00031.png");
|
||||
expect(seq(at(5, { playbackRate: 2 }))).toBe("/media/matte/take-person/m00041.png");
|
||||
// contained, or stretched to the box, the matte is too
|
||||
expect(at(10, { style: { objectFit: "contain" } })).toContain("mask-size:contain");
|
||||
expect(at(10, { style: { objectFit: "fill" } })).toContain("mask-size:100% 100%");
|
||||
});
|
||||
|
||||
test("one matte each few frames is held until the next; past the last, the last", () => {
|
||||
const sparse = { matte: { src: "/media/matte/take-person/", fps: 30, every: 4, count: 23 } };
|
||||
expect(seq(at(10, sparse))).toBe("/media/matte/take-person/m00011.png");
|
||||
expect(seq(at(13, sparse))).toBe("/media/matte/take-person/m00011.png");
|
||||
expect(seq(at(14, sparse))).toBe("/media/matte/take-person/m00012.png");
|
||||
expect(seq(at(110, sparse))).toBe("/media/matte/take-person/m00023.png");
|
||||
});
|
||||
|
||||
test("a file at another rate than the composition's: the matte of the file's own frame", () => {
|
||||
// a 24 fps file in a 30 fps composition: the composition's frame 30 from the start is the file's 1 s, its frame 24
|
||||
expect(seq(renderFrame(<Video src="/media/clips/take.mp4" matte={{ src: "/media/matte/t", fps: 24, count: 72 }} />, { ...opts, durationInFrames: 120, frame: 30 }))).toBe("/media/matte/t/m00025.png");
|
||||
});
|
||||
|
||||
test("none without a matte; what it can't wear is said", () => {
|
||||
expect(seq(renderFrame(<Video src="/media/clips/take.mp4" />, opts))).toBeUndefined();
|
||||
expect(() => at(0, { framing: "face" })).toThrow(/can't go with framing/);
|
||||
expect(() => at(0, { matte: { src: "/media/matte/t", fps: 0, count: 3 } })).toThrow(/fps/);
|
||||
expect(() => at(0, { matte: { src: "/media/matte/t", fps: 30, count: 0 } })).toThrow(/count/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,44 @@
|
||||
// <Effect>: a look on the picture under it for its part's frames (docs/timeline.feature TL7b).
|
||||
import { expect, test } from "bun:test";
|
||||
import { AbsoluteFill, Effect, EFFECTS, effectAt, effectFilter, effectPartsError, partsFilter, Sequence } from "../src";
|
||||
import { renderFrame } from "../src/test";
|
||||
|
||||
const base = { frame: 0, fps: 30, width: 1080, height: 1920, durationInFrames: 90 };
|
||||
const at = (frame: number, el: JSX.Element) => renderFrame(<AbsoluteFill><div>under</div><Sequence from={30} durationInFrames={30}>{el}</Sequence></AbsoluteFill>, { ...base, frame });
|
||||
|
||||
test("an effect is on for its sequence's frames, as a filter on what is behind it", () => {
|
||||
expect(at(10, <Effect kind="mono" />)).not.toContain("data-effect");
|
||||
const on = at(40, <Effect kind="mono" />);
|
||||
expect(on).toContain('data-effect="mono"');
|
||||
expect(on).toContain("backdrop-filter:grayscale(1)");
|
||||
expect(at(70, <Effect kind="mono" />)).not.toContain("data-effect");
|
||||
});
|
||||
|
||||
test("its amount scales it, and it comes on and goes off over the frames it is given", () => {
|
||||
expect(at(40, <Effect kind="blur" amount={0.5} />)).toContain("backdrop-filter:blur(12px)");
|
||||
// 10 frames in: a tenth on its first frame, all of it from its tenth; 10 frames out: a tenth on its last
|
||||
expect(at(30, <Effect kind="mono" in={10} />)).toContain("backdrop-filter:grayscale(0.1)");
|
||||
expect(at(39, <Effect kind="mono" in={10} />)).toContain("backdrop-filter:grayscale(1)");
|
||||
expect(at(59, <Effect kind="mono" out={10} />)).toContain("backdrop-filter:grayscale(0.1)");
|
||||
expect(effectAt(0, 30, 10, 10)).toBeCloseTo(0.1, 6);
|
||||
expect(effectAt(15, 30, 10, 10)).toBe(1);
|
||||
});
|
||||
|
||||
test("every kind gives a filter, none at amount 0 changes the picture's numbers, and an unknown kind fails", () => {
|
||||
for (const e of EFFECTS) expect(effectFilter(e.kind, 1)).toMatch(/^[a-z-]+\(/);
|
||||
expect(effectFilter("vivid", 0)).toBe("saturate(1) contrast(1)");
|
||||
expect(effectFilter("nope")).toBeUndefined();
|
||||
expect(() => at(40, <Effect kind="nope" />)).toThrow(/kind is one of/);
|
||||
expect(() => at(40, <Effect kind="blur" amount={2} />)).toThrow(/amount/);
|
||||
});
|
||||
|
||||
test("an effect of its own is its parts: CSS filter functions from amount 0 to amount 1", () => {
|
||||
const dream = [["blur", 0, 6, "px"], ["saturate", 1, 1.6]] as [string, number, number, string?][];
|
||||
expect(partsFilter(dream, 1)).toBe("blur(6px) saturate(1.6)");
|
||||
expect(partsFilter(dream, 0)).toBe("blur(0px) saturate(1)");
|
||||
expect(at(40, <Effect kind="dream" parts={dream} amount={0.5} />)).toContain("backdrop-filter:blur(3px) saturate(1.3)");
|
||||
expect(effectPartsError(dream)).toBeUndefined();
|
||||
expect(effectPartsError([["drop-shadow", 0, 1]])).toMatch(/function is one of/);
|
||||
expect(effectPartsError([["blur", 0, 6, "em"]])).toMatch(/blur takes px/);
|
||||
expect(() => at(40, <Effect kind="dream" parts={[["url", 0, 1]] as never} />)).toThrow(/function is one of/);
|
||||
});
|
||||
@@ -0,0 +1,99 @@
|
||||
// <Nudge keys>: a placed part's properties over time, as the timeline writes them (docs/timeline.feature TL5d).
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { keyedAt, Nudge, type NudgeKey } from "@raea/video/nudge";
|
||||
import { Sequence } from "../src";
|
||||
import { renderFrame } from "../src/test";
|
||||
|
||||
const opts = { fps: 30, width: 1920, height: 1080, durationInFrames: 300 };
|
||||
|
||||
describe("a keyed property's value at a frame", () => {
|
||||
const scale: NudgeKey[] = [[10, 1], [40, 2]];
|
||||
|
||||
test("holds before its first key and after its last, and travels in a straight line between", () => {
|
||||
expect([0, 10, 25, 40, 99].map((f) => keyedAt(scale, f))).toEqual([1, 1, 1.5, 2, 2]);
|
||||
});
|
||||
|
||||
test("follows the first key's ease: hold stays then jumps, a bezier is CSS's", () => {
|
||||
expect(keyedAt([[10, 1, "hold"], [40, 2]], 39)).toBe(1);
|
||||
expect(keyedAt([[10, 1, "hold"], [40, 2]], 40)).toBe(2);
|
||||
const eased = keyedAt([[0, 0, [0.42, 0, 0.58, 1]], [100, 1]], 25);
|
||||
expect(eased).toBeCloseTo(0.1292, 3);
|
||||
// a handle above the graph overshoots
|
||||
expect(Math.max(...Array.from({ length: 50 }, (_, i) => keyedAt([[0, 0, [0.3, 1.6, 0.6, 1]], [49, 1]], i)))).toBeGreaterThan(1);
|
||||
});
|
||||
|
||||
test("keys are read in time order whatever order they are written in", () => {
|
||||
expect(keyedAt([[40, 2], [10, 1]], 25)).toBe(1.5);
|
||||
});
|
||||
|
||||
test("in a <Sequence> the keys run from the sequence's first frame, and a keyed property wins over its still value", () => {
|
||||
const at = (frame: number) => renderFrame(<Sequence from={50}><Nudge scale={3} keys={{ scale: [[0, 1], [30, 2]], opacity: [[0, 0], [10, 1]] }}><div>hi</div></Nudge></Sequence>, { ...opts, frame });
|
||||
expect(at(50)).toContain("opacity:0");
|
||||
expect(at(55)).toContain("opacity:0.5");
|
||||
expect(at(65)).toContain("scale(1.5)");
|
||||
expect(at(80)).toContain("scale(2)");
|
||||
expect(at(80)).not.toContain("scale(3)");
|
||||
// with no keys it is the still Nudge it was
|
||||
expect(renderFrame(<Nudge scale={3}><div>hi</div></Nudge>, { ...opts, frame: 0 })).toContain("scale(3)");
|
||||
});
|
||||
});
|
||||
|
||||
describe("the numbers inside a mask, a key and a crop, keyed by a dotted name (TL5a)", () => {
|
||||
const at = (el: JSX.Element, frame: number) => renderFrame(el, { ...opts, frame });
|
||||
const mask = { kind: "circle" as const, x: 0.5, y: 0.5, w: 0.3, h: 0.5 };
|
||||
// the mask image's SVG, decoded
|
||||
const svg = (html: string) => decodeURIComponent(/mask-image:url\("data:image\/svg\+xml,([^&]*)"\)/.exec(html)?.[1] ?? "");
|
||||
|
||||
test("a mask moves and softens over time, its still kind kept", () => {
|
||||
const el = (frame: number) => at(<Nudge mask={mask} keys={{ "mask.x": [[0, 0.25], [30, 0.75]], "mask.feather": [[0, 0], [30, 0.4]] }}><div>hi</div></Nudge>, frame);
|
||||
// 0.25 of 1920 at the first frame, the middle halfway, 0.75 at the last
|
||||
expect(svg(el(0))).toContain('cx="480"');
|
||||
expect(svg(el(15))).toContain('cx="960"');
|
||||
expect(svg(el(30))).toContain('cx="1440"');
|
||||
expect(svg(el(0))).not.toContain("feGaussianBlur");
|
||||
expect(svg(el(30))).toContain('stdDeviation="21.6"');
|
||||
});
|
||||
|
||||
test("a key's strength over time is a filter of its own each frame", () => {
|
||||
const el = (frame: number) => at(<Nudge chroma={{ color: "#00ff00" }} keys={{ "chroma.strength": [[0, 0.2], [10, 0.8]] }}><div>hi</div></Nudge>, frame);
|
||||
expect(el(0)).toContain("raea-key-00ff00-20-20");
|
||||
expect(el(10)).toContain("raea-key-00ff00-80-20");
|
||||
});
|
||||
|
||||
test("a crop's side over time, the others as still", () => {
|
||||
const el = (frame: number) => at(<Nudge crop={[0, 0.1, 0, 0]} keys={{ "crop.left": [[0, 0], [20, 0.5]] }}><div>hi</div></Nudge>, frame);
|
||||
expect(el(10)).toContain("clip-path:inset(10% 0% 0% 25%)");
|
||||
});
|
||||
|
||||
test("a curve that overshoots stays inside what the value can be", () => {
|
||||
const el = at(<Nudge mask={mask} keys={{ "mask.feather": [[0, 0, [0.3, 1.8, 0.6, 1]], [30, 1]] }}><div>hi</div></Nudge>, 12);
|
||||
expect(svg(el)).toContain('stdDeviation="54"');
|
||||
});
|
||||
|
||||
test("keys for a mask with no mask, or a name it hasn't, fail", () => {
|
||||
expect(() => at(<Nudge keys={{ "mask.x": [[0, 0.2]] }}><div>hi</div></Nudge>, 0)).toThrow(/need a mask/);
|
||||
expect(() => at(<Nudge keys={{ "mask.kind": [[0, 1]] } as never}><div>hi</div></Nudge>, 0)).toThrow(/keys are for/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("a placed part mirrored and cropped (docs/timeline.feature TL3h)", () => {
|
||||
const at = (el: JSX.Element) => renderFrame(el, { ...opts, frame: 0 });
|
||||
|
||||
test("mirror flips it left to right, with its scale", () => {
|
||||
expect(at(<Nudge mirror><div>hi</div></Nudge>)).toContain("transform:scale(-1, 1)");
|
||||
expect(at(<Nudge mirror scale={2} x={10}><div>hi</div></Nudge>)).toContain("transform:translate(10px, 0px) scale(-2, 2)");
|
||||
});
|
||||
|
||||
test("crop cuts each side off by its share, on an element and on a component's layer", () => {
|
||||
expect(at(<Nudge crop={[0.1, 0, 0, 0.25]}><div>hi</div></Nudge>)).toContain("clip-path:inset(0% 0% 25% 10%)");
|
||||
const Part = () => <p>part</p>;
|
||||
expect(at(<Nudge crop={[0, 0.5, 0, 0]}><Part /></Nudge>)).toContain("clip-path:inset(50% 0% 0% 0%)");
|
||||
// no crop, no clip
|
||||
expect(at(<Nudge crop={[0, 0, 0, 0]}><div>hi</div></Nudge>)).not.toContain("clip-path");
|
||||
});
|
||||
|
||||
test("a crop out of range fails", () => {
|
||||
expect(() => at(<Nudge crop={[1, 0, 0, 0]}><div>hi</div></Nudge>)).toThrow(/crop/);
|
||||
expect(() => at(<Nudge crop={[0, 0, 0] as unknown as [number, number, number, number]}><div>hi</div></Nudge>)).toThrow(/crop/);
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
// registerRoot, from spec/motion.feature ("Declaring and registering"), including a root with no Composition.
|
||||
import { beforeEach, expect, test } from "bun:test";
|
||||
import { Composition, Sequence, getCompositions, registerRoot, useCurrentFrame } from "../src";
|
||||
import { resetRegistry } from "../src/test";
|
||||
import { Composition, Sequence, getCompositions, registerRoot, useCurrentFrame, useVideoConfig } from "../src";
|
||||
import { renderFrame, resetRegistry } from "../src/test";
|
||||
|
||||
beforeEach(() => resetRegistry());
|
||||
function Uses() { useCurrentFrame(); return null; }
|
||||
@@ -51,3 +51,27 @@ test("an edit plays its segments one after another, and the length is their sum"
|
||||
test("an edit's segment must sit inside the composition", () => {
|
||||
expect(() => registerRoot(() => <Composition id="cut" component={Uses} width={1920} height={1080} fps={30} durationInFrames={90} edit={{ segments: [[60, 120]] }} />)).toThrow(/edit.segments/);
|
||||
});
|
||||
|
||||
test("an edit's scale draws the composition smaller, laid out at its own size", () => {
|
||||
let cfg: any;
|
||||
function Reads() { cfg = useVideoConfig(); return <div>drawn</div>; }
|
||||
registerRoot(() => <Composition id="draft" component={Reads} width={1920} height={1080} fps={30} durationInFrames={90} edit={{ segments: [[0, 30]], scale: 0.5 }} />);
|
||||
const c = getCompositions()[0];
|
||||
expect(c).toMatchObject({ width: 960, height: 540, durationInFrames: 30 });
|
||||
const html = renderFrame(<c.component />, { frame: 0, fps: 30, width: c.width, height: c.height, durationInFrames: c.durationInFrames });
|
||||
// inside, the composition sees the size it says, in a box that size drawn at half
|
||||
expect(cfg).toMatchObject({ width: 1920, height: 1080 });
|
||||
expect(html).toContain("width:1920px");
|
||||
expect(html).toContain("transform:scale(0.5, 0.5)");
|
||||
expect(html).toContain("drawn");
|
||||
});
|
||||
|
||||
test("an edit's scale of 1 changes nothing, and one outside (0, 1] fails", () => {
|
||||
registerRoot(() => <Composition id="same" component={Uses} width={1080} height={1920} fps={30} durationInFrames={9} edit={{ scale: 1 }} />);
|
||||
expect(getCompositions()[0]).toMatchObject({ width: 1080, height: 1920 });
|
||||
expect(getCompositions()[0].component).toBe(Uses);
|
||||
for (const scale of [0, 1.5, Number.NaN]) {
|
||||
resetRegistry();
|
||||
expect(() => registerRoot(() => <Composition id="bad" component={Uses} width={1080} height={1920} fps={30} durationInFrames={9} edit={{ scale }} />)).toThrow(/edit.scale/);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,58 @@
|
||||
// A <Video>'s or an <Audio>'s speed as a curve over its source (docs/timeline.feature TL6b): the source frame each
|
||||
// frame shows, the rate its sound plays at, and how long the curve takes.
|
||||
import { expect, test } from "bun:test";
|
||||
import { Audio, Sequence, speedLength, Video } from "../src";
|
||||
import { renderFrame } from "../src/test";
|
||||
|
||||
const base = { frame: 0, fps: 30, width: 1080, height: 1920, durationInFrames: 600 };
|
||||
const attr = (html: string, name: string) => new RegExp(`${name}="([^"]*)"`).exec(html)?.[1];
|
||||
const at = (frame: number, curve: [number, number][], more: object = {}) => {
|
||||
const html = renderFrame(<Video src="media/v.mp4" startFrom={30} endAt={150} speedCurve={curve} {...more} />, { ...base, frame });
|
||||
return { source: Number(attr(html, "data-source-frame")), rate: Number(attr(html, "data-playback-rate")), ended: attr(html, "data-ended") };
|
||||
};
|
||||
|
||||
test("a flat curve is a playbackRate", () => {
|
||||
expect(at(10, [[0, 2], [1, 2]]).source).toBeCloseTo(50, 6);
|
||||
expect(at(10, [[0, 2], [1, 2]]).rate).toBeCloseTo(2, 6);
|
||||
expect(speedLength([[0, 2], [1, 2]], 120)).toBeCloseTo(60, 6);
|
||||
});
|
||||
|
||||
test("the source moves faster where the curve is higher, and each frame's rate is the source it passes", () => {
|
||||
const curve: [number, number][] = [[0, 1], [0.5, 4], [1, 1]];
|
||||
const steps = Array.from({ length: 20 }, (_, f) => at(f, curve));
|
||||
for (let f = 0; f + 1 < steps.length; f++) {
|
||||
// the next frame's source is where this frame's rate takes it: the sound stays with the picture
|
||||
expect(steps[f + 1].source - steps[f].source).toBeCloseTo(steps[f].rate, 6);
|
||||
expect(steps[f + 1].rate).toBeGreaterThan(steps[f].rate);
|
||||
}
|
||||
expect(steps[0].source).toBe(30);
|
||||
expect(steps[0].rate).toBeGreaterThan(1);
|
||||
});
|
||||
|
||||
test("it ends when the curve has played its source, holding the frame before endAt", () => {
|
||||
const curve: [number, number][] = [[0, 1], [1, 3]];
|
||||
const length = speedLength(curve, 120);
|
||||
expect(length).toBeCloseTo((120 * Math.log(3)) / 2, 6);
|
||||
expect(at(Math.floor(length) - 1, curve).ended).toBeUndefined();
|
||||
const after = at(Math.ceil(length), curve);
|
||||
expect(after.ended).toBe("true");
|
||||
expect(after.source).toBe(149);
|
||||
});
|
||||
|
||||
test("a looped curve starts over", () => {
|
||||
const curve: [number, number][] = [[0, 2], [1, 2]];
|
||||
expect(at(70, curve, { loop: true }).source).toBeCloseTo(30 + 10 * 2, 6);
|
||||
});
|
||||
|
||||
test("a fadeOut ends where the curve does", () => {
|
||||
const curve: [number, number][] = [[0, 2], [1, 2]];
|
||||
const vol = (frame: number) => Number(attr(renderFrame(<Sequence from={0} durationInFrames={300}><Audio src="media/a.wav" endAt={120} speedCurve={curve} fadeOut={1} /></Sequence>, { ...base, frame }), "data-volume"));
|
||||
expect(vol(20)).toBe(1);
|
||||
expect(vol(45)).toBeCloseTo(0.5, 6);
|
||||
});
|
||||
|
||||
test("a curve needs endAt, and its points stay in range", () => {
|
||||
expect(() => renderFrame(<Video src="media/v.mp4" speedCurve={[[0, 1]]} />, base)).toThrow(/endAt/);
|
||||
expect(() => renderFrame(<Video src="media/v.mp4" endAt={60} speedCurve={[[0, 20]]} />, base)).toThrow(/speed/);
|
||||
expect(() => renderFrame(<Video src="media/v.mp4" endAt={60} speedCurve={[[2, 1]]} />, base)).toThrow(/place/);
|
||||
});
|
||||
@@ -0,0 +1,57 @@
|
||||
// <Transition>: how a part comes in and goes out, as the timeline writes a transition on a cut
|
||||
// (docs/timeline.feature TL7a).
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { COMBOS, comboStyle, joinStyles, Transition, transitionAt, transitionStyle } from "@raea/video/transition";
|
||||
import { Sequence } from "../src";
|
||||
import { renderFrame } from "../src/test";
|
||||
|
||||
const opts = { fps: 30, width: 1920, height: 1080, durationInFrames: 300 };
|
||||
|
||||
describe("a part comes in over its first frames and goes out over its last", () => {
|
||||
test("how far into view it is: 0 before, 1 once in, counted in the part's own frames", () => {
|
||||
const edge = { kind: "fade" as const, frames: 10 };
|
||||
expect([0, 4, 9, 50].map((f) => transitionAt(edge, "in", f, 60))).toEqual([0.1, 0.5, 1, 1]);
|
||||
expect([0, 49, 50, 55, 59].map((f) => transitionAt(edge, "out", f, 60))).toEqual([1, 1, 1, 0.5, 0.1]);
|
||||
expect(transitionAt(undefined, "in", 0, 60)).toBe(1);
|
||||
expect(transitionAt({ kind: "fade", frames: 0 }, "in", 0, 60)).toBe(1);
|
||||
});
|
||||
|
||||
test("each kind's look: a fade's opacity, a slide's move, a wipe's cover, a zoom's size; nothing once it is in", () => {
|
||||
expect(transitionStyle("fade", "in", 0.5)).toEqual({ opacity: 0.5 });
|
||||
expect(transitionStyle("slide", "in", 0)).toEqual({ transform: "translateX(100%)" });
|
||||
expect(transitionStyle("slide", "out", 0)).toEqual({ transform: "translateX(-100%)" });
|
||||
expect(transitionStyle("wipe", "in", 0)).toEqual({ clipPath: "inset(0 100% 0 0)" });
|
||||
expect(transitionStyle("zoom", "in", 0)).toEqual({ transform: "scale(0.85)", opacity: 0 });
|
||||
expect(transitionStyle("slide", "in", 1)).toEqual({});
|
||||
});
|
||||
|
||||
test("in a <Sequence> it plays at the sequence's ends and leaves the middle as it was", () => {
|
||||
const at = (frame: number) => renderFrame(<Sequence from={100} durationInFrames={60}><Transition in={{ kind: "fade", frames: 10 }} out={{ kind: "slide", frames: 10 }}><p>hi</p></Transition></Sequence>, { ...opts, frame });
|
||||
expect(at(104)).toContain("opacity:0.5");
|
||||
expect(at(130)).not.toContain("opacity");
|
||||
expect(at(130)).not.toContain("translateX");
|
||||
expect(at(159)).toContain("translateX(-81%)");
|
||||
expect(() => renderFrame(<Transition in={{ kind: "spin" as never, frames: 10 }}>x</Transition>, { ...opts, frame: 0 })).toThrow(/kind is one of/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("a Combo moves the part over its whole length (TL7e)", () => {
|
||||
const pulse = COMBOS.find((c) => c.kind === "pulse");
|
||||
test("its wave eased between evenly spaced values, at rest where a cycle starts and ends, looping", () => {
|
||||
expect(comboStyle(pulse, 0, 60)).toEqual({ transform: "scale(1)" });
|
||||
expect(comboStyle(pulse, 30, 60)).toEqual({ transform: "scale(1.08)" });
|
||||
expect(comboStyle(pulse, 15, 60)).toEqual({ transform: "scale(1.04)" });
|
||||
expect(comboStyle(pulse, 90, 60)).toEqual(comboStyle(pulse, 30, 60));
|
||||
// a spin keeps turning at one pace
|
||||
expect(comboStyle(COMBOS.find((c) => c.kind === "spin"), 15, 60)).toEqual({ transform: "rotate(90deg)" });
|
||||
expect(comboStyle(undefined, 15, 60)).toEqual({});
|
||||
});
|
||||
|
||||
test("in a <Sequence> with its In and Out: the moves side by side, the fades multiplied", () => {
|
||||
const at = (frame: number) => renderFrame(<Sequence from={0} durationInFrames={60}><Transition in={{ kind: "fade", frames: 10 }} combo={{ kind: "pulse", frames: 60 }}><p>hi</p></Transition></Sequence>, { ...opts, frame });
|
||||
expect(at(4)).toContain("opacity:0.5");
|
||||
expect(at(30)).toContain("scale(1.08)");
|
||||
expect(joinStyles({ transform: "a", opacity: 0.5 }, { transform: "b", opacity: 0.5, clipPath: "c" })).toEqual({ transform: "a b", opacity: 0.25, clipPath: "c" });
|
||||
expect(() => renderFrame(<Transition combo={{ kind: "wobble", frames: 10 }}>x</Transition>, { ...opts, frame: 0 })).toThrow(/combo.kind is one of/);
|
||||
});
|
||||
});
|
||||
@@ -12,6 +12,7 @@ import { domSvgText } from "./dom-svgtext";
|
||||
import { domObservers } from "./dom-observers";
|
||||
import { domTree } from "./dom-tree";
|
||||
import { boxOf, type Box } from "./page-layout";
|
||||
import { retime } from "@raea/video/timeline";
|
||||
|
||||
/** The web's DOMRect, as getBoundingClientRect answers it. */
|
||||
export class DOMRect {
|
||||
@@ -63,7 +64,12 @@ const inline = (b: Box) => b.inline;
|
||||
|
||||
/** A ref's DOM, from the entry, given bevy-react's exports: LR3's geometry, LR4's tree and LR5's style on its BevyElement and
|
||||
* BevyTextNode, and LR7's document and window (raea's patch; a bridge without it has none, and refs stay plain handles). */
|
||||
export function domReads(bevy: { BevyElement?: { prototype: object }; BevyTextNode?: { prototype: object }; containerNode?: unknown }): void {
|
||||
export function domReads(bevy: { BevyElement?: { prototype: object }; BevyTextNode?: { prototype: object }; containerNode?: unknown; addEventListener?: (name: string, cb: (v: unknown) => void) => unknown }): void {
|
||||
// (the one call the entry makes with the bridge's exports, so here too:) the stage's props as they're set, their
|
||||
// sequences retimed by name (`__raeaSequences`: a timeline's edit shown before its file is opened again, TL13a).
|
||||
// Lite's entry hands the nodes instead: its runtime leaves the bridge's listener on globalThis (lite parts/root.ts)
|
||||
const listen = bevy.addEventListener ?? (globalThis as { __raeaListen?: typeof bevy.addEventListener }).__raeaListen;
|
||||
listen?.("raea-props", (v) => retime((v as { __raeaSequences?: unknown } | null)?.__raeaSequences));
|
||||
geometry(bevy.BevyElement);
|
||||
domTree(bevy.BevyElement, bevy.BevyTextNode);
|
||||
domStyle(bevy.BevyElement);
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
// raea/editor (raea's own; Bevy has no timeline editor): docs/timeline.feature TL11b. The timeline the feed edits a film, a scene or a sound on,
|
||||
// as data. Tracks, clips, keys and markers; every edit an operation with its inverse (apply); a composition's
|
||||
// sequences read into it (fromSequences) and an operation turned into the edits to write back (seqEdits); a film's
|
||||
// scenes read into it (fromRender) and its cut read back out as segments (segmentsOf); easings, speed curves, snapping, the
|
||||
// frame store's keys and what a plugin adds. No React and no DOM: an agent's script, the app's host and a test use
|
||||
// the same model the app's strip does.
|
||||
export * from "@raea/timeline";
|
||||
@@ -55,7 +55,11 @@ export {
|
||||
type RegisteredComposition,
|
||||
} from "@raea/video/registry";
|
||||
|
||||
export { Effect, effectAt, type EffectProps } from "@raea/video/effect";
|
||||
export { EFFECTS, EFFECT_FNS, effectFilter, effectPartsError, partsFilter, type EffectKind, type EffectPart } from "@raea/video/effects";
|
||||
export { Nudge, type NudgeProps } from "@raea/video/nudge";
|
||||
export { speedLength, speedPoints, speedSource, type SpeedPoint } from "@raea/video/speed";
|
||||
export { Transition, type TransitionProps, type TransitionEdge, type TransitionKind } from "@raea/video/transition";
|
||||
export { Region, useRegion, proofBoxes, regionBand, type RegionName, type RegionBox, type RegionProps, type ProofInput, type ProofPart } from "@raea/video/region";
|
||||
export { InputRegion } from "@raea/video/input-region";
|
||||
export { lyria, sao, fish, isGeneratedAsset, type AssetKind, type GeneratedAsset } from "@raea/asset/assets";
|
||||
|
||||
@@ -2,4 +2,4 @@
|
||||
// into it at M5; until then the old subpaths and this one export the same values.
|
||||
// raea/video (raea's own; Bevy has no video crate): time-shifted sequences and footage.
|
||||
export { Sequence, Series, Loop, Freeze, type SequenceProps, type SequenceLayout, type SeriesSequenceProps, type LoopProps, type FreezeProps } from "@raea/video/timeline";
|
||||
export { Video, type VideoProps, type MediaProps } from "@raea/video/media";
|
||||
export { Video, type VideoProps, type VideoMatte, type MediaProps } from "@raea/video/media";
|
||||
@@ -1,7 +1,11 @@
|
||||
// The root, and React's default export.
|
||||
import { flush, ROOT_ID } from "../../node_modules/bevy-react/src/bridge";
|
||||
import { addEventListener, flush, ROOT_ID } from "../../node_modules/bevy-react/src/bridge";
|
||||
import { Children, Component, Fragment, Instance, Out, PRUNE_EVERY, ROOT_SLOT, S, children, cloneElement, createContext, createElement, effectsQueue, forwardRef, isValidElement, memo, prune, render, startTransition, sweep, unsee, useCallback, useContext, useDebugValue, useDeferredValue, useEffect, useId, useImperativeHandle, useInsertionEffect, useLayoutEffect, useMemo, useReducer, useRef, useState, useSyncExternalStore, useTransition, version } from "./all";
|
||||
|
||||
// the bridge's events for the SDK's own listeners: React's entry hands the SDK bevy-react's exports (sdk/raea
|
||||
// dom-reads.ts domReads), lite's hands it the nodes, so the SDK finds them here (a timeline's retimed sequences, TL13a)
|
||||
(globalThis as { __raeaListen?: typeof addEventListener }).__raeaListen = addEventListener;
|
||||
|
||||
// ---- the root
|
||||
|
||||
const rootInstance: Instance = { fn: null, hooks: [], effects: [], cleanups: new Map(), kids: new Map(), seen: true, id: ROOT_SLOT, parent: null, el: null, inText: false, out: null, reads: null, codes: null, stale: false, misses: 0, cool: 0, sites: null, stamp: 0 };
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"name": "@raea/task",
|
||||
"license": "FSL-1.1-ALv2",
|
||||
"private": true,
|
||||
"version": "0.1.0",
|
||||
"description": "raea's plans and tasks (docs/plan.feature): a project's plan.org read and written losslessly, its tasks as typed values, every edit by task id, keyword sequences, properties, kinds and views a plugin can add, and React hooks and components. No runtime dependencies; React only for ./react.",
|
||||
"type": "module",
|
||||
"main": "src/index.ts",
|
||||
"exports": {
|
||||
".": "./src/index.ts",
|
||||
"./org": "./src/org.ts",
|
||||
"./react": "./src/react.tsx"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "bun test test/org test/edit test/extend test/tools"
|
||||
},
|
||||
"peerDependencies": { "react": "19.2.0" }
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
// A plan in a few lines for an agent's prompt (docs/plan.feature PL5): the open tasks with their ids, keywords,
|
||||
// priorities, dates and links, under the headings they sit in, and how many are done. An agent reads this each turn
|
||||
// and edits the plan by those ids.
|
||||
import { isClosed, openTasks, type Plan, type Task } from "./model.ts"
|
||||
|
||||
/** One task as a line: its id, keyword, priority, words, tags, dates, item and who has it. */
|
||||
export function taskLine(t: Task): string {
|
||||
const bits = [t.ref, t.keyword ?? "", t.priority ? `[#${t.priority}]` : "", t.text]
|
||||
if (t.tags.length) bits.push(`:${t.tags.join(":")}:`)
|
||||
if (t.deadline) bits.push(`DEADLINE ${t.deadline.date}`)
|
||||
if (t.scheduled) bits.push(`SCHEDULED ${t.scheduled.date}`)
|
||||
if (t.progress) bits.push(`[${t.progress.done}/${t.progress.total}]`)
|
||||
if (t.item) bits.push(`item ${t.item}`)
|
||||
if (t.agents.length) bits.push(`agent ${t.agents.join(" ")}`)
|
||||
if (t.from) bits.push(`from ${t.from}`)
|
||||
return bits.filter(Boolean).join(" ")
|
||||
}
|
||||
|
||||
/** The open tasks under their headings, at most `max` (40) of them, and a count of the closed ones. */
|
||||
export function planDigest(plan: Plan, o: { max?: number } = {}): string {
|
||||
const open = openTasks(plan)
|
||||
const max = o.max ?? 40
|
||||
const lines: string[] = []
|
||||
let stage: string | undefined
|
||||
for (const t of open.slice(0, max)) {
|
||||
if (t.stage !== stage) {
|
||||
stage = t.stage
|
||||
if (stage) lines.push(`${stage}:`)
|
||||
}
|
||||
lines.push(`${" ".repeat(Math.max(0, t.level - 1))}- ${taskLine(t)}`)
|
||||
}
|
||||
if (open.length > max) lines.push(`... and ${open.length - max} more open`)
|
||||
const closed = plan.tasks.filter((t) => isClosed(t.state)).length
|
||||
if (!open.length) lines.push("No open tasks.")
|
||||
if (closed) lines.push(`${closed} closed (done or dropped).`)
|
||||
return lines.join("\n")
|
||||
}
|
||||
@@ -0,0 +1,357 @@
|
||||
// Every change to a plan, as data (docs/plan.feature PL3): add, set, state, move, remove and check, each naming its
|
||||
// task by :ID: (or #N for a headline that has none yet). applyEdits reads the text, makes the edits in order, gives
|
||||
// every task an :ID: it lacks, brings progress cookies up to date and writes the text back; what no edit touched is
|
||||
// as it was, byte for byte. The page, the host's tools and an agent's own script all change a plan this way.
|
||||
import { plans, STATES, type PlanRegistry } from "./extend.ts"
|
||||
import { isClosed, readPlan, type Plan, type State } from "./model.ts"
|
||||
import { bare, checksOf, COOKIE, fileSequences, lineOf, printOrg, setCheck, type OrgDoc, type Planning, type Section } from "./org.ts"
|
||||
import { dayOf, nowStamp } from "./time.ts"
|
||||
|
||||
export interface TaskFields {
|
||||
title?: string
|
||||
/** A, B or C (any capital or digit); null takes it off */
|
||||
priority?: string | null
|
||||
/** replaces its tags */
|
||||
tags?: string[]
|
||||
/** YYYY-MM-DD, MM-DD or an Org timestamp; null takes it off */
|
||||
deadline?: string | null
|
||||
scheduled?: string | null
|
||||
/** the feed item it stands on */
|
||||
item?: string | null
|
||||
/** who has it, by agent id; [] takes them off */
|
||||
agents?: string[]
|
||||
from?: string | null
|
||||
kind?: string | null
|
||||
verb?: string | null
|
||||
/** any other property; null takes it off */
|
||||
props?: Record<string, string | null>
|
||||
/** a line of text added under it */
|
||||
note?: string
|
||||
}
|
||||
|
||||
export type PlanEdit =
|
||||
| ({ op: "add"; title: string; id?: string; state?: string; under?: string; before?: string; after?: string; checks?: string[] } & TaskFields)
|
||||
| ({ op: "set"; ref: string } & TaskFields)
|
||||
| { op: "state"; ref: string; state: string; item?: string; note?: string }
|
||||
| { op: "move"; ref: string; before?: string; after?: string; under?: string }
|
||||
| { op: "remove"; ref: string }
|
||||
| { op: "check"; ref: string; index?: number; done?: boolean; add?: string }
|
||||
|
||||
export interface ApplyOptions {
|
||||
now?: Date
|
||||
newId?: (taken: ReadonlySet<string>) => string
|
||||
registry?: PlanRegistry
|
||||
}
|
||||
|
||||
export interface Applied {
|
||||
text: string
|
||||
/** each edit's task by its :ID: (an add's new id; a removed task's id as it was) */
|
||||
refs: string[]
|
||||
plan: Plan
|
||||
}
|
||||
|
||||
/** A new task id: t- and eight letters and digits, unused in `taken`. */
|
||||
export function newId(taken: ReadonlySet<string> = new Set()): string {
|
||||
for (;;) {
|
||||
const id = `t-${(Date.now() % 1e9).toString(36).padStart(6, "0")}${Math.floor(Math.random() * 1296).toString(36).padStart(2, "0")}`
|
||||
if (!taken.has(id)) return id
|
||||
}
|
||||
}
|
||||
|
||||
/** A tag as Org reads one: letters, digits, _ @ # %. Anything else (a dash, a space) becomes _. */
|
||||
export const tagOf = (s: string) => s.trim().replace(/^[#:]+/, "").replace(/[^\p{L}\p{N}_@#%]+/gu, "_").replace(/^_+|_+$/g, "")
|
||||
|
||||
/** The edit a checkbox makes: a closed task opens again, an open one is done. */
|
||||
export const toggled = (t: { ref: string; state?: State }): PlanEdit => ({ op: "state", ref: t.ref, state: isClosed(t.state) ? "todo" : "done" })
|
||||
|
||||
/** A new project's plan: its title, and raea's keywords spelled out for Emacs and any other Org reader. */
|
||||
export const newPlan = (title: string) => `#+TITLE: ${title.replace(/\s+/g, " ").trim()}\n#+TODO: TODO MAKING REVIEW | DONE DROPPED\n\n`
|
||||
|
||||
const oneLine = (s: string) => s.replace(/\s+/g, " ").trim()
|
||||
const propOf = (s: Section, key: string) => s.props?.find(([k]) => k.toUpperCase() === key)?.[1]
|
||||
|
||||
function setProp(s: Section, key: string, value: string | null | undefined) {
|
||||
const k = key.toUpperCase()
|
||||
if (!/^[A-Z][\w-]*$/.test(k)) throw new Error(`a property is one word: ${key}`)
|
||||
const at = s.props?.findIndex(([x]) => x.toUpperCase() === k) ?? -1
|
||||
if (value === null || value === undefined || value === "") {
|
||||
if (at >= 0) s.props = s.props!.filter((_, i) => i !== at)
|
||||
if (s.props && !s.props.length) s.props = undefined
|
||||
return
|
||||
}
|
||||
const v = oneLine(value)
|
||||
if (at >= 0) s.props = s.props!.map((p, i) => (i === at ? [p[0], v] : p))
|
||||
else s.props = [...(s.props ?? []), [k, v]]
|
||||
}
|
||||
|
||||
/** A line added to an entry's own text, before the blank lines that end it. */
|
||||
function addLine(doc: OrgDoc, s: Section, text: string, after?: number) {
|
||||
let at = after ?? s.body.length
|
||||
if (after === undefined) while (at > 0 && !bare(s.body[at - 1]).trim()) at--
|
||||
s.body = [...s.body.slice(0, at), lineOf(doc, text), ...s.body.slice(at)]
|
||||
}
|
||||
|
||||
interface Ctx {
|
||||
doc: OrgDoc
|
||||
words: Map<string, State>
|
||||
now: Date
|
||||
reg: PlanRegistry
|
||||
mint: () => string
|
||||
/** the headlines as they were before any edit, for #N */
|
||||
initial: Section[]
|
||||
}
|
||||
|
||||
/** The keyword for a state or a keyword: a plan's own #+TODO: words first, then raea's. */
|
||||
function wordFor(c: Ctx, want: string): string {
|
||||
if (c.words.has(want)) return want
|
||||
if (c.words.has(want.toUpperCase())) return want.toUpperCase()
|
||||
const state = want.toLowerCase() as State
|
||||
if (!STATES.includes(state)) throw new Error(`${want} is neither a keyword nor a state: ${[...c.words.keys()].join(" ")}, or ${STATES.join(", ")}`)
|
||||
for (const s of fileSequences(c.doc.head)) for (const w of [...s.open, ...s.done]) if (c.words.get(w) === state) return w
|
||||
for (const [w, st] of c.words) if (st === state) return w
|
||||
throw new Error(`no keyword in this plan means ${state}`)
|
||||
}
|
||||
|
||||
/** The headline a ref names: an :ID:, or #N as the plan was before these edits. */
|
||||
function find(c: Ctx, ref: string): Section | undefined {
|
||||
const n = /^#(\d+)$/.exec(ref)
|
||||
if (n) {
|
||||
const s = c.initial[Number(n[1])]
|
||||
return s && c.doc.sections.includes(s) ? s : undefined
|
||||
}
|
||||
return c.doc.sections.find((s) => propOf(s, "ID") === ref)
|
||||
}
|
||||
|
||||
function must(c: Ctx, ref: string): Section {
|
||||
const s = find(c, ref)
|
||||
if (!s) throw new Error(`no task ${ref} in the plan; read the plan for its tasks' ids`)
|
||||
return s
|
||||
}
|
||||
|
||||
/** A heading by its words (no keyword), made at the end of the plan when there's none. */
|
||||
function heading(c: Ctx, title: string): Section {
|
||||
const words = oneLine(title).toLowerCase()
|
||||
const had = c.doc.sections.find((s) => !s.keyword && oneLine(s.title).toLowerCase() === words)
|
||||
if (had) return had
|
||||
const s: Section = { level: 1, title: oneLine(title), tags: [], planning: {}, body: [] }
|
||||
c.doc.sections.push(s)
|
||||
return s
|
||||
}
|
||||
|
||||
/** Where a headline's subtree ends: the next headline at its level or above. */
|
||||
function subtreeEnd(doc: OrgDoc, at: number): number {
|
||||
const level = doc.sections[at].level
|
||||
let end = at + 1
|
||||
while (end < doc.sections.length && doc.sections[end].level > level) end++
|
||||
return end
|
||||
}
|
||||
|
||||
function fields(c: Ctx, s: Section, f: TaskFields) {
|
||||
if (f.title !== undefined) {
|
||||
const t = oneLine(f.title)
|
||||
if (!t) throw new Error("a task needs words")
|
||||
s.title = t
|
||||
}
|
||||
if (f.priority !== undefined) {
|
||||
const p = f.priority?.trim().toUpperCase()
|
||||
if (p && !/^[A-Z0-9]$/.test(p)) throw new Error(`a priority is one letter or digit (A, B, C): ${f.priority}`)
|
||||
s.priority = p || undefined
|
||||
}
|
||||
if (f.tags) s.tags = [...new Set(f.tags.map(tagOf).filter(Boolean))]
|
||||
for (const k of ["deadline", "scheduled"] as const) {
|
||||
const v = f[k]
|
||||
if (v === undefined) continue
|
||||
const { [k]: _, ...rest } = withoutRaw(s.planning, k)
|
||||
if (v === null || v === "") {
|
||||
s.planning = rest
|
||||
continue
|
||||
}
|
||||
const t = dayOf(v, c.now)
|
||||
if (!t) throw new Error(`${k}: a day as YYYY-MM-DD (or MM-DD this year): ${v}`)
|
||||
s.planning = { ...rest, [k]: t }
|
||||
}
|
||||
if (f.item !== undefined) setProp(s, "ITEM", f.item)
|
||||
if (f.agents) setProp(s, "AGENT", [...new Set(f.agents.map((a) => a.trim()).filter(Boolean))].join(" "))
|
||||
if (f.from !== undefined) setProp(s, "FROM", f.from)
|
||||
if (f.kind !== undefined) setProp(s, "KIND", f.kind)
|
||||
if (f.verb !== undefined) setProp(s, "VERB", f.verb)
|
||||
for (const [k, v] of Object.entries(f.props ?? {})) setProp(s, k, v)
|
||||
if (f.note?.trim()) addLine(c.doc, s, oneLine(f.note))
|
||||
}
|
||||
|
||||
/** A planning line without the parts of one key that raea kept as written: a value set for that key replaces them. */
|
||||
function withoutRaw(p: Planning, key: keyof Omit<Planning, "rest">): Planning {
|
||||
const rest = p.rest?.filter((r) => !r.toLowerCase().startsWith(`${key}:`))
|
||||
const { rest: _, ...out } = p
|
||||
return rest?.length ? { ...out, rest } : out
|
||||
}
|
||||
|
||||
/** The file's #+TODO: lines name `word`'s sequence, so Emacs cycles it: a line is added after the head's last
|
||||
* #+TODO: line (or its #+ lines) when a plugin's word is written into a file that doesn't name it. TODO and DONE, Org's
|
||||
* own, need none in a file with no #+TODO: line. */
|
||||
function declare(c: Ctx, word: string) {
|
||||
const seqs = fileSequences(c.doc.head)
|
||||
if (seqs.some((s) => s.open.includes(word) || s.done.includes(word))) return
|
||||
if (!seqs.length && (word === "TODO" || word === "DONE")) return
|
||||
const seq = [...c.reg.sequences.values()].find((s) => s.words.some((w) => w.word === word))
|
||||
if (!seq) return
|
||||
const open = seq.words.filter((w) => !isClosed(w.state)).map((w) => w.word)
|
||||
const done = seq.words.filter((w) => isClosed(w.state)).map((w) => w.word)
|
||||
const head = c.doc.head
|
||||
let at = 0
|
||||
head.forEach((l, i) => /^#\+(?:SEQ_|TYP_)?TODO:/i.test(bare(l)) && (at = i + 1))
|
||||
if (!at) while (at < head.length && bare(head[at]).startsWith("#+")) at++
|
||||
c.doc.head = [...head.slice(0, at), lineOf(c.doc, `#+TODO: ${open.join(" ")} | ${done.join(" ")}`), ...head.slice(at)]
|
||||
}
|
||||
|
||||
/** A task's state set: closing it stamps CLOSED, reopening it takes CLOSED off (Org's org-log-done time). */
|
||||
function mark(c: Ctx, s: Section, want: string) {
|
||||
const to = wordFor(c, want)
|
||||
const was = s.keyword ? c.words.get(s.keyword) : undefined
|
||||
s.keyword = to
|
||||
declare(c, to)
|
||||
const now = c.words.get(to)
|
||||
if (isClosed(now) && !isClosed(was)) s.planning = { ...withoutRaw(s.planning, "closed"), closed: nowStamp(c.now) }
|
||||
if (!isClosed(now)) {
|
||||
const { closed: _, ...rest } = withoutRaw(s.planning, "closed")
|
||||
s.planning = rest
|
||||
}
|
||||
}
|
||||
|
||||
/** Where a block of headlines goes, and at what level: before or after a task, or last under a parent or heading. */
|
||||
function place(c: Ctx, e: { before?: string; after?: string; under?: string }, level: number): { at: number; level: number } {
|
||||
if (e.before) {
|
||||
const t = must(c, e.before)
|
||||
return { at: c.doc.sections.indexOf(t), level: t.level }
|
||||
}
|
||||
if (e.after) {
|
||||
const t = must(c, e.after)
|
||||
return { at: subtreeEnd(c.doc, c.doc.sections.indexOf(t)), level: t.level }
|
||||
}
|
||||
if (e.under) {
|
||||
// a task's id that isn't there is a mistake, not a stage to make
|
||||
const p = find(c, e.under) ?? (/^(?:t-[a-z0-9]+|#\d+)$/i.test(e.under.trim()) ? must(c, e.under.trim()) : heading(c, e.under))
|
||||
return { at: subtreeEnd(c.doc, c.doc.sections.indexOf(p)), level: p.level + 1 }
|
||||
}
|
||||
return { at: c.doc.sections.length, level }
|
||||
}
|
||||
|
||||
function one(c: Ctx, e: PlanEdit): Section | string {
|
||||
switch (e.op) {
|
||||
case "add": {
|
||||
const kind = e.kind ? c.reg.kinds.get(e.kind) : undefined
|
||||
const f: TaskFields = { ...kind?.defaults, ...e }
|
||||
const id = e.id?.trim() || c.mint()
|
||||
if (find(c, id)) throw new Error(`a task already has the id ${id}`)
|
||||
const s: Section = { level: 1, title: "", tags: [], planning: {}, props: [["ID", id]], body: [] }
|
||||
fields(c, s, { ...f, title: e.title })
|
||||
// a kind with a sequence of its own starts at that sequence's first word
|
||||
const first = kind?.keywords ? c.reg.sequences.get(kind.keywords)?.words[0]?.word : undefined
|
||||
mark(c, s, e.state ?? first ?? "todo")
|
||||
for (const check of e.checks ?? []) addLine(c.doc, s, `- [ ] ${oneLine(check)}`)
|
||||
const { at, level } = place(c, e, 1)
|
||||
s.level = level
|
||||
c.doc.sections.splice(at, 0, s)
|
||||
return s
|
||||
}
|
||||
case "set": {
|
||||
const s = must(c, e.ref)
|
||||
fields(c, s, e)
|
||||
return s
|
||||
}
|
||||
case "state": {
|
||||
const s = must(c, e.ref)
|
||||
mark(c, s, e.state)
|
||||
fields(c, s, { item: e.item, note: e.note })
|
||||
return s
|
||||
}
|
||||
case "move": {
|
||||
const s = must(c, e.ref)
|
||||
if (!e.before && !e.after && !e.under) throw new Error("a move needs before, after or under")
|
||||
const from = c.doc.sections.indexOf(s)
|
||||
const block = c.doc.sections.slice(from, subtreeEnd(c.doc, from))
|
||||
for (const r of [e.before, e.after, e.under]) if (r && block.some((b) => b === find(c, r))) throw new Error("a task can't move into itself")
|
||||
c.doc.sections.splice(from, block.length)
|
||||
const { at, level } = place(c, e, s.level)
|
||||
const delta = level - s.level
|
||||
for (const b of block) b.level = Math.max(1, b.level + delta)
|
||||
c.doc.sections.splice(at, 0, ...block)
|
||||
return s
|
||||
}
|
||||
case "remove": {
|
||||
const s = must(c, e.ref)
|
||||
const from = c.doc.sections.indexOf(s)
|
||||
c.doc.sections.splice(from, subtreeEnd(c.doc, from) - from)
|
||||
return propOf(s, "ID") ?? e.ref
|
||||
}
|
||||
case "check": {
|
||||
const s = must(c, e.ref)
|
||||
const checks = checksOf(s.body)
|
||||
if (e.add?.trim()) {
|
||||
const last = checks.at(-1)
|
||||
const indent = last ? bare(s.body[last.line]).match(/^[ \t]*/)![0] : ""
|
||||
addLine(c.doc, s, `${indent}- [ ] ${oneLine(e.add)}`, last ? last.line + 1 : undefined)
|
||||
return s
|
||||
}
|
||||
const ch = e.index === undefined ? undefined : checks[e.index]
|
||||
if (!ch) throw new Error(`no checkbox ${e.index} under ${e.ref}: it has ${checks.length}`)
|
||||
s.body = s.body.map((l, i) => (i === ch.line ? setCheck(l, e.done ?? !ch.done) : l))
|
||||
return s
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Each [n/m] or [n%] cookie counts again: the tasks right under its headline, or, with none, its checkboxes. */
|
||||
function cookies(c: Ctx) {
|
||||
const parents: number[] = []
|
||||
const stack: number[] = []
|
||||
c.doc.sections.forEach((s, i) => {
|
||||
while (stack.length && c.doc.sections[stack.at(-1)!].level >= s.level) stack.pop()
|
||||
parents[i] = stack.at(-1) ?? -1
|
||||
stack.push(i)
|
||||
})
|
||||
c.doc.sections.forEach((s, i) => {
|
||||
const m = COOKIE.exec(s.title)
|
||||
if (!m) return
|
||||
const kids = c.doc.sections.filter((k, j) => parents[j] === i && k.keyword)
|
||||
let done: number
|
||||
let total: number
|
||||
if (kids.length) {
|
||||
done = kids.filter((k) => isClosed(c.words.get(k.keyword!))).length
|
||||
total = kids.length
|
||||
} else {
|
||||
const checks = checksOf(s.body)
|
||||
const top = Math.min(...checks.map((x) => x.indent))
|
||||
const own = checks.filter((x) => x.indent === top)
|
||||
done = own.filter((x) => x.done).length
|
||||
total = own.length
|
||||
}
|
||||
const cookie = m[3] !== undefined ? `[${total ? Math.round((100 * done) / total) : 0}%]` : `[${done}/${total}]`
|
||||
if (cookie !== m[0]) s.title = s.title.replace(COOKIE, cookie)
|
||||
})
|
||||
}
|
||||
|
||||
/** Makes the edits on the plan's text, in order, and answers with the new text. Throws, changing nothing, on an edit
|
||||
* that names no task or a value that can't be written. */
|
||||
export function applyEdits(text: string, edits: readonly PlanEdit[], o: ApplyOptions = {}): Applied {
|
||||
const reg = o.registry ?? plans
|
||||
const before = readPlan(text, reg)
|
||||
const taken = new Set(before.entries.flatMap((t) => (t.id ? [t.id] : [])))
|
||||
const c: Ctx = {
|
||||
doc: before.doc,
|
||||
words: before.words,
|
||||
now: o.now ?? new Date(),
|
||||
reg,
|
||||
initial: [...before.doc.sections],
|
||||
mint: () => {
|
||||
const id = (o.newId ?? newId)(taken)
|
||||
taken.add(id)
|
||||
return id
|
||||
},
|
||||
}
|
||||
const done = edits.map((e) => one(c, e))
|
||||
for (const s of c.doc.sections) if (s.keyword && !propOf(s, "ID")) setProp(s, "ID", c.mint())
|
||||
cookies(c)
|
||||
const out = printOrg(c.doc)
|
||||
return { text: out, refs: done.map((d) => (typeof d === "string" ? d : (propOf(d, "ID") ?? ""))), plan: readPlan(out, reg) }
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
// What a plugin adds to plans (docs/plan.feature PL6): TODO keyword sequences, properties with a check, kinds of task
|
||||
// with the properties they need and a check of their own, and views (an agenda, board lanes, anything built from a
|
||||
// plan). A registry holds them; `plans` is the one everything uses unless it's handed another. raea's own sequence
|
||||
// (TODO MAKING REVIEW | DONE DROPPED), its properties and its views are in every registry from the start.
|
||||
import type { TaskFields } from "./edit.ts"
|
||||
import type { Plan, State, Task } from "./model.ts"
|
||||
import { agenda, board, outline } from "./views.ts"
|
||||
|
||||
export const STATES: readonly State[] = ["todo", "making", "review", "done", "dropped"]
|
||||
|
||||
export interface KeywordSequence {
|
||||
name: string
|
||||
words: { word: string; state: State }[]
|
||||
}
|
||||
|
||||
export interface PropertyDef {
|
||||
/** as written in the drawer, upper case: SHOT, not :shot: */
|
||||
key: string
|
||||
about?: string
|
||||
/** what is wrong with a value, or undefined when it's fine */
|
||||
check?: (value: string) => string | undefined
|
||||
}
|
||||
|
||||
export interface PlanKind {
|
||||
/** what :KIND: says */
|
||||
name: string
|
||||
about?: string
|
||||
/** the keyword sequence its tasks move through, by name */
|
||||
keywords?: string
|
||||
/** the properties a task of this kind must have */
|
||||
props?: string[]
|
||||
/** what is wrong with a task of this kind, or undefined */
|
||||
check?: (task: Task, plan: Plan) => string | undefined
|
||||
/** what a new task of this kind starts with (plan edits read it when an add names the kind) */
|
||||
defaults?: Partial<TaskFields>
|
||||
}
|
||||
|
||||
export interface PlanView<T = unknown, O = never> {
|
||||
name: string
|
||||
about?: string
|
||||
build: (plan: Plan, options?: O) => T
|
||||
}
|
||||
|
||||
export interface PlanRegistry {
|
||||
sequences: Map<string, KeywordSequence>
|
||||
/** every keyword any sequence has, with its state; the first sequence to name a word decides it */
|
||||
words: Map<string, State>
|
||||
props: Map<string, PropertyDef>
|
||||
kinds: Map<string, PlanKind>
|
||||
views: Map<string, PlanView<unknown, never>>
|
||||
}
|
||||
|
||||
/** A sequence's states, Org's way when a word's state isn't given or known: before the bar, the first word is to do
|
||||
* and the rest are under way; after it, the first is done and the rest dropped. */
|
||||
export function sequence(name: string, open: string[], done: string[], states: Record<string, State> = {}, known?: ReadonlyMap<string, State>): KeywordSequence {
|
||||
const pick = (word: string, fallback: State): State => states[word] ?? known?.get(word) ?? fallback
|
||||
return { name, words: [...open.map((word, i) => ({ word, state: pick(word, i === 0 ? "todo" : "making") })), ...done.map((word, i) => ({ word, state: pick(word, i === 0 ? "done" : "dropped") }))] }
|
||||
}
|
||||
|
||||
/** A sequence written the way a #+TODO: line writes it: "DRAFT CUT GRADE | DELIVERED". */
|
||||
export function defineKeywords(def: { name: string; words: string; states?: Record<string, State> }, reg: PlanRegistry = plans): KeywordSequence {
|
||||
const words = def.words.trim().split(/\s+/)
|
||||
const bar = words.indexOf("|")
|
||||
const open = bar >= 0 ? words.slice(0, bar) : words.slice(0, -1)
|
||||
const done = bar >= 0 ? words.slice(bar + 1) : words.slice(-1)
|
||||
for (const w of [...open, ...done]) if (!/^[A-Z][A-Z0-9_-]*$/.test(w)) throw new Error(`a TODO keyword is one word in capitals: ${w}`)
|
||||
const seq = sequence(def.name, open, done, def.states, reg.words)
|
||||
reg.sequences.set(seq.name, seq)
|
||||
for (const { word, state } of seq.words) if (!reg.words.has(word)) reg.words.set(word, state)
|
||||
return seq
|
||||
}
|
||||
|
||||
export function defineProperty(def: PropertyDef, reg: PlanRegistry = plans): PropertyDef {
|
||||
const key = def.key.toUpperCase()
|
||||
if (!/^[A-Z][A-Z0-9_-]*$/.test(key)) throw new Error(`a property is one word: ${def.key}`)
|
||||
const d = { ...def, key }
|
||||
reg.props.set(key, d)
|
||||
return d
|
||||
}
|
||||
|
||||
export function definePlanKind(def: PlanKind, reg: PlanRegistry = plans): PlanKind {
|
||||
if (!/^[a-z][\w-]*$/.test(def.name)) throw new Error(`a kind is one lower-case word: ${def.name}`)
|
||||
if (def.keywords && !reg.sequences.has(def.keywords)) throw new Error(`no keyword sequence ${def.keywords}; defineKeywords it first`)
|
||||
reg.kinds.set(def.name, def)
|
||||
return def
|
||||
}
|
||||
|
||||
export function defineView<T, O = never>(def: PlanView<T, O>, reg: PlanRegistry = plans): PlanView<T, O> {
|
||||
reg.views.set(def.name, def as unknown as PlanView<unknown, never>)
|
||||
return def
|
||||
}
|
||||
|
||||
/** A view of a plan by name: what its build makes. */
|
||||
export function view<T = unknown, O = never>(plan: Plan, name: string, options?: O, reg: PlanRegistry = plans): T {
|
||||
const v = reg.views.get(name)
|
||||
if (!v) throw new Error(`no plan view ${name}: ${[...reg.views.keys()].join(", ")}`)
|
||||
return (v.build as (p: Plan, o?: O) => T)(plan, options)
|
||||
}
|
||||
|
||||
/** A registry with raea's own sequence, properties and views. */
|
||||
export function createRegistry(): PlanRegistry {
|
||||
const reg: PlanRegistry = { sequences: new Map(), words: new Map(), props: new Map(), kinds: new Map(), views: new Map() }
|
||||
// only raea's words: a plain heading such as "* NEXT steps" stays a heading unless the file's #+TODO: names NEXT
|
||||
defineKeywords({ name: "raea", words: "TODO MAKING REVIEW | DONE DROPPED", states: { REVIEW: "review" } }, reg)
|
||||
const id = (v: string) => (/^[\w.:#@-]+$/.test(v) ? undefined : "an id is letters, digits and . _ - : # @, no spaces")
|
||||
defineProperty({ key: "ID", about: "the task's id, which never changes: everything links to a task by it", check: id }, reg)
|
||||
defineProperty({ key: "ITEM", about: "the feed item the task stands on, by id: what was made", check: id }, reg)
|
||||
defineProperty({ key: "AGENT", about: "who has it: agent ids, space-separated (an @name only until an agent has that name)" }, reg)
|
||||
defineProperty({ key: "FROM", about: "what asked for it: a feed message's id, or ITEM#COMMENT for a comment" }, reg)
|
||||
defineProperty({ key: "KIND", about: "the task's kind (definePlanKind)" }, reg)
|
||||
defineProperty({ key: "VERB", about: "the craft verb it asks for (polish, recut, regrade ...)" }, reg)
|
||||
defineView({ name: "board", about: "lanes by state: to do, making, to review, done", build: board }, reg)
|
||||
defineView({ name: "agenda", about: "what's due or scheduled, day by day, and what's overdue", build: agenda }, reg)
|
||||
defineView({ name: "outline", about: "the plan as a tree", build: outline }, reg)
|
||||
return reg
|
||||
}
|
||||
|
||||
/** The registry everything uses unless handed another. */
|
||||
export const plans: PlanRegistry = createRegistry()
|
||||
|
||||
export interface Diagnostic {
|
||||
ref: string
|
||||
/** 0-based line of the headline in the file */
|
||||
line: number
|
||||
severity: "error" | "warning"
|
||||
message: string
|
||||
}
|
||||
|
||||
/** What is wrong in a plan by the registry's rules: ids used twice, properties that fail their check, kinds nobody
|
||||
* defined, a kind's missing properties, keywords outside a kind's sequence, and the kinds' own checks. */
|
||||
export function checkPlan(plan: Plan, reg: PlanRegistry = plans): Diagnostic[] {
|
||||
const out: Diagnostic[] = []
|
||||
const seen = new Map<string, Task>()
|
||||
for (const t of plan.entries) {
|
||||
const say = (message: string, severity: Diagnostic["severity"] = "warning") => out.push({ ref: t.ref, line: t.line, severity, message })
|
||||
if (t.id) {
|
||||
if (seen.has(t.id)) say(`:ID: ${t.id} is also ${seen.get(t.id)!.text}'s; an id is one task's`, "error")
|
||||
else seen.set(t.id, t)
|
||||
}
|
||||
for (const [k, v] of Object.entries(t.props)) {
|
||||
const why = reg.props.get(k)?.check?.(v)
|
||||
if (why) say(`:${k}: ${why}`)
|
||||
}
|
||||
if (!t.kind) continue
|
||||
const kind = reg.kinds.get(t.kind)
|
||||
if (!kind) {
|
||||
say(`no kind ${t.kind} is defined (${[...reg.kinds.keys()].join(", ") || "none yet"})`)
|
||||
continue
|
||||
}
|
||||
for (const p of kind.props ?? []) if (!(p.toUpperCase() in t.props)) say(`a ${kind.name} needs :${p.toUpperCase()}:`)
|
||||
const seq = kind.keywords ? reg.sequences.get(kind.keywords) : undefined
|
||||
if (seq && t.keyword && !seq.words.some((w) => w.word === t.keyword)) say(`a ${kind.name} moves through ${seq.words.map((w) => w.word).join(" ")}, not ${t.keyword}`)
|
||||
const why = kind.check?.(t, plan)
|
||||
if (why) say(why)
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
// @raea/task (docs/plan.feature): a project's plan.org as typed tasks. Org mode is the base layer, the file people,
|
||||
// raea's agents and outside agents all read and write; this package reads it without losing a byte, edits it by task
|
||||
// id, and lets a plugin add keywords, properties, kinds and views. React hooks and components are in ./react.
|
||||
export { bare, checksOf, fileSequences, headValue, linksIn, linkText, parseOrg, printOrg, readHeadline, renderHeadline, setCheck, type Check, type Link, type OrgDoc, type Planning, type Props, type Section } from "./org.ts"
|
||||
export { dateOf, dayName, dayOf, formatStamp, nowStamp, parseStamp, type Timestamp } from "./time.ts"
|
||||
export { find, isClosed, keywordsOf, openTasks, planOf, readPlan, shortDay, type Plan, type State, type Task } from "./model.ts"
|
||||
export { applyEdits, newId, newPlan, tagOf, toggled, type Applied, type ApplyOptions, type PlanEdit, type TaskFields } from "./edit.ts"
|
||||
export { checkPlan, createRegistry, defineKeywords, definePlanKind, defineProperty, defineView, plans, sequence, STATES, view, type Diagnostic, type KeywordSequence, type PlanKind, type PlanRegistry, type PlanView, type PropertyDef } from "./extend.ts"
|
||||
export { agenda, board, outline, type Agenda, type AgendaDay, type Lane, type OutlineNode } from "./views.ts"
|
||||
export { planDigest, taskLine } from "./digest.ts"
|
||||
export { answerPlanTool, PLAN_TOOLS, planToolEdits, type NewTaskInput, type PlanTool, type PlanToolHost, type TaskChange } from "./tools.ts"
|
||||
@@ -0,0 +1,160 @@
|
||||
// A plan as values (docs/plan.feature PL2): every headline of the plan.org as an entry, the ones with a TODO keyword
|
||||
// as tasks, each with its state, priority, tags, dates, properties, checkboxes, progress and links. Read-only: edits
|
||||
// go through edit.ts, by task id, and come back as text.
|
||||
import { plans, sequence, type PlanRegistry } from "./extend.ts"
|
||||
import { bare, checksOf, COOKIE, fileSequences, headValue, linksIn, linkText, parseOrg, printSection, type Check, type Link, type OrgDoc } from "./org.ts"
|
||||
import type { Timestamp } from "./time.ts"
|
||||
|
||||
/** Where a task stands, whatever its keyword is called: the board's lanes, and done or dropped for closed. */
|
||||
export type State = "todo" | "making" | "review" | "done" | "dropped"
|
||||
|
||||
/** Done and dropped are closed: Org's words after the bar. */
|
||||
export const isClosed = (s: State | undefined) => s === "done" || s === "dropped"
|
||||
|
||||
export interface Task {
|
||||
/** how an edit names it: its :ID:, or #N (its place among the headlines) for one that has none yet */
|
||||
ref: string
|
||||
id?: string
|
||||
/** its place among the plan's headlines */
|
||||
index: number
|
||||
/** 0-based line of its headline in the file */
|
||||
line: number
|
||||
level: number
|
||||
keyword?: string
|
||||
/** undefined for a heading that only groups tasks */
|
||||
state?: State
|
||||
priority?: string
|
||||
/** the headline as written: links and a progress cookie included */
|
||||
title: string
|
||||
/** the headline as a reader sees it: each link as its words, no cookie */
|
||||
text: string
|
||||
tags: string[]
|
||||
/** tags from the headings above it and #+FILETAGS (Org's tag inheritance) */
|
||||
inherited: string[]
|
||||
scheduled?: Timestamp
|
||||
deadline?: Timestamp
|
||||
closed?: Timestamp
|
||||
/** every property, keys in upper case */
|
||||
props: Record<string, string>
|
||||
/** :ITEM:, the feed item it stands on */
|
||||
item?: string
|
||||
/** :AGENT:, who has it, by id */
|
||||
agents: string[]
|
||||
/** :FROM:, what asked for it */
|
||||
from?: string
|
||||
kind?: string
|
||||
verb?: string
|
||||
parent?: string
|
||||
children: string[]
|
||||
/** the nearest heading above it that isn't a task ("" at the top): the stage it's in */
|
||||
stage: string
|
||||
checks: Check[]
|
||||
/** its tasks under it, done of all; or, with none, its checkboxes */
|
||||
progress?: { done: number; total: number }
|
||||
links: Link[]
|
||||
/** the text under it after its planning line and drawer, as written */
|
||||
body: string
|
||||
}
|
||||
|
||||
export interface Plan {
|
||||
title?: string
|
||||
filetags: string[]
|
||||
/** every headline in file order: the tasks and the headings that group them */
|
||||
entries: Task[]
|
||||
/** the entries with a keyword */
|
||||
tasks: Task[]
|
||||
/** the keywords this plan knows, each with its state: the registry's and its own #+TODO: lines' */
|
||||
words: Map<string, State>
|
||||
doc: OrgDoc
|
||||
}
|
||||
|
||||
/** The keywords a plan's head and the registry know, with their states (the registry's win). */
|
||||
export function keywordsOf(head: readonly string[], reg: PlanRegistry = plans): Map<string, State> {
|
||||
const words = new Map(reg.words)
|
||||
for (const s of fileSequences(head)) for (const w of sequence("file", s.open, s.done, {}, reg.words).words) if (!words.has(w.word)) words.set(w.word, w.state)
|
||||
return words
|
||||
}
|
||||
|
||||
/** Reads a plan.org. Never throws: anything it doesn't read is kept as text. */
|
||||
export function readPlan(text: string, reg: PlanRegistry = plans): Plan {
|
||||
const lines = text.split("\n")
|
||||
const first = lines.findIndex((l) => /^\*+[ \t]/.test(bare(l)))
|
||||
const words = keywordsOf(first < 0 ? lines : lines.slice(0, first), reg)
|
||||
return planOf(parseOrg(text, new Set(words.keys())), words)
|
||||
}
|
||||
|
||||
const split = (v: string | undefined) => (v ? v.split(/[\s,]+/).filter(Boolean) : [])
|
||||
const shown = (title: string) => linkText(title).replace(COOKIE, "").replace(/\s+/g, " ").trim()
|
||||
|
||||
/** The plan of an Org document already read. */
|
||||
export function planOf(doc: OrgDoc, words: Map<string, State>): Plan {
|
||||
const filetags = split(headValue(doc.head, "FILETAGS")?.replace(/:/g, " "))
|
||||
const entries: Task[] = []
|
||||
const stack: Task[] = []
|
||||
let line = doc.head.length
|
||||
doc.sections.forEach((s, index) => {
|
||||
const props: Record<string, string> = {}
|
||||
for (const [k, v] of s.props ?? []) props[k.toUpperCase()] = v
|
||||
while (stack.length && stack.at(-1)!.level >= s.level) stack.pop()
|
||||
const parent = stack.at(-1)
|
||||
const heading = [...stack].reverse().find((t) => !t.state)
|
||||
const id = props.ID || undefined
|
||||
const t: Task = {
|
||||
ref: id ?? `#${index}`,
|
||||
...(id && { id }),
|
||||
index,
|
||||
line,
|
||||
level: s.level,
|
||||
...(s.keyword && { keyword: s.keyword, state: words.get(s.keyword) }),
|
||||
...(s.priority && { priority: s.priority }),
|
||||
title: s.title,
|
||||
text: shown(s.title),
|
||||
tags: s.tags,
|
||||
inherited: [...new Set([...filetags, ...(parent ? [...parent.inherited, ...parent.tags] : [])])],
|
||||
...(s.planning.scheduled && { scheduled: s.planning.scheduled }),
|
||||
...(s.planning.deadline && { deadline: s.planning.deadline }),
|
||||
...(s.planning.closed && { closed: s.planning.closed }),
|
||||
props,
|
||||
...(props.ITEM && { item: props.ITEM }),
|
||||
agents: split(props.AGENT),
|
||||
...(props.FROM && { from: props.FROM }),
|
||||
...(props.KIND && { kind: props.KIND }),
|
||||
...(props.VERB && { verb: props.VERB }),
|
||||
...(parent && { parent: parent.ref }),
|
||||
children: [],
|
||||
stage: heading?.text ?? "",
|
||||
checks: checksOf(s.body),
|
||||
links: linksIn([s.title, ...s.body].join("\n")),
|
||||
body: s.body.map(bare).join("\n"),
|
||||
}
|
||||
parent?.children.push(t.ref)
|
||||
stack.push(t)
|
||||
entries.push(t)
|
||||
line += printSection(s, doc.cr).length
|
||||
})
|
||||
const byRef = new Map(entries.map((t) => [t.ref, t]))
|
||||
for (const t of entries) {
|
||||
const kids = t.children.map((r) => byRef.get(r)!).filter((c) => c.state)
|
||||
if (kids.length) t.progress = { done: kids.filter((c) => isClosed(c.state)).length, total: kids.length }
|
||||
else if (t.checks.length) {
|
||||
const top = Math.min(...t.checks.map((c) => c.indent))
|
||||
const own = t.checks.filter((c) => c.indent === top)
|
||||
t.progress = { done: own.filter((c) => c.done).length, total: own.length }
|
||||
}
|
||||
}
|
||||
return { title: headValue(doc.head, "TITLE"), filetags, entries, tasks: entries.filter((t) => t.state), words, doc }
|
||||
}
|
||||
|
||||
/** An entry by its ref: its :ID:, or #N. */
|
||||
export function find(plan: Plan, ref: string): Task | undefined {
|
||||
return plan.entries.find((t) => t.ref === ref || t.id === ref)
|
||||
}
|
||||
|
||||
/** The open tasks (not done or dropped), in the plan's order. */
|
||||
export const openTasks = (plan: Plan) => plan.tasks.filter((t) => !isClosed(t.state))
|
||||
|
||||
/** A deadline or schedule as the app shows it: MM-DD this year, YYYY-MM-DD otherwise. */
|
||||
export function shortDay(t: Timestamp | undefined, now = new Date()): string | undefined {
|
||||
if (!t) return undefined
|
||||
return t.date.startsWith(`${now.getFullYear()}-`) ? t.date.slice(5) : t.date
|
||||
}
|
||||
@@ -0,0 +1,329 @@
|
||||
// A lossless reader and writer for the slice of Org mode (orgmode.org) a plan uses: headlines with a TODO keyword, a
|
||||
// [#A] priority and :tags:, the planning line under them (SCHEDULED, DEADLINE, CLOSED), the PROPERTIES drawer, and
|
||||
// everything else as the lines it was. printOrg(parseOrg(text)) is text, byte for byte. An entry that changed is
|
||||
// written again part by part: a headline that didn't change keeps its line (one whose keyword or words changed keeps
|
||||
// its spacing and tag column), a drawer keeps the lines of the properties that didn't change, a planning line keeps
|
||||
// its order and what raea can't read, and body text (lists, other drawers, prose) is never rewritten.
|
||||
import { formatStamp, parseStamp, type Timestamp } from "./time.ts"
|
||||
|
||||
export interface Planning {
|
||||
closed?: Timestamp
|
||||
deadline?: Timestamp
|
||||
scheduled?: Timestamp
|
||||
/** the parts raea doesn't read (a range across days, a stamp it can't parse, a key written twice), each as written
|
||||
* ("SCHEDULED: <2026-11-20 Fri>--<2026-11-22 Sun>"), kept when the line is written again */
|
||||
rest?: string[]
|
||||
}
|
||||
|
||||
/** A PROPERTIES drawer, in order, keys as written. */
|
||||
export type Props = [key: string, value: string][]
|
||||
|
||||
export interface Section {
|
||||
level: number
|
||||
keyword?: string
|
||||
priority?: string
|
||||
title: string
|
||||
tags: string[]
|
||||
planning: Planning
|
||||
/** the PROPERTIES drawer; undefined when the entry has none */
|
||||
props?: Props
|
||||
/** every line after the headline, its planning line and its drawer, up to the next headline, as written */
|
||||
body: string[]
|
||||
/** how it was written, so what didn't change prints as it was; none on a new entry */
|
||||
src?: Source
|
||||
}
|
||||
|
||||
interface Source {
|
||||
headline: string
|
||||
/** the headline's parts as read */
|
||||
head: Head
|
||||
planning?: string
|
||||
pk: string
|
||||
drawer?: string[]
|
||||
props: Props
|
||||
/** the indentation of its planning line or drawer, kept for lines written into them */
|
||||
indent: string
|
||||
}
|
||||
|
||||
export interface OrgDoc {
|
||||
/** the lines before the first headline (#+TITLE:, #+TODO:, text), as written */
|
||||
head: string[]
|
||||
sections: Section[]
|
||||
/** lines end in CRLF: a line raea writes ends so too */
|
||||
cr: boolean
|
||||
/** the text ends with a line break */
|
||||
final: boolean
|
||||
}
|
||||
|
||||
const HEAD = /^(\*+)[ \t]+(.*)$/
|
||||
const TAGS = /(?:^|[ \t]+)(:[\p{L}\p{N}_@#%:]+:)$/u
|
||||
// a planning line's parts: each stamp may be a range of days, <2026-11-20 Fri>--<2026-11-22 Sun>
|
||||
const STAMP_TEXT = String.raw`[<[][^>\]]*[>\]](?:--[<[][^>\]]*[>\]])?`
|
||||
const PLAN_LINE = new RegExp(String.raw`^[ \t]*(?:(?:SCHEDULED|DEADLINE|CLOSED):[ \t]*${STAMP_TEXT}[ \t]*)+$`)
|
||||
const PLAN_PART = new RegExp(String.raw`(SCHEDULED|DEADLINE|CLOSED):[ \t]*(${STAMP_TEXT})`, "g")
|
||||
const PLAN_KEYS = ["closed", "deadline", "scheduled"] as const
|
||||
const DRAWER_START = /^[ \t]*:PROPERTIES:[ \t]*$/i
|
||||
const DRAWER_END = /^[ \t]*:END:[ \t]*$/i
|
||||
const PROP = /^[ \t]*:([^\s:]+):(?:[ \t]+(.*?))?[ \t]*$/
|
||||
|
||||
/** A line without the \r of a CRLF ending. */
|
||||
export const bare = (line: string) => (line.endsWith("\r") ? line.slice(0, -1) : line)
|
||||
|
||||
/** A headline's parts, or null when the line isn't a headline. `keywords` are the TODO keywords the file knows. */
|
||||
export function readHeadline(line: string, keywords: ReadonlySet<string>): Omit<Section, "planning" | "body"> | null {
|
||||
const m = HEAD.exec(bare(line))
|
||||
if (!m) return null
|
||||
let rest = m[2].trimEnd()
|
||||
let keyword: string | undefined
|
||||
const kw = /^(\S+)(?:[ \t]+|$)/.exec(rest)
|
||||
if (kw && keywords.has(kw[1])) {
|
||||
keyword = kw[1]
|
||||
rest = rest.slice(kw[0].length)
|
||||
}
|
||||
let priority: string | undefined
|
||||
const pr = /^\[#([A-Z0-9])\](?:[ \t]+|$)/.exec(rest)
|
||||
if (pr) {
|
||||
priority = pr[1]
|
||||
rest = rest.slice(pr[0].length)
|
||||
}
|
||||
let tags: string[] = []
|
||||
const tg = TAGS.exec(rest)
|
||||
if (tg) {
|
||||
tags = tg[1].split(":").filter(Boolean)
|
||||
rest = rest.slice(0, tg.index)
|
||||
}
|
||||
return { level: m[1].length, ...(keyword && { keyword }), ...(priority && { priority }), title: rest.trim(), tags }
|
||||
}
|
||||
|
||||
/** A planning line's stamps. Whatever it can't read is kept in `rest`, so the line is still the planning line and the
|
||||
* drawer under it is still read. */
|
||||
function readPlanning(line: string): Planning | null {
|
||||
const b = bare(line)
|
||||
if (!PLAN_LINE.test(b)) return null
|
||||
const p: Planning = {}
|
||||
const rest: string[] = []
|
||||
for (const m of b.matchAll(PLAN_PART)) {
|
||||
const key = m[1].toLowerCase() as (typeof PLAN_KEYS)[number]
|
||||
const t = parseStamp(m[2])
|
||||
if (t && !p[key]) p[key] = t
|
||||
else rest.push(m[0])
|
||||
}
|
||||
if (rest.length) p.rest = rest
|
||||
return p
|
||||
}
|
||||
|
||||
/** The drawer starting at `at`: its properties and where it ends, or null when the lines there aren't one. */
|
||||
function readDrawer(lines: string[], at: number, end: number): { props: Props; next: number } | null {
|
||||
if (at >= end || !DRAWER_START.test(bare(lines[at]))) return null
|
||||
const props: Props = []
|
||||
for (let i = at + 1; i < end; i++) {
|
||||
const b = bare(lines[i])
|
||||
if (DRAWER_END.test(b)) return { props, next: i + 1 }
|
||||
const m = PROP.exec(b)
|
||||
if (!m) return null
|
||||
props.push([m[1], m[2] ?? ""])
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
type Head = Pick<Section, "level" | "keyword" | "priority" | "title" | "tags">
|
||||
const headKey = (s: Head) => JSON.stringify([s.level, s.keyword ?? "", s.priority ?? "", s.title, s.tags])
|
||||
const planKey = (p: Planning) => (p.closed || p.deadline || p.scheduled || p.rest?.length ? JSON.stringify([p.closed, p.deadline, p.scheduled, p.rest]) : "")
|
||||
|
||||
/** Reads an Org file. `keywords` are the TODO keywords to read headlines with (the file's #+TODO lines and the
|
||||
* registry's; model.ts keywordsOf gathers them). */
|
||||
export function parseOrg(text: string, keywords: ReadonlySet<string>): OrgDoc {
|
||||
const final = text.endsWith("\n")
|
||||
const lines = text === "" ? [] : text.split("\n")
|
||||
if (final) lines.pop()
|
||||
const doc: OrgDoc = { head: [], sections: [], cr: text.includes("\r\n"), final }
|
||||
const starts: number[] = []
|
||||
lines.forEach((l, i) => HEAD.test(bare(l)) && starts.push(i))
|
||||
doc.head = lines.slice(0, starts[0] ?? lines.length)
|
||||
starts.forEach((start, n) => {
|
||||
const end = starts[n + 1] ?? lines.length
|
||||
const h = readHeadline(lines[start], keywords)!
|
||||
let at = start + 1
|
||||
let planning: Planning = {}
|
||||
let planningLine: string | undefined
|
||||
const p = at < end ? readPlanning(lines[at]) : null
|
||||
if (p) {
|
||||
planning = p
|
||||
planningLine = lines[at]
|
||||
at++
|
||||
}
|
||||
const d = readDrawer(lines, at, end)
|
||||
const drawer = d ? lines.slice(at, d.next) : undefined
|
||||
if (d) at = d.next
|
||||
const indent = /^[ \t]*/.exec(bare(planningLine ?? drawer?.[0] ?? ""))![0]
|
||||
const s: Section = { ...h, planning, ...(d && { props: d.props }), body: lines.slice(at, end) }
|
||||
s.src = { headline: lines[start], head: { level: h.level, keyword: h.keyword, priority: h.priority, title: h.title, tags: [...h.tags] }, planning: planningLine, pk: planKey(planning), drawer, props: d ? d.props.map(([k, v]) => [k, v]) : [], indent }
|
||||
doc.sections.push(s)
|
||||
})
|
||||
return doc
|
||||
}
|
||||
|
||||
/** A headline as Org writes it, its tags ending at column 77 (org-tags-column -77). */
|
||||
export function renderHeadline(s: Head): string {
|
||||
const left = [`${"*".repeat(s.level)}`, s.keyword, s.priority && `[#${s.priority}]`, s.title].filter(Boolean).join(" ")
|
||||
if (!s.tags.length) return left
|
||||
const tags = `:${s.tags.join(":")}:`
|
||||
return `${left}${" ".repeat(Math.max(1, 77 - left.length - tags.length))}${tags}`
|
||||
}
|
||||
|
||||
/** A headline whose keyword, priority or words changed, written into its old line the way Org's org-todo does: the
|
||||
* line's own spacing kept, its tags ending where they ended. Undefined when its stars or tags changed too, or the
|
||||
* old line can't be followed; renderHeadline writes it then. */
|
||||
function editHeadline(line: string, was: Head, s: Head): string | undefined {
|
||||
if (was.level !== s.level || was.tags.join(":") !== s.tags.join(":") || !was.title || !s.title) return undefined
|
||||
let at = /^\*+[ \t]+/.exec(line)![0].length
|
||||
const prefix = line.slice(0, at)
|
||||
/** a part of the old line (its keyword, its priority) and the space after it */
|
||||
const part = (text: string | undefined) => {
|
||||
if (!text) return { gap: " " }
|
||||
if (!line.startsWith(text, at)) return undefined
|
||||
const gap = /^[ \t]*/.exec(line.slice(at + text.length))![0]
|
||||
at += text.length + gap.length
|
||||
return { gap }
|
||||
}
|
||||
const kw = part(was.keyword)
|
||||
const pr = kw && part(was.priority && `[#${was.priority}]`)
|
||||
if (!pr || !line.startsWith(was.title, at)) return undefined
|
||||
const end = at + was.title.length
|
||||
const left = `${prefix}${s.keyword ? s.keyword + kw!.gap : ""}${s.priority ? `[#${s.priority}]${pr.gap}` : ""}${s.title}`
|
||||
const tail = line.slice(end)
|
||||
const pad = /^[ \t]*/.exec(tail)![0]
|
||||
const next = s.tags.length ? left + " ".repeat(Math.max(1, pad.length + end - left.length)) + tail.slice(pad.length) : left + tail
|
||||
// read back as it was meant, or not used
|
||||
const back = readHeadline(next, new Set(s.keyword ? [s.keyword] : []))
|
||||
return back && headKey(back) === headKey(s) ? next : undefined
|
||||
}
|
||||
|
||||
/** A planning line again: its parts in the order they were written, a new CLOSED first (as Org puts it) and a new
|
||||
* DEADLINE or SCHEDULED last, then the parts raea doesn't read, as written. */
|
||||
function renderPlanning(p: Planning, was?: string): string {
|
||||
const order = was ? [...bare(was).matchAll(/(SCHEDULED|DEADLINE|CLOSED):/g)].map((m) => m[1].toLowerCase()) : []
|
||||
const keys = [...PLAN_KEYS.filter((k) => k === "closed" && !order.includes(k)), ...order, ...PLAN_KEYS.filter((k) => k !== "closed" && !order.includes(k))]
|
||||
const parts = [...new Set(keys)].flatMap((k) => {
|
||||
const t = p[k as (typeof PLAN_KEYS)[number]]
|
||||
return t ? [`${k.toUpperCase()}: ${formatStamp(t)}`] : []
|
||||
})
|
||||
return [...parts, ...(p.rest ?? [])].join(" ")
|
||||
}
|
||||
|
||||
/** A property line the way Org's org-property-format writes it ("%-10s %s"). */
|
||||
const renderProp = (indent: string, k: string, v: string) => `${indent}${`:${k}:`.padEnd(10)}${v ? ` ${v}` : ""}`.trimEnd()
|
||||
|
||||
/** One entry's lines: the parts that didn't change as they were written, the rest written again. */
|
||||
export function printSection(s: Section, cr: boolean): string[] {
|
||||
const nl = (l: string) => (cr ? `${l}\r` : l)
|
||||
const src = s.src
|
||||
const indent = src?.indent ?? ""
|
||||
const out = [src && headKey(src.head) === headKey(s) ? src.headline : nl((src && editHeadline(bare(src.headline), src.head, s)) ?? renderHeadline(s))]
|
||||
const pk = planKey(s.planning)
|
||||
if (src?.planning !== undefined && src.pk === pk) out.push(src.planning)
|
||||
else if (pk) out.push(nl(indent + renderPlanning(s.planning, src?.planning)))
|
||||
if (s.props) {
|
||||
const was = src?.drawer
|
||||
if (was && JSON.stringify(src!.props) === JSON.stringify(s.props)) out.push(...was)
|
||||
else {
|
||||
// each property that is as it was keeps its line
|
||||
const used = new Set<number>()
|
||||
const lines = s.props.map(([k, v]) => {
|
||||
const j = src ? src.props.findIndex(([k0, v0], i) => !used.has(i) && k0 === k && v0 === v) : -1
|
||||
if (j >= 0 && was) {
|
||||
used.add(j)
|
||||
return was[j + 1]
|
||||
}
|
||||
return nl(renderProp(indent, k, v))
|
||||
})
|
||||
out.push(was?.[0] ?? nl(`${indent}:PROPERTIES:`), ...lines, was?.at(-1) ?? nl(`${indent}:END:`))
|
||||
}
|
||||
}
|
||||
out.push(...s.body)
|
||||
return out
|
||||
}
|
||||
|
||||
/** The file again: what wasn't changed exactly as it was read. */
|
||||
export function printOrg(doc: OrgDoc): string {
|
||||
const lines = [...doc.head, ...doc.sections.flatMap((s) => printSection(s, doc.cr))]
|
||||
return lines.join("\n") + (doc.final && lines.length ? "\n" : "")
|
||||
}
|
||||
|
||||
/** A line to add to the file, with its line ending's \r when the file uses CRLF. */
|
||||
export const lineOf = (doc: Pick<OrgDoc, "cr">, text: string) => (doc.cr ? `${text}\r` : text)
|
||||
|
||||
/** A #+KEY: line's value in the file's head (TITLE, FILETAGS), the last one when there are several. */
|
||||
export function headValue(head: readonly string[], key: string): string | undefined {
|
||||
const re = new RegExp(`^#\\+${key}:[ \\t]*(.*?)[ \\t]*$`, "i")
|
||||
let v: string | undefined
|
||||
for (const l of head) {
|
||||
const m = re.exec(bare(l))
|
||||
if (m) v = m[1]
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
/** The keyword sequences the file declares with #+TODO:, #+SEQ_TODO: or #+TYP_TODO:, each as its words before and
|
||||
* after the bar. Fast-access keys and logging marks ("DONE(d!)") are dropped. */
|
||||
export function fileSequences(head: readonly string[]): { open: string[]; done: string[] }[] {
|
||||
const out: { open: string[]; done: string[] }[] = []
|
||||
for (const l of head) {
|
||||
const m = /^#\+(?:SEQ_|TYP_)?TODO:[ \t]*(.*)$/i.exec(bare(l))
|
||||
if (!m) continue
|
||||
const words = m[1].trim().split(/[ \t]+/).filter(Boolean).map((w) => w.replace(/\(.*\)$/, ""))
|
||||
const bar = words.indexOf("|")
|
||||
if (bar >= 0) out.push({ open: words.slice(0, bar), done: words.slice(bar + 1).filter((w) => w !== "|") })
|
||||
else if (words.length) out.push({ open: words.slice(0, -1), done: words.slice(-1) })
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
export interface Check {
|
||||
/** the line in the entry's body */
|
||||
line: number
|
||||
done: boolean
|
||||
/** [-]: some of its own sub-items are done */
|
||||
partial: boolean
|
||||
text: string
|
||||
indent: number
|
||||
}
|
||||
|
||||
const CHECK = /^([ \t]*)(?:[-+*]|\d+[.)])[ \t]+\[([ xX-])\](?:[ \t]+(.*))?$/
|
||||
|
||||
/** The checkbox items in an entry's body: "- [ ] what", "- [X] what", "1. [-] what". */
|
||||
export function checksOf(body: readonly string[]): Check[] {
|
||||
return body.flatMap((l, line) => {
|
||||
const m = CHECK.exec(bare(l))
|
||||
return m ? [{ line, done: m[2] === "X" || m[2] === "x", partial: m[2] === "-", text: (m[3] ?? "").trim(), indent: m[1].replace(/\t/g, " ").length }] : []
|
||||
})
|
||||
}
|
||||
|
||||
/** The body line with its checkbox ticked or cleared. */
|
||||
export const setCheck = (line: string, done: boolean) => line.replace(/\[[ xX-]\]/, done ? "[X]" : "[ ]")
|
||||
|
||||
export interface Link {
|
||||
/** as written inside the brackets: item:i-abc, id:t-1, https://... */
|
||||
target: string
|
||||
desc?: string
|
||||
/** its type before the colon (item, id, comment, agent, file, https), or "fuzzy" for a plain [[name]] */
|
||||
type: string
|
||||
/** what follows the type */
|
||||
path: string
|
||||
}
|
||||
|
||||
const LINK = /\[\[([^[\]]+)\](?:\[([^[\]]*)\])?\]/g
|
||||
|
||||
/** The links in a line of text: [[target]] and [[target][description]]. */
|
||||
export function linksIn(text: string): Link[] {
|
||||
return [...text.matchAll(LINK)].map((m) => {
|
||||
const t = /^([a-z][\w+-]*):(.*)$/i.exec(m[1])
|
||||
return { target: m[1], ...(m[2] !== undefined && { desc: m[2] }), type: t ? t[1].toLowerCase() : "fuzzy", path: t ? t[2] : m[1] }
|
||||
})
|
||||
}
|
||||
|
||||
/** Text with each link as its description (or its path), as a reader sees it. */
|
||||
export const linkText = (text: string) => text.replace(LINK, (_, target: string, desc?: string) => desc ?? target.replace(/^[a-z][\w+-]*:/i, ""))
|
||||
|
||||
/** A progress cookie in a headline: [2/5] or [40%]. */
|
||||
export const COOKIE = /\[(\d*)\/(\d*)\]|\[(\d*)%\]/
|
||||
@@ -0,0 +1,182 @@
|
||||
// React for plans (docs/plan.feature PL6): usePlan reads a plan from text or from a source that changes (the app's
|
||||
// store, a file an agent edits), and edits it by task id; the components draw a task, the outline, an agenda and
|
||||
// board lanes as plain elements with data- attributes to style, nothing else. They work in raea's own window too:
|
||||
// no portals, no dangerouslySetInnerHTML, nothing loaded later.
|
||||
import { useCallback, useMemo, useSyncExternalStore, type ReactNode } from "react"
|
||||
import { applyEdits, toggled, type PlanEdit } from "./edit.ts"
|
||||
import { plans, view, type PlanRegistry } from "./extend.ts"
|
||||
import { isClosed, readPlan, type Plan, type State, type Task } from "./model.ts"
|
||||
import { agenda, board, outline, type OutlineNode } from "./views.ts"
|
||||
|
||||
/** Where a plan's text lives: read it, hear when it changes, and (when it can be written) edit it. */
|
||||
export interface PlanSource {
|
||||
read(): string | undefined
|
||||
subscribe(onChange: () => void): () => void
|
||||
edit?(edits: PlanEdit[]): void
|
||||
}
|
||||
|
||||
/** A plan kept in memory: a composition's own, or a test's. */
|
||||
export function memorySource(text = ""): PlanSource & { text: string } {
|
||||
const subs = new Set<() => void>()
|
||||
const src = {
|
||||
text,
|
||||
read: () => src.text,
|
||||
subscribe: (f: () => void) => (subs.add(f), () => void subs.delete(f)),
|
||||
edit: (edits: PlanEdit[]) => {
|
||||
src.text = applyEdits(src.text, edits).text
|
||||
subs.forEach((f) => f())
|
||||
},
|
||||
}
|
||||
return src
|
||||
}
|
||||
|
||||
const fixed = (text: string | undefined): PlanSource => ({ read: () => text, subscribe: () => () => {} })
|
||||
|
||||
/** The plan, read again whenever its source changes, and its edits. Text alone is read-only. */
|
||||
export function usePlan(source: string | PlanSource | undefined, registry: PlanRegistry = plans): { plan: Plan; text: string; edit: (edits: PlanEdit[]) => void } {
|
||||
const src = useMemo(() => (source && typeof source === "object" ? source : fixed(source)), [source])
|
||||
const subscribe = useCallback((f: () => void) => src.subscribe(f), [src])
|
||||
const read = useCallback(() => src.read(), [src])
|
||||
const text = useSyncExternalStore(subscribe, read, read) ?? ""
|
||||
const plan = useMemo(() => readPlan(text, registry), [text, registry])
|
||||
const edit = useCallback(
|
||||
(edits: PlanEdit[]) => {
|
||||
if (!src.edit) throw new Error("this plan is read-only: its source has no edit")
|
||||
src.edit(edits)
|
||||
},
|
||||
[src],
|
||||
)
|
||||
return { plan, text, edit }
|
||||
}
|
||||
|
||||
/** A view of the plan by name (extend.ts defineView), built again when the plan changes. */
|
||||
export function useView<T = unknown, O = never>(plan: Plan, name: string, options?: O, registry: PlanRegistry = plans): T {
|
||||
return useMemo(() => view<T, O>(plan, name, options, registry), [plan, name, options, registry])
|
||||
}
|
||||
|
||||
export interface TaskProps {
|
||||
task: Task
|
||||
/** its checkbox: called with the task; edits(toggled(task)) is the usual answer */
|
||||
onToggle?: (task: Task) => void
|
||||
onOpen?: (task: Task) => void
|
||||
className?: string
|
||||
children?: ReactNode
|
||||
}
|
||||
|
||||
/** One task on one line: its checkbox, priority, words, progress, deadline and tags. A heading has no checkbox. */
|
||||
export function TaskLine({ task, onToggle, onOpen, className, children }: TaskProps) {
|
||||
const done = isClosed(task.state)
|
||||
return (
|
||||
<div className={className} data-task={task.ref} data-state={task.state ?? "heading"} data-keyword={task.keyword} data-priority={task.priority}>
|
||||
{task.state && (
|
||||
<button type="button" role="checkbox" aria-checked={done} aria-label={`${done ? "Open again" : "Mark done"}: ${task.text}`} disabled={!onToggle} onClick={() => onToggle?.(task)} data-part="box">
|
||||
{done ? "✓" : ""}
|
||||
</button>
|
||||
)}
|
||||
{task.priority && <span data-part="priority">{task.priority}</span>}
|
||||
{onOpen ? (
|
||||
<button type="button" onClick={() => onOpen(task)} data-part="text">
|
||||
{task.text}
|
||||
</button>
|
||||
) : (
|
||||
<span data-part="text">{task.text}</span>
|
||||
)}
|
||||
{task.progress && <span data-part="progress">{`${task.progress.done}/${task.progress.total}`}</span>}
|
||||
{task.deadline && <span data-part="deadline">{task.deadline.date}</span>}
|
||||
{task.tags.map((t) => (
|
||||
<span key={t} data-part="tag">
|
||||
{t}
|
||||
</span>
|
||||
))}
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
type Render = (task: Task) => ReactNode
|
||||
|
||||
interface ListProps {
|
||||
plan: Plan
|
||||
onToggle?: (task: Task) => void
|
||||
onOpen?: (task: Task) => void
|
||||
/** draws a task in place of TaskLine */
|
||||
renderTask?: Render
|
||||
className?: string
|
||||
}
|
||||
|
||||
function line(p: ListProps, task: Task) {
|
||||
return p.renderTask ? p.renderTask(task) : <TaskLine task={task} onToggle={p.onToggle} onOpen={p.onOpen} />
|
||||
}
|
||||
|
||||
/** The plan as a tree: each headline, the tasks under it nested. */
|
||||
export function PlanOutline(p: ListProps & { filter?: (task: Task) => boolean }) {
|
||||
const keep = (n: OutlineNode): boolean => !p.filter || p.filter(n.task) || n.children.some(keep)
|
||||
const tree = (nodes: OutlineNode[]): ReactNode => (
|
||||
<ul data-part="outline">
|
||||
{nodes.filter(keep).map((n) => (
|
||||
<li key={n.task.ref} data-task={n.task.ref}>
|
||||
{line(p, n.task)}
|
||||
{n.children.length > 0 && tree(n.children)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)
|
||||
return <div className={p.className}>{tree(outline(p.plan))}</div>
|
||||
}
|
||||
|
||||
/** What's due and scheduled, day by day, with what's overdue first. */
|
||||
export function Agenda(p: ListProps & { from?: string; days?: number; label?: (date: string) => ReactNode }) {
|
||||
const a = agenda(p.plan, { from: p.from, days: p.days })
|
||||
return (
|
||||
<div className={p.className} data-part="agenda">
|
||||
{a.overdue.length > 0 && (
|
||||
<section data-part="overdue">
|
||||
<h3>Overdue</h3>
|
||||
<ul>
|
||||
{a.overdue.map((e) => (
|
||||
<li key={`${e.task.ref}-${e.why}`} data-why={e.why} data-date={e.date}>
|
||||
{line(p, e.task)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
)}
|
||||
{a.days.map((d) => (
|
||||
<section key={d.date} data-part="day" data-date={d.date} data-empty={d.entries.length === 0 || undefined}>
|
||||
<h3>{p.label ? p.label(d.date) : d.date}</h3>
|
||||
<ul>
|
||||
{d.entries.map((e) => (
|
||||
<li key={`${e.task.ref}-${e.why}`} data-why={e.why}>
|
||||
{line(p, e.task)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const LANE: Record<State, string> = { todo: "To do", making: "Making", review: "To review", done: "Done", dropped: "Dropped" }
|
||||
|
||||
/** Board lanes by state: to do, making, to review, done. */
|
||||
export function BoardLanes(p: ListProps & { states?: State[]; labels?: Partial<Record<State, string>>; filter?: (task: Task) => boolean }) {
|
||||
return (
|
||||
<div className={p.className} data-part="board">
|
||||
{board(p.plan, { states: p.states, filter: p.filter }).map((lane) => (
|
||||
<section key={lane.state} data-part="lane" data-state={lane.state}>
|
||||
<h3>
|
||||
{p.labels?.[lane.state] ?? LANE[lane.state]} <span data-part="count">{lane.tasks.length}</span>
|
||||
</h3>
|
||||
<ul>
|
||||
{lane.tasks.map((t) => (
|
||||
<li key={t.ref}>{line(p, t)}</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export { toggled }
|
||||
@@ -0,0 +1,74 @@
|
||||
// Org-mode timestamps (orgmode.org/manual/Timestamps.html): <2026-11-14 Sat> is active (it shows in an agenda),
|
||||
// [2026-11-14 Sat 16:40] inactive (a record, like CLOSED). A time range, a repeater (+1w, .+1d, ++1m) and a warning
|
||||
// (-2d) are read and written back; the day name is whatever was written, and English when raea writes one.
|
||||
|
||||
export interface Timestamp {
|
||||
active: boolean
|
||||
/** YYYY-MM-DD */
|
||||
date: string
|
||||
/** HH:MM */
|
||||
time?: string
|
||||
/** HH:MM, the end of a range on the same day */
|
||||
end?: string
|
||||
/** +1w, .+1d or ++1m; a habit's .+2d/3d */
|
||||
repeat?: string
|
||||
/** -2d or --2d */
|
||||
warn?: string
|
||||
}
|
||||
|
||||
const DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
|
||||
const STAMP = /^([<[])(\d{4}-\d{2}-\d{2})(?:[ \t]+([^\s\d>\]+-][^\s>\]]*))?(?:[ \t]+(\d{1,2}:\d{2})(?:-(\d{1,2}:\d{2}))?)?((?:[ \t]+(?:\.\+|\+\+|\+|--|-)\d+[hdwmy](?:\/\d+[hdwmy])?)*)[ \t]*([>\]])$/
|
||||
|
||||
/** A timestamp as written, or undefined when it isn't one (its brackets must match). */
|
||||
export function parseStamp(s: string): Timestamp | undefined {
|
||||
const m = STAMP.exec(s.trim())
|
||||
if (!m || (m[1] === "<") !== (m[7] === ">")) return undefined
|
||||
const t: Timestamp = { active: m[1] === "<", date: m[2] }
|
||||
if (m[4]) t.time = m[4].padStart(5, "0")
|
||||
if (m[5]) t.end = m[5].padStart(5, "0")
|
||||
for (const part of m[6].trim().split(/[ \t]+/).filter(Boolean)) {
|
||||
if (part.startsWith("-")) t.warn = part
|
||||
else t.repeat = part
|
||||
}
|
||||
return t
|
||||
}
|
||||
|
||||
/** The English day name of a YYYY-MM-DD date. */
|
||||
export function dayName(date: string): string {
|
||||
const [y, m, d] = date.split("-").map(Number)
|
||||
return DAYS[new Date(Date.UTC(y, m - 1, d)).getUTCDay()]
|
||||
}
|
||||
|
||||
/** A timestamp written the way Org writes it: <2026-11-14 Sat 10:00-11:00 +1w -2d>. */
|
||||
export function formatStamp(t: Timestamp): string {
|
||||
const parts = [t.date, dayName(t.date)]
|
||||
if (t.time) parts.push(t.end ? `${t.time}-${t.end}` : t.time)
|
||||
if (t.repeat) parts.push(t.repeat)
|
||||
if (t.warn) parts.push(t.warn)
|
||||
return t.active ? `<${parts.join(" ")}>` : `[${parts.join(" ")}]`
|
||||
}
|
||||
|
||||
const pad = (n: number) => String(n).padStart(2, "0")
|
||||
|
||||
/** A local date as YYYY-MM-DD. */
|
||||
export const dateOf = (d: Date) => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`
|
||||
|
||||
/** Now as Org records a change: an inactive stamp with the time, [2026-11-14 Sat 16:40]. */
|
||||
export function nowStamp(now = new Date()): Timestamp {
|
||||
return { active: false, date: dateOf(now), time: `${pad(now.getHours())}:${pad(now.getMinutes())}` }
|
||||
}
|
||||
|
||||
/** A day as a person or an agent writes it: YYYY-MM-DD, MM-DD (this year, as a brief wrote due dates), or an Org
|
||||
* timestamp. Undefined when it is none of those. */
|
||||
export function dayOf(s: string, now = new Date()): Timestamp | undefined {
|
||||
const v = s.trim()
|
||||
if (/^[<[]/.test(v)) return parseStamp(v)
|
||||
const full = /^(\d{4})-(\d{2})-(\d{2})$/.exec(v)
|
||||
const short = /^(\d{2})-(\d{2})$/.exec(v)
|
||||
const date = full ? v : short ? `${now.getFullYear()}-${short[1]}-${short[2]}` : undefined
|
||||
if (!date) return undefined
|
||||
const [y, m, d] = date.split("-").map(Number)
|
||||
const back = new Date(Date.UTC(y, m - 1, d))
|
||||
if (back.getUTCMonth() !== m - 1 || back.getUTCDate() !== d) return undefined
|
||||
return { active: true, date }
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
// A plan's tools for an agent (docs/plan.feature PL5): plan_read, plan_add, plan_update and plan_close, as the raea
|
||||
// app offers them to every agent it launches. Any host answers them the same way: it says how to read the plan's text
|
||||
// and how to make edits on it, and these turn a tool's input into plan edits (edit.ts) and its answer into the open
|
||||
// tasks with their ids. The app's page answers them through its plans, a headless run on the folder's plan.org.
|
||||
import { planDigest } from "./digest.ts"
|
||||
import type { PlanEdit, TaskFields } from "./edit.ts"
|
||||
import { isClosed, readPlan } from "./model.ts"
|
||||
|
||||
export const PLAN_TOOLS = ["plan_read", "plan_add", "plan_update", "plan_close"] as const
|
||||
export type PlanTool = (typeof PLAN_TOOLS)[number]
|
||||
|
||||
/** A task as plan_add takes it. Left without agents, it's the calling agent's. */
|
||||
export interface NewTaskInput extends Omit<TaskFields, "title"> {
|
||||
title: string
|
||||
state?: string
|
||||
under?: string
|
||||
before?: string
|
||||
after?: string
|
||||
checks?: string[]
|
||||
}
|
||||
|
||||
/** One change as plan_update takes it: fields to set, and at most one of state, check, move or remove. */
|
||||
export interface TaskChange extends TaskFields {
|
||||
id: string
|
||||
state?: string
|
||||
/** a checkbox under it, by its place (0 is the first): ticked, or as `done` says */
|
||||
check?: number
|
||||
done?: boolean
|
||||
/** a checkbox added under it */
|
||||
add_check?: string
|
||||
move?: { before?: string; after?: string; under?: string }
|
||||
remove?: boolean
|
||||
}
|
||||
|
||||
export interface PlanToolHost {
|
||||
/** the calling agent's id: a new task with no agents is its */
|
||||
who: string
|
||||
/** the plan's text now */
|
||||
text(): string
|
||||
/** the edits made on the plan: its text after, and each edit's task id */
|
||||
apply(edits: PlanEdit[]): Promise<{ text: string; refs: string[] }> | { text: string; refs: string[] }
|
||||
/** where the plan is, for the agent to say or open */
|
||||
file?: string
|
||||
}
|
||||
|
||||
const list = <T>(v: unknown, what: string): T[] => {
|
||||
if (!Array.isArray(v) || !v.length) throw new Error(`${what}: a list, with at least one`)
|
||||
return v as T[]
|
||||
}
|
||||
|
||||
/** The fields of a change that set a task's own values (title, priority, tags, dates, item, agents, properties, note). */
|
||||
function fieldsOf(c: TaskChange): TaskFields | undefined {
|
||||
const { id: _, state: _s, check: _c, done: _d, add_check: _a, move: _m, remove: _r, ...f } = c
|
||||
return Object.keys(f).length ? f : undefined
|
||||
}
|
||||
|
||||
/** A tool's input as plan edits, in order. Throws, naming what's wrong, on an input that isn't one. */
|
||||
export function planToolEdits(tool: Exclude<PlanTool, "plan_read">, input: Record<string, unknown>, who: string): PlanEdit[] {
|
||||
if (tool === "plan_add")
|
||||
return list<NewTaskInput>(input.tasks, "tasks").map((t) => {
|
||||
if (!t || typeof t.title !== "string" || !t.title.trim()) throw new Error("each task needs a title")
|
||||
return { ...t, op: "add" as const, agents: t.agents ?? [who] }
|
||||
})
|
||||
if (tool === "plan_close") {
|
||||
if (typeof input.id !== "string") throw new Error("id: the task to close (plan_read lists them)")
|
||||
const state = input.state === undefined ? "done" : String(input.state)
|
||||
if (!/^(done|dropped)$/i.test(state) && state !== state.toUpperCase()) throw new Error(`state: done or dropped (or a closing keyword of the plan's), not ${state}`)
|
||||
return [{ op: "state", ref: input.id, state, ...(typeof input.item === "string" && { item: input.item }), ...(typeof input.note === "string" && { note: input.note }) }]
|
||||
}
|
||||
return list<TaskChange>(input.changes, "changes").flatMap((c): PlanEdit[] => {
|
||||
if (!c || typeof c.id !== "string") throw new Error("each change names its task by id (plan_read lists them)")
|
||||
if (c.remove) return [{ op: "remove", ref: c.id }]
|
||||
const out: PlanEdit[] = []
|
||||
const f = fieldsOf(c)
|
||||
if (f) out.push({ op: "set", ref: c.id, ...f })
|
||||
if (c.state) out.push({ op: "state", ref: c.id, state: c.state })
|
||||
if (c.check !== undefined) out.push({ op: "check", ref: c.id, index: c.check, ...(c.done !== undefined && { done: c.done }) })
|
||||
if (c.add_check) out.push({ op: "check", ref: c.id, add: c.add_check })
|
||||
if (c.move) out.push({ op: "move", ref: c.id, ...c.move })
|
||||
if (!out.length) throw new Error(`nothing to change on ${c.id}: give a field, state, check, move or remove`)
|
||||
return out
|
||||
})
|
||||
}
|
||||
|
||||
/** A tool answered: plan_read gives the open tasks by id (and the whole text with full), giving any task without an id
|
||||
* one first; an edit gives the ids it touched and the open tasks after it. */
|
||||
export async function answerPlanTool(tool: PlanTool, input: Record<string, unknown>, h: PlanToolHost): Promise<unknown> {
|
||||
const file = h.file ?? "plan.org"
|
||||
if (tool === "plan_read") {
|
||||
let text = h.text()
|
||||
// a task written without an id (by hand, in Emacs) is given one first: an agent names tasks by id, never by place
|
||||
if (readPlan(text).tasks.some((t) => !t.id)) text = (await h.apply([])).text
|
||||
return { file, open: planDigest(readPlan(text), { max: 200 }), ...(input.full ? { text } : {}) }
|
||||
}
|
||||
const edits = planToolEdits(tool, input, h.who)
|
||||
// plan_close closes: a keyword of the plan's that isn't after its bar (MAKING) is plan_update's
|
||||
const close = edits[0]
|
||||
if (tool === "plan_close" && close.op === "state" && !/^(done|dropped)$/i.test(close.state) && !isClosed(readPlan(h.text()).words.get(close.state)))
|
||||
throw new Error(`state: done or dropped, or a closing keyword of the plan's; ${close.state} doesn't close (plan_update sets it)`)
|
||||
const r = await h.apply(edits)
|
||||
return { file, ids: [...new Set(r.refs.filter(Boolean))], open: planDigest(readPlan(r.text)) }
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
// raea's own views of a plan (extend.ts registers them): board lanes by state, an agenda by day, and the outline as a
|
||||
// tree. Pure functions of the plan; a plugin's views are built the same way (defineView).
|
||||
import type { Plan, State, Task } from "./model.ts"
|
||||
|
||||
export interface Lane {
|
||||
state: State
|
||||
tasks: Task[]
|
||||
}
|
||||
|
||||
/** Lanes by state, in the board's order. Dropped tasks are on no lane unless asked for. */
|
||||
export function board(plan: Plan, options?: { states?: State[]; filter?: (t: Task) => boolean }): Lane[] {
|
||||
const states = options?.states ?? ["todo", "making", "review", "done"]
|
||||
const tasks = plan.tasks.filter((t) => !options?.filter || options.filter(t))
|
||||
return states.map((state) => ({ state, tasks: tasks.filter((t) => t.state === state) }))
|
||||
}
|
||||
|
||||
export interface AgendaDay {
|
||||
date: string
|
||||
entries: { task: Task; why: "deadline" | "scheduled" }[]
|
||||
}
|
||||
|
||||
export interface Agenda {
|
||||
/** open tasks whose deadline or schedule is before the first day */
|
||||
overdue: { task: Task; why: "deadline" | "scheduled"; date: string }[]
|
||||
days: AgendaDay[]
|
||||
}
|
||||
|
||||
const addDays = (date: string, n: number) => {
|
||||
const [y, m, d] = date.split("-").map(Number)
|
||||
const t = new Date(Date.UTC(y, m - 1, d + n))
|
||||
return t.toISOString().slice(0, 10)
|
||||
}
|
||||
|
||||
/** What's due and scheduled day by day from `from` (YYYY-MM-DD, today by default) for `days` days, and what's
|
||||
* overdue. Closed tasks are left out. */
|
||||
export function agenda(plan: Plan, options?: { from?: string; days?: number }): Agenda {
|
||||
const now = new Date()
|
||||
const from = options?.from ?? `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}-${String(now.getDate()).padStart(2, "0")}`
|
||||
const n = Math.max(1, options?.days ?? 7)
|
||||
const open = plan.tasks.filter((t) => t.state !== "done" && t.state !== "dropped")
|
||||
const dated = open.flatMap((task) => [...(task.deadline ? [{ task, why: "deadline" as const, date: task.deadline.date }] : []), ...(task.scheduled ? [{ task, why: "scheduled" as const, date: task.scheduled.date }] : [])])
|
||||
const days = Array.from({ length: n }, (_, i) => addDays(from, i)).map((date) => ({ date, entries: dated.filter((e) => e.date === date).map(({ task, why }) => ({ task, why })) }))
|
||||
return { overdue: dated.filter((e) => e.date < from).sort((a, b) => a.date.localeCompare(b.date)), days }
|
||||
}
|
||||
|
||||
export interface OutlineNode {
|
||||
task: Task
|
||||
children: OutlineNode[]
|
||||
}
|
||||
|
||||
/** The plan as a tree of its headlines. */
|
||||
export function outline(plan: Plan): OutlineNode[] {
|
||||
const nodes = new Map(plan.entries.map((t) => [t.ref, { task: t, children: [] as OutlineNode[] }]))
|
||||
const roots: OutlineNode[] = []
|
||||
for (const t of plan.entries) (t.parent ? nodes.get(t.parent)!.children : roots).push(nodes.get(t.ref)!)
|
||||
return roots
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
// PL3: every change by task id, the rest of the file untouched (src/edit.ts), and the plan as values (src/model.ts).
|
||||
import { describe, expect, test } from "vitest"
|
||||
import { applyEdits, createRegistry, defineKeywords, find, newPlan, planDigest, readPlan, toggled, type PlanEdit } from "../src"
|
||||
|
||||
const NOW = new Date(2026, 10, 14, 16, 40)
|
||||
let n = 0
|
||||
const ids = () => `t-${++n}`
|
||||
const apply = (text: string, edits: PlanEdit[]) => applyEdits(text, edits, { now: NOW, newId: ids })
|
||||
|
||||
const PLAN = `#+TITLE: Ides
|
||||
#+TODO: TODO MAKING REVIEW | DONE DROPPED
|
||||
|
||||
* Act one
|
||||
** TODO Rome storyboard [0/2]
|
||||
:PROPERTIES:
|
||||
:ID: t-rome
|
||||
:END:
|
||||
Notes a person wrote, kept.
|
||||
*** TODO The forum
|
||||
:PROPERTIES:
|
||||
:ID: t-forum
|
||||
:END:
|
||||
*** TODO The steps
|
||||
:PROPERTIES:
|
||||
:ID: t-steps
|
||||
:END:
|
||||
** DONE Cast the narrator
|
||||
CLOSED: [2026-11-02 Mon 10:14]
|
||||
:PROPERTIES:
|
||||
:ID: t-cast
|
||||
:END:
|
||||
* Sound
|
||||
** TODO Foley for the fire
|
||||
`
|
||||
|
||||
describe("PL2: the plan as values", () => {
|
||||
const p = readPlan(PLAN)
|
||||
test("tasks and the headings that group them; states from the keywords; stages, parents and progress", () => {
|
||||
expect(p.title).toBe("Ides")
|
||||
expect(p.entries.map((t) => [t.ref, t.keyword ?? "", t.state ?? "", t.stage])).toEqual([
|
||||
["#0", "", "", ""],
|
||||
["t-rome", "TODO", "todo", "Act one"],
|
||||
["t-forum", "TODO", "todo", "Act one"],
|
||||
["t-steps", "TODO", "todo", "Act one"],
|
||||
["t-cast", "DONE", "done", "Act one"],
|
||||
["#5", "", "", ""],
|
||||
["#6", "TODO", "todo", "Sound"],
|
||||
])
|
||||
expect(find(p, "t-rome")!.children).toEqual(["t-forum", "t-steps"])
|
||||
expect(find(p, "t-rome")!.progress).toEqual({ done: 0, total: 2 })
|
||||
expect(find(p, "t-rome")!.text).toBe("Rome storyboard")
|
||||
expect(find(p, "t-rome")!.line).toBe(4)
|
||||
expect(find(p, "t-cast")!.closed?.date).toBe("2026-11-02")
|
||||
})
|
||||
test("a file's own keywords are read with their states, Org's way", () => {
|
||||
const own = readPlan("#+TODO: OPEN NEXT | SHIPPED KILLED\n* NEXT a\n* KILLED b\n* REVIEW c\n")
|
||||
expect(own.tasks.map((t) => [t.keyword, t.state])).toEqual([
|
||||
["NEXT", "making"],
|
||||
["KILLED", "dropped"],
|
||||
["REVIEW", "review"],
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe("PL3: edits by id", () => {
|
||||
test("closing a subtask stamps CLOSED, links what was made and counts the cookie; nothing else moves", () => {
|
||||
const r = apply(PLAN, [{ op: "state", ref: "t-forum", state: "done", item: "i-forum-1", note: "Made the forum still." }])
|
||||
expect(r.refs).toEqual(["t-forum"])
|
||||
expect(r.text).toContain("** TODO Rome storyboard [1/2]\n")
|
||||
expect(r.text).toContain("*** DONE The forum\nCLOSED: [2026-11-14 Sat 16:40]\n:PROPERTIES:\n:ID: t-forum\n:ITEM: i-forum-1\n:END:\nMade the forum still.\n")
|
||||
// every line no edit touched is as it was
|
||||
const kept = PLAN.split("\n").filter((l) => !/Rome storyboard|The forum/.test(l))
|
||||
for (const l of kept) expect(r.text.split("\n")).toContain(l)
|
||||
// and opened again: CLOSED comes off
|
||||
const back = apply(r.text, [toggled(find(r.plan, "t-forum")!)])
|
||||
expect(back.text).toContain("*** TODO The forum\n:PROPERTIES:")
|
||||
expect(back.text).not.toContain("CLOSED: [2026-11-14")
|
||||
})
|
||||
test("add: under a heading by its words (made when missing), with priority, tags, deadline, agent and checkboxes", () => {
|
||||
n = 0
|
||||
const r = apply(PLAN, [
|
||||
{ op: "add", title: "Senate theme, final mix", under: "Sound", priority: "a", tags: ["trailer", "final-mix"], deadline: "11-20", agents: ["a-score"], from: "m-1", checks: ["stems", "master"] },
|
||||
{ op: "add", title: "Colour the titles", under: "Look" },
|
||||
])
|
||||
expect(r.refs).toEqual(["t-1", "t-2"])
|
||||
const head = r.text.split("\n").find((l) => l.includes("Senate theme"))!
|
||||
expect(head).toMatch(/^\*\* TODO \[#A\] Senate theme, final mix +:trailer:final_mix:$/)
|
||||
expect(head.length).toBe(77)
|
||||
expect(r.text).toContain(`${head}\nDEADLINE: <2026-11-20 Fri>\n:PROPERTIES:\n:ID: t-1\n:AGENT: a-score\n:FROM: m-1\n:END:\n- [ ] stems\n- [ ] master\n`)
|
||||
expect(r.text.endsWith("* Look\n** TODO Colour the titles\n:PROPERTIES:\n:ID: t-2\n:END:\n")).toBe(true)
|
||||
// the task with no id got one on this write (t-3), so every task can be named from now on
|
||||
expect(find(r.plan, "t-3")?.text).toBe("Foley for the fire")
|
||||
expect(find(r.plan, "t-1")).toMatchObject({ priority: "A", tags: ["trailer", "final_mix"], agents: ["a-score"], from: "m-1", stage: "Sound", progress: { done: 0, total: 2 } })
|
||||
})
|
||||
test("#N names a headline with no id as the plan was before the edits, even after an add moved it", () => {
|
||||
const r = apply(PLAN, [
|
||||
{ op: "add", title: "First", before: "t-rome" },
|
||||
{ op: "set", ref: "#6", title: "Foley for the fire and the crowd" },
|
||||
])
|
||||
expect(r.text).toContain("** TODO Foley for the fire and the crowd\n")
|
||||
})
|
||||
test("move: a subtree goes before another task, taking its level; under a heading; never into itself", () => {
|
||||
const r = apply(PLAN, [{ op: "move", ref: "t-rome", before: "#6" }])
|
||||
expect(readPlan(r.text).entries.map((t) => `${t.level}${t.text}`)).toEqual(["1Act one", "2Cast the narrator", "1Sound", "2Rome storyboard", "3The forum", "3The steps", "2Foley for the fire"])
|
||||
const up = apply(PLAN, [{ op: "move", ref: "t-forum", under: "Sound" }])
|
||||
expect(find(up.plan, "t-forum")).toMatchObject({ level: 2, stage: "Sound" })
|
||||
expect(find(up.plan, "t-rome")!.title).toBe("Rome storyboard [0/1]")
|
||||
expect(() => apply(PLAN, [{ op: "move", ref: "t-rome", after: "t-steps" }])).toThrow(/into itself/)
|
||||
})
|
||||
test("set and remove; a checkbox ticked and one added; what's wrong is said and nothing is written", () => {
|
||||
const r = apply(PLAN, [
|
||||
{ op: "set", ref: "t-steps", deadline: "2026-11-21", tags: ["gate"], props: { SHOT: "12" } },
|
||||
{ op: "remove", ref: "t-cast" },
|
||||
])
|
||||
expect(r.text).toContain("*** TODO The steps")
|
||||
expect(find(r.plan, "t-steps")).toMatchObject({ deadline: { date: "2026-11-21" }, tags: ["gate"], props: { ID: "t-steps", SHOT: "12" } })
|
||||
expect(find(r.plan, "t-cast")).toBeUndefined()
|
||||
const c = apply("* TODO Grade [0%]\n:PROPERTIES:\n:ID: g\n:END:\n- [ ] warm\n- [ ] cool\n", [{ op: "check", ref: "g", index: 1 }, { op: "check", ref: "g", add: "contrast" }])
|
||||
expect(c.text).toBe("* TODO Grade [33%]\n:PROPERTIES:\n:ID: g\n:END:\n- [ ] warm\n- [X] cool\n- [ ] contrast\n")
|
||||
expect(() => apply(PLAN, [{ op: "state", ref: "t-nope", state: "done" }])).toThrow(/no task t-nope/)
|
||||
expect(() => apply(PLAN, [{ op: "state", ref: "t-rome", state: "finished" }])).toThrow(/neither a keyword nor a state/)
|
||||
expect(() => apply(PLAN, [{ op: "set", ref: "t-rome", deadline: "someday" }])).toThrow(/YYYY-MM-DD/)
|
||||
})
|
||||
test("closing one task in a file kept by hand changes that task's lines and nothing else", () => {
|
||||
const mine = `#+TITLE: Kept in Emacs
|
||||
#+STARTUP: content
|
||||
#+OPTIONS: toc:nil
|
||||
|
||||
* Notes :notes:
|
||||
#+BEGIN_SRC typescript :tangle yes
|
||||
const x = { a: 1 }
|
||||
* a headline-looking line is one in Org too, so it is one here
|
||||
#+END_SRC
|
||||
| col | other |
|
||||
|-----+-------|
|
||||
| 1 | 2 |
|
||||
#+TBLFM: $2=$1*2
|
||||
- plain list
|
||||
- nested
|
||||
* Work
|
||||
** TODO [#B] Light the door :look:
|
||||
SCHEDULED: <2026-11-20 Fri> DEADLINE: <2026-11-22 Sun>
|
||||
:PROPERTIES:
|
||||
:ID: t-door
|
||||
:Effort: 1:00
|
||||
:END:
|
||||
:LOGBOOK:
|
||||
CLOCK: [2026-11-14 Sat 10:00]--[2026-11-14 Sat 11:00] => 1:00
|
||||
:END:
|
||||
** TODO Score it
|
||||
:PROPERTIES:
|
||||
:ID: t-score
|
||||
:END:
|
||||
`
|
||||
const r = apply(mine, [{ op: "state", ref: "t-door", state: "done" }])
|
||||
const before = mine.split("\n")
|
||||
const after = r.text.split("\n")
|
||||
expect(after.filter((l) => !before.includes(l))).toEqual(["** DONE [#B] Light the door :look:", " CLOSED: [2026-11-14 Sat 16:40] SCHEDULED: <2026-11-20 Fri> DEADLINE: <2026-11-22 Sun>"])
|
||||
expect(before.filter((l) => !after.includes(l))).toEqual(["** TODO [#B] Light the door :look:", " SCHEDULED: <2026-11-20 Fri> DEADLINE: <2026-11-22 Sun>"])
|
||||
expect(after.length).toBe(before.length)
|
||||
})
|
||||
test("under a task's id that isn't there is a mistake, not a stage to make", () => {
|
||||
expect(() => apply(PLAN, [{ op: "add", title: "x", under: "t-gone" }])).toThrow(/no task t-gone/)
|
||||
expect(() => apply(PLAN, [{ op: "move", ref: "t-forum", under: "#99" }])).toThrow(/no task #99/)
|
||||
})
|
||||
test("a plugin's keyword written into a file that doesn't name it gets a #+TODO: line, so Emacs cycles it", () => {
|
||||
const reg = createRegistry()
|
||||
defineKeywords({ name: "shots", words: "SHOT LIT | APPROVED" }, reg)
|
||||
const r = applyEdits(PLAN, [{ op: "add", title: "Shot 12", state: "SHOT" }], { now: NOW, registry: reg })
|
||||
expect(r.text.startsWith("#+TITLE: Ides\n#+TODO: TODO MAKING REVIEW | DONE DROPPED\n#+TODO: SHOT LIT | APPROVED\n\n")).toBe(true)
|
||||
// raea's own words in a file with no #+TODO: line: Org's TODO and DONE need none, MAKING does
|
||||
expect(applyEdits("* TODO a\n:PROPERTIES:\n:ID: a\n:END:\n", [{ op: "state", ref: "a", state: "done" }], { now: NOW }).text.startsWith("* DONE a")).toBe(true)
|
||||
expect(applyEdits("#+TITLE: x\n* TODO a\n:PROPERTIES:\n:ID: a\n:END:\n", [{ op: "state", ref: "a", state: "making" }], { now: NOW }).text.startsWith("#+TITLE: x\n#+TODO: TODO MAKING REVIEW | DONE DROPPED\n* MAKING a")).toBe(true)
|
||||
})
|
||||
test("a new plan is raea's keywords spelled out; the digest an agent reads lists open tasks by id", () => {
|
||||
const r = apply(newPlan("Pong"), [{ op: "add", title: "Tune the paddle", under: "Feel" }, { op: "add", title: "Old idea", state: "dropped" }])
|
||||
expect(r.text.startsWith("#+TITLE: Pong\n#+TODO: TODO MAKING REVIEW | DONE DROPPED\n\n* Feel\n** TODO Tune the paddle\n")).toBe(true)
|
||||
expect(planDigest(r.plan)).toMatch(/^Feel:\n {2}- t-\d+ {2}TODO {2}Tune the paddle\n1 closed \(done or dropped\)\.$/)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,51 @@
|
||||
// PL6: a plugin's keywords, properties, kinds and views (src/extend.ts, src/views.ts).
|
||||
import { describe, expect, test } from "vitest"
|
||||
import { applyEdits, checkPlan, createRegistry, defineKeywords, definePlanKind, defineProperty, defineView, readPlan, view, type Task } from "../src"
|
||||
|
||||
describe("PL6: extending plans", () => {
|
||||
test("a keyword sequence a plugin defines is read in any plan, with the states it gives", () => {
|
||||
const reg = createRegistry()
|
||||
defineKeywords({ name: "film", words: "SHOOT CUT GRADE | DELIVERED", states: { GRADE: "review" } }, reg)
|
||||
const p = readPlan("* SHOOT the steps\n* GRADE the steps\n* DELIVERED the trailer\n", reg)
|
||||
expect(p.tasks.map((t) => [t.keyword, t.state])).toEqual([
|
||||
["SHOOT", "todo"],
|
||||
["GRADE", "review"],
|
||||
["DELIVERED", "done"],
|
||||
])
|
||||
// the default registry doesn't know them: a plain heading
|
||||
expect(readPlan("* SHOOT the steps\n").tasks).toEqual([])
|
||||
expect(() => defineKeywords({ name: "bad", words: "to do | done" }, reg)).toThrow(/capitals/)
|
||||
})
|
||||
|
||||
test("a kind names its sequence, the properties it needs and a check of its own; checkPlan says what's wrong", () => {
|
||||
const reg = createRegistry()
|
||||
defineKeywords({ name: "film", words: "SHOOT CUT | DELIVERED" }, reg)
|
||||
defineProperty({ key: "shot", about: "the shot's number", check: (v) => (/^\d+$/.test(v) ? undefined : "a shot is a number") }, reg)
|
||||
definePlanKind({ name: "shot", keywords: "film", props: ["SHOT"], check: (t: Task) => (t.deadline ? undefined : "a shot needs a deadline"), defaults: { tags: ["shot"] } }, reg)
|
||||
const r = applyEdits("", [{ op: "add", id: "s1", title: "The steps, wide", kind: "shot", state: "SHOOT", props: { SHOT: "x" } }, { op: "add", id: "s2", title: "No kind", kind: "nope" }], { registry: reg })
|
||||
expect(r.plan.tasks[0]).toMatchObject({ kind: "shot", keyword: "SHOOT", tags: ["shot"] })
|
||||
// with no state, a task of a kind starts at its sequence's first word
|
||||
const first = reg.sequences.get("film")!.words[0].word
|
||||
expect(applyEdits("", [{ op: "add", title: "Another", kind: "shot" }], { registry: reg }).plan.tasks[0].keyword).toBe(first)
|
||||
expect(checkPlan(r.plan, reg).map((d) => `${d.ref}: ${d.message}`)).toEqual(["s1: :SHOT: a shot is a number", "s1: a shot needs a deadline", "s2: no kind nope is defined (shot)"])
|
||||
const dup = readPlan("* TODO a\n:PROPERTIES:\n:ID: x\n:END:\n* TODO b\n:PROPERTIES:\n:ID: x\n:END:\n", reg)
|
||||
expect(checkPlan(dup, reg)).toMatchObject([{ ref: "x", severity: "error", line: 4 }])
|
||||
expect(() => definePlanKind({ name: "take", keywords: "nope" }, reg)).toThrow(/defineKeywords it first/)
|
||||
})
|
||||
|
||||
test("views: raea's board and agenda, and one a plugin adds", () => {
|
||||
const reg = createRegistry()
|
||||
const p = readPlan(
|
||||
"* TODO a\nDEADLINE: <2026-11-13 Fri>\n* MAKING b\nSCHEDULED: <2026-11-15 Sun>\n* REVIEW c\n* DONE d\nDEADLINE: <2026-11-14 Sat>\n* DROPPED e\n* TODO f :x:\n:PROPERTIES:\n:AGENT: a-grade\n:END:\n",
|
||||
reg,
|
||||
)
|
||||
const lanes = view<{ state: string; tasks: Task[] }[]>(p, "board", undefined, reg)
|
||||
expect(lanes.map((l) => `${l.state}:${l.tasks.map((t) => t.text).join("")}`)).toEqual(["todo:af", "making:b", "review:c", "done:d"])
|
||||
const a = view<{ overdue: { task: Task }[]; days: { date: string; entries: { task: Task; why: string }[] }[] }, { from: string; days: number }>(p, "agenda", { from: "2026-11-14", days: 3 }, reg)
|
||||
expect(a.overdue.map((e) => e.task.text)).toEqual(["a"])
|
||||
expect(a.days.map((d) => `${d.date}:${d.entries.map((e) => `${e.task.text}/${e.why}`).join(",")}`)).toEqual(["2026-11-14:", "2026-11-15:b/scheduled", "2026-11-16:"])
|
||||
defineView({ name: "by-agent", build: (plan) => Object.groupBy(plan.tasks.filter((t) => t.agents.length), (t) => t.agents[0]) }, reg)
|
||||
expect(Object.keys(view<Record<string, Task[]>>(p, "by-agent", undefined, reg))).toEqual(["a-grade"])
|
||||
expect(() => view(p, "nope", undefined, reg)).toThrow(/no plan view nope: board, agenda, outline, by-agent/)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,151 @@
|
||||
// PL2: the plan.org read and written without losing a byte (src/org.ts, src/time.ts).
|
||||
import { describe, expect, test } from "vitest"
|
||||
import { checksOf, dayOf, formatStamp, linksIn, linkText, parseOrg, parseStamp, printOrg, readHeadline } from "../src"
|
||||
|
||||
const KW = new Set(["TODO", "MAKING", "REVIEW", "DONE", "DROPPED"])
|
||||
|
||||
const GNARLY = `#+TITLE: The Ides of March
|
||||
#+TODO: TODO MAKING REVIEW | DONE DROPPED
|
||||
#+STARTUP: overview
|
||||
Some words before any headline, kept as they are.
|
||||
|
||||
* Act one :act_one:
|
||||
** DONE [#A] Cast the narrator :score:
|
||||
CLOSED: [2026-11-02 Mon 10:14] DEADLINE: <2026-11-01 Sun>
|
||||
:PROPERTIES:
|
||||
:ID: t-cast
|
||||
:AGENT: a-score
|
||||
:CUSTOM_thing: kept as written
|
||||
:END:
|
||||
:LOGBOOK:
|
||||
- State "DONE" from "TODO" [2026-11-02 Mon 10:14]
|
||||
:END:
|
||||
** TODO Rome storyboard [1/3]
|
||||
SCHEDULED: <2026-11-20 Fri 10:00-11:00 +1w -2d>
|
||||
- [X] the forum
|
||||
- [ ] the steps
|
||||
- [x] a nested one
|
||||
- [-] the senate
|
||||
| a | table |
|
||||
|---+-------|
|
||||
#+BEGIN_SRC tsx
|
||||
* not a headline inside a block? Org says it is one, and so do we
|
||||
#+END_SRC
|
||||
*bold* at the start of a line is no headline
|
||||
* WAITING an unknown keyword is part of the title
|
||||
*** Deep, skipping a level
|
||||
:PROPERTIES:
|
||||
:ID: unterminated drawer, so this is body
|
||||
* COMMENT a commented heading
|
||||
* Last line without a newline`
|
||||
|
||||
describe("PL2a: a round trip changes nothing", () => {
|
||||
test("a file with drawers, logbooks, tables, blocks, odd spacing and no final newline prints back byte for byte", () => {
|
||||
expect(printOrg(parseOrg(GNARLY, KW))).toBe(GNARLY)
|
||||
expect(printOrg(parseOrg(`${GNARLY}\n`, KW))).toBe(`${GNARLY}\n`)
|
||||
})
|
||||
test("CRLF files, empty files, a file of only a head, trailing blank lines", () => {
|
||||
for (const t of ["", "\n", "\n\n", "#+TITLE: x\n", "* TODO a\r\n** DONE b\r\n :PROPERTIES:\r\n :ID: x\r\n :END:\r\n", "* a\n\n\n", "text\n* h\nbody\n\n"]) expect(printOrg(parseOrg(t, KW))).toBe(t)
|
||||
})
|
||||
})
|
||||
|
||||
describe("PL2b: what a headline says", () => {
|
||||
test("stars, keyword, priority, title and tags", () => {
|
||||
expect(readHeadline("** DONE [#A] Cast the narrator :score:x@y:", KW)).toEqual({ level: 2, keyword: "DONE", priority: "A", title: "Cast the narrator", tags: ["score", "x@y"] })
|
||||
expect(readHeadline("* TODO", KW)).toEqual({ level: 1, keyword: "TODO", title: "", tags: [] })
|
||||
expect(readHeadline("* WAITING on the cut", KW)).toEqual({ level: 1, title: "WAITING on the cut", tags: [] })
|
||||
expect(readHeadline("*bold*", KW)).toBeNull()
|
||||
expect(readHeadline("* Tags need a space before them:no:", KW)!.tags).toEqual([])
|
||||
})
|
||||
test("planning, drawer and body are told apart; an unterminated drawer is body", () => {
|
||||
const d = parseOrg(GNARLY, KW)
|
||||
const cast = d.sections[1]
|
||||
expect(cast.planning.closed).toEqual({ active: false, date: "2026-11-02", time: "10:14" })
|
||||
expect(cast.planning.deadline).toEqual({ active: true, date: "2026-11-01" })
|
||||
expect(cast.props).toEqual([["ID", "t-cast"], ["AGENT", "a-score"], ["CUSTOM_thing", "kept as written"]])
|
||||
expect(cast.body[0]).toBe(" :LOGBOOK:")
|
||||
const rome = d.sections[2]
|
||||
expect(rome.planning.scheduled).toEqual({ active: true, date: "2026-11-20", time: "10:00", end: "11:00", repeat: "+1w", warn: "-2d" })
|
||||
expect(checksOf(rome.body).map((c) => [c.done, c.partial, c.indent, c.text])).toEqual([
|
||||
[true, false, 0, "the forum"],
|
||||
[false, false, 0, "the steps"],
|
||||
[true, false, 2, "a nested one"],
|
||||
[false, true, 0, "the senate"],
|
||||
])
|
||||
const deep = d.sections.find((s) => s.title.startsWith("Deep"))!
|
||||
expect(deep.props).toBeUndefined()
|
||||
expect(deep.body).toEqual([":PROPERTIES:", ":ID: unterminated drawer, so this is body"])
|
||||
})
|
||||
})
|
||||
|
||||
describe("PL2c: a changed entry is written again part by part", () => {
|
||||
test("a new keyword rewrites the headline, keeps the planning line and drawer as they were", () => {
|
||||
const d = parseOrg(GNARLY, KW)
|
||||
d.sections[2].keyword = "MAKING"
|
||||
const out = printOrg(d)
|
||||
expect(out).toContain("** MAKING Rome storyboard [1/3]\nSCHEDULED: <2026-11-20 Fri 10:00-11:00 +1w -2d>\n- [X] the forum")
|
||||
expect(out.replace("MAKING Rome", "TODO Rome")).toBe(GNARLY)
|
||||
})
|
||||
test("a property added keeps every other property's line, indentation and all", () => {
|
||||
const d = parseOrg(GNARLY, KW)
|
||||
d.sections[1].props = [...d.sections[1].props!, ["ITEM", "i-cast"]]
|
||||
const out = printOrg(d)
|
||||
expect(out).toContain(" :CUSTOM_thing: kept as written\n :ITEM: i-cast\n :END:")
|
||||
expect(out.split("\n").length).toBe(GNARLY.split("\n").length + 1)
|
||||
})
|
||||
test("tags end at column 77; a new drawer and planning line are written Org's way", () => {
|
||||
const d = parseOrg("* TODO Grade it\n", KW)
|
||||
d.sections[0].tags = ["trailer"]
|
||||
d.sections[0].planning = { deadline: { active: true, date: "2026-11-03" } }
|
||||
d.sections[0].props = [["ID", "t-1"]]
|
||||
const out = printOrg(d).split("\n")
|
||||
expect(out[0].length).toBe(77)
|
||||
expect(out[0]).toMatch(/^\* TODO Grade it +:trailer:$/)
|
||||
expect(out.slice(1, 5)).toEqual(["DEADLINE: <2026-11-03 Tue>", ":PROPERTIES:", ":ID: t-1", ":END:"])
|
||||
})
|
||||
test("a headline whose keyword or words change keeps its own spacing, and its tags end where they ended", () => {
|
||||
const d = parseOrg("* TODO [#B] Foo bar :a:b:\n** NEXT\tTabbed\n", new Set([...KW, "NEXT"]))
|
||||
d.sections[0].keyword = "DONE"
|
||||
d.sections[0].title = "Foo bar [1/2]"
|
||||
d.sections[1].keyword = undefined
|
||||
expect(printOrg(d)).toBe("* DONE [#B] Foo bar [1/2] :a:b:\n** Tabbed\n")
|
||||
// tags aligned to a column stay at it
|
||||
const aligned = parseOrg("** TODO Light the door :look:\n", KW)
|
||||
aligned.sections[0].keyword = "MAKING"
|
||||
expect(printOrg(aligned)).toBe("** MAKING Light the door :look:\n")
|
||||
})
|
||||
test("a planning line raea can't wholly read (a range of days, a habit) is still the planning line", () => {
|
||||
const text = "* TODO Shoot the steps\n SCHEDULED: <2026-11-20 Fri>--<2026-11-22 Sun> DEADLINE: <2026-11-23 Mon .+2d/3d>\n :PROPERTIES:\n :ID: t-steps\n :END:\n"
|
||||
const d = parseOrg(text, KW)
|
||||
expect(d.sections[0].props).toEqual([["ID", "t-steps"]])
|
||||
expect(d.sections[0].planning).toEqual({ deadline: { active: true, date: "2026-11-23", repeat: ".+2d/3d" }, rest: ["SCHEDULED: <2026-11-20 Fri>--<2026-11-22 Sun>"] })
|
||||
expect(printOrg(d)).toBe(text)
|
||||
// closed: CLOSED comes first, and the rest is written as it was, in its order
|
||||
d.sections[0].keyword = "DONE"
|
||||
d.sections[0].planning = { ...d.sections[0].planning, closed: { active: false, date: "2026-11-14", time: "16:40" } }
|
||||
expect(printOrg(d).split("\n")[1]).toBe(" CLOSED: [2026-11-14 Sat 16:40] DEADLINE: <2026-11-23 Mon .+2d/3d> SCHEDULED: <2026-11-20 Fri>--<2026-11-22 Sun>")
|
||||
})
|
||||
test("a CRLF file's new lines end in CRLF", () => {
|
||||
const d = parseOrg("* TODO a\r\n", KW)
|
||||
d.sections[0].props = [["ID", "x"]]
|
||||
expect(printOrg(d)).toBe("* TODO a\r\n:PROPERTIES:\r\n:ID: x\r\n:END:\r\n")
|
||||
})
|
||||
})
|
||||
|
||||
describe("timestamps and links", () => {
|
||||
test("read and written back; a day as a person writes it", () => {
|
||||
for (const s of ["<2026-11-14 Sat>", "[2026-11-14 Sat 16:40]", "<2026-11-14 Sat 10:00-11:30 .+1d --3d>"]) expect(formatStamp(parseStamp(s)!)).toBe(s)
|
||||
expect(parseStamp("<2026-11-14 Sat]")).toBeUndefined()
|
||||
expect(dayOf("11-03", new Date(2026, 0, 1))).toEqual({ active: true, date: "2026-11-03" })
|
||||
expect(dayOf("2026-02-30")).toBeUndefined()
|
||||
expect(dayOf("soon")).toBeUndefined()
|
||||
})
|
||||
test("links by type: a feed item, a task by id, a web page", () => {
|
||||
expect(linksIn("Made [[item:i-hero][the trailer]], see [[id:t-cast]] and [[https://raea.io]]").map((l) => [l.type, l.path, l.desc])).toEqual([
|
||||
["item", "i-hero", "the trailer"],
|
||||
["id", "t-cast", undefined],
|
||||
["https", "//raea.io", undefined],
|
||||
])
|
||||
expect(linkText("Grade [[item:i-hero][the trailer]] after [[id:t-1]]")).toBe("Grade the trailer after t-1")
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,55 @@
|
||||
// PL6: the React side (src/react.tsx): a plan read from a source that changes, and the components drawn as plain
|
||||
// elements. Run by the app's vitest, which has react-dom (apps/app vite.config.ts test.include).
|
||||
import { renderToStaticMarkup } from "react-dom/server"
|
||||
import { describe, expect, test } from "vitest"
|
||||
import { readPlan } from "../src"
|
||||
import { Agenda, BoardLanes, memorySource, PlanOutline, TaskLine, toggled, usePlan } from "../src/react"
|
||||
|
||||
const TEXT = "* Act one\n** TODO [#A] Rome storyboard [0/1]\n:PROPERTIES:\n:ID: t-rome\n:END:\n*** TODO The forum\nDEADLINE: <2026-11-14 Sat>\n:PROPERTIES:\n:ID: t-forum\n:END:\n** DONE Cast\n"
|
||||
|
||||
describe("PL6: React", () => {
|
||||
test("TaskLine: a checkbox, the words, priority, progress, deadline; a heading has no checkbox", () => {
|
||||
const p = readPlan(TEXT)
|
||||
const html = renderToStaticMarkup(<TaskLine task={p.entries[1]} onToggle={() => {}} />)
|
||||
expect(html).toContain('data-task="t-rome"')
|
||||
expect(html).toContain('role="checkbox" aria-checked="false"')
|
||||
expect(html).toContain('<span data-part="priority">A</span>')
|
||||
expect(html).toContain('<span data-part="text">Rome storyboard</span>')
|
||||
expect(html).toContain('<span data-part="progress">0/1</span>')
|
||||
expect(renderToStaticMarkup(<TaskLine task={p.entries[0]} />)).not.toContain("checkbox")
|
||||
})
|
||||
|
||||
test("the outline nests, the board has its lanes, the agenda its days", () => {
|
||||
const p = readPlan(TEXT)
|
||||
const outline = renderToStaticMarkup(<PlanOutline plan={p} />)
|
||||
expect(outline.indexOf("The forum")).toBeGreaterThan(outline.indexOf("Rome storyboard"))
|
||||
expect(outline.match(/<ul/g)!.length).toBe(3)
|
||||
const board = renderToStaticMarkup(<BoardLanes plan={p} labels={{ todo: "Next" }} />)
|
||||
expect(board).toMatch(/data-state="todo"><h3>Next <span data-part="count">2<\/span>/)
|
||||
expect(board).toMatch(/data-state="done"><h3>Done <span data-part="count">1<\/span>/)
|
||||
const agenda = renderToStaticMarkup(<Agenda plan={p} from="2026-11-14" days={2} />)
|
||||
expect(agenda).toMatch(/data-date="2026-11-14"><h3>2026-11-14<\/h3><ul><li data-why="deadline">.*The forum/)
|
||||
})
|
||||
|
||||
test("usePlan reads a source and edits it by id; a source of text alone is read-only", () => {
|
||||
const src = memorySource(TEXT)
|
||||
let seen: ReturnType<typeof usePlan> | undefined
|
||||
const Probe = () => {
|
||||
seen = usePlan(src)
|
||||
return null
|
||||
}
|
||||
renderToStaticMarkup(<Probe />)
|
||||
expect(seen!.plan.tasks.length).toBe(3)
|
||||
seen!.edit([toggled(seen!.plan.tasks[1])])
|
||||
expect(readPlan(src.read()!).tasks[1].state).toBe("done")
|
||||
expect(src.read()).toContain("** TODO [#A] Rome storyboard [1/1]")
|
||||
renderToStaticMarkup(<Probe />)
|
||||
expect(seen!.plan.tasks[1].state).toBe("done")
|
||||
const Fixed = () => {
|
||||
seen = usePlan(TEXT)
|
||||
return null
|
||||
}
|
||||
renderToStaticMarkup(<Fixed />)
|
||||
expect(() => seen!.edit([])).toThrow(/read-only/)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,91 @@
|
||||
// PL5: a plan's tools for an agent (src/tools.ts), answered on a plan in memory the way the app and a headless run do.
|
||||
import { describe, expect, test } from "vitest"
|
||||
import { answerPlanTool, applyEdits, find, readPlan, planToolEdits, type PlanToolHost } from "../src"
|
||||
|
||||
const NOW = new Date(2026, 10, 14, 16, 40)
|
||||
const START = `#+TITLE: Stay
|
||||
#+TODO: TODO MAKING REVIEW | DONE DROPPED
|
||||
|
||||
* Look
|
||||
** TODO Light the door
|
||||
:PROPERTIES:
|
||||
:ID: t-door
|
||||
:END:
|
||||
- [ ] warm key
|
||||
- [ ] cool fill
|
||||
`
|
||||
|
||||
/** A host on a plan in memory: the page's and the headless feed's, minus where the text is kept. */
|
||||
function host(text = START): PlanToolHost & { now: () => string } {
|
||||
let n = 0
|
||||
let at = text
|
||||
return {
|
||||
who: "a-light",
|
||||
text: () => at,
|
||||
apply: (edits) => {
|
||||
const r = applyEdits(at, edits, { now: NOW, newId: () => `t-new${++n}` })
|
||||
at = r.text
|
||||
return r
|
||||
},
|
||||
now: () => at,
|
||||
}
|
||||
}
|
||||
|
||||
describe("an agent's plan tools", () => {
|
||||
test("plan_read gives the open tasks by id, and the whole file with full", async () => {
|
||||
const h = host()
|
||||
const r = (await answerPlanTool("plan_read", {}, h)) as { file: string; open: string; text?: string }
|
||||
expect(r.file).toBe("plan.org")
|
||||
expect(r.open).toContain("t-door TODO Light the door")
|
||||
expect(r.text).toBeUndefined()
|
||||
expect(((await answerPlanTool("plan_read", { full: true }, h)) as { text: string }).text).toBe(START)
|
||||
})
|
||||
|
||||
test("plan_add writes tasks under their stage, held by the agent that asked unless it names others", async () => {
|
||||
const h = host()
|
||||
const r = (await answerPlanTool("plan_add", { tasks: [{ title: "Grade the hall", under: "Look", priority: "A", deadline: "2026-11-20", tags: ["look"] }, { title: "Score it", agents: ["a-score"] }] }, h)) as { ids: string[] }
|
||||
expect(r.ids).toEqual(["t-new1", "t-new2"])
|
||||
const plan = readPlan(h.now())
|
||||
expect(find(plan, "t-new1")).toMatchObject({ stage: "Look", level: 2, priority: "A", agents: ["a-light"], tags: ["look"], deadline: { date: "2026-11-20" } })
|
||||
expect(find(plan, "t-new2")).toMatchObject({ level: 1, agents: ["a-score"] })
|
||||
expect(h.now()).toContain("** TODO [#A] Grade the hall")
|
||||
})
|
||||
|
||||
test("plan_update marks, ticks, adds a checkbox, moves and sets fields by id", async () => {
|
||||
const h = host()
|
||||
await answerPlanTool("plan_update", { changes: [{ id: "t-door", state: "making", check: 0, add_check: "rim light", item: "i-door-2" }] }, h)
|
||||
const t = find(readPlan(h.now()), "t-door")!
|
||||
expect([t.keyword, t.item, t.checks.map((c) => `${c.done ? "x" : " "} ${c.text}`)]).toEqual(["MAKING", "i-door-2", ["x warm key", " cool fill", " rim light"]])
|
||||
expect(t.progress).toEqual({ done: 1, total: 3 })
|
||||
})
|
||||
|
||||
test("plan_close closes with CLOSED, the item it made and a note; dropped keeps the task", async () => {
|
||||
const h = host()
|
||||
await answerPlanTool("plan_close", { id: "t-door", item: "i-door-3", note: "Warm key at 3200K." }, h)
|
||||
expect(h.now()).toContain("** DONE Light the door\nCLOSED: [2026-11-14 Sat 16:40]")
|
||||
expect(h.now()).toContain(":ITEM: i-door-3")
|
||||
expect(h.now()).toContain("Warm key at 3200K.")
|
||||
const d = host()
|
||||
await answerPlanTool("plan_close", { id: "t-door", state: "dropped" }, d)
|
||||
expect(find(readPlan(d.now()), "t-door")!.state).toBe("dropped")
|
||||
})
|
||||
|
||||
test("a wrong input or a task that isn't there is said, and nothing is written", async () => {
|
||||
const h = host()
|
||||
expect(() => planToolEdits("plan_add", { tasks: [] }, "a")).toThrow(/at least one/)
|
||||
expect(() => planToolEdits("plan_update", { changes: [{ id: "t-door" }] }, "a")).toThrow(/nothing to change/)
|
||||
expect(() => planToolEdits("plan_close", { id: "t-door", state: "making" }, "a")).toThrow(/done or dropped/)
|
||||
await expect(answerPlanTool("plan_close", { id: "t-door", state: "MAKING" }, h)).rejects.toThrow(/MAKING doesn't close/)
|
||||
await expect(answerPlanTool("plan_close", { id: "t-gone" }, h)).rejects.toThrow(/no task t-gone/)
|
||||
await expect(answerPlanTool("plan_add", { tasks: [{ title: "x", under: "t-gone" }] }, h)).rejects.toThrow(/no task t-gone/)
|
||||
expect(h.now()).toBe(START)
|
||||
})
|
||||
|
||||
test("plan_read gives a task written by hand without an id one first, so the agent never names a task by its place", async () => {
|
||||
const h = host(`${START}** TODO Written in Emacs\n`)
|
||||
const r = (await answerPlanTool("plan_read", {}, h)) as { open: string }
|
||||
expect(r.open).toContain("t-new1 TODO Written in Emacs")
|
||||
expect(r.open).not.toMatch(/#\d/)
|
||||
expect(h.now()).toContain("** TODO Written in Emacs\n:PROPERTIES:\n:ID: t-new1\n:END:\n")
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"extends": "../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"erasableSyntaxOnly": true,
|
||||
"noUnusedLocals": true,
|
||||
"lib": ["ES2023", "DOM"]
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"lockfileVersion": 2,
|
||||
"configVersion": 1,
|
||||
"workspaces": {
|
||||
"": {
|
||||
"name": "@raea/timeline",
|
||||
"devDependencies": {
|
||||
"@types/bun": "1.4.3",
|
||||
},
|
||||
},
|
||||
},
|
||||
"packages": {
|
||||
"@types/bun": ["@types/[email protected]", "", { "dependencies": { "bun-types": "1.4.3" } }, "sha512-N67Pqy8JXbAY/j0tNraS3V5mubGvc6rrrNDmDCtZLlFzccbUJPDb0tvgUBC5q4m8ybkP93Jcn1QB+RYQ6PvBhw=="],
|
||||
|
||||
"@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~8.9.0" } }, "sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog=="],
|
||||
|
||||
"bun-types": ["[email protected]", "", { "dependencies": { "@types/node": "*", "undici-types": "*" } }, "sha512-tinRJNGOmUN+tEAsn2y2e942n9JHRHR42iUYzDH75NmhJqVBokGSQkkfSFdNWwsANIdrK6ACH9t01M452YyTwg=="],
|
||||
|
||||
"undici-types": ["[email protected]", "", {}, "sha512-GNCQH3MbVGB8OAVAoTiLH8pu4wx5Ni3DWKpnBzGj3WDsi8EwmK0aOVBooNEt+g5YL1eHPxcS9XUTouwFU6j1kQ=="],
|
||||
|
||||
"@types/node/undici-types": ["[email protected]", "", {}, "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg=="],
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"name": "@raea/timeline",
|
||||
"license": "FSL-1.1-ALv2",
|
||||
"private": true,
|
||||
"version": "0.1.0",
|
||||
"description": "raea's timeline (docs/timeline.feature): tracks, clips, keys and markers, and every edit to them as a pure operation with its inverse. No React and no DOM: the app's strip, the host and an agent's script use the same model.",
|
||||
"type": "module",
|
||||
"main": "src/index.ts",
|
||||
"exports": {
|
||||
".": "./src/index.ts"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "bun test test"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/bun": "1.4.3"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
// A clip's own Adjust (docs/timeline.feature TL7g; CapCut's Adjust tab) as its props: one a kind (brightness is
|
||||
// adjustBrightness), 0 as shot, each keyed as any number is (TL5a). The preview's look and a composition's
|
||||
// <Nudge adjust> are drawn by sdk/video adjust.ts, one SVG filter and a vignette layer.
|
||||
import { ADJUST_KINDS, ADJUSTS, adjustError as error, adjustId, adjustSteps, vignetteStyle, type Adjust, type AdjustKind, type FilterStep } from "@raea/video/adjust"
|
||||
import type { Value } from "./model"
|
||||
|
||||
export { ADJUST_KINDS, ADJUSTS, type Adjust, type AdjustKind, type FilterStep }
|
||||
|
||||
type Props = Record<string, Value | boolean>
|
||||
|
||||
/** Each adjustment as a clip's prop: brightness is adjustBrightness. */
|
||||
export const ADJUST_PROPS = Object.fromEntries(ADJUST_KINDS.map((k) => [k, `adjust${k[0].toUpperCase()}${k.slice(1)}`])) as Record<AdjustKind, string>
|
||||
/** The clip props an adjustment is held in. */
|
||||
export const ADJUST_PROP_LIST: string[] = Object.values(ADJUST_PROPS)
|
||||
|
||||
/** A clip's adjustment read from its props: the kinds that aren't 0. */
|
||||
export function adjustOf(props: Props = {}): Adjust {
|
||||
return Object.fromEntries(ADJUST_KINDS.flatMap((k) => {
|
||||
const v = props[ADJUST_PROPS[k]]
|
||||
return typeof v === "number" && Number.isFinite(v) && v !== 0 ? [[k, v]] : []
|
||||
})) as Adjust
|
||||
}
|
||||
|
||||
/** An adjustment as a clip's props, to three places: every kind, 0 for what it hasn't got, so a set puts it whole. */
|
||||
export function adjustProps(a: Adjust): Props {
|
||||
return Object.fromEntries(ADJUST_KINDS.map((k) => [ADJUST_PROPS[k], Math.round((a[k] ?? 0) * 1000) / 1000]))
|
||||
}
|
||||
|
||||
/** What is wrong with a clip's adjustment props as they stand, or undefined: a value out of its range. */
|
||||
export function adjustError(props: Props = {}): string | undefined {
|
||||
for (const k of ADJUST_KINDS) {
|
||||
const v = props[ADJUST_PROPS[k]]
|
||||
if (v !== undefined && typeof v !== "number") return `an adjust's ${k} is a number, got ${JSON.stringify(v)}`
|
||||
}
|
||||
return error(adjustOf(props))
|
||||
}
|
||||
|
||||
/** How the editor's preview draws a clip's adjustment on its picture, as <Nudge adjust> draws it: its SVG filter's
|
||||
* id and steps (to put beside the picture), and its vignette's background (a layer over the picture). A wrong one
|
||||
* draws nothing rather than throwing in the editor. */
|
||||
export function adjustLook(props: Props | undefined, seed = 0): { filter?: { id: string; steps: FilterStep[] }; vignette?: string } {
|
||||
const a = adjustOf(props)
|
||||
if (error(a)) return {}
|
||||
const steps = adjustSteps(a, seed)
|
||||
const v = vignetteStyle(a.vignette ?? 0)
|
||||
return { ...(steps.length && { filter: { id: adjustId(a, seed), steps } }), ...(v && { vignette: v.background }) }
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
// A clip's own animations as the picture shows them (docs/timeline.feature TL7d, TL7e): the In and Out edges and the
|
||||
// Combo a composition's <Transition> draws (sdk/video edges.ts), so the timeline's preview of a film matches the render.
|
||||
import { COMBOS, type ComboKind, comboStyle, edgesStyle, type EdgeStyle, joinStyles, TRANSITION_KINDS, type TransitionKind } from "@raea/video/edges"
|
||||
import type { Anim, Clip, Frames } from "./model"
|
||||
|
||||
export { COMBO_KINDS, COMBOS, type ComboKind, type ComboWave, type EdgeStyle } from "@raea/video/edges"
|
||||
|
||||
/** raea's own kind, or a fade for a plugin's, which only its own code draws. */
|
||||
const kindOf = (k: string): TransitionKind => (TRANSITION_KINDS.includes(k as TransitionKind) ? (k as TransitionKind) : "fade")
|
||||
|
||||
/** The clip's style `into` frames from its start: coming in by its In, going out by its Out (each over no more of it
|
||||
* than it has) and moving by its Combo, one of `combos` (a plugin's among them). Empty when none plays there. */
|
||||
export function animStyle(c: Clip, into: Frames, combos: ComboKind[] = COMBOS): EdgeStyle {
|
||||
const edge = (a?: Anim) => (a ? { kind: kindOf(a.kind), frames: Math.min(a.length, c.length) } : undefined)
|
||||
const combo = c.combo ? comboStyle(combos.find((k) => k.kind === c.combo!.kind), into, c.combo.length) : {}
|
||||
return joinStyles(edgesStyle(edge(c.enter), edge(c.exit), into, c.length), combo)
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
// The frames kept while editing (docs/timeline.feature TL10): which ranges an edit changed (so only those are drawn
|
||||
// again, TL10c), what a kept range is kept under (TL10b), and what goes first when the store is over its size
|
||||
// (TL10e). Pure: the stage that draws frames and the store that holds them use these to decide.
|
||||
import { type Clip, end, type Frames, type Timeline, type Track } from "./model"
|
||||
|
||||
export type Range = [from: Frames, to: Frames]
|
||||
|
||||
/** Ranges in order, touching and overlapping ones joined, empty ones dropped. */
|
||||
export function joined(ranges: Range[]): Range[] {
|
||||
const out: Range[] = []
|
||||
for (const [a, b] of [...ranges].filter(([a, b]) => b > a).sort((x, y) => x[0] - y[0])) {
|
||||
const last = out[out.length - 1]
|
||||
if (last && a <= last[1]) last[1] = Math.max(last[1], b)
|
||||
else out.push([a, b])
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** `ranges` with `cut` taken out of them. */
|
||||
export function without(ranges: Range[], cut: Range[]): Range[] {
|
||||
let out = joined(ranges)
|
||||
for (const [c0, c1] of joined(cut)) out = out.flatMap(([a, b]): Range[] => (c1 <= a || c0 >= b ? [[a, b]] : [[a, Math.min(b, c0)], [Math.max(a, c1), b]])).filter(([a, b]) => b > a)
|
||||
return out
|
||||
}
|
||||
|
||||
const drawn = (k: Track, c: Clip) => !c.off && !(k.kind === "sound" ? k.muted : k.hidden)
|
||||
/** What a clip draws, said so that the same pictures give the same words wherever the clip is cut: a media clip
|
||||
* by where its source sits against the timeline (so the two halves of a split say what the whole did), anything
|
||||
* else by where it starts (its content runs from its own first frame). Keys and fades are said at their timeline
|
||||
* frames. Its name, its lock and its group aren't in it. */
|
||||
function look(k: Track, n: number, c: Clip): string {
|
||||
const still = c.in !== undefined && !c.curve
|
||||
const phase = still ? `p${c.in! - c.start * (c.speed && c.speed > 0 ? c.speed : 1)}` : `s${c.start}+${c.length}`
|
||||
const keys = Object.entries(c.keys ?? {}).map(([p, ks]) => [p, ks.map((x) => [x.at + c.start, x.value, x.ease ?? "linear"])])
|
||||
const fades = [c.fadeIn ? [c.start, c.fadeIn] : 0, c.fadeOut ? [end(c), c.fadeOut] : 0]
|
||||
// footage whose sound was taken out says so only then, so what was kept before it was a field still matches
|
||||
return JSON.stringify([n, k.kind, c.kind, c.freeze ? `f${c.in}` : c.reverse ? `r${c.start}+${c.length}:${c.in}` : phase, c.speed ?? 1, c.curve ?? null, c.shows ?? null, c.props ?? null, keys, c.volume ?? 1, fades, c.at ?? null, ...(c.muted ? ["muted"] : [])])
|
||||
}
|
||||
|
||||
/** Every drawn thing on the timeline as the span it covers and what it draws there. */
|
||||
function spans(t: Timeline): { span: Range; look: string }[] {
|
||||
const out: { span: Range; look: string }[] = []
|
||||
t.tracks.forEach((k, n) => {
|
||||
for (const c of k.clips) if (drawn(k, c)) out.push({ span: [c.start, end(c)], look: look(k, n, c) })
|
||||
})
|
||||
for (const x of t.transitions) {
|
||||
const c = t.tracks.flatMap((k) => k.clips).find((o) => o.id === x.after)
|
||||
const half = Math.ceil(x.length / 2)
|
||||
if (c) out.push({ span: [end(c) - half, end(c) + half], look: `x:${x.kind}:${x.length}:${end(c)}` })
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** The frames whose picture or sound differ between two states of a timeline: wherever what is drawn over a frame
|
||||
* isn't what was. Moving a clip from 2:00-2:05 to 2:10-2:15 gives those two ranges and nothing else (TL10c); a
|
||||
* split of footage gives none. */
|
||||
export function changed(before: Timeline, after: Timeline): Range[] {
|
||||
const a = spans(before), b = spans(after)
|
||||
const edges = [...new Set([...a, ...b].flatMap((x) => x.span))].sort((x, y) => x - y)
|
||||
const over = (xs: { span: Range; look: string }[], from: Frames, to: Frames) => xs.filter((x) => x.span[0] < to && x.span[1] > from).map((x) => x.look).sort().join("\n")
|
||||
const out: Range[] = []
|
||||
for (let i = 0; i + 1 < edges.length; i++) if (over(a, edges[i], edges[i + 1]) !== over(b, edges[i], edges[i + 1])) out.push([edges[i], edges[i + 1]])
|
||||
return joined(out)
|
||||
}
|
||||
|
||||
/** What a range of kept frames is kept under: everything that draws it. Two states of a timeline that draw the
|
||||
* range the same give the same key, so frames drawn before an edit elsewhere (or before an undo) are found again. */
|
||||
export function keyOf(t: Timeline, [from, to]: Range, media: (clip: Clip) => string = () => ""): string {
|
||||
const parts: string[] = [`${t.fps}`]
|
||||
t.tracks.forEach((k, n) => {
|
||||
for (const c of k.clips) if (drawn(k, c) && c.start < to && end(c) > from) parts.push(`${look(k, n, c)}:${media(c)}`)
|
||||
})
|
||||
for (const x of spans(t)) if (x.look.startsWith("x:") && x.span[0] < to && x.span[1] > from) parts.push(x.look)
|
||||
// FNV-1a over the parts: a short name for a file, not a secret
|
||||
let h = 0x811c9dc5
|
||||
for (const ch of parts.sort().join("|")) h = Math.imul(h ^ ch.charCodeAt(0), 0x01000193) >>> 0
|
||||
return `${from}-${to}-${h.toString(16).padStart(8, "0")}`
|
||||
}
|
||||
|
||||
/** A drawn range in the store, as the clearing reads it (TL10e). */
|
||||
export interface Kept {
|
||||
/** the range's key (rangeKey): what it is drawn from */
|
||||
key: string
|
||||
/** what it takes on disk */
|
||||
bytes: number
|
||||
/** when it was last played (ms) */
|
||||
used: number
|
||||
/** it belongs to a version that was closed or discarded: it goes at once */
|
||||
stale?: boolean
|
||||
}
|
||||
|
||||
/** The keys to drop so the store is at most `limit` bytes: stale ones first, then the least recently played. What
|
||||
* is under the playhead (`hold`) stays while anything else can go (TL10e). */
|
||||
export function evict(kept: Kept[], limit: number, hold: Set<string> = new Set()): string[] {
|
||||
let total = kept.reduce((n, k) => n + k.bytes, 0)
|
||||
const out: string[] = []
|
||||
const order = [...kept].sort((a, b) => Number(!!b.stale) - Number(!!a.stale) || Number(hold.has(a.key)) - Number(hold.has(b.key)) || a.used - b.used)
|
||||
for (const k of order) {
|
||||
if (!k.stale && total <= limit) break
|
||||
out.push(k.key)
|
||||
total -= k.bytes
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** The ranges to draw next while there is time (TL10d): what isn't kept from the playhead on, nearest first, each
|
||||
* at most `chunk` frames, then what is before it. */
|
||||
export function ahead(length: Frames, kept: Range[], playhead: Frames, chunk: Frames): Range[] {
|
||||
const missing = without([[0, length]], kept)
|
||||
const pieces = missing.flatMap(([a, b]): Range[] => Array.from({ length: Math.ceil((b - a) / chunk) }, (_, i) => [a + i * chunk, Math.min(b, a + (i + 1) * chunk)] as Range))
|
||||
const after = pieces.filter(([, b]) => b > playhead).sort((x, y) => x[0] - y[0])
|
||||
const before = pieces.filter(([, b]) => b <= playhead).sort((x, y) => y[0] - x[0])
|
||||
return [...after, ...before]
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
// Captions made from what is said (docs/timeline.feature TL7c, CapCut's auto captions): the transcript's words as
|
||||
// the edited timeline says them, gathered into the lines a caption track shows one at a time. The `captions`
|
||||
// operation (ops.ts) puts the lines on the timeline.
|
||||
import { type Clip, end, type Frames, speedOf, type Timeline } from "./model"
|
||||
|
||||
/** A word, or a line of them: its text, its first frame and the frame after it ends. */
|
||||
export interface Said {
|
||||
/** what is said: a word, or a line's words with a space between */
|
||||
text: string
|
||||
/** its first frame */
|
||||
start: Frames
|
||||
/** the frame after it ends */
|
||||
end: Frames
|
||||
}
|
||||
|
||||
/** How words are gathered into lines. */
|
||||
export interface LineRules {
|
||||
/** the most words on a line (7) */
|
||||
words?: number
|
||||
/** the most characters on a line, spaces counted (42) */
|
||||
chars?: number
|
||||
/** a pause at least this long starts a new line (0.6 s) */
|
||||
gap?: Frames
|
||||
}
|
||||
|
||||
/** A clip that plays the film's own words as they were said: footage at a steady speed, forward. */
|
||||
const speaks = (c: Clip) => !c.off && c.in !== undefined && !c.curve && !c.freeze && !c.reverse
|
||||
|
||||
/** The words as the edited timeline says them. `words` are in the film's own frames (where its transcript has them);
|
||||
* each is said where a main-track clip plays that part of the film, at that clip's speed. A word in a scene taken out
|
||||
* is gone, a scene duplicated says its words twice, and a clip curved, reversed or frozen says none. */
|
||||
export function heard(t: Timeline, words: Said[]): Said[] {
|
||||
const main = (t.tracks.find((k) => k.kind === "main" && !k.hidden)?.clips ?? []).filter(speaks)
|
||||
const out: Said[] = []
|
||||
for (const w of words) {
|
||||
for (const c of main) {
|
||||
const v = speedOf(c), from = c.in!
|
||||
if (w.start < from || w.start >= from + c.length * v) continue
|
||||
const start = Math.round(c.start + (w.start - from) / v)
|
||||
const stop = Math.min(end(c), Math.round(c.start + (w.end - from) / v))
|
||||
out.push({ text: w.text, start, end: Math.max(start + 1, stop) })
|
||||
}
|
||||
}
|
||||
return out.sort((a, b) => a.start - b.start)
|
||||
}
|
||||
|
||||
/** The words gathered into caption lines: a line ends after a sentence does, at a pause, or once it holds as many
|
||||
* words or characters as it may. Each line runs from its first word to its last and ends by the next line's start. */
|
||||
export function captionLines(words: Said[], fps: number, o: LineRules = {}): Said[] {
|
||||
const most = o.words ?? 7, chars = o.chars ?? 42, gap = o.gap ?? Math.round(fps * 0.6)
|
||||
const lines: Said[] = []
|
||||
let line: Said[] = []
|
||||
const close = () => {
|
||||
if (line.length) lines.push({ text: line.map((w) => w.text).join(" "), start: line[0].start, end: line[line.length - 1].end })
|
||||
line = []
|
||||
}
|
||||
const said = words.map((w) => ({ ...w, text: w.text.trim() })).filter((w) => w.text).sort((a, b) => a.start - b.start)
|
||||
for (const w of said) {
|
||||
const last = line[line.length - 1]
|
||||
const long = [...line, w].map((x) => x.text).join(" ").length > chars
|
||||
if (last && (/[.!?…]["'”’)\]]?$/.test(last.text) || w.start - last.end >= gap || line.length >= most || long)) close()
|
||||
line.push(w)
|
||||
}
|
||||
close()
|
||||
return lines.map((l, i) => ({ ...l, end: Math.max(l.start + 1, Math.min(l.end, lines[i + 1]?.start ?? l.end)) }))
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
// A composition's footage or sound played from a copy the host made of its file (raea docs/timeline.feature TL8d,
|
||||
// TL7k, TL7n): a sound with its noise reduced or its voice changed, footage held steady, footage with its faces
|
||||
// retouched. The element's src is the copy and its data-* props say what it was made from and how; its clip's props are
|
||||
// a film's for the same (its own file, the copy and the settings), and a set of those is the host's edit back. Footage
|
||||
// cut out (TL7l, TL7m) wears mattes made of what it plays, as raea's Video matte prop.
|
||||
import { find, type Timeline, type Value } from "./model"
|
||||
import type { Op } from "./ops"
|
||||
|
||||
/** What a copy was made from (`of`, a path in the composition's media folder) and how, as the host reads its element. */
|
||||
export interface Copied {
|
||||
/** what it plays is a copy of `of` with its noise reduced or its voice changed (an <Audio>'s) */
|
||||
heard?: { of: string; denoise?: boolean; voice?: string }
|
||||
/** what it plays is a copy of `of` held steady at `level` (a <Video>'s) */
|
||||
steady?: { of: string; level: string }
|
||||
/** what it plays is a copy of `of` with its faces retouched, each amount 0 to 1 (a <Video>'s): `of` is its file, or
|
||||
* its steadied copy when it is held steady too (the retouch over the steadying) */
|
||||
retouch?: { of: string; smooth?: number; brighten?: number; slim?: number; eyes?: number }
|
||||
/** it wears a cutout's mattes (a <Video>'s): the folder in the media folder, the file's rate, one each `every` frames,
|
||||
* how many; what they are of (person, subject or brushed) and, brushed, the second brushed at and the strokes' JSON */
|
||||
cutout?: CutoutMatte & { kind: string; at?: number; strokes?: string }
|
||||
}
|
||||
|
||||
/** A cutout's mattes as a <Video>'s matte prop holds them. */
|
||||
export interface CutoutMatte {
|
||||
dir: string
|
||||
fps: number
|
||||
every: number
|
||||
count: number
|
||||
}
|
||||
|
||||
/** The host's edits that set what an element plays: `file`, a copy of `of` made so; no `of`, `file` as it is. A
|
||||
* cutout's sets the mattes it wears; with none, it wears none. */
|
||||
export type CopyEdit =
|
||||
| { op: "heard"; i: number; file: string; of?: string; denoise?: boolean; voice?: string }
|
||||
| { op: "steady"; i: number; file: string; of?: string; level?: string }
|
||||
| { op: "retouch"; i: number; file: string; of?: string; smooth?: number; brighten?: number; slim?: number; eyes?: number }
|
||||
| { op: "cutout"; i: number; kind?: string; matte?: CutoutMatte; at?: number; strokes?: string }
|
||||
|
||||
const RETOUCH = { smooth: "retouchSmooth", brighten: "retouchBrighten", slim: "retouchSlim", eyes: "retouchEyes" } as const
|
||||
|
||||
/** A media element's clip props: its own file, and the copy it plays with what was done to it (steadied under a
|
||||
* retouch: the copy the retouch was made from). */
|
||||
export function copyProps(file: string, r: Copied): Record<string, Value | boolean> {
|
||||
const own = r.heard?.of ?? r.steady?.of ?? r.retouch?.of ?? file
|
||||
return {
|
||||
file: own,
|
||||
...(r.heard && { voiced: file, denoise: !!r.heard.denoise, voice: r.heard.voice ?? "" }),
|
||||
...(r.steady && { stabilise: r.steady.level, steadied: r.retouch?.of ?? file }),
|
||||
...(r.retouch && { retouched: file, ...Object.fromEntries(Object.entries(RETOUCH).map(([k, p]) => [p, r.retouch![k as keyof typeof RETOUCH] ?? 0])) }),
|
||||
...(r.cutout && {
|
||||
matte: r.cutout.kind,
|
||||
matted: `${r.cutout.dir}/index.json`,
|
||||
matteFps: r.cutout.fps,
|
||||
matteEvery: r.cutout.every,
|
||||
matteCount: r.cutout.count,
|
||||
...(r.cutout.at !== undefined && { brushAt: r.cutout.at }),
|
||||
...(r.cutout.strokes && { brushStrokes: r.cutout.strokes }),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/** The host's edits for a set of copy props on media clips `ids` (each `i` its element's place), or undefined when `op`
|
||||
* isn't one: a sound's voice (TL8d), footage held steady (TL7k), retouched (TL7n) or cut out (TL7l, TL7m). */
|
||||
export function copyEdits(t: Timeline, op: Op, ids: string[], place: (id: string) => number | undefined): CopyEdit[] | undefined {
|
||||
const p = op.op === "set" && Object.keys(op.set).join() === "props" ? op.set.props : undefined
|
||||
if (!p) return undefined
|
||||
const of = (id: string) => find(t, id)?.clip.props?.file
|
||||
const has = (kind: string, keys: string[]) => Object.keys(p).every((k) => keys.includes(k)) && ids.every((id) => find(t, id)?.clip.kind === kind && typeof of(id) === "string" && place(id) !== undefined)
|
||||
const each = (f: (i: number, own: string) => CopyEdit) => ids.map((id) => f(place(id)!, of(id) as string))
|
||||
// a retouch is made from what plays under it: its steadied copy, when it is held steady
|
||||
const under = (id: string) => {
|
||||
const s = find(t, id)?.clip.props?.steadied
|
||||
return typeof s === "string" && s ? s : (of(id) as string)
|
||||
}
|
||||
if (has("audio", ["denoise", "voice", "voiced"]))
|
||||
return each((i, own) => (p.voiced ? { op: "heard", i, file: String(p.voiced), of: own, ...(p.denoise === true && { denoise: true }), ...(p.voice && { voice: String(p.voice) }) } : { op: "heard", i, file: own }))
|
||||
if (has("video", ["stabilise", "steadied", "stabiliseZoom"]))
|
||||
return each((i, own) => (p.steadied ? { op: "steady", i, file: String(p.steadied), of: own, level: String(p.stabilise ?? "") } : { op: "steady", i, file: own }))
|
||||
if (has("video", [...Object.values(RETOUCH), "retouched", "retouchFrom", "retouchTo"]))
|
||||
return ids.map((id) => {
|
||||
const i = place(id)!, from = under(id)
|
||||
if (!p.retouched) return { op: "retouch", i, file: from }
|
||||
const amounts = Object.entries(RETOUCH).flatMap(([k, prop]) => (typeof p[prop] === "number" && (p[prop] as number) > 0 ? [[k, p[prop] as number]] : []))
|
||||
return { op: "retouch", i, file: String(p.retouched), of: from, ...Object.fromEntries(amounts) }
|
||||
})
|
||||
if (has("video", ["matte", "matted", "matteFps", "matteEvery", "matteCount", "brushAt", "brushStrokes"]))
|
||||
return each((i) => {
|
||||
const dir = typeof p.matted === "string" ? p.matted.replace(/\/index\.json$/, "") : ""
|
||||
if (!dir) return { op: "cutout", i }
|
||||
const brushed = p.matte === "brushed"
|
||||
return {
|
||||
op: "cutout",
|
||||
i,
|
||||
kind: String(p.matte ?? ""),
|
||||
matte: { dir, fps: Number(p.matteFps), every: Number(p.matteEvery ?? 1), count: Number(p.matteCount) },
|
||||
...(brushed && typeof p.brushAt === "number" && { at: p.brushAt }),
|
||||
...(brushed && typeof p.brushStrokes === "string" && { strokes: p.brushStrokes }),
|
||||
}
|
||||
})
|
||||
return undefined
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
// A clip's mask, blend and chroma key (docs/timeline.feature TL7f: CapCut's Mask, Basic's Blend, Cutout's Chroma
|
||||
// key) as its props, a prop a value as a film's crop is a prop a side, so a preset sets them, the editor's preview
|
||||
// draws them and a composition's <Nudge mask blend chroma> holds them, drawn by sdk/video cutout.ts in both.
|
||||
// Taken off as crop and mirror are, by their plain value: the mask "none", the blend "normal", the key colour "".
|
||||
import { BLEND_KINDS, BLENDS, chromaError, chromaId, chromaMatrix, MASK_KINDS, maskError, maskPlain, maskStyle, type Blend, type ChromaKey, type Mask, type MaskKind } from "@raea/video/cutout"
|
||||
import type { Value } from "./model"
|
||||
|
||||
export { BLEND_KINDS, BLENDS, MASK_KINDS, maskPlain, type Blend, type ChromaKey, type Mask, type MaskKind }
|
||||
|
||||
/** A mask's values as a clip's props. */
|
||||
export const MASK_PROPS = { kind: "mask", x: "maskX", y: "maskY", w: "maskW", h: "maskH", rotate: "maskRotate", feather: "maskFeather", round: "maskRound", invert: "maskInvert" } as const
|
||||
/** A chroma key's values as a clip's props. */
|
||||
export const KEY_PROPS = { color: "keyColor", strength: "keyStrength", shadow: "keyShadow" } as const
|
||||
/** Every prop a clip's cutout is held in. */
|
||||
export const CUTOUT_PROPS: string[] = [...Object.values(MASK_PROPS), "blend", ...Object.values(KEY_PROPS)]
|
||||
|
||||
/** A clip's mask, blend and key, each there only when it has one. */
|
||||
export interface Cutout {
|
||||
/** what of it is seen: a shape in shares of the frame */
|
||||
mask?: Mask
|
||||
/** how it is drawn over what is under it */
|
||||
blend?: Blend
|
||||
/** a colour taken out of it */
|
||||
chroma?: ChromaKey
|
||||
}
|
||||
|
||||
type Props = Record<string, Value | boolean>
|
||||
const NUMS = ["x", "y", "w", "h", "rotate", "feather", "round"] as const
|
||||
|
||||
/** A clip's cutout read from its props: a mask when its kind is one, a blend other than normal, a key when it has a
|
||||
* colour. */
|
||||
export function cutoutOf(props: Props = {}): Cutout {
|
||||
const num = (k: string) => (typeof props[k] === "number" && Number.isFinite(props[k]) ? (props[k] as number) : undefined)
|
||||
const kind = props[MASK_PROPS.kind]
|
||||
const mask: Mask | undefined =
|
||||
typeof kind === "string" && (MASK_KINDS as readonly string[]).includes(kind)
|
||||
? { kind: kind as MaskKind, ...Object.fromEntries(NUMS.flatMap((k) => (num(MASK_PROPS[k]) === undefined ? [] : [[k, num(MASK_PROPS[k])]]))), ...(props[MASK_PROPS.invert] === true && { invert: true }) }
|
||||
: undefined
|
||||
const blend = typeof props.blend === "string" && props.blend !== "normal" && (BLEND_KINDS as string[]).includes(props.blend) ? (props.blend as Blend) : undefined
|
||||
const color = props[KEY_PROPS.color]
|
||||
const chroma: ChromaKey | undefined =
|
||||
typeof color === "string" && color
|
||||
? { color, ...(num(KEY_PROPS.strength) !== undefined && { strength: num(KEY_PROPS.strength) }), ...(num(KEY_PROPS.shadow) !== undefined && { shadow: num(KEY_PROPS.shadow) }) }
|
||||
: undefined
|
||||
return { ...(mask && { mask }), ...(blend && { blend }), ...(chroma && { chroma }) }
|
||||
}
|
||||
|
||||
/** A cutout as a clip's props: every one of them, what it hasn't got at its plain value, so a set takes off the
|
||||
* rest. Values to five places. */
|
||||
export function cutoutProps(c: Cutout): Props {
|
||||
const r = (n: number) => Math.round(n * 100000) / 100000
|
||||
const m = c.mask
|
||||
return {
|
||||
[MASK_PROPS.kind]: m?.kind ?? "none",
|
||||
...(m ? Object.fromEntries(NUMS.flatMap((k) => (m[k] === undefined ? [] : [[MASK_PROPS[k], r(m[k]!)]]))) : {}),
|
||||
[MASK_PROPS.invert]: !!m?.invert,
|
||||
blend: c.blend ?? "normal",
|
||||
[KEY_PROPS.color]: c.chroma?.color ?? "",
|
||||
...(c.chroma?.strength !== undefined && { [KEY_PROPS.strength]: r(c.chroma.strength) }),
|
||||
...(c.chroma?.shadow !== undefined && { [KEY_PROPS.shadow]: r(c.chroma.shadow) }),
|
||||
}
|
||||
}
|
||||
|
||||
/** What is wrong with a clip's cutout props as they stand, or undefined: a mask kind or blend it hasn't got, a value
|
||||
* out of range, a grey key. */
|
||||
export function cutoutError(props: Props = {}): string | undefined {
|
||||
const kind = props[MASK_PROPS.kind]
|
||||
if (kind !== undefined && kind !== "none" && !(MASK_KINDS as readonly unknown[]).includes(kind)) return `a mask is one of ${MASK_KINDS.join(", ")}, or none: "${String(kind)}" isn't one`
|
||||
if (props.blend !== undefined && !(BLEND_KINDS as unknown[]).includes(props.blend)) return `a blend is one of ${BLEND_KINDS.join(", ")}: "${String(props.blend)}" isn't one`
|
||||
const c = cutoutOf(props)
|
||||
return (c.mask && maskError(c.mask)) || (c.chroma && chromaError(c.chroma)) || undefined
|
||||
}
|
||||
|
||||
/** How the editor's preview draws a clip's cutout on its picture, as <Nudge> draws it in a composition: CSS for the
|
||||
* picture, and the SVG filter its key needs (an feColorMatrix's values under `id`, to put beside the picture). */
|
||||
export function cutoutLook(props: Props | undefined, width: number, height: number): { style: Record<string, string>; key?: { id: string; matrix: string } } {
|
||||
const c = cutoutOf(props)
|
||||
if (cutoutError(props)) return { style: {} }
|
||||
const key = c.chroma && { id: chromaId(c.chroma), matrix: chromaMatrix(c.chroma) }
|
||||
return {
|
||||
style: { ...(c.mask ? (maskStyle(c.mask, width, height) as Record<string, string>) : {}), ...(c.blend && { mixBlendMode: c.blend }), ...(key && { filter: `url(#${key.id})` }) },
|
||||
...(key && { key }),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
// raea's timeline (docs/timeline.feature): the model, every edit as an operation, keys and their easing, speed
|
||||
// curves, and snapping. No React and no DOM (TL11b).
|
||||
export * from "./model"
|
||||
export * from "./ops"
|
||||
export * from "./keys"
|
||||
export * from "./speed"
|
||||
export * from "./snap"
|
||||
export * from "./read"
|
||||
export * from "./cache"
|
||||
export * from "./registry"
|
||||
export * from "./play"
|
||||
export * from "./captions"
|
||||
export * from "./anim"
|
||||
export * from "./cutout"
|
||||
export * from "./adjust"
|
||||
export * from "./sounds"
|
||||
@@ -0,0 +1,103 @@
|
||||
// A keyed property's value at a frame (docs/timeline.feature TL5): between two keys it follows the first key's ease,
|
||||
// before the first and after the last it holds. An ease is a cubic bezier's two handles, as CSS writes them.
|
||||
import type { Ease, Frames, Key, Value } from "./model"
|
||||
|
||||
/** The easing presets raea registers (TL5c); a plugin adds its own beside them (TL11a). */
|
||||
export const EASES: Record<string, Ease> = {
|
||||
linear: "linear",
|
||||
hold: "hold",
|
||||
"ease in": [0.42, 0, 1, 1],
|
||||
"ease out": [0, 0, 0.58, 1],
|
||||
"ease in-out": [0.42, 0, 0.58, 1],
|
||||
}
|
||||
|
||||
/** y at x on the cubic bezier (0,0) (x1,y1) (x2,y2) (1,1): x is solved by Newton's steps, then bisection where the
|
||||
* slope is too flat for them. The handles' x are kept in 0..1 so the curve is a function of time. */
|
||||
export function bezier(x1: number, y1: number, x2: number, y2: number): (x: number) => number {
|
||||
const a = Math.min(1, Math.max(0, x1)), b = Math.min(1, Math.max(0, x2))
|
||||
const at = (p1: number, p2: number, t: number) => 3 * p1 * t * (1 - t) * (1 - t) + 3 * p2 * t * t * (1 - t) + t * t * t
|
||||
const slope = (p1: number, p2: number, t: number) => 3 * p1 * (1 - t) * (1 - 3 * t) + 3 * p2 * t * (2 - 3 * t) + 3 * t * t
|
||||
return (x) => {
|
||||
if (x <= 0) return 0
|
||||
if (x >= 1) return 1
|
||||
let t = x
|
||||
for (let i = 0; i < 8; i++) {
|
||||
const d = slope(a, b, t)
|
||||
if (Math.abs(d) < 1e-6) break
|
||||
const next = t - (at(a, b, t) - x) / d
|
||||
if (Math.abs(next - t) < 1e-7) {
|
||||
t = next
|
||||
break
|
||||
}
|
||||
t = next
|
||||
}
|
||||
if (!(t >= 0 && t <= 1) || Math.abs(at(a, b, t) - x) > 1e-5) {
|
||||
let lo = 0, hi = 1
|
||||
for (let i = 0; i < 40; i++) {
|
||||
t = (lo + hi) / 2
|
||||
if (at(a, b, t) < x) lo = t
|
||||
else hi = t
|
||||
}
|
||||
}
|
||||
return at(y1, y2, t)
|
||||
}
|
||||
}
|
||||
|
||||
/** How far along (0..1, or past it for a handle that overshoots) a value is at `p` of the way between two keys. */
|
||||
export function eased(ease: Ease | undefined, p: number): number {
|
||||
if (ease === "hold") return p >= 1 ? 1 : 0
|
||||
if (!ease || ease === "linear") return Math.min(1, Math.max(0, p))
|
||||
return bezier(...ease)(p)
|
||||
}
|
||||
|
||||
const mix = (a: Value, b: Value, k: number): Value => {
|
||||
if (typeof a === "number" && typeof b === "number") return a + (b - a) * k
|
||||
if (Array.isArray(a) && Array.isArray(b) && a.length === b.length) return a.map((v, i) => v + (b[i] - v) * k)
|
||||
// what can't be mixed (words, lists of different lengths) holds, then jumps
|
||||
return k >= 1 ? b : a
|
||||
}
|
||||
|
||||
/** The keys in time order (two at one frame: the later one written wins). */
|
||||
export const sorted = (keys: Key[]): Key[] => {
|
||||
const by = new Map<Frames, Key>()
|
||||
for (const k of keys) by.set(k.at, k)
|
||||
return [...by.values()].sort((a, b) => a.at - b.at)
|
||||
}
|
||||
|
||||
/** The property's value at `frame` (frames from its clip's start), or undefined with no keys. */
|
||||
export function valueAt(keys: Key[] | undefined, frame: Frames): Value | undefined {
|
||||
if (!keys?.length) return undefined
|
||||
const ks = sorted(keys)
|
||||
if (frame <= ks[0].at) return ks[0].value
|
||||
const last = ks[ks.length - 1]
|
||||
if (frame >= last.at) return last.value
|
||||
const i = ks.findIndex((k) => k.at > frame) - 1
|
||||
const a = ks[i], b = ks[i + 1]
|
||||
return mix(a.value, b.value, eased(a.ease, (frame - a.at) / (b.at - a.at)))
|
||||
}
|
||||
|
||||
/** A clip's props as they stand `frame` frames from its start: each keyed one at its value there, the rest as set
|
||||
* (what a mask's, a key's or a crop's look is drawn from while its numbers are keyed, TL5a). */
|
||||
export function propsAt(clip: { props?: Record<string, Value | boolean>; keys?: Record<string, Key[]> }, frame: Frames): Record<string, Value | boolean> {
|
||||
const keyed = Object.entries(clip.keys ?? {}).flatMap(([p, ks]) => {
|
||||
const v = valueAt(ks, frame)
|
||||
return v === undefined ? [] : [[p, v] as const]
|
||||
})
|
||||
return { ...clip.props, ...Object.fromEntries(keyed) }
|
||||
}
|
||||
|
||||
/** The keys either side of a cut at `frame` (TL3d: a split clip's keys stay at their frames): the left clip's, and
|
||||
* the right clip's in its own frames. A cut between two keys puts a key of the value there on both sides, so each
|
||||
* half moves as the whole did up to the cut. */
|
||||
export function cut(keys: Key[], frame: Frames): [Key[], Key[]] {
|
||||
const ks = sorted(keys)
|
||||
const left = ks.filter((k) => k.at < frame)
|
||||
const right = ks.filter((k) => k.at >= frame).map((k) => ({ ...k, at: k.at - frame }))
|
||||
const between = left.length > 0 && ks.some((k) => k.at > frame) && !ks.some((k) => k.at === frame)
|
||||
if (between) {
|
||||
const value = valueAt(ks, frame)!
|
||||
left.push({ at: frame, value })
|
||||
right.unshift({ at: 0, value, ease: left[left.length - 2].ease })
|
||||
}
|
||||
return [left, right]
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
// The timeline's model (docs/timeline.feature TL0). Time is whole frames (TL0a): a clip's start, length and trim, a
|
||||
// key and a marker are integers; seconds and timecodes are drawn from them, never the other way.
|
||||
|
||||
/** A count of frames, always whole (TL0a). */
|
||||
export type Frames = number
|
||||
|
||||
/** A track's kind, in the order they stack from the top (TL1a): effect, text, overlay, main, sound. A plugin adds
|
||||
* its own (TL11a); an unknown kind sorts with the overlays. */
|
||||
export type TrackKind = "effect" | "text" | "overlay" | "main" | "sound" | (string & {})
|
||||
export const ORDER: TrackKind[] = ["effect", "text", "overlay", "main", "sound"]
|
||||
|
||||
/** How a value travels from one key to the next: a straight line, no travel (it holds, then jumps), or a cubic
|
||||
* bezier's two handles [x1, y1, x2, y2] as CSS writes them (TL5c). */
|
||||
export type Ease = "linear" | "hold" | [number, number, number, number]
|
||||
|
||||
/** A property's value: a number, a list of numbers (a colour, a point) or a string. */
|
||||
export type Value = number | number[] | string
|
||||
|
||||
/** A property's value at a frame of its clip (frames from the clip's start), and how it leaves for the next key. */
|
||||
export interface Key {
|
||||
/** the frame it is at, counted from its clip's start */
|
||||
at: Frames
|
||||
/** the property's value there: a number, a list of them (a colour, a point) or a string */
|
||||
value: Value
|
||||
/** how the value travels to the next key (linear when unset) */
|
||||
ease?: Ease
|
||||
}
|
||||
|
||||
/** A point of a speed curve (TL6b): how fast the source plays at a place in it (0 its first frame shown, 1 its last). */
|
||||
export interface SpeedPoint {
|
||||
/** where in the source, from 0 (its first frame shown) to 1 (its last) */
|
||||
at: number
|
||||
/** how fast it plays there: 1 as recorded, 2 twice as fast, 0.5 half */
|
||||
speed: number
|
||||
}
|
||||
|
||||
/** A mark at a frame (TL2e): a beat, a comment's time (TL12b) or one put there by hand. */
|
||||
export interface Marker {
|
||||
/** its own id, unique on the timeline */
|
||||
id: string
|
||||
/** its frame on the timeline (on a clip: from the clip's start) */
|
||||
at: Frames
|
||||
/** what it says, shown on hover */
|
||||
name?: string
|
||||
/** its colour, any CSS colour */
|
||||
color?: string
|
||||
}
|
||||
|
||||
/** How a clip comes in or goes out on its own (TL7d): a transition's kind over its own first or last frames. */
|
||||
export interface Anim {
|
||||
/** fade, slide, wipe, zoom or a plugin's (TRANSITIONS) */
|
||||
kind: string
|
||||
/** how many of the clip's frames it takes */
|
||||
length: Frames
|
||||
}
|
||||
|
||||
/** A span of something on a track: footage, a sound, words, a composition's sequence, an effect. */
|
||||
export interface Clip {
|
||||
/** its own id, unique on the timeline */
|
||||
id: string
|
||||
/** what it is: "video", "audio", "text", "sequence", "component", "effect", a plugin's own */
|
||||
kind: string
|
||||
/** what its head says (its file's or its sequence's name when unset) */
|
||||
name?: string
|
||||
/** where it starts on the timeline */
|
||||
start: Frames
|
||||
/** how long it lasts on the timeline */
|
||||
length: Frames
|
||||
/** media: the first source frame it shows */
|
||||
in?: Frames
|
||||
/** media: how many frames the source has (unset: no end to trim against) */
|
||||
source?: Frames
|
||||
/** a constant speed (1 when unset, TL6a) */
|
||||
speed?: number
|
||||
/** a speed curve, which wins over `speed` (TL6b) */
|
||||
curve?: SpeedPoint[]
|
||||
/** under a curve: how many source frames the clip shows (its length is the time the curve takes over them) */
|
||||
shows?: Frames
|
||||
/** footage played backward: its last source frame first (TL3h) */
|
||||
reverse?: boolean
|
||||
/** a still: the source frame `in` held for the clip's whole length (TL3h) */
|
||||
freeze?: boolean
|
||||
/** turned off: drawn dimmed, left out of the picture and the sound (TL3g) */
|
||||
off?: boolean
|
||||
/** footage whose own sound was taken out onto a sound track (TL4c): its picture plays silent */
|
||||
muted?: boolean
|
||||
/** it can't be changed here, and why ("set in code", TL0c) */
|
||||
locked?: string
|
||||
/** clips with one group pick and move as one (TL3g) */
|
||||
group?: string
|
||||
/** its still values by property (x, y, scale, rotate, opacity, text, a plugin's): a keyed one is ignored */
|
||||
props?: Record<string, Value | boolean>
|
||||
/** its keys by property, in frame order (TL5) */
|
||||
keys?: Record<string, Key[]>
|
||||
/** sound: its level, 1 as recorded (TL8a) */
|
||||
volume?: number
|
||||
/** sound: how long it fades in from its start */
|
||||
fadeIn?: Frames
|
||||
/** sound: how long it fades out to its end */
|
||||
fadeOut?: Frames
|
||||
/** the picture or words: how it comes in over its first frames (TL7d, CapCut's In animation) */
|
||||
enter?: Anim
|
||||
/** the picture or words: how it goes out over its last frames (TL7d, CapCut's Out animation) */
|
||||
exit?: Anim
|
||||
/** the picture or words: how it moves over its whole length (TL7e, CapCut's Combo and its text Loop), a cycle every
|
||||
* `length` frames from its first; its own length plays it once */
|
||||
combo?: Anim
|
||||
/** its element in the code (file:line:col, docs/editing.feature E2) */
|
||||
at?: string
|
||||
/** markers on the clip itself, in frames from its start (TL2e) */
|
||||
markers?: Marker[]
|
||||
/** a compound clip (TL3g): the clips it holds, each with the kind of track it came from, their starts in frames
|
||||
* from this clip's own start */
|
||||
inside?: { kind: TrackKind; clip: Clip }[]
|
||||
}
|
||||
|
||||
/** A row of clips that don't overlap, with its head's switches (TL1b). */
|
||||
export interface Track {
|
||||
/** its own id, unique on the timeline */
|
||||
id: string
|
||||
/** what it holds, which places it in the stack (TL1a) */
|
||||
kind: TrackKind
|
||||
/** what its head says (its kind's title when unset) */
|
||||
name?: string
|
||||
/** its clips can't be picked or changed */
|
||||
locked?: boolean
|
||||
/** left out of the picture */
|
||||
hidden?: boolean
|
||||
/** left out of the sound */
|
||||
muted?: boolean
|
||||
/** drawn this tall, in px (TL1c) */
|
||||
height?: number
|
||||
/** its clips, in start order */
|
||||
clips: Clip[]
|
||||
}
|
||||
|
||||
/** A transition on the cut between two clips that touch on one track (TL7a): the cut is the end of clip `after`,
|
||||
* so it follows that cut wherever an edit moves it. */
|
||||
export interface Transition {
|
||||
/** its own id, unique on the timeline */
|
||||
id: string
|
||||
/** its kind: fade, slide, wipe, zoom or a plugin's (TRANSITIONS) */
|
||||
kind: string
|
||||
/** the clip whose end is the cut it sits on */
|
||||
after: string
|
||||
/** how long it takes, centred on the cut */
|
||||
length: Frames
|
||||
}
|
||||
|
||||
/** A whole timeline: its tracks top to bottom, its marks, its transitions and its three switches. */
|
||||
export interface Timeline {
|
||||
/** frames a second, which every Frames value counts in */
|
||||
fps: number
|
||||
/** its tracks, top to bottom */
|
||||
tracks: Track[]
|
||||
/** marks on the ruler (TL2e) */
|
||||
markers: Marker[]
|
||||
/** transitions on cuts (TL7a) */
|
||||
transitions: Transition[]
|
||||
/** the main track holds no gap (P, TL4a) */
|
||||
magnet: boolean
|
||||
/** edges snap to cuts, the playhead, marks and beats (N, TL4b) */
|
||||
snapping: boolean
|
||||
/** what sits over a main clip moves with it (~, TL4c) */
|
||||
linkage: boolean
|
||||
}
|
||||
|
||||
export const empty = (fps = 30): Timeline => ({ fps, tracks: [], markers: [], transitions: [], magnet: true, snapping: true, linkage: true })
|
||||
|
||||
export const end = (c: Clip): Frames => c.start + c.length
|
||||
/** The timeline's length: its last clip's end. */
|
||||
export const length = (t: Timeline): Frames => Math.max(0, ...t.tracks.flatMap((k) => k.clips.map(end)))
|
||||
export const clips = (t: Timeline): Clip[] => t.tracks.flatMap((k) => k.clips)
|
||||
export const find = (t: Timeline, id: string): { track: Track; clip: Clip } | undefined => {
|
||||
for (const track of t.tracks) {
|
||||
const clip = track.clips.find((c) => c.id === id)
|
||||
if (clip) return { track, clip }
|
||||
}
|
||||
}
|
||||
/** A clip's speed where it is constant. */
|
||||
export const speedOf = (c: Clip): number => (c.speed && c.speed > 0 ? c.speed : 1)
|
||||
|
||||
/** mm:ss:ff, drawn from frames (TL0a). */
|
||||
export function timecode(frames: Frames, fps: number): string {
|
||||
const f = Math.max(0, Math.round(frames))
|
||||
const whole = Math.round(fps)
|
||||
const two = (n: number) => String(n).padStart(2, "0")
|
||||
return `${two(Math.floor(f / whole / 60))}:${two(Math.floor(f / whole) % 60)}:${two(f % whole)}`
|
||||
}
|
||||
|
||||
/** Kinds a plugin said stack under the picture, with the sound (registry.ts sets them). */
|
||||
export const under = new Set<string>()
|
||||
|
||||
/** Where a track of this kind goes among the others (TL1a): after the last of its own kind, else in ORDER's place. */
|
||||
export function slot(tracks: Track[], kind: TrackKind): number {
|
||||
const rank = (k: TrackKind) => (ORDER.includes(k) ? ORDER.indexOf(k) : ORDER.indexOf("overlay"))
|
||||
// sound tracks grow downward (a new one goes under the others); every other kind grows upward
|
||||
if (kind === "sound" || under.has(kind)) return tracks.length
|
||||
const first = tracks.findIndex((t) => rank(t.kind) >= rank(kind))
|
||||
return first < 0 ? tracks.length : first
|
||||
}
|
||||
Loaded 100 of 154 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user