mirror of
https://github.com/storytold/figcraft.git
synced 2026-11-27 17:01:38 +01:00
M8: Code Connect keeps a connect file it can't read, and maps values as it checks them
- Export refuses to write over a connect file it can't read (not JSON, not an object, or over
4 MB) instead of replacing it with this design's links alone.
- Import skips an entry whose `values` is malformed, with a warning, instead of replacing the
component's link with one that maps nothing.
- `{Property ? "a" : "b"}` reads the design's value, so mapping Off to `inactive` doesn't make the
condition true.
- A `values` key that is only a parameter name (`state` for State) is reported as unknown, since
the mapping is read by property name and it would do nothing.
This commit is contained in:
1 parent
dbccabce41
commit
d243347fd0
3 files changed
+115
-16
No files matched your search
@@ -419,3 +419,86 @@ fn listing_refuses_a_malformed_target_rather_than_reading_the_selection() {
|
||||
assert!(s.execute("codeConnect.list", &p).is_err(), "{p}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A set called `name` with a variant `prop=value` for each of `values`. Returns (set, variants).
|
||||
fn set_of(s: &mut Session, name: &str, prop: &str, values: &[&str]) -> (NodeId, Vec<NodeId>) {
|
||||
let variants: Vec<NodeId> = values
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(k, v)| {
|
||||
let f = idv(&ex(s, "frame.create", json!({"x": k as f64 * 150.0, "y": 600, "width": 100, "height": 40, "name": format!("{prop}={v}")})));
|
||||
idv(&ex(s, "component.create", json!({"ids": [f]})))
|
||||
})
|
||||
.collect();
|
||||
let set = idv(&ex(s, "component.combineVariants", json!({"ids": variants.clone()})));
|
||||
ex(s, "node.set", json!({"id": set, "props": {"name": name}}));
|
||||
(set, variants)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_condition_reads_the_designs_value_not_its_name_in_code() {
|
||||
let mut s = Session::new();
|
||||
ex(&mut s, "file.new", json!({}));
|
||||
let (set, variants) = set_of(&mut s, "Toggle", "State", &["On", "Off"]);
|
||||
ex(&mut s, "codeConnect.set", json!({"id": set, "name": "Toggle", "template": "{State ? \"enabled\" : \"disabled\"} {State}"}));
|
||||
let off = idv(&ex(&mut s, "instance.create", json!({"component": variants[1]})));
|
||||
assert!(code(&mut s, off, "react").starts_with("disabled"), "{}", code(&mut s, off, "react"));
|
||||
// `inactive` reads as true, but the condition is about the design's Off.
|
||||
ex(&mut s, "codeConnect.set", json!({"id": set, "values": {"State": {"Off": "inactive"}}}));
|
||||
let out = code(&mut s, off, "react");
|
||||
assert!(out.starts_with("disabled") && out.contains("inactive"), "{out}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mapping_keyed_by_a_name_it_cant_use_is_reported() {
|
||||
let mut s = Session::new();
|
||||
ex(&mut s, "file.new", json!({}));
|
||||
let (set, hover) = button(&mut s);
|
||||
let r = ex(
|
||||
&mut s,
|
||||
"codeConnect.set",
|
||||
json!({"id": set, "name": "Button", "template": "<Button state={State} />", "values": {"state": {"Hover": "hovered"}}}),
|
||||
);
|
||||
assert!(r.to_string().contains("\"state\""), "the lowercase key does nothing, so it's named: {r}");
|
||||
let i = idv(&ex(&mut s, "instance.create", json!({"component": hover})));
|
||||
assert!(code(&mut s, i, "react").contains(r#"state="Hover""#));
|
||||
let r = ex(&mut s, "codeConnect.set", json!({"id": set, "values": {"State": {"Hover": "hovered"}}}));
|
||||
assert!(!r.to_string().contains("\"State\""), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_import_with_malformed_values_keeps_the_link_there() {
|
||||
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 />", "values": {"State": {"Hover": "h"}}}));
|
||||
let links = json!([{"component": "Button", "language": "react", "name": "Other", "template": "<Other />", "values": {"State": {"Hover": 7}}}]);
|
||||
let r = ex(&mut s, "codeConnect.import", json!({"json": {"version": 1, "links": links}}));
|
||||
assert_eq!(r["linked"], 0, "{r}");
|
||||
assert!(r["warnings"][0].as_str().unwrap().contains("values"), "{r}");
|
||||
let link = &s.doc().unwrap().node(set).unwrap().code_links[0];
|
||||
assert_eq!((link.name.as_str(), link.values["State"]["Hover"].as_str()), ("Button", "h"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exporting_over_a_file_it_cant_read_is_refused() {
|
||||
let dir = std::env::temp_dir().join(format!("figcraft-connect-unread-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).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 />"}));
|
||||
let big = vec![b' '; 4 * 1024 * 1024 + 1];
|
||||
for (name, bytes) in [("broken.json", b"{\"links\": [".to_vec()), ("list.json", b"[]".to_vec()), ("big.json", big)] {
|
||||
let path = dir.join(name);
|
||||
std::fs::write(&path, &bytes).unwrap();
|
||||
assert!(s.execute("codeConnect.export", &json!({"path": path})).is_err(), "{name}");
|
||||
assert_eq!(std::fs::read(&path).unwrap(), bytes, "{name} is left as it was");
|
||||
}
|
||||
// A file that isn't there yet is written.
|
||||
let new = dir.join("figcraft.connect.json");
|
||||
let _ = std::fs::remove_file(&new);
|
||||
ex(&mut s, "codeConnect.export", json!({"path": new}));
|
||||
assert!(new.exists());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -382,7 +382,8 @@ 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);
|
||||
// A value is written as code calls it; a condition reads the design's own value.
|
||||
let coded = &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.
|
||||
@@ -397,7 +398,7 @@ pub(crate) fn render(doc: &Document, c: &Component, values: &[(String, Value)],
|
||||
vue_attr = None;
|
||||
}
|
||||
}
|
||||
Piece::Value { name, inner } => match find(c, values, name) {
|
||||
Piece::Value { name, inner } => match find(c, coded, name) {
|
||||
Some((p, v)) => {
|
||||
let e = expr(doc, c, p, v, lang);
|
||||
// JSX and `view!`: a plain string reads best as an attribute value, anything
|
||||
@@ -544,8 +545,9 @@ pub fn check(c: &Component, link: &CodeLink, lang: CodeLang) -> std::result::Res
|
||||
unknown.push(name.to_string());
|
||||
}
|
||||
}
|
||||
// `in_code` reads a mapping by property name, so a key that is only a parameter name does nothing.
|
||||
for prop in link.values.keys() {
|
||||
if find(c, &values, prop).is_none() && !unknown.iter().any(|u| u == prop) {
|
||||
if !c.params.iter().any(|p| p.prop == *prop) && !unknown.iter().any(|u| u == prop) {
|
||||
unknown.push(prop.clone());
|
||||
}
|
||||
}
|
||||
@@ -741,7 +743,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
spec!(
|
||||
"codeConnect.export",
|
||||
"Export code connections",
|
||||
"{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}",
|
||||
"{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; a file there it can't read is left alone and the export refused)} 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";
|
||||
@@ -754,7 +756,10 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
let count = links.len();
|
||||
// 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 old = match path.as_deref() {
|
||||
Some(path) => kept_keys(cmd, path)?,
|
||||
None => serde_json::Map::new(),
|
||||
};
|
||||
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());
|
||||
@@ -785,14 +790,15 @@ 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>> {
|
||||
/// The top-level keys of the connect file at `path`, none when there is no file. A file that
|
||||
/// can't be read as one is an error: writing over it would lose what it holds.
|
||||
fn kept_keys(cmd: &str, path: &str) -> Result<serde_json::Map<String, Value>> {
|
||||
if !crate::file_access::exists(path) {
|
||||
return None;
|
||||
return Ok(serde_json::Map::new());
|
||||
}
|
||||
match serde_json::from_slice(&crate::cmd::file::read_capped(path, MAX_FILE).ok()?).ok()? {
|
||||
Value::Object(fields) => Some(fields),
|
||||
_ => None,
|
||||
match serde_json::from_slice(&crate::cmd::file::read_capped(path, MAX_FILE)?) {
|
||||
Ok(Value::Object(fields)) => Ok(fields),
|
||||
_ => Err(bad(cmd, format!("{path} isn't a connect file it can read, so it was left as it is"))),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -834,7 +840,16 @@ 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 values = match e.get("values") {
|
||||
None | Some(Value::Null) => Default::default(),
|
||||
Some(v) => match serde_json::from_value(v.clone()) {
|
||||
Ok(values) => values,
|
||||
Err(_) => {
|
||||
warnings.push(format!("link {}: values: {{property: {{design value: code value}}}}, all strings", i + 1));
|
||||
continue;
|
||||
}
|
||||
},
|
||||
};
|
||||
let link = CodeLink {
|
||||
language: lang.id().into(),
|
||||
import_path: field("importPath").unwrap_or_default().to_string(),
|
||||
|
||||
+5
-4
@@ -1864,13 +1864,14 @@ permissions: without it nothing is downloaded); `plugin.directory.publish {path
|
||||
{path?}` → `{text, links}` (or writes the file): `{version: 1, links: [{component, language,
|
||||
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
|
||||
and the links of components this design doesn't have, so several designs can share one file; a
|
||||
file there that isn't a connect file it can read is left alone and the export refused); `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). A link can also say where the code component lives (`source`, a path inside the
|
||||
templates up to 4,000 characters, names 100, import paths 300; invalid entries, a malformed `values`
|
||||
among them, are skipped with a 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.
|
||||
keeps its design name; `{Variant ? "a" : "b"}` still reads the design's value) 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`
|
||||
|
||||
Reference in new issue
Block a user