mirror of
https://github.com/storytold/figcraft.git
synced 2026-11-28 17:31:00 +01:00
M8: Code Connect for agents
A link can say where the code component lives (`source`, a path inside the
repository), what a property's design values are called in code (`values`:
{"State": {"Hover": "hovered"}} renders `hovered`; a value without an entry
keeps its design name) and `notes`, through codeConnect.set, the connect file
and Inspect ▸ Connect to code (a Source file field and a row per variant
value). The fields are skipped when empty, so existing files and exports don't
change.
codeConnect.list and the MCP tool component_mappings say which code
component each design component is: import line, name, ready snippet,
properties and variants, and with a repository root whether each source file
is there. sync_mappings imports or exports a repository's connect file.
codeConnect.export {path} keeps the file's other top-level keys and the links
of components this design doesn't have, so several designs can share one file.
This commit is contained in:
1 parent
6cc578cede
commit
d23c8b6456
10 files changed
+447
-17
No files matched your search
@@ -367,6 +367,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md).
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-18 | minor | M8: design context for AI agents. `inspect.designContext` and the MCP tool `design_context` read the selection (or `ids`, or a `scope`) in one call: a tree where each layer keeps apart `explicit` values, `derived` ones layout worked out and `unsupported` ones with no direct CSS equivalent, joined with the variables (every mode's stored and resolved value), styles, components, fonts and assets it uses, and what the design leaves `missing`. A connected instance gives its code instead of its layers, and a result that wouldn't fit the client asks for fewer layers. Numbers unchanged |
|
||||
| 2026-11-19 | minor | M8: Code Connect for agents. A link can name its source file, what variant values are called in code (Primary becomes `primary` in the snippet) and notes, in the Inspect tab, `codeConnect.set` and `figcraft.connect.json`. `codeConnect.list` and the MCP tool `component_mappings` say which code component each design component is, and whether its source file exists; `sync_mappings` imports and exports a repository's file. `codeConnect.export {path}` keeps the file's other keys and the links of components the design doesn't have, so several designs can share one file. Numbers unchanged |
|
||||
| 2026-11-18 | minor | M3, gap 10: library analytics count insertions and detachments of styles and variables. Applying one, or copying or duplicating content that uses it, inserts it; the Detach button detaches it; an instance counts as its component alone. Show usage and `library.usage` give them per style and variable over the chosen period. Modes aren't counted. Numbers unchanged. Tests: `library_asset_counts_tests`, `library_assets_tests`. |
|
||||
| 2026-11-18 | minor | M9, gap 6: the browser build uses team libraries and plugin directories on a server, through its WebSocket requests: adding a library by its link, its styles and components, publishing to it, Show usage and the reports a file sends; browsing a directory and installing from it, for the page only. Scripts through `window.figcraft` still can't, as commands there don't wait for the server. Numbers unchanged. Tests: `exchange_tests`. |
|
||||
| 2026-11-17 | minor | M6: Android Vector Drawable XML serialization uses the shared writer; application projection and colour policy remain local. Byte-parity tests cover full documents and generated deep wrappers; no new format capability or incumbent certification. |
|
||||
|
||||
@@ -250,6 +250,15 @@ pub struct CodeLink {
|
||||
pub name: String,
|
||||
/// The snippet with `{property}` and `{property ? "a" : "b"}` placeholders.
|
||||
pub template: String,
|
||||
/// Where the code component lives, relative to the code repository.
|
||||
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||
pub source: String,
|
||||
/// What a property's design values are called in code: property → design value → code value.
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub values: BTreeMap<String, BTreeMap<String, String>>,
|
||||
/// Notes for whoever uses the component.
|
||||
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||
pub notes: String,
|
||||
}
|
||||
|
||||
/// A dev resource: a link for developers attached to a layer. The URL is data only: it is shown
|
||||
|
||||
@@ -298,3 +298,124 @@ fn many_entries_for_one_component_each_link() {
|
||||
let i = idv(&ex(&mut s, "instance.create", json!({"component": hover, "x": 0, "y": 500})));
|
||||
assert_eq!(code(&mut s, i, "react"), "<Button />\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_link_names_its_source_and_translates_variant_values() {
|
||||
let mut s = Session::new();
|
||||
ex(&mut s, "file.new", json!({}));
|
||||
let (set, hover) = button(&mut s);
|
||||
ex(
|
||||
&mut s,
|
||||
"codeConnect.set",
|
||||
json!({"id": set, "name": "Button", "importPath": "@/ui/button", "template": "<Button state={State} />",
|
||||
"source": "src/ui/button.tsx", "values": {"State": {"Hover": "hovered"}}, "notes": "Primary action"}),
|
||||
);
|
||||
let instance = idv(&ex(&mut s, "instance.create", json!({"component": hover})));
|
||||
assert!(code(&mut s, instance, "react").contains(r#"state="hovered""#), "{}", code(&mut s, instance, "react"));
|
||||
// A value without a mapping keeps the design's name.
|
||||
let plain = idv(&ex(&mut s, "instance.create", json!({"component": set})));
|
||||
assert!(code(&mut s, plain, "react").contains(r#"state="Default""#));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_source_outside_the_repository_is_refused() {
|
||||
let mut s = Session::new();
|
||||
ex(&mut s, "file.new", json!({}));
|
||||
let c = card(&mut s);
|
||||
for source in ["../up.tsx", "/etc/passwd", "a\\b.tsx", "a/../../b.tsx"] {
|
||||
let e = s.execute("codeConnect.set", &json!({"id": c, "source": source})).unwrap_err();
|
||||
assert!(e.to_string().contains("source"), "{source}: {e}");
|
||||
}
|
||||
assert!(s.execute("codeConnect.set", &json!({"id": c, "values": 3})).is_err());
|
||||
assert!(s.execute("codeConnect.set", &json!({"id": c, "source": "src/card.tsx"})).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_new_fields_survive_a_trip_through_the_file() {
|
||||
let mut s = Session::new();
|
||||
ex(&mut s, "file.new", json!({}));
|
||||
let (set, _) = button(&mut s);
|
||||
ex(
|
||||
&mut s,
|
||||
"codeConnect.set",
|
||||
json!({"id": set, "name": "Button", "template": "<Button />", "source": "src/b.tsx", "values": {"State": {"Hover": "h"}}, "notes": "n"}),
|
||||
);
|
||||
let text = ex(&mut s, "codeConnect.export", json!({}))["text"].as_str().unwrap().to_string();
|
||||
let mut other = Session::new();
|
||||
ex(&mut other, "file.new", json!({}));
|
||||
let (set2, _) = button(&mut other);
|
||||
assert_eq!(ex(&mut other, "codeConnect.import", json!({"json": text}))["linked"], 1);
|
||||
let link = &other.doc().unwrap().node(set2).unwrap().code_links[0];
|
||||
assert_eq!((link.source.as_str(), link.notes.as_str()), ("src/b.tsx", "n"));
|
||||
assert_eq!(link.values["State"]["Hover"], "h");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_from_before_stays_as_it_was() {
|
||||
let mut s = Session::new();
|
||||
ex(&mut s, "file.new", json!({}));
|
||||
let (set, _) = button(&mut s);
|
||||
ex(&mut s, "codeConnect.set", json!({"id": set, "name": "Button", "template": "<Button />"}));
|
||||
let v = ex(&mut s, "codeConnect.export", json!({}));
|
||||
let parsed: Value = serde_json::from_str(v["text"].as_str().unwrap()).unwrap();
|
||||
let keys: Vec<&String> = parsed["links"][0].as_object().unwrap().keys().collect();
|
||||
assert_eq!(keys, ["component", "importPath", "language", "name", "template"], "no new keys unless they're used");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn listing_answers_what_an_agent_asks() {
|
||||
let dir = std::env::temp_dir().join(format!("figcraft-connect-list-{}", std::process::id()));
|
||||
std::fs::create_dir_all(dir.join("src")).unwrap();
|
||||
std::fs::write(dir.join("src/button.tsx"), "").unwrap();
|
||||
let mut s = Session::new();
|
||||
ex(&mut s, "file.new", json!({}));
|
||||
let (set, hover) = button(&mut s);
|
||||
let c = card(&mut s);
|
||||
ex(
|
||||
&mut s,
|
||||
"codeConnect.set",
|
||||
json!({"id": set, "name": "Button", "importPath": "@/ui/button", "template": "<Button />", "source": "src/button.tsx"}),
|
||||
);
|
||||
let v = ex(&mut s, "codeConnect.list", json!({"root": dir}));
|
||||
assert_eq!((v["mapped"].as_u64(), v["unmapped"].as_u64()), (Some(1), Some(1)));
|
||||
let b = v["components"].as_array().unwrap().iter().find(|e| e["id"] == json!(set)).unwrap();
|
||||
assert_eq!(b["links"][0]["import"], r#"import { Button } from "@/ui/button";"#);
|
||||
assert_eq!(b["links"][0]["sourceFound"], true);
|
||||
assert!(b["links"][0]["snippet"].as_str().unwrap().contains("<Button"));
|
||||
assert!(b["properties"].as_array().unwrap().iter().any(|p| p["type"] == "variant"));
|
||||
let only = ex(&mut s, "codeConnect.list", json!({"unmapped": true}));
|
||||
assert_eq!(only["components"][0]["id"], json!(c));
|
||||
// A layer leads to the component it uses, a frame to those it holds.
|
||||
let i = idv(&ex(&mut s, "instance.create", json!({"component": hover})));
|
||||
assert_eq!(ex(&mut s, "codeConnect.list", json!({"ids": [i]}))["components"][0]["id"], json!(set));
|
||||
ex(&mut s, "codeConnect.set", json!({"id": set, "source": "src/gone.tsx"}));
|
||||
assert_eq!(ex(&mut s, "codeConnect.list", json!({"root": dir, "ids": [set]}))["components"][0]["links"][0]["sourceFound"], false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exporting_keeps_what_other_designs_put_in_the_file() {
|
||||
let dir = std::env::temp_dir().join(format!("figcraft-connect-others-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("figcraft.connect.json");
|
||||
std::fs::write(&path, r#"{"version":1,"project":{"name":"shop"},"links":[{"component":"Other","language":"react","name":"Other","template":"<Other />"},{"component":"Button","language":"react","name":"Old","template":"<Old />"}]}"#).unwrap();
|
||||
let mut s = Session::new();
|
||||
ex(&mut s, "file.new", json!({}));
|
||||
let (set, _) = button(&mut s);
|
||||
ex(&mut s, "codeConnect.set", json!({"id": set, "name": "Button", "template": "<Button />"}));
|
||||
ex(&mut s, "codeConnect.export", json!({"path": path}));
|
||||
let v: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
|
||||
let names: Vec<&str> = v["links"].as_array().unwrap().iter().map(|l| l["name"].as_str().unwrap()).collect();
|
||||
assert_eq!(names, ["Button", "Other"], "this design's link wins, the other design's stays");
|
||||
assert_eq!(v["project"]["name"], "shop", "keys the command doesn't own stay");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn listing_refuses_a_malformed_target_rather_than_reading_the_selection() {
|
||||
let mut s = Session::new();
|
||||
ex(&mut s, "file.new", json!({}));
|
||||
let (set, _) = button(&mut s);
|
||||
ex(&mut s, "select.set", json!({"ids": [set]}));
|
||||
for p in [json!({"id": "not-an-id"}), json!({"ids": [set, "nope"]}), json!({"ids": "1"}), json!({"ids": [999_999]})] {
|
||||
assert!(s.execute("codeConnect.list", &p).is_err(), "{p}");
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,11 @@ pub const MAX_TEMPLATE: usize = 4_000;
|
||||
pub const MAX_NAME: usize = 100;
|
||||
/// Longest import path (chars).
|
||||
pub const MAX_IMPORT: usize = 300;
|
||||
/// Longest source path, and notes (chars).
|
||||
pub const MAX_SOURCE: usize = 300;
|
||||
pub const MAX_NOTES: usize = 2_000;
|
||||
/// Most properties with mapped values on a link, and values on each.
|
||||
const MAX_MAPPED: usize = 100;
|
||||
/// Most links a connect file holds.
|
||||
pub const MAX_FILE_LINKS: usize = 5_000;
|
||||
/// Largest connect file read (bytes).
|
||||
@@ -377,6 +382,7 @@ fn html_text(s: &str) -> String {
|
||||
|
||||
/// `link`'s template with `values` (one per parameter of `c`), every line prefixed by `pad`.
|
||||
pub(crate) fn render(doc: &Document, c: &Component, values: &[(String, Value)], link: &CodeLink, lang: CodeLang, pad: &str) -> String {
|
||||
let values = &in_code(values, link);
|
||||
let mut out = String::new();
|
||||
// A quoted attribute stays open across substitutions: `title="{a} {b}"` must treat both
|
||||
// placeholders as attribute values, not text after the first one.
|
||||
@@ -454,6 +460,12 @@ pub(crate) fn render(doc: &Document, c: &Component, values: &[(String, Value)],
|
||||
out.lines().map(|l| if l.is_empty() { "\n".to_string() } else { format!("{pad}{l}\n") }).collect()
|
||||
}
|
||||
|
||||
/// `values` with each design value the link names turned into what code calls it.
|
||||
fn in_code(values: &[(String, Value)], link: &CodeLink) -> Vec<(String, Value)> {
|
||||
let code = |prop: &str, v: &Value| link.values.get(prop)?.get(v.as_str()?).cloned();
|
||||
values.iter().map(|(prop, v)| (prop.clone(), code(prop, v).map_or_else(|| v.clone(), Value::String))).collect()
|
||||
}
|
||||
|
||||
/// A starting template: the code component called with every property (but slots) passed.
|
||||
fn default_template(c: &Component, lang: CodeLang, name: &str) -> String {
|
||||
let params: Vec<&str> = c.params.iter().filter(|p| p.kind != ParamKind::Slot).map(|p| p.ident.as_str()).collect();
|
||||
@@ -469,6 +481,15 @@ fn default_template(c: &Component, lang: CodeLang, name: &str) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// Why `source` can't name a file in a code repository: it goes down from the repository's root.
|
||||
fn check_source(source: &str) -> std::result::Result<(), String> {
|
||||
let plain = source.chars().count() <= MAX_SOURCE
|
||||
&& !source.contains('\\')
|
||||
&& !source.chars().any(char::is_control)
|
||||
&& std::path::Path::new(source).components().all(|c| matches!(c, std::path::Component::Normal(_) | std::path::Component::CurDir));
|
||||
if plain { Ok(()) } else { Err(format!("source: a path inside the code repository, up to {MAX_SOURCE} characters")) }
|
||||
}
|
||||
|
||||
/// Checks a link: its name, import path and template. Returns the placeholder names that aren't
|
||||
/// properties of `c` (kept as written).
|
||||
pub fn check(c: &Component, link: &CodeLink, lang: CodeLang) -> std::result::Result<Vec<String>, String> {
|
||||
@@ -500,6 +521,14 @@ pub fn check(c: &Component, link: &CodeLink, lang: CodeLang) -> std::result::Res
|
||||
_ => format!("importPath: a module or package name (letters, digits, _ and .), up to {MAX_IMPORT} characters"),
|
||||
});
|
||||
}
|
||||
check_source(&link.source)?;
|
||||
if link.notes.chars().count() > MAX_NOTES {
|
||||
return Err(format!("notes: up to {MAX_NOTES} characters"));
|
||||
}
|
||||
let long = |s: &String| s.chars().count() > MAX_NAME;
|
||||
if link.values.len() > MAX_MAPPED || link.values.values().any(|m| m.len() > MAX_MAPPED || m.iter().any(|(k, v)| long(k) || long(v))) {
|
||||
return Err(format!("values: at most {MAX_MAPPED} properties of {MAX_MAPPED} values, each up to {MAX_NAME} characters"));
|
||||
}
|
||||
let t = &link.template;
|
||||
if t.trim().is_empty() || t.chars().count() > MAX_TEMPLATE || t.chars().any(|ch| ch.is_control() && !"\n\t\r".contains(ch)) {
|
||||
return Err(format!("template: the snippet, up to {MAX_TEMPLATE} characters"));
|
||||
@@ -515,6 +544,11 @@ pub fn check(c: &Component, link: &CodeLink, lang: CodeLang) -> std::result::Res
|
||||
unknown.push(name.to_string());
|
||||
}
|
||||
}
|
||||
for prop in link.values.keys() {
|
||||
if find(c, &values, prop).is_none() && !unknown.iter().any(|u| u == prop) {
|
||||
unknown.push(prop.clone());
|
||||
}
|
||||
}
|
||||
Ok(unknown)
|
||||
}
|
||||
|
||||
@@ -557,12 +591,98 @@ fn store(doc: &mut Document, owner: NodeId, link: CodeLink) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The variant properties of component or set `owner`, with their values.
|
||||
pub fn variants(doc: &Document, owner: NodeId) -> Vec<(String, Vec<String>)> {
|
||||
main_of(doc, owner)
|
||||
.and_then(|m| describe(doc, m))
|
||||
.map(|c| c.params.iter().filter_map(|p| if let ParamKind::Variant(v) = &p.kind { Some((p.prop.clone(), v.clone())) } else { None }).collect())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// A link as the connect file holds it.
|
||||
fn link_json(component: &str, l: &CodeLink) -> Value {
|
||||
let mut v = json!({"component": component, "language": l.language, "importPath": l.import_path, "name": l.name, "template": l.template});
|
||||
if !l.source.is_empty() {
|
||||
v["source"] = json!(l.source);
|
||||
}
|
||||
if !l.values.is_empty() {
|
||||
v["values"] = json!(l.values);
|
||||
}
|
||||
if !l.notes.is_empty() {
|
||||
v["notes"] = json!(l.notes);
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
/// The components and sets `ids` are, use or hold (every one in the file without `ids`).
|
||||
fn listed(doc: &Document, ids: Option<&[NodeId]>) -> Vec<NodeId> {
|
||||
let mut out: Vec<NodeId> = match ids {
|
||||
None => doc.nodes().filter(|n| owner(doc, n.id) == Some(n.id)).map(|n| n.id).collect(),
|
||||
Some(ids) => ids.iter().flat_map(|i| doc.subtree(*i)).filter_map(|i| owner(doc, i)).collect(),
|
||||
};
|
||||
out.sort_unstable();
|
||||
out.dedup();
|
||||
out
|
||||
}
|
||||
|
||||
/// What an agent needs to use a component: its code link for each language, or that it has none.
|
||||
fn entry(doc: &Document, id: NodeId, root: Option<&str>) -> Option<Value> {
|
||||
let n = doc.node(id)?;
|
||||
let links: Vec<Value> = n
|
||||
.code_links
|
||||
.iter()
|
||||
.map(|l| {
|
||||
let lang = CodeLang::from_id(&l.language);
|
||||
let mut v = link_json(&n.name, l);
|
||||
if let Some(o) = v.as_object_mut() {
|
||||
o.remove("component");
|
||||
}
|
||||
v["import"] = json!(lang.map(|k| import_line(l, k)));
|
||||
v["snippet"] = json!(lang.and_then(|k| connected_code(doc, id, k, l)));
|
||||
if let Some(root) = root.filter(|_| !l.source.is_empty()) {
|
||||
v["sourceFound"] = json!(crate::file_access::exists(std::path::Path::new(root).join(&l.source)));
|
||||
}
|
||||
v
|
||||
})
|
||||
.collect();
|
||||
Some(json!({
|
||||
"id": id,
|
||||
"name": n.name,
|
||||
"type": n.kind.type_name(),
|
||||
"mapped": !links.is_empty(),
|
||||
"properties": crate::cmd::component::describe_props(doc, id)["properties"],
|
||||
"links": links,
|
||||
}))
|
||||
}
|
||||
|
||||
fn list(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "codeConnect.list";
|
||||
let doc = s.doc()?;
|
||||
// Anything named must be layers; nothing named lists every component in the file.
|
||||
let named = get(p, "ids").is_some() || get(p, "id").is_some();
|
||||
let ids = if named { Some(crate::params::req_targets(cmd, s, p)?) } else { None };
|
||||
let root = text(cmd, p, "root")?;
|
||||
let unmapped = crate::params::boolean(p, "unmapped").unwrap_or(false);
|
||||
let all: Vec<Value> = listed(doc, ids.as_deref()).into_iter().filter_map(|id| entry(doc, id, root.as_deref())).collect();
|
||||
let count = |m: bool| all.iter().filter(|e| e["mapped"] == m).count();
|
||||
let (mapped, missing) = (count(true), count(false));
|
||||
let components: Vec<Value> = all.into_iter().filter(|e| !unmapped || e["mapped"] == false).collect();
|
||||
Ok(json!({"components": components, "mapped": mapped, "unmapped": missing}))
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
spec!(
|
||||
"codeConnect.list",
|
||||
"List code connections",
|
||||
"{ids? | id? (the components those layers are, use or hold; default every component in the file), unmapped? (only those without a link), root? (the code repository: says if each link's source is there)} → {components: [{id, name, type, mapped, properties, links: [{language, importPath, import, name, template, snippet, source?, sourceFound?, values?, notes?}]}], mapped, unmapped}",
|
||||
false,
|
||||
list
|
||||
),
|
||||
spec!(
|
||||
"codeConnect.set",
|
||||
"Connect to code",
|
||||
"{id? (component, set or instance; default the selection), language?: react|leptos|vue|swiftui|compose|arkui|flutter (default react), importPath?, name? (default the generated name), template? (default a call passing every property)} links the component (its set, for a variant) to its code component; fields left out keep their current value. Placeholders: {property} (its name or parameter name) and {property ? \"a\" : \"b\"}; other {…} stay as written → {component, language, code (the snippet for the layer), unknown (placeholder names that aren't properties)}",
|
||||
"{id? (component, set or instance; default the selection), language?: react|leptos|vue|swiftui|compose|arkui|flutter (default react), importPath?, name? (default the generated name), template? (default a call passing every property), source? (the file, relative to the code repository), values? ({property: {design value: code value}}), notes?} links the component (its set, for a variant) to its code component; fields left out keep their current value. Placeholders: {property} (its name or parameter name) and {property ? \"a\" : \"b\"}; other {…} stay as written → {component, language, code (the snippet for the layer), unknown (placeholder names that aren't properties)}",
|
||||
true,
|
||||
|s, p| {
|
||||
let cmd = "codeConnect.set";
|
||||
@@ -578,7 +698,13 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
None => old.template,
|
||||
};
|
||||
let import_path = text(cmd, p, "importPath")?.map_or(old.import_path, |i| i.trim().to_string());
|
||||
let link = CodeLink { language: lang.id().into(), import_path, name, template };
|
||||
let source = text(cmd, p, "source")?.map_or(old.source, |v| v.trim().to_string());
|
||||
let notes = text(cmd, p, "notes")?.unwrap_or(old.notes);
|
||||
let values = match get(p, "values") {
|
||||
None => old.values,
|
||||
Some(v) => serde_json::from_value(v.clone()).map_err(|_| bad(cmd, "values: {property: {design value: code value}}"))?,
|
||||
};
|
||||
let link = CodeLink { language: lang.id().into(), import_path, name, template, source, values, notes };
|
||||
let unknown = check(&c, &link, lang).map_err(|e| bad(cmd, e))?;
|
||||
let code = connected_code(doc, id, lang, &link);
|
||||
store(s.doc_mut()?, owner, link)?;
|
||||
@@ -610,27 +736,32 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
spec!(
|
||||
"codeConnect.export",
|
||||
"Export code connections",
|
||||
"{path? (write it there, e.g. figcraft.connect.json in the code repository)} every component's links as {version: 1, links: [{component (its name), language, importPath, name, template}]}, sorted → {text, links} or {path, links}",
|
||||
"{path? (write it there, e.g. figcraft.connect.json in the code repository; other top-level keys of a file already there stay, and so do the links of components this file doesn't have)} every component's links as {version: 1, links: [{component (its name), language, importPath, name, template, source?, values?, notes?}]}, sorted → {text, links} or {path, links}",
|
||||
false,
|
||||
|s, p| {
|
||||
let cmd = "codeConnect.export";
|
||||
let path = text(cmd, p, "path")?;
|
||||
let doc = s.doc()?;
|
||||
let mut links: Vec<Value> = doc
|
||||
.nodes()
|
||||
.filter(|n| owner(doc, n.id) == Some(n.id))
|
||||
.flat_map(|n| {
|
||||
n.code_links.iter().map(|l| {
|
||||
json!({"component": n.name, "language": l.language, "importPath": l.import_path, "name": l.name, "template": l.template})
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let mut links: Vec<Value> =
|
||||
doc.nodes().filter(|n| owner(doc, n.id) == Some(n.id)).flat_map(|n| n.code_links.iter().map(|l| link_json(&n.name, l))).collect();
|
||||
let key =
|
||||
|v: &Value| (v["component"].as_str().unwrap_or_default().to_string(), v["language"].as_str().unwrap_or_default().to_string());
|
||||
links.sort_by_key(key);
|
||||
let count = links.len();
|
||||
let text =
|
||||
serde_json::to_string_pretty(&json!({"version": VERSION, "links": links})).map_err(|e| EngineError::Other(e.to_string()))? + "\n";
|
||||
// The file also holds the project's settings and the links of other designs: only
|
||||
// the links of this file's components are this command's.
|
||||
let old = path.as_deref().and_then(kept_keys).unwrap_or_default();
|
||||
let here: Vec<&str> = doc.nodes().filter(|n| owner(doc, n.id) == Some(n.id)).map(|n| n.name.as_str()).collect();
|
||||
let others = old.get("links").and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default();
|
||||
links.extend(others.iter().filter(|l| !l.get("component").and_then(Value::as_str).is_some_and(|c| here.contains(&c))).cloned());
|
||||
links.sort_by_key(key);
|
||||
let mut file = json!({"version": VERSION, "links": links});
|
||||
if let Some(fields) = file.as_object_mut() {
|
||||
for (k, v) in old {
|
||||
fields.entry(k).or_insert(v);
|
||||
}
|
||||
}
|
||||
let text = serde_json::to_string_pretty(&file).map_err(|e| EngineError::Other(e.to_string()))? + "\n";
|
||||
match path {
|
||||
Some(path) => {
|
||||
crate::cmd::file::write(&path, text.as_bytes())?;
|
||||
@@ -650,6 +781,17 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
]
|
||||
}
|
||||
|
||||
/// The top-level keys of the connect file at `path`, if there is a readable one.
|
||||
fn kept_keys(path: &str) -> Option<serde_json::Map<String, Value>> {
|
||||
if !crate::file_access::exists(path) {
|
||||
return None;
|
||||
}
|
||||
match serde_json::from_slice(&crate::cmd::file::read_capped(path, MAX_FILE).ok()?).ok()? {
|
||||
Value::Object(fields) => Some(fields),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "codeConnect.import";
|
||||
let parse_json = |b: &[u8]| serde_json::from_slice::<Value>(b).map_err(|e| bad(cmd, format!("not JSON: {e}")));
|
||||
@@ -688,11 +830,15 @@ fn import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
));
|
||||
continue;
|
||||
};
|
||||
let values = e.get("values").and_then(|v| serde_json::from_value(v.clone()).ok()).unwrap_or_default();
|
||||
let link = CodeLink {
|
||||
language: lang.id().into(),
|
||||
import_path: field("importPath").unwrap_or_default().to_string(),
|
||||
name: name.into(),
|
||||
template: template.into(),
|
||||
source: field("source").unwrap_or_default().to_string(),
|
||||
values,
|
||||
notes: field("notes").unwrap_or_default().to_string(),
|
||||
};
|
||||
let matches = owners.get(component).cloned().unwrap_or_default();
|
||||
if matches.is_empty() {
|
||||
|
||||
@@ -101,6 +101,8 @@ pub const TOOL_NAMES: &[&str] = &[
|
||||
"inspect_document",
|
||||
"get_node",
|
||||
"design_context",
|
||||
"component_mappings",
|
||||
"sync_mappings",
|
||||
"select",
|
||||
"export",
|
||||
"screenshot",
|
||||
@@ -124,6 +126,8 @@ const DOCUMENT_TOOLS: &[&str] = &[
|
||||
"inspect_document",
|
||||
"get_node",
|
||||
"design_context",
|
||||
"component_mappings",
|
||||
"sync_mappings",
|
||||
"select",
|
||||
"export",
|
||||
"screenshot",
|
||||
@@ -270,6 +274,33 @@ fn tools() -> Vec<Value> {
|
||||
),
|
||||
true,
|
||||
),
|
||||
tool(
|
||||
"component_mappings",
|
||||
"Component mappings",
|
||||
"Which code component each design component is: its import, code name, source file, a ready snippet, its properties and variants, and which design values need translating. Check this before writing a component: reuse a mapped one, never recreate it. `unmapped` lists those with no code component yet.",
|
||||
obj(
|
||||
json!({
|
||||
"ids": ids_schema("Layers: the components they are, use or hold (default every component in the file)"),
|
||||
"unmapped": boolean("Only components without a mapping"),
|
||||
"root": string("The code repository, to check each link's source file is there (default where this server runs)")
|
||||
}),
|
||||
&[],
|
||||
),
|
||||
true,
|
||||
),
|
||||
tool(
|
||||
"sync_mappings",
|
||||
"Sync mappings with a repository",
|
||||
"Apply a code repository's figcraft.connect.json to the open design (`import`, one undo step), or write the design's mappings to it (`export`, keeping its other keys and the links of components this design doesn't have). Run `import` first when component_mappings shows less than the repository should have.",
|
||||
obj(
|
||||
json!({
|
||||
"direction": {"type": "string", "enum": ["import", "export"], "description": "import: file to design. export: design to file"},
|
||||
"path": string("The file (default figcraft.connect.json where this server runs)")
|
||||
}),
|
||||
&["direction"],
|
||||
),
|
||||
false,
|
||||
),
|
||||
tool(
|
||||
"select",
|
||||
"Select layers",
|
||||
@@ -456,6 +487,26 @@ fn design_context(b: &mut dyn Backend, a: &Map<String, Value>) -> Result<ToolRes
|
||||
}
|
||||
}
|
||||
|
||||
/// `codeConnect.list`, checking source files against `root`, else where this server runs.
|
||||
fn component_mappings(b: &mut dyn Backend, a: &Map<String, Value>) -> Result<ToolResult, String> {
|
||||
let mut params = a.clone();
|
||||
let root = std::path::absolute(s_arg(a, "root")?.unwrap_or(".")).map_err(|e| format!("root: {e}"))?;
|
||||
params.insert("root".into(), json!(root.to_string_lossy()));
|
||||
exec(b, "codeConnect.list", Value::Object(params)).map(|v| ToolResult::json(&v))
|
||||
}
|
||||
|
||||
/// `codeConnect.import` or `.export` with a code repository's connect file, made absolute here: an
|
||||
/// attached app runs in another folder.
|
||||
fn sync_mappings(b: &mut dyn Backend, a: &Map<String, Value>) -> Result<ToolResult, String> {
|
||||
let command = match s_arg(a, "direction")? {
|
||||
Some("import") => "codeConnect.import",
|
||||
Some("export") => "codeConnect.export",
|
||||
_ => return Err("`direction`: import or export".into()),
|
||||
};
|
||||
let path = std::path::absolute(s_arg(a, "path")?.unwrap_or("figcraft.connect.json")).map_err(|e| format!("path: {e}"))?;
|
||||
exec(b, command, json!({"path": path.to_string_lossy()})).map(|v| ToolResult::json(&v))
|
||||
}
|
||||
|
||||
fn wait_for_changes(b: &mut dyn Backend, a: &Map<String, Value>) -> Result<ToolResult, String> {
|
||||
b.call("events.poll", Value::Object(a.clone())).map(|v| ToolResult::json(&v))
|
||||
}
|
||||
@@ -602,6 +653,8 @@ pub fn call_tool(b: &mut dyn Backend, name: &str, args: &Value) -> ToolResult {
|
||||
"inspect_document" => inspect_document(b, &a),
|
||||
"get_node" => get_node(b, &a),
|
||||
"design_context" => design_context(b, &a),
|
||||
"component_mappings" => component_mappings(b, &a),
|
||||
"sync_mappings" => sync_mappings(b, &a),
|
||||
"select" => select(b, &a),
|
||||
"export" => export(b, &a),
|
||||
"screenshot" => screenshot(b, &a),
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
//! `component_mappings` and `sync_mappings` against a code repository's connect file.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::common::Client;
|
||||
|
||||
fn repo(name: &str) -> std::path::PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("figcraft-mcp-connect-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::canonicalize(dir).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mappings_travel_through_a_repositorys_file() {
|
||||
let dir = repo("travel");
|
||||
let mut c = Client::new();
|
||||
let frame = c.create(json!({"type": "frame", "name": "Tag", "width": 80, "height": 24}));
|
||||
let main = c.run("component.create", json!({"ids": [frame]}))["id"].clone();
|
||||
let file = dir.join("figcraft.connect.json");
|
||||
std::fs::write(&file, r#"{"version":1,"project":{"name":"shop"},"links":[{"component":"Tag","language":"react","importPath":"@/ui/tag","name":"Tag","template":"<Tag />","source":"src/tag.tsx"}]}"#).unwrap();
|
||||
let before = c.ok("component_mappings", json!({"unmapped": true, "root": dir}));
|
||||
assert_eq!(before["unmapped"], 1);
|
||||
c.ok("sync_mappings", json!({"direction": "import", "path": file}));
|
||||
let after = c.ok("component_mappings", json!({"ids": [main], "root": dir}));
|
||||
let link = &after["components"][0]["links"][0];
|
||||
assert_eq!(link["import"], r#"import { Tag } from "@/ui/tag";"#);
|
||||
assert_eq!(link["sourceFound"], false, "src/tag.tsx isn't there yet");
|
||||
std::fs::create_dir_all(dir.join("src")).unwrap();
|
||||
std::fs::write(dir.join("src/tag.tsx"), "").unwrap();
|
||||
assert_eq!(c.ok("component_mappings", json!({"ids": [main], "root": dir}))["components"][0]["links"][0]["sourceFound"], true);
|
||||
c.ok("sync_mappings", json!({"direction": "export", "path": file}));
|
||||
let written: Value = serde_json::from_slice(&std::fs::read(&file).unwrap()).unwrap();
|
||||
assert_eq!(written["project"]["name"], "shop", "keys the export doesn't own stay");
|
||||
assert_eq!(written["links"][0]["source"], "src/tag.tsx");
|
||||
assert!(c.err("sync_mappings", json!({"direction": "sideways"})).contains("import or export"));
|
||||
}
|
||||
@@ -8,6 +8,8 @@ mod agent_tasks;
|
||||
mod attached;
|
||||
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::disallowed_methods)]
|
||||
mod automation_roots;
|
||||
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
mod code_connect;
|
||||
#[allow(dead_code, clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
mod common;
|
||||
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
@@ -392,6 +392,9 @@ name = "English"
|
||||
"Ctrl+arrows" = "Ctrl+arrows"
|
||||
"Ctrl+click" = "Ctrl+click"
|
||||
"Ctrl+click a padding field" = "Ctrl+click a padding field"
|
||||
"In code" = "In code"
|
||||
"Source file" = "Source file"
|
||||
"Variant value" = "Variant value"
|
||||
"⌘ click a padding field" = "⌘ click a padding field"
|
||||
"Ctrl+scroll" = "Ctrl+scroll"
|
||||
"Current name" = "Current name"
|
||||
|
||||
@@ -481,11 +481,21 @@ pub fn connect_section(app: &mut FigApp, ui: &mut Ui, doc: &Document, id: NodeId
|
||||
edit = Some(("name", v));
|
||||
}
|
||||
});
|
||||
widgets::sublabels(ui, tr("Source file"), None);
|
||||
row(ui, 32.0, |ui| {
|
||||
let width = ui.available_width() - 2.0 * PAD;
|
||||
if let Some(v) =
|
||||
widgets::text_field(ui, Id::unique(("code_connect_source", owner, lang.id())), &link.source, width, "src/components/button.tsx")
|
||||
{
|
||||
edit = Some(("source", v));
|
||||
}
|
||||
});
|
||||
widgets::sublabels(ui, tr("Template"), None);
|
||||
if let Some(v) = widgets::multiline_field(ui, template_id(owner, lang), &link.template, "<Button size={size}>{label}</Button>", 3) {
|
||||
edit = Some(("template", v));
|
||||
}
|
||||
widgets::note(ui, tr("{property} is its value; {property ? \"a\" : \"b\"} picks a string. Other {…} stays as written."), t.text_secondary);
|
||||
variant_values(app, ui, doc, owner, lang, &link);
|
||||
if let Some((key, value)) = edit {
|
||||
let mut params = params;
|
||||
params[key] = json!(value);
|
||||
@@ -499,6 +509,44 @@ pub fn connect_section(app: &mut FigApp, ui: &mut Ui, doc: &Document, id: NodeId
|
||||
ui.add_space(4.0);
|
||||
}
|
||||
|
||||
/// The variant values of a connected component and what code calls them: a value left empty
|
||||
/// stays as the design names it.
|
||||
fn variant_values(app: &mut FigApp, ui: &mut Ui, doc: &Document, owner: NodeId, lang: CodeLang, link: &CodeLink) {
|
||||
let properties = code_connect::variants(doc, owner);
|
||||
if properties.is_empty() {
|
||||
return;
|
||||
}
|
||||
let mut change: Option<(String, String, String)> = None;
|
||||
widgets::sublabels(ui, tr("Variant value"), Some(tr("In code")));
|
||||
let col = widgets::col_width(ui.available_width());
|
||||
for (property, options) in &properties {
|
||||
for option in options {
|
||||
let current = link.values.get(property).and_then(|m| m.get(option)).map_or("", String::as_str);
|
||||
row(ui, 32.0, |ui| {
|
||||
ui.spacing_mut().item_spacing.x = 8.0;
|
||||
ui.allocate_ui_with_layout(vec2(col, 24.0), egui::Layout::left_to_right(egui::Align::Center), |ui| {
|
||||
ui.set_min_width(col);
|
||||
ui.add(egui::Label::new(format!("{property}: {option}")).truncate());
|
||||
});
|
||||
if let Some(v) = widgets::text_field(ui, Id::unique(("code_connect_value", owner, lang.id(), property, option)), current, col, option)
|
||||
{
|
||||
change = Some((property.clone(), option.clone(), v));
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
let Some((property, option, value)) = change else { return };
|
||||
let mut values = link.values.clone();
|
||||
let mapped = values.entry(property).or_default();
|
||||
if value.trim().is_empty() {
|
||||
mapped.remove(&option);
|
||||
} else {
|
||||
mapped.insert(option, value.trim().to_string());
|
||||
}
|
||||
values.retain(|_, m| !m.is_empty());
|
||||
app.run("codeConnect.set", json!({"id": owner, "language": lang.id(), "values": values}));
|
||||
}
|
||||
|
||||
/// Dev Mode plugins: the installed plugins that only read the document, run from the Inspect tab.
|
||||
pub fn plugins_section(app: &mut FigApp, ui: &mut Ui) {
|
||||
let runnable: Vec<(String, String, String)> = app
|
||||
|
||||
+13
-3
@@ -409,6 +409,8 @@ a later step can use `{"$step": 0, "field": "ids/0"}` to target the first match.
|
||||
| `inspect_document {depth, allPages, fields?, outline?}` | The document as JSON (its `id`, layer tree, styles, selection, history); `fields` selects layer properties, `outline: true` gives a compact tree (below). The tools that act on a document also take `document` (see Naming the document below). |
|
||||
| `get_node {id, depth, fields?, outline?}` | One layer as JSON; takes the same `fields` and `outline` options; `pluginData` (`{key: value}`, values as strings) when the layer or page has layer data written with `set_properties {props: {pluginData}}`. |
|
||||
| `design_context {ids?, scope?, depth?, maxNodes?, maxBytes?}` | Everything needed to build a design in one read: see [Design context](#design-context). |
|
||||
| `component_mappings {ids?, unmapped?, root?}` | Which code component each design component is: `import`, `name`, `source` (and `sourceFound` under `root`, default the server's folder), a ready `snippet`, `properties` with variants, and `values` that need translating. |
|
||||
| `sync_mappings {direction, path?}` | Apply a code repository's `figcraft.connect.json` to the open design (`import`) or write the design's mappings to it (`export`); `path` defaults to that file in the server's folder. |
|
||||
| `select {ids}` | Replace the selection (`[]` deselects). |
|
||||
| `export {ids, format, scale \| size, path?, bleed?, cropMarks?, bleedMarks?, cmyk?, contentsOnly?, includeBoundingBox?, svgOutlineText?, svgIdAttribute?, svgSimplifyStroke?, vdCompat?, colorProfile?, quality?}` | png, jpg, svg, webp, pdf, xml (an Android Vector Drawable: `svgIdAttribute` writes `android:name`, `vdCompat` is `bestEffort` (default: approximated with a warning), `exact` (left out with a warning) or `ignore` (no warnings: overlapping layer opacity dropped, even-odd fills kept as `fillType="evenOdd"`, diamond gradients left out), and the result lists `warnings` for what was changed or left out), or `fig`: the whole file as `.fig`, experimental (see Exporting `.fig` files below); `size` is `2x`, `512w` or `512h`; `quality` is the JPG quality, 1 to 100 (default 90). The image covers what the layers paint (shadows towards their offset, strokes, unclipped children, a mask group's mask; hidden layers take no room; a slice is its area with everything under it, or only the frame or group it sits in while `contentsOnly` is on); `contentsOnly: false` also draws every other layer showing in that area, `includeBoundingBox` exports the layers' own boxes; SVG: `svgOutlineText: false` keeps `<text>`, `svgIdAttribute` writes unique ids from layer names, `svgSimplifyStroke: false` writes every stroke as an outline; png, jpg and webp: `colorProfile` is `sameAsFile` (default: the document's profile), `srgb` or `displayP3`, the pixels converted (out-of-gamut colors clip) and the file tagged for it (PNG: `sRGB` chunk, or ICC and `cICP` for Display P3; JPG: ICC profile; WebP: ICC profile for Display P3, none for sRGB) (SVG, XML and RGB PDF output are always sRGB; PDF with `cmyk` is DeviceCMYK). The same options go in export settings (`export.add` / `export.update`). PDF: frames one page each (sized in points), anything else together on one page; print options: `bleed` (points or a length like `"3mm"`, `"0.125in"`), crop and bleed marks, CMYK colour (see Exports below), also taken by `file.export`, `file.exportLayers`, `file.exportFramesPdf` and stored per export setting by `export.add` / `export.update`; `run_command` `file.exportFramesPdf {page?, path?}` writes every top-level frame of a page. Without `path`, images come back as MCP image content, SVG as text, XML as text followed by `{format, bytes, warnings}`. Layers' own export settings: `run_command` with `export.add` / `export.update {index, size?, suffix?, format?}` / `export.remove` and `file.exportLayers {ids?, dir?, assets?}` (every layer once per setting, named `<layer><suffix>.<format>`, a slash in a layer name making a folder; `assets: true` exports the Inspect tab's assets instead: icons as SVG, images as PNG). |
|
||||
| `screenshot {ids?, scale?, maxSize?, window?}` | PNG of the page (with background) or of layers, scaled to fit `maxSize` (default 1600). `window: true` captures the app window in front when attached, a window id (see Windows below) that window. |
|
||||
@@ -1860,11 +1862,19 @@ permissions: without it nothing is downloaded); `plugin.directory.publish {path
|
||||
`@acme/ui` gives `import { Button } from "@acme/ui";` then `<Button variant="primary" icon="none">{"Buy
|
||||
now"}</Button>`. `codeConnect.remove {id?, language?}` (no language: all). `codeConnect.export
|
||||
{path?}` → `{text, links}` (or writes the file): `{version: 1, links: [{component, language,
|
||||
importPath, name, template}]}`, sorted, meant to live in the code repository as
|
||||
`figcraft.connect.json`; `codeConnect.import {json | path}` → `{linked, warnings}` links each
|
||||
importPath, name, template, source?, values?, notes?}]}`, sorted, meant to live in the code
|
||||
repository as `figcraft.connect.json` (writing a file that's there keeps its other top-level keys
|
||||
and the links of components this design doesn't have, so several designs can share one file); `codeConnect.import {json | path}` → `{linked, warnings}` links each
|
||||
entry to every component or set with that name (one undo step; at most 5,000 links and 4 MB;
|
||||
templates up to 4,000 characters, names 100, import paths 300; invalid entries are skipped with a
|
||||
warning). `get_node` lists a component's links as `codeLinks`. In the app, the Inspect tab's
|
||||
warning). A link can also say where the code component lives (`source`, a path inside the
|
||||
repository), what a property's design values are called in code (`values`:
|
||||
`{"Variant": {"Primary": "primary"}}`, so `{Variant}` renders `primary`; a value without an entry
|
||||
keeps its design name) and `notes`, through `codeConnect.set`, the file and the Inspect tab.
|
||||
`codeConnect.list {ids?, unmapped?, root?}` → `{components: [{id, name, type, mapped, properties,
|
||||
links: [{language, importPath, import, name, template, snippet, source?, sourceFound?, values?,
|
||||
notes?}]}], mapped, unmapped}` answers which code component each design component is; with `root`
|
||||
it says whether each `source` exists there. `get_node` lists a component's links as `codeLinks`. In the app, the Inspect tab's
|
||||
Connect to code section edits them in the Code section's language, with a live preview and a
|
||||
Connected badge. An editor extension isn't needed: agents and editors read the same snippets
|
||||
through this server. Plugins whose manifest asks only for `read` also run from the Inspect tab,
|
||||
|
||||
Reference in new issue
Block a user