mirror of
https://github.com/storytold/figcraft.git
synced 2026-11-29 01:34:37 +01:00
Merge pull request #2397 from gmrmad1/fix/2180-create-font-warnings
Text: creating text warns when its font style draws in another face (#2180)
This commit is contained in:
8 files changed
+85
-5
No files matched your search
@@ -392,10 +392,15 @@ pub fn create(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
}
|
||||
// A `fontStyle` the family lacks draws in its nearest face, the same as `node.set` says.
|
||||
let warnings = match get(p, "props") {
|
||||
Some(Value::Object(props)) if doc.node(nid).is_some_and(|n| n.kind.text().is_some()) => super::edit::font_style_warnings(doc, &[nid], props),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
if boolean(p, "select").unwrap_or(true) {
|
||||
ds.selection = vec![nid];
|
||||
}
|
||||
Ok(json!({"id": nid}))
|
||||
if warnings.is_empty() { Ok(json!({"id": nid})) } else { Ok(json!({"id": nid, "warnings": warnings})) }
|
||||
}
|
||||
|
||||
fn frame_create(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
@@ -15,6 +15,7 @@ use crate::{BatchStep, EngineError, Result, Session, bad, spec};
|
||||
|
||||
mod clipboard;
|
||||
mod props;
|
||||
pub(crate) use props::font_style_warnings;
|
||||
pub(crate) use props::{edit_region_fills, fill_regions};
|
||||
mod select;
|
||||
mod vector_clipboard;
|
||||
|
||||
@@ -206,7 +206,7 @@ pub(super) fn set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// face has another weight or slant than the name asks for ("Black" on a family whose heaviest is
|
||||
/// Bold), say which face it is. Families that aren't installed, and names that match a style or a
|
||||
/// named instance (spelled any way: "SemiBold", "Semi Bold"), say nothing.
|
||||
fn font_style_warnings(doc: &figcraft_doc::Document, ids: &[NodeId], props: &serde_json::Map<String, Value>) -> Vec<String> {
|
||||
pub(crate) fn font_style_warnings(doc: &figcraft_doc::Document, ids: &[NodeId], props: &serde_json::Map<String, Value>) -> Vec<String> {
|
||||
let Some(style) = props.get("fontStyle").and_then(Value::as_str) else { return Vec::new() };
|
||||
let mut families: Vec<String> = match props.get("fontFamily").and_then(Value::as_str) {
|
||||
Some(f) => vec![f.to_string()],
|
||||
|
||||
@@ -84,6 +84,42 @@ fn a_font_style_draws_in_the_nearest_face_and_says_so_when_it_differs() {
|
||||
assert!(out.get("warnings").is_none(), "{out}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn creating_text_in_a_font_style_the_family_lacks_says_so_as_node_set_does() {
|
||||
figcraft_text::scan_system_fonts();
|
||||
// Any installed family with a regular and a bold face and nothing heavier (CI machines differ).
|
||||
let pick = figcraft_text::family_names().into_iter().find_map(|f| {
|
||||
let st = figcraft_text::family_styles(&f);
|
||||
let has = |w: u16| st.iter().any(|x| figcraft_doc::style_weight(x) == w && !x.to_lowercase().contains("italic"));
|
||||
(has(400) && has(700) && !st.iter().any(|x| figcraft_doc::style_weight(x) > 700)).then_some((f, st))
|
||||
});
|
||||
let Some((family, styles)) = pick else { return };
|
||||
let mut s = Session::new();
|
||||
let asked = || json!({"fontFamily": family, "fontStyle": "Black"});
|
||||
// `node.create` warns the same as `node.set` does.
|
||||
let out = ex(&mut s, "node.create", json!({"type": "text", "text": "Hi", "props": asked()}));
|
||||
let w = out["warnings"][0].as_str().unwrap();
|
||||
assert!(w.contains(&family) && w.contains("`Black`") && w.contains("nearest"), "{w}");
|
||||
// `text.create` says so too.
|
||||
let out = ex(&mut s, "text.create", json!({"text": "Hi", "props": asked()}));
|
||||
let w = out["warnings"][0].as_str().unwrap();
|
||||
assert!(w.contains(&family) && w.contains("`Black`") && w.contains("nearest"), "{w}");
|
||||
// So does a `command.batch` step, at the step that creates the text.
|
||||
let out =
|
||||
ex(&mut s, "command.batch", json!({"commands": [{"command": "node.create", "params": {"type": "text", "text": "Hi", "props": asked()}}]}));
|
||||
let w = out[0]["warnings"][0].as_str().unwrap();
|
||||
assert!(w.contains(&family) && w.contains("`Black`") && w.contains("nearest"), "{w}");
|
||||
// A style the family has says nothing, and the result is `{id}` alone as before.
|
||||
let bold = styles.iter().find(|x| figcraft_doc::style_weight(x) == 700).unwrap().clone();
|
||||
let out = ex(&mut s, "node.create", json!({"type": "text", "text": "Hi", "props": {"fontFamily": family, "fontStyle": bold}}));
|
||||
assert!(out.get("warnings").is_none(), "{out}");
|
||||
assert_eq!(out.as_object().unwrap().len(), 1, "{out}");
|
||||
// A layer without text says nothing either.
|
||||
let out = ex(&mut s, "node.create", json!({"type": "rectangle", "props": {"fill": "#FF0000"}}));
|
||||
assert!(out.get("warnings").is_none(), "{out}");
|
||||
assert_eq!(out.as_object().unwrap().len(), 1, "{out}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_refused_call_changes_nothing() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -191,7 +191,7 @@ fn tools() -> Vec<Value> {
|
||||
tool(
|
||||
"create_node",
|
||||
"Create layer",
|
||||
"Create a layer (engine `node.create`) and return its id and inspected properties. Coordinates are page units, y down; x/y are relative to the parent frame (the page when there is none, so then they are page coordinates; groups don't count). Inside an auto-layout frame the position is decided by the layout. The new layer becomes the selection.",
|
||||
"Create a layer (engine `node.create`) and return its id and inspected properties. Coordinates are page units, y down; x/y are relative to the parent frame (the page when there is none, so then they are page coordinates; groups don't count). Inside an auto-layout frame the position is decided by the layout. The new layer becomes the selection. `warnings` reports a fontStyle that draws in another face.",
|
||||
obj(
|
||||
json!({
|
||||
"type": {"type": "string", "enum": ["frame", "rectangle", "ellipse", "polygon", "star", "line", "arrow", "text", "vector", "section", "component", "slice"], "description": "Layer type"},
|
||||
@@ -813,8 +813,13 @@ fn create_node(b: &mut dyn Backend, a: &Map<String, Value>) -> Result<ToolResult
|
||||
}
|
||||
let r = exec(b, "node.create", Value::Object(params))?;
|
||||
let id = r.get("id").cloned().ok_or("node.create returned no id")?;
|
||||
let warnings = r.get("warnings").cloned();
|
||||
let node = b.call("node.get", json!({"id": id, "depth": 0}))?;
|
||||
Ok(ToolResult::json(&json!({"id": id, "node": node})))
|
||||
let mut out = json!({"id": id, "node": node});
|
||||
if let Some(w) = warnings {
|
||||
out["warnings"] = w;
|
||||
}
|
||||
Ok(ToolResult::json(&out))
|
||||
}
|
||||
|
||||
fn set_properties(b: &mut dyn Backend, a: &Map<String, Value>) -> Result<ToolResult, String> {
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
use crate::common::Client;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn create_node_reports_a_font_style_drawn_in_another_face() {
|
||||
let mut c = Client::new();
|
||||
// The headless server indexes system fonts lazily; make sure that walk has happened.
|
||||
let _ = c.run("text.rescanFonts", json!({}));
|
||||
// Any installed family with a regular and a bold face and nothing heavier (CI machines differ).
|
||||
let names = c.run("text.fonts", json!({}));
|
||||
let pick = names.as_array().cloned().unwrap_or_default().into_iter().filter_map(|v| v.as_str().map(str::to_string)).find_map(|f| {
|
||||
let styles: Vec<String> = c
|
||||
.run("text.fonts", json!({"family": f}))
|
||||
.as_array()
|
||||
.cloned()
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.filter_map(|v| v.as_str().map(str::to_string))
|
||||
.collect();
|
||||
let has = |w: u16| styles.iter().any(|x| figcraft_doc::style_weight(x) == w && !x.to_lowercase().contains("italic"));
|
||||
(has(400) && has(700) && !styles.iter().any(|x| figcraft_doc::style_weight(x) > 700)).then_some(f)
|
||||
});
|
||||
let Some(family) = pick else { return };
|
||||
let out = c.ok("create_node", json!({"type": "text", "text": "Hi", "props": {"fontFamily": family, "fontStyle": "Black"}}));
|
||||
let w = out["warnings"][0].as_str().unwrap();
|
||||
assert!(w.contains(&family) && w.contains("`Black`") && w.contains("nearest"), "{w}");
|
||||
// `set_properties` still says so too.
|
||||
let out = c.ok("set_properties", json!({"ids": [out["id"].clone()], "props": {"fontStyle": "Black"}}));
|
||||
let w = out["warnings"][0].as_str().unwrap();
|
||||
assert!(w.contains(&family) && w.contains("`Black`") && w.contains("nearest"), "{w}");
|
||||
}
|
||||
@@ -13,6 +13,8 @@ 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)]
|
||||
mod create_warnings;
|
||||
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
mod export_assets;
|
||||
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
mod export_hidden_roots;
|
||||
|
||||
+1
-1
@@ -407,7 +407,7 @@ a later step can use `{"$step": 0, "field": "ids/0"}` to target the first match.
|
||||
| `list_commands {filter?}` | Every command: id, label, menu, shortcut, undoable, params doc. |
|
||||
| `run_command {command, params}` | Run any command (e.g. `align.left`, `layout.add`, `component.create`, `instance.place` (drop an instance at a page point into the frame or auto layout slot under it), `component.exposeInstance` / `instance.exposed` (nested instance properties on instances), `component.makeSlot` / `instance.slotInsert` / `instance.resetSlot` (slots, below), `inspect.code` (CSS, HTML + CSS for a whole frame, React, Leptos, Vue, SwiftUI, Jetpack Compose, ArkUI or Flutter for a layer; components take their properties as parameters and instances are calls, see Developer Mode below), `inspect.properties` (layout, auto layout, typography, fills, strokes and effects with their style and variable names; `colorFormat`: hex, rgb, css, hsl or hsb), `inspect.assets` (layers under the selection with export settings, icons and images, each with its `kind`), `inspect.code` takes `unit: rem` and `rootFontSize` for CSS, HTML, React, Leptos and Vue, `style.create`, `variable.bind`, `variable.update` (rename, describe, scope), `variable.set` with `{alias}` or a colour calculation (`{alpha}`, `{mix}`), `variable.renameMode` / `variable.removeMode`, `variable.deleteCollection`, `proto.interaction.add`, `codeConnect.set` (components linked to real code, see Developer Mode below)). |
|
||||
| `batch {commands: [{command, params}], label?}` | Several commands as one undo step (`command.batch`), which keeps one copy of the document however many steps there are (an `edit.undo` step undoes the batch's edits so far together); all-or-nothing for open documents and their document state. Failed inner commands are removed from the journal; preferences, clipboard, tool state and UI requests are not rolled back. A step can use what an earlier step returned: name it with `"as": "card"` and `{"$ref": "card"}` anywhere in a later step's params becomes the `id` in its result (`{"$step": n}` does the same by zero-based position); `"field"` takes another key or a slash path such as `ids/0` (see Step references below). |
|
||||
| `create_node {type, x, y, width, height, parent, index, name, text, path, props}` | Create a frame, rectangle, ellipse, polygon, star, line, arrow, text, vector, section, component or slice; returns `{id, node}`. |
|
||||
| `create_node {type, x, y, width, height, parent, index, name, text, path, props}` | Create a frame, rectangle, ellipse, polygon, star, line, arrow, text, vector, section, component or slice; returns `{id, node}`. `warnings` reports a fontStyle that draws in another face. |
|
||||
| `set_properties {ids, props}` | `node.set` on layers (geometry, fills, strokes, effects, corner radius, auto layout, sizing, constraints, masks (`isMask`, `maskType: alpha\|vector\|luminance`), handoff status (`devStatus: none\|readyForDev\|completed`; marking again clears "Changed"), a section's `sectionContentsHidden`, text…); returns the updated layers. |
|
||||
| `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}}`. |
|
||||
|
||||
Reference in new issue
Block a user