mirror of
https://github.com/storytold/figcraft.git
synced 2026-11-29 01:34:37 +01:00
Merge remote-tracking branch 'origin/main' into HEAD
# Conflicts: # docs/ui-parity.md
This commit is contained in:
commit
124e7d318d
116 files changed
+8572
-456
No files matched your search
@@ -368,6 +368,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md).
|
||||
|---|---|---|
|
||||
| 2026-11-26 | minor | #1396, craft-contrib#95: `figcraft-cli` follows RFC-0018. The CLI is a library with `run(args, out, err)` (`main` is a thin wrapper), failures are typed errors (exit 1, usage errors exit 2), output goes through the caller's writers, a closed stdout is quiet, `-V` works after subcommands, `FIGCRAFT_NO_SYSTEM_FONTS` and `FIGCRAFT_SERVER_KEY` are declared on `--no-system-fonts` and `plugin publish --key`, the packages install the man pages and Bash, Zsh and Fish completions (Linux and FreeBSD). Changed behaviour: `convert`/`run` refuse an output that is the input unless `--in-place` is given (it needs `--in`/`--out`); `export -o` and `render -o` refuse the file they read; `plugin publish` accepts `--key`; a blank `FIGCRAFT_NO_SYSTEM_FONTS` counts as unset and an unrecognised value is a usage error. Tests in `apps/figcraft-cli/tests/it/rfc18.rs`. Numbers unchanged |
|
||||
| 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-18 | minor | M8: asset handoff. `file.exportAssets` and the MCP tool `export_assets` write a design's images and vectors into a folder: images as the file's original bytes, never re-encoded, vectors as SVG, layers with export settings by those settings, each saying which it is. Files are named by their content, so an asset has one file and exporting again writes nothing; what a layer does to an image that isn't in its bytes is listed. Numbers unchanged |
|
||||
|
||||
+48
-22
@@ -344,6 +344,14 @@ fn main() -> eframe::Result {
|
||||
let mut session = Session::empty();
|
||||
// Live sessions: the network threads wake the window when something arrives.
|
||||
session.live.install(Box::new(figcraft_collab_net::NetLink::new(Arc::new(wake(&ctx_slot)))));
|
||||
// The preferences first: a file named on the command line opens where it was left and goes to
|
||||
// the top of the recent files, and they hold the online files a recovered document may be one of.
|
||||
let recovery = recovery::Shared::default();
|
||||
let svc = services::Desktop::load(recovery.clone());
|
||||
svc.follow_system_dark(wake(&ctx_slot));
|
||||
if let Some(prefs) = svc.prefs.clone() {
|
||||
session.prefs = prefs;
|
||||
}
|
||||
// A file that won't open is said in the window too: it may have been double-clicked.
|
||||
let mut failed_open = None;
|
||||
for f in &args.files {
|
||||
@@ -353,16 +361,9 @@ fn main() -> eframe::Result {
|
||||
failed_open = Some(format!("{name}: {e}"));
|
||||
}
|
||||
}
|
||||
let opened: Vec<u64> = session.docs.iter().map(|d| d.uid).collect();
|
||||
let mut opened: Vec<u64> = session.docs.iter().map(|d| d.uid).collect();
|
||||
// Documents a crashed or killed run left unsaved come back; this run keeps its own copies.
|
||||
let recovery_root = services::config_dir().map(|d| d.join("Recovery"));
|
||||
// The preferences first: they hold the online files a recovered document may be one of.
|
||||
let recovery = recovery::Shared::default();
|
||||
let svc = services::Desktop::load(recovery.clone());
|
||||
svc.follow_system_dark(wake(&ctx_slot));
|
||||
if let Some(prefs) = svc.prefs.clone() {
|
||||
session.prefs = prefs;
|
||||
}
|
||||
let recovered = recovery_root.as_deref().map(|r| recovery::recover_all(r, &mut session)).unwrap_or_default();
|
||||
let mut copies = recovery_root.as_deref().and_then(recovery::Recovery::start);
|
||||
// Copies of online files stay until their files arrive from their servers.
|
||||
@@ -380,7 +381,20 @@ fn main() -> eframe::Result {
|
||||
session.invite_links_startup();
|
||||
}
|
||||
let first_run = svc.prefs.is_none() && args.join.is_none();
|
||||
if session.docs.is_empty() && opens_new_file(first_run, session.prefs.start_on_home, port.is_some()) {
|
||||
if reopens_files(first_run, session.prefs.start_on_home) {
|
||||
let before: Vec<u64> = session.docs.iter().map(|d| d.uid).collect();
|
||||
for (path, e) in session.reopen_files() {
|
||||
log::error!("{path}: {e}");
|
||||
let name = std::path::Path::new(&path).file_name().map_or_else(|| path.clone(), |n| n.to_string_lossy().into_owned());
|
||||
failed_open = Some(format!("{name}: {e}"));
|
||||
}
|
||||
// A file named on the command line stays in front.
|
||||
if let Some(i) = opened.last().and_then(|uid| session.docs.iter().position(|d| d.uid == *uid)) {
|
||||
session.active = i;
|
||||
}
|
||||
opened.extend(session.docs.iter().map(|d| d.uid).filter(|u| !before.contains(u)));
|
||||
}
|
||||
if session.docs.is_empty() && opens_new_file(first_run, port.is_some()) {
|
||||
let _ = session.execute("file.new", &json!({}));
|
||||
}
|
||||
// The interface language from the first frame on, and for the message when the window can't
|
||||
@@ -395,7 +409,8 @@ fn main() -> eframe::Result {
|
||||
}
|
||||
fig.automation_roots = roots;
|
||||
fig.ui.home = false;
|
||||
// Files named on the command line are the user's too: their missing fonts are listed.
|
||||
// Files named on the command line or reopened are the user's too: their missing fonts are
|
||||
// listed.
|
||||
fig.ui.font_checks = opened;
|
||||
fig.note_recovered(recovered.copies);
|
||||
if let Some(message) = failed_open {
|
||||
@@ -516,12 +531,17 @@ fn main() -> eframe::Result {
|
||||
graphics.finish(result, frames, port.is_some())
|
||||
}
|
||||
|
||||
/// With nothing to open, whether the window starts in a new file rather than on the home screen.
|
||||
/// A first run (no settings kept yet) shows the home screen's tips and templates, and later runs
|
||||
/// start in a new file unless the preference asks for Home, which `--control` overrides: its
|
||||
/// callers expect a document to act on.
|
||||
fn opens_new_file(first_run: bool, start_on_home: bool, control: bool) -> bool {
|
||||
!first_run && (!start_on_home || control)
|
||||
/// Whether the files open when the app last quit open again: not on a first run (no settings kept
|
||||
/// yet), nor when the preference asks for the Home screen.
|
||||
fn reopens_files(first_run: bool, start_on_home: bool) -> bool {
|
||||
!first_run && !start_on_home
|
||||
}
|
||||
|
||||
/// With nothing open, whether the window starts in a new file rather than on the home screen: only
|
||||
/// with a control port open (`--control`), whose callers expect a document to act on. A first run
|
||||
/// shows the home screen's tips and templates whatever the port.
|
||||
fn opens_new_file(first_run: bool, control: bool) -> bool {
|
||||
!first_run && control
|
||||
}
|
||||
|
||||
/// The title bar FigCraft starts with, decided by the shared craft-window crate so every Craft app
|
||||
@@ -617,14 +637,20 @@ mod title_bar_tests {
|
||||
|
||||
#[cfg(test)]
|
||||
mod start_tests {
|
||||
use super::opens_new_file;
|
||||
use super::{opens_new_file, reopens_files};
|
||||
|
||||
#[test]
|
||||
fn the_home_preference_starts_on_home_except_for_control_callers() {
|
||||
assert!(opens_new_file(false, false, false), "a new file by default");
|
||||
assert!(!opens_new_file(false, true, false), "Home when the preference asks");
|
||||
assert!(opens_new_file(false, true, true), "--control still starts with a document");
|
||||
assert!(!opens_new_file(true, false, false), "a first run shows the home screen");
|
||||
fn the_last_files_reopen_unless_the_home_preference_asks_or_on_a_first_run() {
|
||||
assert!(reopens_files(false, false), "by default");
|
||||
assert!(!reopens_files(false, true), "Home when the preference asks");
|
||||
assert!(!reopens_files(true, false), "a first run has nothing to reopen");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn with_nothing_open_only_control_callers_start_in_a_new_file() {
|
||||
assert!(!opens_new_file(false, false), "the home screen, not an empty file");
|
||||
assert!(opens_new_file(false, true), "--control starts with a document");
|
||||
assert!(!opens_new_file(true, true), "a first run shows the home screen");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -357,9 +357,12 @@ fn open_directory(file: &std::fs::File) -> Result<(), String> {
|
||||
const STATE: &str = "state.json";
|
||||
|
||||
/// Everything quitting keeps, all done when it returns (macOS then ends the process): the
|
||||
/// preferences in `dir`, this run's recovery copies ([`Recovery::quit`](crate::recovery::Recovery::quit))
|
||||
/// preferences in `dir` with the files open now, which the next start reopens, and where each was
|
||||
/// left, this run's recovery copies ([`Recovery::quit`](crate::recovery::Recovery::quit))
|
||||
/// and the live sessions' ends (one this app hosts tells everyone and stops; a joined one leaves).
|
||||
pub fn shutdown(app: &mut FigApp, dir: Option<&Path>, recovery: Option<crate::recovery::Recovery>) {
|
||||
app.session.remember_open_files();
|
||||
app.session.remember_views();
|
||||
if let Some(dir) = dir {
|
||||
write_prefs(dir, &app.session.prefs);
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -338,6 +338,8 @@ pub fn prop_default_value(d: &PropDef) -> Value {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod nested_binding_tests;
|
||||
#[cfg(test)]
|
||||
mod rebase_source_tests;
|
||||
|
||||
|
||||
@@ -35,6 +35,38 @@ pub(super) fn bindings_of<'a>(n: &'a Node, g: &'a str) -> impl Iterator<Item = (
|
||||
n.bound.iter().filter(move |(k, _)| binding_group(k) == Some(g))
|
||||
}
|
||||
|
||||
/// Whether `n` binds group `g` to other variables than `src` does. Keys are compared by what they
|
||||
/// bind, so `fill` and `fills/0/color` are the same binding.
|
||||
pub(super) fn bound_differently(n: &Node, src: &Node, g: &str) -> bool {
|
||||
let canonical = |m: &Node| -> std::collections::BTreeSet<(String, String)> {
|
||||
bindings_of(m, g)
|
||||
.map(|(k, v)| {
|
||||
let key = crate::cmd::lists::list_binding(k).map_or_else(|| k.clone(), |(l, i, f)| format!("{}/{i}/{f}", l.prefix()));
|
||||
(key, v.clone())
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
canonical(n) != canonical(src)
|
||||
}
|
||||
|
||||
/// The property groups whose variable bindings differ between layer `n` and its main layer `src`:
|
||||
/// overrides even where both resolve to the same value.
|
||||
pub(super) fn rebound_groups(n: &Node, src: &Node) -> Vec<&'static str> {
|
||||
let mut compared = Vec::new();
|
||||
let mut out = Vec::new();
|
||||
for k in n.bound.keys().chain(src.bound.keys()) {
|
||||
let Some(g) = binding_group(k) else { continue };
|
||||
if compared.contains(&g) {
|
||||
continue;
|
||||
}
|
||||
compared.push(g);
|
||||
if bound_differently(n, src, g) {
|
||||
out.push(g);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Property groups that differ between two versions of a node.
|
||||
pub fn diff_groups(a: &Node, b: &Node) -> Vec<&'static str> {
|
||||
let mut out = Vec::new();
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
use serde_json::json;
|
||||
|
||||
use super::rebase_instance;
|
||||
use super::tests::{button, copy_of, ex, fill, idv, node};
|
||||
use crate::{NodeId, Session};
|
||||
|
||||
fn bound_shape_in_button() -> (Session, NodeId, NodeId, NodeId, NodeId) {
|
||||
let mut s = Session::new();
|
||||
let (_, shape, button, nested) = button(&mut s);
|
||||
ex(&mut s, "variable.createCollection", json!({"name": "T"}));
|
||||
ex(&mut s, "variable.create", json!({"collection": "T", "name": "ink", "type": "color", "value": "#111111"}));
|
||||
let inner = copy_of(&s, nested, shape);
|
||||
ex(&mut s, "variable.bind", json!({"ids": [inner.0], "field": "fill", "variable": "ink"}));
|
||||
assert!(node(&s, inner).overrides.contains("fills"));
|
||||
(s, shape, button, nested, inner)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relinking_an_instance_keeps_a_binding_its_main_lacks_as_an_override() {
|
||||
let (mut s, shape, button, nested, inner) = bound_shape_in_button();
|
||||
let doc = s.ds_mut().unwrap().doc_mut();
|
||||
doc.get_mut(inner).unwrap().overrides.clear();
|
||||
rebase_instance(doc, nested);
|
||||
assert!(node(&s, inner).overrides.contains("fills"), "the same colour from a variable the main doesn't bind");
|
||||
ex(&mut s, "node.set", json!({"id": shape, "props": {"fill": "#FF0000"}}));
|
||||
assert_eq!(fill(&s, inner), "111111", "an edit of the icon's main leaves the bound colour");
|
||||
let placed = idv(&ex(&mut s, "instance.create", json!({"component": button, "x": 400, "y": 400})));
|
||||
let copy = copy_of(&s, placed, inner);
|
||||
assert_eq!(node(&s, copy).bound.values().collect::<Vec<_>>(), [&node(&s, inner).bound["fill"]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hiding_and_showing_a_bound_fill_keeps_its_override() {
|
||||
let (mut s, _, _, _, inner) = bound_shape_in_button();
|
||||
ex(&mut s, "fill.set", json!({"ids": [inner.0], "index": 0, "visible": false}));
|
||||
ex(&mut s, "fill.set", json!({"ids": [inner.0], "index": 0, "visible": true}));
|
||||
let n = node(&s, inner);
|
||||
assert!(n.bound.contains_key("fill"));
|
||||
assert!(n.overrides.contains("fills"), "the binding still differs from the main's");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_top_level_instance_s_own_resizing_binding_is_not_an_override() {
|
||||
let mut s = Session::new();
|
||||
let (_, _, button, _) = button(&mut s);
|
||||
let placed = idv(&ex(&mut s, "instance.create", json!({"component": button, "x": 400, "y": 400})));
|
||||
let doc = s.ds_mut().unwrap().doc_mut();
|
||||
doc.get_mut(placed).unwrap().bound.insert("minWidth".into(), "VariableID:1:1".into());
|
||||
rebase_instance(doc, placed);
|
||||
assert!(!node(&s, placed).overrides.contains("resizing"), "a top-level instance's resizing is its own");
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::diff::{binding_group, bindings_of, diff_groups, follow_boolean_defaults, geometry_derived, variable_groups};
|
||||
use super::diff::{binding_group, bound_differently, diff_groups, follow_boolean_defaults, geometry_derived, rebound_groups, variable_groups};
|
||||
use super::guard::{own_slot_content, relink_copy};
|
||||
use super::instances::{copy_group, field_group, sync_instance};
|
||||
use super::sync::insert_linked;
|
||||
@@ -179,12 +179,17 @@ fn override_groups(doc: &Document, before: &Document, id: NodeId, n: &Node, b: &
|
||||
// Binding another variable (or none) where the main binds one is an override.
|
||||
for (k, _) in b.bound.iter().chain(n.bound.iter()) {
|
||||
let Some(g) = binding_group(k) else { continue };
|
||||
let rebound = b.bound.get(k) != n.bound.get(k) && !bindings_of(n, g).eq(bindings_of(src, g));
|
||||
let rebound = b.bound.get(k) != n.bound.get(k) && bound_differently(n, src, g);
|
||||
if rebound && !groups.contains(&g) {
|
||||
groups.push(g);
|
||||
}
|
||||
}
|
||||
cleared = raw.iter().filter(|g| !matches!(**g, "size" | "position") && !differs.contains(g) && n.overrides.contains(**g)).copied().collect();
|
||||
let rebound = rebound_groups(n, src);
|
||||
cleared = raw
|
||||
.iter()
|
||||
.filter(|g| !matches!(**g, "size" | "position") && !differs.contains(g) && !rebound.contains(g) && n.overrides.contains(**g))
|
||||
.copied()
|
||||
.collect();
|
||||
if top_root {
|
||||
cleared.retain(|g| !matches!(*g, "component" | "props"));
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::diff::{diff_groups, variable_groups};
|
||||
use super::diff::{diff_groups, rebound_groups, variable_groups};
|
||||
use super::instances::{field_group, path_map};
|
||||
use super::{BTreeMap, BTreeSet, Document, MAX_DEPTH, Node, NodeId, NodeKind, default_instance_name, holds_content};
|
||||
|
||||
@@ -216,6 +216,7 @@ pub fn rebase_instance_with(doc: &mut Document, inst: NodeId, mains: &mut MainPa
|
||||
let mut bound: Vec<&str> = m.prop_refs.keys().map(|f| field_group(f)).collect();
|
||||
bound.extend(variable_groups(n, m));
|
||||
overrides.extend(value_groups(m, n).into_iter().filter(|g| !bound.contains(&g.as_str())));
|
||||
overrides.extend(rebound_groups(n, m).into_iter().map(str::to_string));
|
||||
if matches!((&m.kind, &n.kind), (NodeKind::Instance { component: a, .. }, NodeKind::Instance { component: b, .. }) if a != b) {
|
||||
overrides.insert("component".into());
|
||||
}
|
||||
@@ -233,6 +234,7 @@ pub fn rebase_instance_with(doc: &mut Document, inst: NodeId, mains: &mut MainPa
|
||||
let mut groups: Vec<String> = value_groups(m, n)
|
||||
.into_iter()
|
||||
.filter(|g| !matches!(g.as_str(), "name" | "exports" | "interactions") && !from_variables.contains(&g.as_str()))
|
||||
.chain(rebound_groups(n, m).into_iter().map(str::to_string))
|
||||
.filter(|g| placed_source.is_some() || !matches!(g.as_str(), "resizing" | "modes"))
|
||||
.collect();
|
||||
let named = if placed_source.is_some() { n.name != m.name } else { n.name != default_instance_name(doc, component) };
|
||||
|
||||
@@ -115,9 +115,65 @@ fn match_layers(
|
||||
}
|
||||
m.map.insert(*s, nid);
|
||||
}
|
||||
match_text_by_name(doc, inst, component, src, old, &mut m);
|
||||
m
|
||||
}
|
||||
|
||||
/// Main text layers nothing matched take the unmatched old text layer of the same name, when
|
||||
/// exactly one of each has it: text typed into an instance stays when it switches to a variant that
|
||||
/// nests the same text layer in other frames (its name path differs). Only layers outside nested
|
||||
/// instances, which rebuild from their own mains. Names are counted over all those text layers,
|
||||
/// matched ones too, so a name two layers share on either side never pairs by elimination.
|
||||
fn match_text_by_name(
|
||||
doc: &Document,
|
||||
inst: NodeId,
|
||||
component: NodeId,
|
||||
src: &[NodeId],
|
||||
old: &BTreeMap<NodeId, std::sync::Arc<Node>>,
|
||||
m: &mut Matched,
|
||||
) {
|
||||
fn unique<K: Ord>(pairs: impl Iterator<Item = (K, NodeId)>) -> BTreeMap<K, NodeId> {
|
||||
let mut seen: BTreeMap<K, Option<NodeId>> = BTreeMap::new();
|
||||
for (k, id) in pairs {
|
||||
seen.entry(k).and_modify(|e| *e = None).or_insert(Some(id));
|
||||
}
|
||||
seen.into_iter().filter_map(|(k, id)| Some((k, id?))).collect()
|
||||
}
|
||||
let text = |n: &Node| matches!(n.kind, NodeKind::Text(_));
|
||||
let mut mains =
|
||||
unique(src.iter().filter_map(|s| doc.node(*s)).filter(|s| text(s) && outside_nested(doc, s.id, component)).map(|s| (s.name.clone(), s.id)));
|
||||
mains.retain(|_, s| m.fresh.contains(s));
|
||||
if mains.is_empty() {
|
||||
return;
|
||||
}
|
||||
let olds = unique(
|
||||
old.iter()
|
||||
.filter(|(id, o)| text(o) && outside_nested(doc, **id, inst))
|
||||
.map(|(id, o)| (o.source.and_then(|s| doc.node(s)).map_or(&o.name, |s| &s.name).clone(), *id)),
|
||||
);
|
||||
for (name, s) in mains {
|
||||
if let Some(o) = olds.get(&name).filter(|o| !m.used.contains(*o)) {
|
||||
m.used.insert(*o);
|
||||
m.map.insert(s, *o);
|
||||
m.fresh.retain(|f| *f != s);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether layer `id` is below `root` with no instance between them.
|
||||
fn outside_nested(doc: &Document, id: NodeId, root: NodeId) -> bool {
|
||||
let mut cur = doc.node(id).and_then(|n| n.parent);
|
||||
for _ in 0..=1_000_000 {
|
||||
match cur.and_then(|c| doc.node(c)) {
|
||||
Some(n) if n.id == root => return true,
|
||||
Some(n) if matches!(n.kind, NodeKind::Instance { .. }) => return false,
|
||||
Some(n) => cur = n.parent,
|
||||
None => return false,
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// A rebuild's copies of the main's layers, pre-order (parents first).
|
||||
struct Copies {
|
||||
nodes: Vec<Node>,
|
||||
|
||||
@@ -282,6 +282,50 @@ fn variant_switch_keeps_compatible_overrides() {
|
||||
healthy(&s);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_text_stays_across_variants_that_nest_it_differently() {
|
||||
let mut s = Session::new();
|
||||
// Each variant's Label layers, by the frames holding them.
|
||||
let shapes: [(&str, &[&[&str]]); 4] =
|
||||
[("Kind=Plain", &[&["text"]]), ("Kind=Boxed", &[&["div", "text"]]), ("Kind=Twice", &[&["a"], &["b"]]), ("Kind=Moved", &[&["a"], &["c"]])];
|
||||
let mut labels = Vec::new();
|
||||
let mut variants = Vec::new();
|
||||
for (k, (name, paths)) in shapes.into_iter().enumerate() {
|
||||
let v = idv(&ex(&mut s, "frame.create", json!({"x": k as f64 * 300.0, "y": 0, "width": 200, "height": 60, "name": name})));
|
||||
for frames in paths {
|
||||
let mut parent = v;
|
||||
for f in *frames {
|
||||
parent = idv(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 200, "height": 60, "parent": parent, "name": f})));
|
||||
}
|
||||
labels.push(idv(&ex(&mut s, "text.create", json!({"text": "I agree", "x": 0, "y": 0, "parent": parent, "props": {"name": "Label"}}))));
|
||||
}
|
||||
variants.push(idv(&ex(&mut s, "component.create", json!({"ids": [v]}))));
|
||||
}
|
||||
ex(&mut s, "component.combineVariants", json!({"ids": variants.clone()}));
|
||||
let i = idv(&ex(&mut s, "instance.create", json!({"component": variants[0], "x": 0, "y": 300})));
|
||||
let typed = copy_of(&s, i, labels[0]);
|
||||
ex(&mut s, "text.set", json!({"id": typed, "characters": "Architect"}));
|
||||
|
||||
ex(&mut s, "instance.setProperties", json!({"ids": [i], "properties": {"Kind": "Boxed"}}));
|
||||
healthy(&s);
|
||||
assert_eq!(chars(&s, copy_of(&s, i, labels[1])), "Architect", "one frame deeper, same name");
|
||||
ex(&mut s, "instance.setProperties", json!({"ids": [i], "properties": {"Kind": "Plain"}}));
|
||||
assert_eq!(chars(&s, copy_of(&s, i, labels[0])), "Architect", "and back");
|
||||
|
||||
ex(&mut s, "instance.setProperties", json!({"ids": [i], "properties": {"Kind": "Twice"}}));
|
||||
healthy(&s);
|
||||
let texts: Vec<String> = labels[2..4].iter().map(|l| chars(&s, copy_of(&s, i, *l))).collect();
|
||||
assert_eq!(texts, ["I agree", "I agree"], "two layers of that name: neither is the one typed into");
|
||||
|
||||
// `a › Label` matches by path; the leftover `b › Label` and `c › Label` still share a name with it.
|
||||
let typed = copy_of(&s, i, labels[3]);
|
||||
ex(&mut s, "text.set", json!({"id": typed, "characters": "Architect"}));
|
||||
ex(&mut s, "instance.setProperties", json!({"ids": [i], "properties": {"Kind": "Moved"}}));
|
||||
healthy(&s);
|
||||
let texts: Vec<String> = labels[4..].iter().map(|l| chars(&s, copy_of(&s, i, *l))).collect();
|
||||
assert_eq!(texts, ["I agree", "I agree"], "a name two layers share doesn't pair what path matching left over");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detach_keeps_the_look() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -1422,25 +1422,7 @@ pub fn adopt_pasted(doc: &mut Document, src: &Document, src_path: Option<&str>,
|
||||
remote.extend(merge_components(doc, src, &BTreeMap::new(), Some(&foreign))?);
|
||||
}
|
||||
// Components `src` publishes: from its library.
|
||||
if let Some(lib) = src.published.as_ref().filter(|l| own.as_deref() != Some(l.manifest.id.as_str())) {
|
||||
let keys: Vec<NodeId> =
|
||||
roots.iter().copied().filter(|r| !src.is_remote(*r) && lib.manifest.component(*r).is_some() && lib.doc.contains(*r)).collect();
|
||||
if !keys.is_empty() {
|
||||
remote.extend(import(doc, lib, &keys, false)?);
|
||||
let m = &lib.manifest;
|
||||
if doc.libraries.link(&m.id).is_none()
|
||||
&& let Some(path) = src_path
|
||||
{
|
||||
doc.libraries_mut().enabled.push(LibraryLink {
|
||||
id: m.id.clone(),
|
||||
name: m.name.clone(),
|
||||
path: path.to_string(),
|
||||
version: m.version,
|
||||
relative: String::new(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
remote.extend(from_published(doc, src, src_path, &roots)?);
|
||||
// Point the pasted layers at those mains; what stays behind gets ids of its own.
|
||||
let mut behind: BTreeMap<NodeId, NodeId> = BTreeMap::new();
|
||||
let mut follow = |doc: &mut Document, id: NodeId| -> NodeId {
|
||||
@@ -1479,6 +1461,45 @@ pub fn adopt_pasted(doc: &mut Document, src: &Document, src_path: Option<&str>,
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `doc`'s copies of the components among `roots` (assets of `src`) that `src` publishes as a
|
||||
/// library (`src`'s ids → `doc`'s), taken from that library, which gets enabled in `doc` when `src`
|
||||
/// is saved at `src_path`. Empty when `src` publishes no library, or publishes `doc`'s own.
|
||||
fn from_published(doc: &mut Document, src: &Document, src_path: Option<&str>, roots: &[NodeId]) -> Result<BTreeMap<NodeId, NodeId>> {
|
||||
let own = doc.published.as_ref().map(|p| p.manifest.id.as_str());
|
||||
let Some(lib) = src.published.as_ref().filter(|l| own != Some(l.manifest.id.as_str())) else { return Ok(BTreeMap::new()) };
|
||||
let keys: Vec<NodeId> =
|
||||
roots.iter().copied().filter(|r| !src.is_remote(*r) && lib.manifest.component(*r).is_some() && lib.doc.contains(*r)).collect();
|
||||
if keys.is_empty() {
|
||||
return Ok(BTreeMap::new());
|
||||
}
|
||||
let remote = import(doc, lib, &keys, false)?;
|
||||
let m = &lib.manifest;
|
||||
if doc.libraries.link(&m.id).is_none()
|
||||
&& let Some(path) = src_path
|
||||
{
|
||||
doc.libraries_mut().enabled.push(LibraryLink {
|
||||
id: m.id.clone(),
|
||||
name: m.name.clone(),
|
||||
path: path.to_string(),
|
||||
version: m.version,
|
||||
relative: String::new(),
|
||||
});
|
||||
}
|
||||
Ok(remote)
|
||||
}
|
||||
|
||||
/// The main in `doc` that pasting main component `main`, copied from another document `src`,
|
||||
/// makes an instance of: `doc`'s copy of it from the library `src` publishes, as
|
||||
/// [`adopt_pasted`] uses for instances. `None` when `src` doesn't offer it, so the paste copies
|
||||
/// the main itself: also when the library holds it only because an offered component uses it.
|
||||
pub fn published_main(doc: &mut Document, src: &Document, src_path: Option<&str>, main: NodeId) -> Result<Option<NodeId>> {
|
||||
let Some(root) = asset_root(src, main) else { return Ok(None) };
|
||||
if !src.published.as_ref().and_then(|l| l.manifest.component(root)).is_some_and(|a| a.published) {
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(from_published(doc, src, src_path, &[root])?.get(&main).copied())
|
||||
}
|
||||
|
||||
/// Refuse edits of library copies, except by library commands (and imports of other files,
|
||||
/// which bring their copies along).
|
||||
pub fn check_read_only(cmd: &str, before: &Document, after: &Document) -> std::result::Result<(), String> {
|
||||
|
||||
@@ -695,3 +695,72 @@ fn library_links_follow_a_moved_folder() {
|
||||
link_found(&mut s, &lid);
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
/// A main component copied from a library file and pasted into another file is an instance of it
|
||||
/// from that library, which gets enabled, as pasting an instance of it is; a variant is an instance
|
||||
/// of that variant. A component the library doesn't offer pastes as a copy of itself, also one the
|
||||
/// library holds because an offered component uses it.
|
||||
#[test]
|
||||
fn a_main_pasted_from_its_library_file_is_an_instance_of_it() {
|
||||
let d = dir("paste-main");
|
||||
let lib_path = path_str(&d.join("kit.figcraft"));
|
||||
let mut s = Session::new();
|
||||
let k = kit(&mut s);
|
||||
let sizes: Vec<NodeId> = ["Size=S", "Size=L"]
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(n, name)| {
|
||||
idv(&ex(
|
||||
&mut s,
|
||||
"node.create",
|
||||
json!({"type": "component", "name": name, "x": 600.0 + n as f64 * 100.0, "y": 0, "width": 40, "height": 20}),
|
||||
))
|
||||
})
|
||||
.collect();
|
||||
ex(&mut s, "component.combineVariants", json!({"ids": sizes.clone()}));
|
||||
let spare = idv(&ex(&mut s, "frame.create", json!({"x": 300, "y": 300, "width": 10, "height": 10, "name": "_Spare"})));
|
||||
let spare = idv(&ex(&mut s, "component.create", json!({"ids": [spare]})));
|
||||
let icon = idv(&ex(&mut s, "frame.create", json!({"x": 400, "y": 300, "width": 10, "height": 10, "name": "_Icon"})));
|
||||
let icon = idv(&ex(&mut s, "component.create", json!({"ids": [icon]})));
|
||||
let badge = idv(&ex(&mut s, "frame.create", json!({"x": 500, "y": 300, "width": 30, "height": 30, "name": "Badge"})));
|
||||
ex(&mut s, "instance.create", json!({"component": icon, "x": 5, "y": 5, "parent": badge}));
|
||||
ex(&mut s, "component.create", json!({"ids": [badge]}));
|
||||
let lid = publish_to(&mut s, &lib_path);
|
||||
assert!(s.doc().unwrap().published.as_ref().unwrap().manifest.component(icon).is_some_and(|a| !a.published));
|
||||
let at = s.doc().unwrap().world_bounds(k.button).unwrap();
|
||||
ex(&mut s, "file.new", json!({"name": "Design"}));
|
||||
let paste = |s: &mut Session, main: NodeId| -> NodeId {
|
||||
ex(s, "doc.switch", json!({"index": 0}));
|
||||
ex(s, "edit.copy", json!({"ids": [main]}));
|
||||
ex(s, "doc.switch", json!({"index": 1}));
|
||||
id_of(&ex(s, "edit.paste", json!({}))["ids"][0]).unwrap()
|
||||
};
|
||||
let main_of = |s: &Session, id: NodeId| match node(s, id).kind {
|
||||
NodeKind::Instance { component, .. } => component,
|
||||
k => panic!("not an instance: {k:?}"),
|
||||
};
|
||||
let button = paste(&mut s, k.button);
|
||||
let doc = s.doc().unwrap();
|
||||
assert_eq!(library_source(doc, main_of(&s, button)), Some((lid.as_str(), k.button)));
|
||||
assert_eq!(doc.libraries.enabled.iter().map(|l| l.path.as_str()).collect::<Vec<_>>(), [lib_path.as_str()]);
|
||||
assert_eq!(doc.world_bounds(button), Some(at), "where the main was");
|
||||
let label = node(&s, button).children[0];
|
||||
assert_eq!(chars(&s, label), "OK");
|
||||
healthy(&s);
|
||||
let copies = s.doc().unwrap().libraries.components.len();
|
||||
let again = paste(&mut s, k.button);
|
||||
assert_eq!(main_of(&s, again), main_of(&s, button), "the same library copy");
|
||||
assert_eq!(s.doc().unwrap().libraries.components.len(), copies);
|
||||
let large = paste(&mut s, sizes[1]);
|
||||
assert_eq!(library_source(s.doc().unwrap(), main_of(&s, large)), Some((lid.as_str(), sizes[1])));
|
||||
let card = paste(&mut s, k.card);
|
||||
assert_eq!(library_source(s.doc().unwrap(), main_of(&s, card)), Some((lid.as_str(), k.card)));
|
||||
let copy = paste(&mut s, spare);
|
||||
assert!(matches!(node(&s, copy).kind, NodeKind::Component { .. }), "not offered by the library: a copy");
|
||||
assert!(!s.doc().unwrap().is_remote(copy));
|
||||
let icon_copy = paste(&mut s, icon);
|
||||
assert!(matches!(node(&s, icon_copy).kind, NodeKind::Component { .. }), "only used by an offered component: a copy");
|
||||
assert!(!s.doc().unwrap().is_remote(icon_copy));
|
||||
healthy(&s);
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
@@ -4,13 +4,32 @@
|
||||
//! guide lines (with spacing labels) for the canvas to draw in red. Vector points also snap to
|
||||
//! other points (see `vectoredit::snap`); landing on one shows a marker (a zero-length guide).
|
||||
|
||||
use figcraft_doc::{BoardItem, Document, NodeId};
|
||||
use figcraft_doc::{BoardItem, Document, Node, NodeId, NodeKind};
|
||||
use figcraft_geom::{Affine, Point, Rect, Vec2, transform_rect_bbox};
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::guides;
|
||||
use crate::tools::UNMEASURED_SNAP_PX;
|
||||
|
||||
/// Whether `n` lands on whole pixels when dragged whatever Snap to pixel grid says: frames,
|
||||
/// sections, components, component sets and instances. Figma's help: they "always snap to the
|
||||
/// pixel grid, even if Snap to pixel grid is disabled". Other layers follow the setting.
|
||||
pub fn always_on_pixels(n: &Node) -> bool {
|
||||
n.kind.is_frame_like() || matches!(n.kind, NodeKind::Section { .. })
|
||||
}
|
||||
|
||||
/// Put `id`'s position in its parent on whole pixels when its axes are its parent's: returns
|
||||
/// whether it moved. A layer turned off its parent's axes keeps its position.
|
||||
pub fn settle_on_pixels(doc: &mut Document, id: NodeId) -> crate::Result<bool> {
|
||||
let n = doc.get_mut(id)?;
|
||||
let [a, b, c, d, e, f] = n.transform.as_coeffs();
|
||||
if !guides::axis_aligned(n.transform) || (e.round() == e && f.round() == f) {
|
||||
return Ok(false);
|
||||
}
|
||||
n.transform = Affine::new([a, b, c, d, e.round(), f.round()]);
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// A guide line to draw: from (x0, y0) to (x1, y1) in page coordinates, with an optional label
|
||||
/// (a distance) at its middle; `dashed` marks a measurement's extension line.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize)]
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
//! On-canvas text editing: caret, selection, typing. A whole editing session is one undo step.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::{LazyLock, Mutex};
|
||||
|
||||
use figcraft_doc::{Document, ListStyle, NodeId, NodeKind, TextData};
|
||||
use figcraft_doc::{Document, ImageData, ListStyle, NodeId, NodeKind, TextData};
|
||||
|
||||
use crate::{EngineError, Preedit, Result, Session, TextEdit};
|
||||
|
||||
@@ -401,6 +402,94 @@ pub fn list_indent(s: &mut Session, out: bool) -> Result<bool> {
|
||||
Ok(text_of(s, id)? != before)
|
||||
}
|
||||
|
||||
/// Whether Tab in text layer `id` moves between text layers: not in a board object's text (a
|
||||
/// sticky's note, a table cell, a code block) or a widget's field, where it types as before.
|
||||
fn tabs_between_texts(doc: &Document, id: NodeId) -> bool {
|
||||
!in_board_object(doc, id) && crate::widgets::field_of(doc, id).is_none()
|
||||
}
|
||||
|
||||
fn in_board_object(doc: &Document, id: NodeId) -> bool {
|
||||
std::iter::once(id).chain(doc.ancestors(id)).any(|a| doc.node(a).is_some_and(|n| n.board.is_some()))
|
||||
}
|
||||
|
||||
/// Tab (Shift+Tab: `back`) while editing text layer `from`: editing it ends as Escape ends it, and
|
||||
/// the next (previous) text layer in reading order is edited with all of its text selected. At the
|
||||
/// last (first) one nothing happens.
|
||||
fn tab_to_next_text(s: &mut Session, from: NodeId, back: bool) -> Result<()> {
|
||||
let order = reading_order(s.doc()?, tab_stops(s.doc()?, from));
|
||||
let Some(at) = order.iter().position(|t| *t == from) else { return Ok(()) };
|
||||
let next = if back { at.checked_sub(1).and_then(|i| order.get(i)) } else { order.get(at + 1) };
|
||||
let Some(&next) = next else { return Ok(()) };
|
||||
end(s)?;
|
||||
begin(s, next, None, false)
|
||||
}
|
||||
|
||||
/// The text layers Tab moves between from text layer `from`: those in the top-level layer holding
|
||||
/// it (the frame or group on the page or in a section), at any depth and inside instances, that are
|
||||
/// visible and unlocked with every layer around them and not in a board object; for a text on the
|
||||
/// page or in a section itself, the text layers beside it there. `from` is always one of them.
|
||||
fn tab_stops(doc: &Document, from: NodeId) -> Vec<NodeId> {
|
||||
let is_section = |id: &NodeId| doc.node(*id).is_some_and(|n| matches!(n.kind, NodeKind::Section { .. }));
|
||||
let chain: Vec<NodeId> = std::iter::once(from).chain(doc.ancestors(from)).collect();
|
||||
let Some(page_at) = chain.iter().position(|c| doc.node(*c).is_some_and(|n| n.is_page())) else { return vec![from] };
|
||||
let top = chain.get(..page_at).and_then(|below| below.iter().rev().copied().find(|c| !is_section(c)));
|
||||
let stop = |n: &figcraft_doc::Node| n.visible && !n.locked && n.board.is_none();
|
||||
let mut out = Vec::new();
|
||||
match top {
|
||||
Some(top) if top != from => {
|
||||
let mut stack = vec![top];
|
||||
let mut seen = 0usize;
|
||||
while let Some(id) = stack.pop() {
|
||||
seen += 1;
|
||||
if seen > 1_000_000 {
|
||||
break;
|
||||
}
|
||||
let Some(n) = doc.node(id).filter(|n| stop(n)) else { continue };
|
||||
if matches!(n.kind, NodeKind::Text(_)) {
|
||||
out.push(id);
|
||||
}
|
||||
stack.extend(n.children.iter().copied());
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
let beside = doc.node(from).and_then(|n| n.parent).and_then(|p| doc.node(p)).map(|p| p.children.clone()).unwrap_or_default();
|
||||
out.extend(beside.into_iter().filter(|c| doc.node(*c).is_some_and(|n| stop(n) && matches!(n.kind, NodeKind::Text(_)))));
|
||||
}
|
||||
}
|
||||
if !out.contains(&from) {
|
||||
out.push(from);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `ids` in reading order by their boxes on the page: rows top to bottom, each row left to right.
|
||||
/// Rows are made from the top down: a layer joins the row of the topmost layer before it when the
|
||||
/// two overlap vertically by more than nothing and by at least half the height of the shorter one,
|
||||
/// else it starts the next row. Layers without bounds are left out.
|
||||
fn reading_order(doc: &Document, ids: Vec<NodeId>) -> Vec<NodeId> {
|
||||
let mut boxes: Vec<(NodeId, figcraft_geom::Rect)> = ids.into_iter().filter_map(|i| Some((i, doc.world_bounds(i)?))).collect();
|
||||
boxes.sort_by(|a, b| a.1.y0.total_cmp(&b.1.y0).then(a.1.x0.total_cmp(&b.1.x0)));
|
||||
let mut rows: Vec<Vec<(NodeId, figcraft_geom::Rect)>> = Vec::new();
|
||||
for (id, b) in boxes {
|
||||
let joins = |row: &Vec<(NodeId, figcraft_geom::Rect)>| {
|
||||
row.first().is_some_and(|(_, a)| {
|
||||
let overlap = a.y1.min(b.y1) - a.y0.max(b.y0);
|
||||
overlap > 0.0 && overlap >= 0.5 * a.height().min(b.height())
|
||||
})
|
||||
};
|
||||
match rows.last_mut() {
|
||||
Some(row) if joins(row) => row.push((id, b)),
|
||||
_ => rows.push(vec![(id, b)]),
|
||||
}
|
||||
}
|
||||
rows.into_iter()
|
||||
.flat_map(|mut row| {
|
||||
row.sort_by(|a, b| a.1.x0.total_cmp(&b.1.x0).then(a.1.y0.total_cmp(&b.1.y0)));
|
||||
row.into_iter().map(|(id, _)| id)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The kind of word char `i` belongs to: 0 for spaces and punctuation, else its script, so a word
|
||||
/// ends where the script changes (Han, hiragana, katakana and Hangul runs are words of their own in
|
||||
/// text without spaces). Combining marks and voicing marks belong to the char before them.
|
||||
@@ -459,7 +548,9 @@ fn word_right(chars: &[char], mut i: usize) -> usize {
|
||||
i
|
||||
}
|
||||
|
||||
/// A named key: Backspace, Delete, Left, Right, Up, Down, Home, End, Enter, Escape, SelectAll.
|
||||
/// A named key: Backspace, Delete, Left, Right, Up, Down, Home, End, Enter, Tab, Escape, SelectAll.
|
||||
/// Tab and Shift+Tab outside a list, a code block, a board object and a widget's field edit the
|
||||
/// next or previous text layer ([`tab_to_next_text`]).
|
||||
/// `word` moves or deletes by word, `line` to the line's ends (Up/Down, Home/End: the text's ends);
|
||||
/// [`crate::keymap::text_motion`] gives them for the platform's keys. `ArrowLeft` etc. also work.
|
||||
pub fn key(s: &mut Session, key: &str, shift: bool, word: bool, line: bool) -> Result<()> {
|
||||
@@ -484,6 +575,7 @@ pub fn key(s: &mut Session, key: &str, shift: bool, word: bool, line: bool) -> R
|
||||
match key {
|
||||
"Escape" => return end(s),
|
||||
"Enter" => return insert(s, "\n"),
|
||||
"Tab" if !word && !line && tabs_between_texts(s.doc()?, te.id) => return tab_to_next_text(s, te.id, shift),
|
||||
"Tab" => return insert(s, "\t"),
|
||||
"Backspace" | "Delete" => {
|
||||
return edit(s, |t, te| {
|
||||
@@ -856,6 +948,106 @@ pub fn selected_text(s: &Session) -> Option<String> {
|
||||
Some(t.characters.chars().skip(a).take(b.saturating_sub(a)).collect())
|
||||
}
|
||||
|
||||
/// Copied characters with their formatting, for a paste into a text edit that keeps it.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct RichText {
|
||||
pub text: String,
|
||||
/// Styled runs as `(from, to, style)` char ranges of `text`. Each style carries its fills,
|
||||
/// the layer's own where the run had none, so the characters keep their colour elsewhere.
|
||||
pub spans: Vec<(usize, usize, figcraft_doc::TextStyle)>,
|
||||
/// The data of the images the runs' fills use, so they resolve in another file.
|
||||
pub images: BTreeMap<String, ImageData>,
|
||||
}
|
||||
|
||||
/// The selected characters while editing, with their formatting (for copy).
|
||||
pub fn selected_rich_text(s: &Session) -> Option<RichText> {
|
||||
let (id, a, b) = selected_range(s)?;
|
||||
rich_text_of(s.doc().ok()?, id, a, b)
|
||||
}
|
||||
|
||||
/// The characters of the text layers `ids`, one per line, with their formatting; None when one of
|
||||
/// them isn't a text layer or there are no characters.
|
||||
pub fn layers_rich_text(doc: &Document, ids: &[NodeId]) -> Option<RichText> {
|
||||
let mut joined = RichText { text: String::new(), spans: Vec::new(), images: BTreeMap::new() };
|
||||
let mut offset = 0;
|
||||
for (i, id) in ids.iter().enumerate() {
|
||||
let layer = rich_text_of(doc, *id, 0, usize::MAX)?;
|
||||
if i > 0 {
|
||||
joined.text.push('\n');
|
||||
offset += 1;
|
||||
}
|
||||
joined.text.push_str(&layer.text);
|
||||
joined.spans.extend(layer.spans.into_iter().map(|(from, to, style)| (from + offset, to + offset, style)));
|
||||
joined.images.extend(layer.images);
|
||||
offset += layer.text.chars().count();
|
||||
}
|
||||
(!joined.text.is_empty()).then_some(joined)
|
||||
}
|
||||
|
||||
/// Chars `a..b` of the text layer `id` (`b` past the end means to the end), with their formatting.
|
||||
fn rich_text_of(doc: &Document, id: NodeId, a: usize, b: usize) -> Option<RichText> {
|
||||
let n = doc.node(id)?;
|
||||
let t = n.kind.text()?;
|
||||
let b = b.min(t.char_count());
|
||||
let text: String = t.characters.chars().skip(a).take(b.saturating_sub(a)).collect();
|
||||
let spans: Vec<(usize, usize, figcraft_doc::TextStyle)> = t
|
||||
.spans()
|
||||
.into_iter()
|
||||
.filter(|(from, to, _)| *to > a && *from < b)
|
||||
.map(|(from, to, style)| {
|
||||
let mut style = style.clone();
|
||||
style.fills.get_or_insert_with(|| n.fills.clone());
|
||||
(from.max(a) - a, to.min(b) - a, style)
|
||||
})
|
||||
.collect();
|
||||
let mut images = BTreeMap::new();
|
||||
for paint in spans.iter().flat_map(|(_, _, style)| style.fills.iter().flatten()) {
|
||||
if let figcraft_color::PaintKind::Image(img) = &paint.kind
|
||||
&& let Some(d) = doc.images.get(&img.image)
|
||||
{
|
||||
images.insert(img.image.clone(), d.clone());
|
||||
}
|
||||
}
|
||||
Some(RichText { text, spans, images })
|
||||
}
|
||||
|
||||
/// Replace the selection in the text edit with `rich`, keeping its formatting. A link to a style
|
||||
/// this file doesn't have is dropped, a fill equal to the layer's is left to the layer, and the
|
||||
/// copied image data is added where this file lacks the key, as a pasted layer's is.
|
||||
pub fn insert_rich(s: &mut Session, rich: &RichText) -> Result<()> {
|
||||
if s.ds()?.text_edit.is_some() {
|
||||
let doc = s.doc_mut()?;
|
||||
for (k, v) in &rich.images {
|
||||
doc.images.entry(k.clone()).or_insert_with(|| v.clone());
|
||||
}
|
||||
}
|
||||
let doc = s.doc()?;
|
||||
let layer_fills = s.ds()?.text_edit.as_ref().and_then(|te| doc.node(te.id)).map(|n| n.fills.clone());
|
||||
let spans: Vec<(usize, usize, figcraft_doc::TextStyle)> = rich
|
||||
.spans
|
||||
.iter()
|
||||
.map(|(from, to, style)| {
|
||||
let mut style = style.clone();
|
||||
if style.style_id.as_deref().is_some_and(|id| doc.style(id).is_none()) {
|
||||
style.style_id = None;
|
||||
}
|
||||
if style.fills == layer_fills {
|
||||
style.fills = None;
|
||||
}
|
||||
(*from, *to, style)
|
||||
})
|
||||
.collect();
|
||||
edit(s, |t, te| {
|
||||
let (a, b) = range(te);
|
||||
t.replace_range(a, b, &rich.text);
|
||||
for (from, to, style) in &spans {
|
||||
t.restyle(a + from, a + to, |x| *x = style.clone());
|
||||
}
|
||||
te.caret = a + rich.text.chars().count();
|
||||
te.anchor = te.caret;
|
||||
})
|
||||
}
|
||||
|
||||
/// The selected range while editing (for styling commands), or None.
|
||||
pub fn selected_range(s: &Session) -> Option<(NodeId, usize, usize)> {
|
||||
let te = s.ds().ok()?.text_edit.clone()?;
|
||||
|
||||
@@ -569,3 +569,52 @@ fn an_empty_ime_commit_ends_the_composition_without_inserting_text() {
|
||||
end(&mut s).unwrap();
|
||||
assert_eq!(insert_ime_commit(&mut s, "").unwrap(), ImeInsertion::Nothing);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rich_text_pastes_its_runs_and_drops_a_link_to_a_style_this_file_lacks() {
|
||||
let (mut s, id) = setup("ab");
|
||||
begin(&mut s, id, Some(2), false).unwrap();
|
||||
let mut bold = data(&s, id).style.clone();
|
||||
bold.font_style = "Bold".into();
|
||||
bold.style_id = Some("from another file".into());
|
||||
let plain = data(&s, id).style.clone();
|
||||
insert_rich(&mut s, &RichText { text: "XY".into(), spans: vec![(0, 1, bold), (1, 2, plain)], images: Default::default() }).unwrap();
|
||||
let t = data(&s, id);
|
||||
assert_eq!(t.characters, "abXY");
|
||||
assert_eq!(t.style_at(2).font_style, "Bold");
|
||||
assert_eq!(t.style_at(2).style_id, None, "a link to a style this file doesn't have");
|
||||
assert_eq!(t.style_at(3).font_style, "Regular");
|
||||
assert_eq!(sel(&s), (4, 4));
|
||||
set_caret(&mut s, 2, false).unwrap();
|
||||
set_caret(&mut s, 4, true).unwrap();
|
||||
let copied = selected_rich_text(&s).unwrap();
|
||||
assert_eq!(copied.text, "XY");
|
||||
assert_eq!(copied.spans.iter().map(|(a, b, st)| (*a, *b, st.font_style.as_str())).collect::<Vec<_>>(), [(0, 1, "Bold"), (1, 2, "Regular")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copied_characters_bring_the_image_their_fill_uses_into_another_file() {
|
||||
let (mut source, id) = setup("ab");
|
||||
let data = figcraft_doc::ImageData { bytes: std::sync::Arc::new(vec![1, 2, 3]), width: 2, height: 2 };
|
||||
{
|
||||
let doc = source.doc_mut().unwrap();
|
||||
doc.images.insert("pic".into(), data.clone());
|
||||
doc.get_mut(id).unwrap().fills = vec![figcraft_color::Paint::image("pic", figcraft_color::ImageScaleMode::Fill)];
|
||||
}
|
||||
begin(&mut source, id, Some(0), false).unwrap();
|
||||
set_caret(&mut source, 2, true).unwrap();
|
||||
let copied = selected_rich_text(&source).unwrap();
|
||||
let (mut s, target) = setup("cd");
|
||||
begin(&mut s, target, Some(2), false).unwrap();
|
||||
insert_rich(&mut s, &copied).unwrap();
|
||||
assert_eq!(s.doc().unwrap().images.get("pic"), Some(&data), "the run's image fill resolves here");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copied_text_layers_join_one_per_line_with_their_runs_in_place() {
|
||||
let (mut s, first) = setup("ab");
|
||||
let second = crate::params::id_of(&s.execute("text.create", &json!({"text": "cdé", "x": 0, "y": 50})).unwrap()["id"]).unwrap();
|
||||
let joined = layers_rich_text(s.doc().unwrap(), &[first, second]).unwrap();
|
||||
assert_eq!(joined.text, "ab\ncdé");
|
||||
assert_eq!(joined.spans.iter().map(|(a, b, _)| (*a, *b)).collect::<Vec<_>>(), [(0, 2), (3, 6)]);
|
||||
}
|
||||
@@ -249,7 +249,11 @@ impl Session {
|
||||
let raw = d;
|
||||
let snap_on = self.ds().map(|ds| ds.view.snap_objects).unwrap_or(true) && !ev.cmd && !ev.ctrl;
|
||||
let mut guides = Vec::new();
|
||||
if self.ds().map(|ds| ds.view.snap_pixel).unwrap_or(true) {
|
||||
let boards = {
|
||||
let doc = self.doc()?;
|
||||
ids.iter().all(|i| doc.node(*i).is_some_and(crate::snap::always_on_pixels))
|
||||
};
|
||||
if boards || self.ds().map(|ds| ds.view.snap_pixel).unwrap_or(true) {
|
||||
// Keep the box's origin on whole pixels (a rotated parent frame's, inside one);
|
||||
// snapping to layers comes after, so it wins on the axes it snaps.
|
||||
d = targets.round_move(d);
|
||||
@@ -259,6 +263,11 @@ impl Session {
|
||||
d += c;
|
||||
guides = g2;
|
||||
}
|
||||
if boards {
|
||||
// Frames, sections and components stay on whole pixels even where a layer
|
||||
// they snap to doesn't.
|
||||
d = targets.round_move(d);
|
||||
}
|
||||
let ids = ids.clone();
|
||||
let dup = *duplicate;
|
||||
let page = self.page()?;
|
||||
@@ -343,6 +352,9 @@ impl Session {
|
||||
doc.reparent(*m, page, None)?;
|
||||
}
|
||||
move_world(doc, *m, d.x, d.y)?;
|
||||
if doc.node(*m).is_some_and(crate::snap::always_on_pixels) {
|
||||
shifted &= !crate::snap::settle_on_pixels(doc, *m)?;
|
||||
}
|
||||
}
|
||||
drop_target = (flow && target != page).then_some(target);
|
||||
Ok(())
|
||||
@@ -521,7 +533,13 @@ impl Session {
|
||||
// The pixel grid: an upright box's dragged sides land on whole pixels (the Scale tool
|
||||
// scales by the factor as dragged). Snapping to layers comes after, so it wins on the axes
|
||||
// it snaps.
|
||||
if !scale_tool && self.ds().map(|d| d.view.snap_pixel).unwrap_or(true) && crate::guides::axis_aligned(frame) {
|
||||
// Frames, sections and components land on whole pixels whatever the setting, also where a
|
||||
// layer they snap to doesn't.
|
||||
let boards = {
|
||||
let doc = self.doc()?;
|
||||
!scale_tool && crate::guides::axis_aligned(frame) && ids.iter().all(|i| doc.node(*i).is_some_and(crate::snap::always_on_pixels))
|
||||
};
|
||||
if boards || !scale_tool && self.ds().map(|d| d.view.snap_pixel).unwrap_or(true) && crate::guides::axis_aligned(frame) {
|
||||
p = Point::new(p.x.round(), p.y.round());
|
||||
}
|
||||
if let Some(t) = &targets {
|
||||
@@ -530,6 +548,9 @@ impl Session {
|
||||
p.y += dy;
|
||||
guides = g;
|
||||
}
|
||||
if boards {
|
||||
p = Point::new(p.x.round(), p.y.round());
|
||||
}
|
||||
let q = frame.inverse() * p;
|
||||
let is_line = r.single && ids.first().and_then(|i| self.doc().ok()?.node(*i).map(|n| matches!(n.kind, NodeKind::Line))).unwrap_or(false);
|
||||
if scale_tool {
|
||||
@@ -557,9 +578,16 @@ impl Session {
|
||||
self.tool.overlay.guides = guides;
|
||||
return Ok(());
|
||||
}
|
||||
// Constrain proportions (Shift, or the node's lock).
|
||||
let keep = ev.shift || r.single && ids.first().and_then(|i| self.doc().ok()?.node(*i).map(|n| n.constrain_proportions)).unwrap_or(false);
|
||||
let (x0, y0, x1, y1) = resized_box(r.handle, q, w0, h0, keep, ev.alt);
|
||||
let image_box = ids.first().filter(|_| ev.cmd && r.single).and_then(|i| self.image_box(*i));
|
||||
// Constrain proportions (Shift, or the node's lock; cropping an image ignores the lock).
|
||||
let locked =
|
||||
r.single && image_box.is_none() && ids.first().and_then(|i| self.doc().ok()?.node(*i).map(|n| n.constrain_proportions)).unwrap_or(false);
|
||||
let keep = ev.shift || locked;
|
||||
let resized = resized_box(r.handle, q, w0, h0, keep, ev.alt);
|
||||
let (x0, y0, x1, y1) = match image_box {
|
||||
Some(image) => within_the_image(resized, image, (w0, h0), keep),
|
||||
None => resized,
|
||||
};
|
||||
let (flip_x, flip_y) = (x1 < x0, y1 < y0);
|
||||
let (nx0, ny0) = (x0.min(x1), y0.min(y1));
|
||||
let (nw, nh) = ((x1 - x0).abs(), (y1 - y0).abs());
|
||||
@@ -571,46 +599,30 @@ impl Session {
|
||||
let keeps = |doc: &Document, id: NodeId| {
|
||||
doc.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Section { .. }) || (ev.cmd && single && n.kind.is_frame_like()))
|
||||
};
|
||||
let dragged_box = |world: Affine, (ox, oy): (f64, f64)| {
|
||||
let mut t = world * Affine::translate((ox, oy));
|
||||
if flip_x {
|
||||
t *= Affine::new([-1.0, 0.0, 0.0, 1.0, nw, 0.0]);
|
||||
}
|
||||
if flip_y {
|
||||
t *= Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, nh]);
|
||||
}
|
||||
t
|
||||
};
|
||||
self.preview(|doc, _| {
|
||||
if single {
|
||||
let Some((id, world, _, _)) = nodes.first() else { return Ok(()) };
|
||||
let kept = if keeps(doc, *id) { crate::cmd::props::children_worlds(doc, *id) } else { Vec::new() };
|
||||
let mut t = *world * Affine::translate((nx0, ny0));
|
||||
if flip_x {
|
||||
t *= Affine::new([-1.0, 0.0, 0.0, 1.0, nw, 0.0]);
|
||||
}
|
||||
if flip_y {
|
||||
t *= Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, nh]);
|
||||
}
|
||||
let t = dragged_box(*world, (nx0, ny0));
|
||||
// Text reflow and auto layout can recompute this box after the preview (a size bound
|
||||
// to a variable lets go of it: the resize is an explicit edit).
|
||||
// to a variable lets go of it: the resize is an explicit edit). A text keeps its
|
||||
// fills; any other layer's image is cropped again for the box layout leaves
|
||||
// (`crop_to_the_laid_out_box`).
|
||||
let n = doc.get(*id)?;
|
||||
let crop_images = ev.cmd
|
||||
&& !matches!(n.kind, NodeKind::Text(_))
|
||||
&& !std::iter::once(*id).chain(doc.ancestors(*id)).any(|a| doc.node(a).is_some_and(|n| n.layout.is_some()));
|
||||
if crop_images {
|
||||
// Crop the layer's image fills without moving their pixels on the page.
|
||||
// Work from the interaction snapshot, just like the geometry on every move.
|
||||
let (w, h) = (n.width.max(1e-6), n.height.max(1e-6));
|
||||
let to_old =
|
||||
Affine::scale_non_uniform(1.0 / w, 1.0 / h) * world.inverse() * t * Affine::scale_non_uniform(nw.max(0.01), nh.max(0.01));
|
||||
let mut fills = n.fills.clone();
|
||||
for paint in &mut fills {
|
||||
let PaintKind::Image(img) = &mut paint.kind else { continue };
|
||||
// A repeating image cannot be represented by a single Crop placement.
|
||||
if img.scale_mode == ImageScaleMode::Tile {
|
||||
continue;
|
||||
}
|
||||
let Some(data) = doc.images.get(&img.image) else { continue };
|
||||
let (iw, ih) = (f64::from(data.width), f64::from(data.height));
|
||||
// A degenerate (zero-scale) layer has no inverse: its image keeps its placement.
|
||||
let crop = (Affine::new(img.placement_crop(iw, ih, w, h)) * to_old).as_coeffs();
|
||||
if !crop.iter().all(|c| c.is_finite()) {
|
||||
continue;
|
||||
}
|
||||
img.crop = Some(crop);
|
||||
img.scale_mode = ImageScaleMode::Crop;
|
||||
}
|
||||
// Crop the layer's image fills without moving their pixels on the page.
|
||||
// Work from the interaction snapshot, just like the geometry on every move.
|
||||
if ev.cmd && !matches!(n.kind, NodeKind::Text(_)) {
|
||||
let fills = cropped_image_fills(doc, n, *world, t, (nw, nh));
|
||||
doc.get_mut(*id)?.fills = fills;
|
||||
}
|
||||
doc.set_world_transform(*id, t)?;
|
||||
@@ -650,16 +662,81 @@ impl Session {
|
||||
let lin = (mirror * local).with_translation(Vec2::ZERO);
|
||||
let origin = Point::new(x0 + center.x * sx, y0 + center.y * sy) - lin * Point::new(w2 / 2.0, h2 / 2.0);
|
||||
let kept = if keeps(doc, *id) { crate::cmd::props::children_worlds(doc, *id) } else { Vec::new() };
|
||||
doc.set_world_transform(*id, frame * lin.with_translation(origin))?;
|
||||
let (t, w2, h2) = if boards {
|
||||
on_whole_pixels(doc, *id, frame * lin.with_translation(origin), w2, h2)
|
||||
} else {
|
||||
(frame * lin.with_translation(origin), w2, h2)
|
||||
};
|
||||
doc.set_world_transform(*id, t)?;
|
||||
crate::cmd::props::resize_node(doc, *id, w2, h2)?;
|
||||
if boards {
|
||||
crate::snap::settle_on_pixels(doc, *id)?;
|
||||
}
|
||||
crate::cmd::props::restore_worlds(doc, &kept)?;
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
if single
|
||||
&& ev.cmd
|
||||
&& let Some((id, world, _, _)) = nodes.first()
|
||||
{
|
||||
let laid_out_box = |(fw, fh): (f64, f64)| {
|
||||
let origin = match image_box {
|
||||
Some((ix0, iy0, ix1, iy1)) => {
|
||||
(slid_onto_the_image(nx0, fw, flip_x, (ix0, ix1), w0), slid_onto_the_image(ny0, fh, flip_y, (iy0, iy1), h0))
|
||||
}
|
||||
None => (nx0, ny0),
|
||||
};
|
||||
dragged_box(*world, origin)
|
||||
};
|
||||
self.crop_to_the_laid_out_box(*id, *world, laid_out_box, (nw, nh))?;
|
||||
}
|
||||
self.tool.overlay.guides = guides;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The box `(x0, y0, x1, y1)` of the first visible, untiled image fill of `id` in the layer's
|
||||
/// own axes, as it was when the gesture began; `None` for a text or a layer without one.
|
||||
fn image_box(&self, id: NodeId) -> Option<(f64, f64, f64, f64)> {
|
||||
let snapshot = self.ds().ok()?.interaction.as_ref()?.doc.clone();
|
||||
let n = snapshot.node(id)?;
|
||||
if matches!(n.kind, NodeKind::Text(_)) {
|
||||
return None;
|
||||
}
|
||||
n.fills.iter().filter(|p| p.visible).find_map(|p| match &p.kind {
|
||||
PaintKind::Image(img) if img.scale_mode != ImageScaleMode::Tile => {
|
||||
let data = snapshot.images.get(&img.image)?;
|
||||
let crop = img.effective_crop(f64::from(data.width), f64::from(data.height), n.width, n.height);
|
||||
let (x0, y0, x1, y1) = figcraft_doc::color::ImagePaint::crop_rect(crop);
|
||||
Some((x0 * n.width, y0 * n.height, x1 * n.width, y1 * n.height))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
/// After the preview's layout: when the layer didn't keep the dragged size `(nw, nh)` (a
|
||||
/// minimum size, a Hug frame), crop its image fills again from the snapshot for the size it
|
||||
/// has, the box placed by `laid_out_box` (given that size) in the layer's starting axes.
|
||||
fn crop_to_the_laid_out_box(
|
||||
&mut self,
|
||||
id: NodeId,
|
||||
world: Affine,
|
||||
laid_out_box: impl Fn((f64, f64)) -> Affine,
|
||||
(nw, nh): (f64, f64),
|
||||
) -> Result<()> {
|
||||
let ds = self.ds_mut()?;
|
||||
let Some(snapshot) = ds.interaction.as_ref().map(|it| it.doc.clone()) else { return Ok(()) };
|
||||
let Some(before) = snapshot.node(id).filter(|n| !matches!(n.kind, NodeKind::Text(_))) else { return Ok(()) };
|
||||
let Some((fw, fh)) = ds.doc.node(id).map(|n| (n.width, n.height)) else { return Ok(()) };
|
||||
if (fw - nw.max(0.01)).abs() < 1e-9 && (fh - nh.max(0.01)).abs() < 1e-9 {
|
||||
return Ok(());
|
||||
}
|
||||
let fills = cropped_image_fills(&snapshot, before, world, laid_out_box((fw, fh)), (fw, fh));
|
||||
std::sync::Arc::make_mut(&mut ds.doc).get_mut(id)?.fills = fills;
|
||||
ds.revision += 1;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Scale tool handle drag (`q`: the snapped pointer in the handle box's axes): everything
|
||||
/// scales by one factor about the anchor point (Alt: the centre), strokes, effects, radii and
|
||||
/// text included, children by the same factor whatever their constraints.
|
||||
@@ -697,6 +774,25 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
/// `world` and the size `w` x `h` a layer of a resized selection takes, moved so its box in its
|
||||
/// parent has its edges on whole pixels, each on the nearest one and the box at least a pixel
|
||||
/// wide: a frame resized with others lands on whole pixels as one resized alone does. A layer
|
||||
/// turned or scaled in its parent keeps them.
|
||||
fn on_whole_pixels(doc: &Document, id: NodeId, world: Affine, w: f64, h: f64) -> (Affine, f64, f64) {
|
||||
let pw = doc.node(id).and_then(|n| n.parent).map_or(Affine::IDENTITY, |p| doc.world_transform(p));
|
||||
let local = pw.inverse() * world;
|
||||
let [a, b, c, d, e, f] = local.as_coeffs();
|
||||
if !crate::guides::axis_aligned(local) || (a.abs() - 1.0).abs() > 1e-9 || (d.abs() - 1.0).abs() > 1e-9 {
|
||||
return (world, w, h);
|
||||
}
|
||||
let edges = |at: f64, flip: bool, len: f64| if flip { (at - len, at) } else { (at, at + len) };
|
||||
let ((x0, x1), (y0, y1)) = (edges(e, a < 0.0, w), edges(f, d < 0.0, h));
|
||||
let (x0, y0) = (x0.round(), y0.round());
|
||||
let (w, h) = ((x1.round() - x0).max(1.0), (y1.round() - y0).max(1.0));
|
||||
let (e, f) = (if a < 0.0 { x0 + w } else { x0 }, if d < 0.0 { y0 + h } else { y0 });
|
||||
(pw * Affine::new([a, b, c, d, e, f]), w, h)
|
||||
}
|
||||
|
||||
/// Moving `moving` by the same offset moves nothing else and changes nothing about them but where
|
||||
/// they are: none is inside another (it would move twice) or placed by its parent's auto layout
|
||||
/// (the layout would put it back, or close the gap it leaves).
|
||||
@@ -714,3 +810,78 @@ fn only_shifted(doc: &Document, moving: &[NodeId]) -> bool {
|
||||
!in_flow && !nested
|
||||
})
|
||||
}
|
||||
|
||||
/// `before`'s fills (from the snapshot `doc`) with each image cropped to the box `dragged` (the
|
||||
/// layer's new transform, `nw` × `nh`), its pixels left where they were on the page (`world`:
|
||||
/// the layer's transform before the drag).
|
||||
fn cropped_image_fills(
|
||||
doc: &Document,
|
||||
before: &figcraft_doc::Node,
|
||||
world: Affine,
|
||||
dragged: Affine,
|
||||
(nw, nh): (f64, f64),
|
||||
) -> Vec<figcraft_doc::color::Paint> {
|
||||
let (w, h) = (before.width.max(1e-6), before.height.max(1e-6));
|
||||
let to_before = Affine::scale_non_uniform(1.0 / w, 1.0 / h) * world.inverse() * dragged * Affine::scale_non_uniform(nw.max(0.01), nh.max(0.01));
|
||||
let mut fills = before.fills.clone();
|
||||
for paint in &mut fills {
|
||||
let PaintKind::Image(img) = &mut paint.kind else { continue };
|
||||
// A repeating image cannot be represented by a single Crop placement.
|
||||
if img.scale_mode == ImageScaleMode::Tile {
|
||||
continue;
|
||||
}
|
||||
let Some(data) = doc.images.get(&img.image) else { continue };
|
||||
let (iw, ih) = (f64::from(data.width), f64::from(data.height));
|
||||
// A degenerate (zero-scale) layer has no inverse: its image keeps its placement.
|
||||
let crop = (Affine::new(img.placement_crop(iw, ih, w, h)) * to_before).as_coeffs();
|
||||
if !crop.iter().all(|c| c.is_finite()) {
|
||||
continue;
|
||||
}
|
||||
img.crop = Some(crop);
|
||||
img.scale_mode = ImageScaleMode::Crop;
|
||||
}
|
||||
fills
|
||||
}
|
||||
|
||||
/// The extent `lo..hi` an image of extent `image` lets a crop reach on one axis of a layer that
|
||||
/// started `len` long: the image's, or the layer's where that reaches further (a Fit image is
|
||||
/// smaller than its layer).
|
||||
fn crop_reach(image: (f64, f64), len: f64) -> (f64, f64) {
|
||||
(image.0.min(image.1).min(0.0), image.0.max(image.1).max(len))
|
||||
}
|
||||
|
||||
/// The dragged box `(x0, y0, x1, y1)` drawn back towards the starting box `(0, 0, w0, h0)` until
|
||||
/// its sides stop at the image's box `image` (see [`crop_reach`]). Both ends of an axis go back by
|
||||
/// the same fraction, so an Alt resize stays centred, and with `keep` (Shift) both axes do, so the
|
||||
/// ratio holds. A flipped axis stays as dragged.
|
||||
fn within_the_image((x0, y0, x1, y1): (f64, f64, f64, f64), image: (f64, f64, f64, f64), (w0, h0): (f64, f64), keep: bool) -> (f64, f64, f64, f64) {
|
||||
let fraction = |a: f64, b: f64, image: (f64, f64), len: f64| {
|
||||
if b < a {
|
||||
return 1.0;
|
||||
}
|
||||
let (lo, hi) = crop_reach(image, len);
|
||||
let mut t: f64 = 1.0;
|
||||
if a < lo {
|
||||
t = t.min(lo / a);
|
||||
}
|
||||
if b > hi {
|
||||
t = t.min((hi - len) / (b - len));
|
||||
}
|
||||
if t.is_finite() { t.clamp(0.0, 1.0) } else { 0.0 }
|
||||
};
|
||||
let (tx, ty) = (fraction(x0, x1, (image.0, image.2), w0), fraction(y0, y1, (image.1, image.3), h0));
|
||||
let (tx, ty) = if keep { (tx.min(ty), tx.min(ty)) } else { (tx, ty) };
|
||||
(x0 * tx, y0 * ty, w0 + (x1 - w0) * tx, h0 + (y1 - h0) * ty)
|
||||
}
|
||||
|
||||
/// Where a crop box `len` long, placed at `start` on one axis, starts once it is slid back onto
|
||||
/// the image (see [`crop_reach`]): layout can make a layer longer than it was dragged (a minimum
|
||||
/// size), and the crop then moves along the image rather than past its edge. A flipped axis, or
|
||||
/// a box longer than the reach, stays where it is.
|
||||
fn slid_onto_the_image(start: f64, len: f64, flipped: bool, image: (f64, f64), len0: f64) -> f64 {
|
||||
let (lo, hi) = crop_reach(image, len0);
|
||||
if flipped || len.is_nan() || len > hi - lo {
|
||||
return start;
|
||||
}
|
||||
start.max(lo).min(hi - len)
|
||||
}
|
||||
@@ -30,7 +30,10 @@ impl Session {
|
||||
let tool = self.tool.tool;
|
||||
let mut p = ev.p();
|
||||
let mut guides = Vec::new();
|
||||
let pixel = self.ds().map(|d| d.view.snap_pixel).unwrap_or(true);
|
||||
// Frames and sections land on whole pixels whatever the setting, also where a layer they
|
||||
// snap to doesn't (see `snap::always_on_pixels`).
|
||||
let board = matches!(tool, ToolId::Frame | ToolId::Section);
|
||||
let pixel = board || self.ds().map(|d| d.view.snap_pixel).unwrap_or(true);
|
||||
// The pixel grid first: snapping to layers comes after, so it wins on the axes it snaps.
|
||||
if pixel {
|
||||
p = Point::new(p.x.round(), p.y.round());
|
||||
@@ -41,6 +44,9 @@ impl Session {
|
||||
p.y += dy;
|
||||
guides = g;
|
||||
}
|
||||
if board {
|
||||
p = Point::new(p.x.round(), p.y.round());
|
||||
}
|
||||
let mut created = id;
|
||||
let page = self.page()?;
|
||||
// Edit ▸ Set default properties: what new shapes take (not frames, sections, slices, lines
|
||||
@@ -100,6 +106,9 @@ impl Session {
|
||||
n.transform = pw.inverse() * Affine::translate((r.x0, r.y0));
|
||||
}
|
||||
doc.insert(n, parent, None)?;
|
||||
if board {
|
||||
crate::snap::settle_on_pixels(doc, nid)?;
|
||||
}
|
||||
if let Some(d) = &defaults {
|
||||
// Best effort: a default the shape can't take leaves it as drawn.
|
||||
let _ = crate::cmd::edit::apply_copied_props("edit.setDefaultProperties", doc, nid, d);
|
||||
@@ -156,6 +165,11 @@ impl Session {
|
||||
}
|
||||
// A layer can't go into itself; it stays where it is.
|
||||
let _ = d.reparent(*m, target, None);
|
||||
// Frames, sections and components land on whole pixels of the frame
|
||||
// they are dropped into too.
|
||||
if d.node(*m).is_some_and(crate::snap::always_on_pixels) {
|
||||
crate::snap::settle_on_pixels(d, *m)?;
|
||||
}
|
||||
}
|
||||
crate::normalize(ds.doc_mut(), &before);
|
||||
}
|
||||
|
||||
@@ -642,10 +642,12 @@ fn index(cmd: &str, p: &Value, key: &str) -> Result<usize> {
|
||||
}
|
||||
|
||||
/// Delete the points and segments of `parts` (`heal` keeps paths through deleted points closed).
|
||||
pub(crate) fn delete_selection(s: &mut Session, parts: Vec<EditPart>, heal: bool) -> Result<()> {
|
||||
pub(crate) fn delete_selection(s: &mut Session, parts: Vec<EditPart>, heal: bool, then_select_next: bool) -> Result<()> {
|
||||
let doc = s.doc_mut()?;
|
||||
let mut next = Vec::new();
|
||||
for EditPart { id, vertices: verts, segments: segs } in parts {
|
||||
edit(doc, id, |net| {
|
||||
let following = edit(doc, id, |net| {
|
||||
let following = if then_select_next { points_following(net, &verts) } else { Vec::new() };
|
||||
// Segments first (their indices refer to the network before points go).
|
||||
let segs: Vec<usize> =
|
||||
segs.into_iter().filter(|si| net.segments.get(*si).is_some_and(|x| !verts.contains(&x.a) && !verts.contains(&x.b))).collect();
|
||||
@@ -654,15 +656,52 @@ pub(crate) fn delete_selection(s: &mut Session, parts: Vec<EditPart>, heal: bool
|
||||
// Point indices may have shifted: find them again by position.
|
||||
let now: Vec<usize> = pts.iter().filter_map(|p| net.vertices.iter().position(|v| v.point() == *p)).collect();
|
||||
ops::delete_vertices(net, &now, heal);
|
||||
following.iter().filter_map(|p| net.vertices.iter().position(|v| v.point() == *p)).collect::<Vec<usize>>()
|
||||
})?;
|
||||
next.push((id, following));
|
||||
}
|
||||
set_state(s, |ve| {
|
||||
ve.clear_selection();
|
||||
ve.anchor = None;
|
||||
ve.pen_out = None;
|
||||
for (id, following) in next {
|
||||
if id == ve.id {
|
||||
ve.vertices = following;
|
||||
} else if let Some(o) = ve.others.iter_mut().find(|o| o.id == id) {
|
||||
o.vertices = following;
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn points_following(net: &VectorNetwork, deleted: &[usize]) -> Vec<Point> {
|
||||
let step = |from: usize, forward: bool| {
|
||||
net.segments.iter().find_map(|sg| match forward {
|
||||
true => (sg.a == from).then_some(sg.b),
|
||||
false => (sg.b == from).then_some(sg.a),
|
||||
})
|
||||
};
|
||||
let mut out: Vec<Point> = Vec::new();
|
||||
for &v in deleted {
|
||||
let found = [true, false].into_iter().find_map(|forward| {
|
||||
let mut at = v;
|
||||
for _ in 0..net.vertices.len() {
|
||||
at = step(at, forward)?;
|
||||
if !deleted.contains(&at) {
|
||||
return Some(at);
|
||||
}
|
||||
}
|
||||
None
|
||||
});
|
||||
if let Some(p) = found.and_then(|i| net.vertices.get(i)).map(|x| x.point())
|
||||
&& !out.contains(&p)
|
||||
{
|
||||
out.push(p);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The points a command acts on, per layer: `vertices` names points of the active layer; without
|
||||
/// it, every edited layer's selected points (with `ends`, the ends of selected segments too).
|
||||
fn point_sets(s: &Session, p: &Value, ends: bool) -> Result<Vec<(NodeId, Vec<usize>)>> {
|
||||
@@ -1112,7 +1151,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
}),
|
||||
spec!("vector.deleteHeal", "Delete and heal selection", "{vertices?} (default the selected points of every edited layer)", true, |s, p| {
|
||||
let parts = point_sets(s, p, false)?.into_iter().map(|(id, vertices)| EditPart { id, vertices, segments: vec![] }).collect();
|
||||
delete_selection(s, parts, true)?;
|
||||
delete_selection(s, parts, true, true)?;
|
||||
Ok(json!({"ok": true}))
|
||||
}),
|
||||
spec!("vector.edit.delete", "Delete points", "{vertices?, segments?} (default the selection in every edited layer)", true, |s, p| {
|
||||
@@ -1121,7 +1160,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
(None, None) => ve.parts(),
|
||||
(v, sg) => vec![EditPart { id: ve.id, vertices: v.unwrap_or_default(), segments: sg.unwrap_or_default() }],
|
||||
};
|
||||
delete_selection(s, parts, false)?;
|
||||
delete_selection(s, parts, false, true)?;
|
||||
Ok(json!({"ok": true}))
|
||||
}),
|
||||
spec!("vector.edit.cornerRadius", "Point corner radius", "{radius, vertices?}", true, |s, p| {
|
||||
|
||||
@@ -24,6 +24,7 @@ use instance::{detach, make_slot, push_changes, remove_slot, reset_instance, res
|
||||
pub(crate) use instance::{swap_at, swap_instance};
|
||||
use props::{add_prop, bind_prop, delete_prop, edit_prop, set_props};
|
||||
pub(crate) use props::{apply_prop_bindings, check_prop_binding, describe_props};
|
||||
pub(crate) use variants::fit_set;
|
||||
use variants::{add_variant, combine, create_set};
|
||||
pub use variants::{can_add_variant, can_combine_variants, can_create_set};
|
||||
|
||||
|
||||
@@ -166,7 +166,7 @@ pub(super) fn create_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
/// Grow a component set so it wraps its variants with 20 px of padding (right and bottom).
|
||||
pub(super) fn fit_set(doc: &mut Document, set: NodeId) {
|
||||
pub(crate) fn fit_set(doc: &mut Document, set: NodeId) {
|
||||
let Some(kids) = doc.node(set).map(|n| n.children.clone()) else { return };
|
||||
let (mut w, mut h) = (0.0f64, 0.0f64);
|
||||
for c in kids {
|
||||
|
||||
@@ -358,7 +358,14 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Move layer into",
|
||||
"{ids?, parent, index? (final position among parent's children, bottom first; default top)}",
|
||||
true,
|
||||
reparent
|
||||
|s, p| reparent(s, p, "node.reparent", false)
|
||||
),
|
||||
spec!(
|
||||
"layers.reparent",
|
||||
"Move layer into",
|
||||
"{ids (in the destination's stored child order), parent, index? (final position among parent's children, bottom first; default top)}",
|
||||
true,
|
||||
|s, p| reparent(s, p, "layers.reparent", true)
|
||||
),
|
||||
spec!("node.reorder", "Reorder layer", "{id, index}", true, |s, p| {
|
||||
let i = req_id("node.reorder", p, "id")?;
|
||||
|
||||
@@ -127,6 +127,7 @@ pub(super) fn paste_design_layers(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// A design-app paste replaces the copied layers, not the copied rows: a `fill.copy` before it
|
||||
// still pastes afterwards.
|
||||
let props = s.clipboard.props.take();
|
||||
let props_source_doc = s.clipboard.props_source_doc;
|
||||
let paint = s.clipboard.paint.take();
|
||||
let stroke = s.clipboard.stroke.take();
|
||||
let paint_images = std::mem::take(&mut s.clipboard.paint_images);
|
||||
@@ -138,6 +139,7 @@ pub(super) fn paste_design_layers(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
nodes,
|
||||
images,
|
||||
props,
|
||||
props_source_doc,
|
||||
paint,
|
||||
stroke,
|
||||
paint_images,
|
||||
@@ -219,8 +221,18 @@ pub(super) fn cut(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
delete(s, &json!({"ids": layers}))
|
||||
}
|
||||
|
||||
/// Paste the clipboard under `parent` with the copied top-left moved to `at` (page coords).
|
||||
/// Paste the clipboard under `parent` with the copied top-left moved to `at` (page coords). A
|
||||
/// copied main is pasted as an instance of it; in another file, as an instance of it from the
|
||||
/// library the source file publishes, and as a copy of it when that library doesn't offer it.
|
||||
pub fn paste_into(s: &mut Session, parent: NodeId, at: Option<(f64, f64)>) -> Result<Vec<NodeId>> {
|
||||
paste_layers(s, parent, at, false)
|
||||
}
|
||||
|
||||
/// [`paste_into`]. With `as_variants`, copied variants pasted into `parent`, their own set, are
|
||||
/// deep copies (new variants, as Duplicate makes) and the set grows to hold them. Only a plain
|
||||
/// paste with that set, or a layer in it, selected asks for this; every other paste of a copied
|
||||
/// main, into another set too, still makes an instance.
|
||||
fn paste_layers(s: &mut Session, parent: NodeId, at: Option<(f64, f64)>, as_variants: bool) -> Result<Vec<NodeId>> {
|
||||
let clip = s.clipboard.clone();
|
||||
if clip.nodes.is_empty() {
|
||||
return Err(EngineError::Disabled("edit.paste".into(), "the clipboard is empty".into()));
|
||||
@@ -238,15 +250,20 @@ pub fn paste_into(s: &mut Session, parent: NodeId, at: Option<(f64, f64)>) -> Re
|
||||
(Some((x, y)), Some(b)) => Affine::translate((x - b.x0, y - b.y0)),
|
||||
_ => Affine::IDENTITY,
|
||||
};
|
||||
let into_set = as_variants && copy_local && copied_variants_set(doc, &clip.nodes) == Some(parent);
|
||||
let mut out = Vec::new();
|
||||
let mut all = BTreeMap::new();
|
||||
for (root, nodes) in &clip.nodes {
|
||||
if copy_local
|
||||
&& clip.copied_components.contains(root)
|
||||
&& let Some(n) = nodes.first().filter(|n| matches!(n.kind, NodeKind::Component { .. }))
|
||||
&& doc.node(*root).is_some_and(|n| matches!(n.kind, NodeKind::Component { .. }))
|
||||
{
|
||||
let instance = crate::components::create_instance(doc, *root, parent, 0.0, 0.0)?;
|
||||
let copied_main = nodes.first().filter(|n| clip.copied_components.contains(root) && matches!(n.kind, NodeKind::Component { .. }));
|
||||
let main = match (copied_main, foreign) {
|
||||
(Some(_), _) if copy_local => {
|
||||
(!into_set && doc.node(*root).is_some_and(|n| matches!(n.kind, NodeKind::Component { .. }))).then_some(*root)
|
||||
}
|
||||
(Some(_), Some(src)) => crate::library::published_main(doc, src, clip.source_path.as_deref(), *root)?,
|
||||
_ => None,
|
||||
};
|
||||
if let (Some(main), Some(n)) = (main, copied_main) {
|
||||
let instance = crate::components::create_instance(doc, main, parent, 0.0, 0.0)?;
|
||||
doc.get_mut(instance)?.transform = doc.world_transform(parent).inverse() * shift * n.transform;
|
||||
keep_a_cropped_images_proportions(doc, instance, parent);
|
||||
out.push(instance);
|
||||
@@ -267,6 +284,9 @@ pub fn paste_into(s: &mut Session, parent: NodeId, at: Option<(f64, f64)>) -> Re
|
||||
out.push(pasted);
|
||||
all.extend(map);
|
||||
}
|
||||
if into_set {
|
||||
crate::cmd::component::fit_set(doc, parent);
|
||||
}
|
||||
// Board connectors pasted with what they join join the pasted copies.
|
||||
let originals: Vec<(NodeId, figcraft_doc::BoardItem)> =
|
||||
clip.nodes.iter().flat_map(|(_, nodes)| nodes).filter_map(|n| Some((*all.get(&n.id)?, n.board.clone()?))).collect();
|
||||
@@ -307,7 +327,16 @@ pub(super) fn paste(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let sel = s.selection();
|
||||
let doc = s.doc()?;
|
||||
let copy_local = s.ds()?.uid == s.clipboard.source_doc;
|
||||
let target = id(p, "parent").or_else(|| {
|
||||
let variants_set = copied_variants_set(doc, &s.clipboard.nodes)
|
||||
.filter(|set| copy_local && id(p, "parent").is_none() && !sel.is_empty() && sel.iter().all(|i| doc.is_ancestor(*set, *i)));
|
||||
// Where the copied variants are now, not where they were copied: the set may have moved since.
|
||||
let below_the_variants = variants_set.and_then(|set| {
|
||||
let copied: Vec<NodeId> = s.clipboard.nodes.iter().map(|(root, _)| *root).collect();
|
||||
let left = doc.bounds_of(&copied)?.x0;
|
||||
let bottom = doc.node(set)?.children.iter().filter_map(|c| doc.world_bounds(*c)).map(|r| r.y1).reduce(f64::max)?;
|
||||
Some((left, bottom + 20.0))
|
||||
});
|
||||
let target = id(p, "parent").or(variants_set).or_else(|| {
|
||||
sel.first()
|
||||
.copied()
|
||||
.filter(|i| {
|
||||
@@ -322,6 +351,7 @@ pub(super) fn paste(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let parent = target.unwrap_or(page);
|
||||
let at = match (num(p, "x"), num(p, "y")) {
|
||||
(Some(x), Some(y)) => Some((x, y)),
|
||||
_ if below_the_variants.is_some() => below_the_variants,
|
||||
_ => {
|
||||
let b = s.clipboard.bounds;
|
||||
match (target, b) {
|
||||
@@ -344,7 +374,7 @@ pub(super) fn paste(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
};
|
||||
let ids = paste_into(s, parent, at)?;
|
||||
let ids = paste_layers(s, parent, at, variants_set.is_some())?;
|
||||
if let Some(sel) = sibling_of {
|
||||
let above = s.doc()?.index_in_parent(sel).map(|ix| ix + 1);
|
||||
move_above(s, &ids, parent, above)?;
|
||||
@@ -381,14 +411,27 @@ fn move_above(s: &mut Session, ids: &[NodeId], parent: NodeId, above: Option<usi
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The set the copied layers are variants of: every copied root is a main component in `doc` whose
|
||||
/// parent is that one component set. `None` for anything else.
|
||||
fn copied_variants_set(doc: &Document, copied: &[(NodeId, Vec<Node>)]) -> Option<NodeId> {
|
||||
let mut sets = copied.iter().map(|(root, _)| {
|
||||
let n = doc.node(*root).filter(|n| matches!(n.kind, NodeKind::Component { .. }))?;
|
||||
n.parent.filter(|set| doc.node(*set).is_some_and(|p| matches!(p.kind, NodeKind::ComponentSet { .. })))
|
||||
});
|
||||
let first = sets.next()??;
|
||||
sets.all(|set| set == Some(first)).then_some(first)
|
||||
}
|
||||
|
||||
/// Paste over selection (Shift+Cmd/Ctrl+V): the copies go into the parent of the selected layer
|
||||
/// [`last_seen`] picks, just above it, at the place it gives.
|
||||
pub(super) fn paste_over(s: &mut Session, _p: &Value) -> Result<Value> {
|
||||
let sel = s.selection();
|
||||
let page = s.page()?;
|
||||
let doc = s.doc()?;
|
||||
let (parent, at, above) = match sel.first() {
|
||||
Some(i) => {
|
||||
let parent = doc.node(*i).and_then(|n| n.parent).unwrap_or(page);
|
||||
(parent, doc.world_bounds(*i).map(|b| (b.x0, b.y0)), doc.index_in_parent(*i).map(|ix| ix + 1))
|
||||
let (parent, at, above) = match last_seen(doc, &sel) {
|
||||
Some((i, at)) => {
|
||||
let parent = doc.node(i).and_then(|n| n.parent).unwrap_or(page);
|
||||
(parent, at, doc.index_in_parent(i).map(|ix| ix + 1))
|
||||
}
|
||||
None => (page, None, None),
|
||||
};
|
||||
@@ -398,6 +441,38 @@ pub(super) fn paste_over(s: &mut Session, _p: &Value) -> Result<Value> {
|
||||
Ok(json!({"ids": ids}))
|
||||
}
|
||||
|
||||
/// The selected layer Paste over selection pastes after, and where the copies' top-left goes.
|
||||
///
|
||||
/// One layer: that layer, at its position. Several in one auto layout frame's flow (none absolutely
|
||||
/// positioned): the last of them in the flow, which the layout follows. Several elsewhere: the lowest (then rightmost), with the copies
|
||||
/// below it, as far below as it is from the selected layers above it. A selection with nothing above
|
||||
/// its lowest layer is a row: the copies go right of the rightmost, as far as it is from its
|
||||
/// neighbour on the left. Layers that overlap every way get the copies right under the lowest.
|
||||
fn last_seen(doc: &Document, sel: &[NodeId]) -> Option<(NodeId, Option<(f64, f64)>)> {
|
||||
let first = *sel.first()?;
|
||||
let top_left = |i: NodeId| doc.world_bounds(i).map(|b| (b.x0, b.y0));
|
||||
if sel.len() == 1 {
|
||||
return Some((first, top_left(first)));
|
||||
}
|
||||
let parent = doc.node(first).and_then(|n| n.parent);
|
||||
let one_flow = parent.and_then(|p| doc.node(p)).is_some_and(|p| p.layout.is_some())
|
||||
&& sel.iter().all(|i| doc.node(*i).is_some_and(|n| n.parent == parent && !n.child_layout.absolute));
|
||||
if one_flow {
|
||||
let last = sel.iter().copied().max_by_key(|i| doc.index_in_parent(*i))?;
|
||||
return Some((last, top_left(last)));
|
||||
}
|
||||
let boxes: Vec<(NodeId, figcraft_geom::Rect)> = sel.iter().filter_map(|i| Some((*i, doc.world_bounds(*i)?))).collect();
|
||||
let (lowest, low) = *boxes.iter().max_by(|(_, a), (_, b)| a.y1.total_cmp(&b.y1).then(a.x1.total_cmp(&b.x1)))?;
|
||||
if let Some(above) = boxes.iter().filter(|(_, o)| o.y1 <= low.y0).map(|(_, o)| o.y1).max_by(f64::total_cmp) {
|
||||
return Some((lowest, Some((low.x0, low.y1 + (low.y0 - above)))));
|
||||
}
|
||||
let (rightmost, right) = *boxes.iter().max_by(|(_, a), (_, b)| a.x1.total_cmp(&b.x1).then(a.y1.total_cmp(&b.y1)))?;
|
||||
match boxes.iter().filter(|(_, o)| o.x1 <= right.x0).map(|(_, o)| o.x1).max_by(f64::total_cmp) {
|
||||
Some(left) => Some((rightmost, Some((right.x1 + (right.x0 - left), right.y0)))),
|
||||
None => Some((lowest, Some((low.x0, low.y1)))),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn paste_replace(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let targets = req_targets("edit.pasteReplace", s, p)?;
|
||||
let mut out = Vec::new();
|
||||
@@ -438,7 +513,19 @@ pub(super) fn copy_props_of(doc: &Document, id: NodeId) -> Value {
|
||||
v["cornerRadius"] = json!(n.corners.radii);
|
||||
v["cornerSmoothing"] = json!(n.corners.smoothing);
|
||||
}
|
||||
// A frame's layout grids go with its look, as its fills do.
|
||||
if n.kind.is_frame_like() {
|
||||
v["grids"] = json!(n.grids);
|
||||
v["gridStyle"] = json!(n.styles.grid);
|
||||
}
|
||||
// The links behind the values: the styles and the variables they come from, so the pasted
|
||||
// layer follows them as the copied one does.
|
||||
v["fillStyle"] = json!(n.styles.fill);
|
||||
v["strokeStyle"] = json!(n.styles.stroke);
|
||||
v["effectStyle"] = json!(n.styles.effect);
|
||||
v["boundVariables"] = Value::Object(n.bound.iter().filter(|(f, _)| copied_binding(f)).map(|(f, v)| (f.clone(), json!(v))).collect());
|
||||
if let NodeKind::Text(t) = &n.kind {
|
||||
v["textStyle"] = json!(n.styles.text);
|
||||
v["fontFamily"] = json!(t.style.font_family);
|
||||
v["fontStyle"] = json!(t.style.font_style);
|
||||
v["fontSize"] = json!(t.style.font_size);
|
||||
@@ -453,26 +540,110 @@ pub(super) fn copy_props(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = targets(s, p).first().copied().ok_or_else(|| bad("edit.copyProperties", "select one layer"))?;
|
||||
let v = copy_props_of(s.doc()?, id);
|
||||
s.clipboard.props = Some(v.clone());
|
||||
s.clipboard.props_source_doc = s.ds()?.uid;
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
/// Copied properties `props` without their style and variable links, for a paste into another
|
||||
/// file: the copied ids name the source file's styles and variables, and the same ids here can
|
||||
/// name unrelated ones. The values paste unlinked, and the layer's own links on them go.
|
||||
fn without_links(mut props: Value) -> Value {
|
||||
if let Some(m) = props.as_object_mut() {
|
||||
for (k, v) in m.iter_mut() {
|
||||
if k.ends_with("Style") && !k.starts_with("font") {
|
||||
*v = Value::Null;
|
||||
} else if k == "boundVariables" {
|
||||
*v = json!({});
|
||||
}
|
||||
}
|
||||
}
|
||||
props
|
||||
}
|
||||
|
||||
/// Give layer `id` the properties [`copy_props_of`] copied (`props`), those it can take: the text
|
||||
/// properties only to text, the corners only to a layer with corners.
|
||||
pub(crate) fn apply_copied_props(cmd: &str, doc: &mut Document, id: NodeId, props: &Value) -> Result<()> {
|
||||
let mut m = props.as_object().cloned().unwrap_or_default();
|
||||
let is_text = matches!(doc.get(id)?.kind, NodeKind::Text(_));
|
||||
if !is_text {
|
||||
m.retain(|k, _| !k.starts_with("font") && k != "lineHeight" && k != "letterSpacing");
|
||||
let n = doc.get(id)?;
|
||||
let (is_text, corners, frame) = (matches!(n.kind, NodeKind::Text(_)), n.kind.has_corner_radius(), n.kind.is_frame_like());
|
||||
let takes = |k: &str| {
|
||||
let text = k.starts_with("font") || k.starts_with("paragraph") || matches!(k, "lineHeight" | "letterSpacing" | "textStyle");
|
||||
let corner = k == "cornerSmoothing" || k.ends_with("Radius");
|
||||
let grid = k == "gridStyle" || k == "grids" || k.starts_with("layoutGrids/");
|
||||
(is_text || !text) && (corners || !corner) && (frame || !grid)
|
||||
};
|
||||
m.retain(|k, _| takes(k));
|
||||
// A style or variable the file doesn't have (deleted since the copy) isn't here to link to: the
|
||||
// values it gave are pasted without a link, so the layer's own link goes too.
|
||||
let here = |v: &Value| v.as_str().is_none_or(|sid| doc.style(sid).is_some());
|
||||
for (k, v) in m.iter_mut() {
|
||||
if k.ends_with("Style") && !k.starts_with("font") && !here(v) {
|
||||
*v = Value::Null;
|
||||
}
|
||||
}
|
||||
if !doc.get(id)?.kind.has_corner_radius() {
|
||||
m.remove("cornerRadius");
|
||||
m.remove("cornerSmoothing");
|
||||
if let Some(Value::Object(copied)) = m.get_mut("boundVariables") {
|
||||
copied.retain(|_, v| v.as_str().is_some_and(|vid| doc.variables.get_by_id(vid).is_some()));
|
||||
}
|
||||
// The layer's own bindings on what is pasted give way to the copied layer's: kept, a binding
|
||||
// would hold the old value over the pasted one. A binding on what the copy doesn't carry (a
|
||||
// text layer's font size, pasted from a frame) stays.
|
||||
if let Some(Value::Object(copied)) = m.get("boundVariables") {
|
||||
let mut bound: serde_json::Map<String, Value> =
|
||||
n.bound.keys().filter(|f| copied_binding(f) && m.contains_key(pasted_key(f))).map(|f| (f.clone(), Value::Null)).collect();
|
||||
bound.extend(copied.iter().filter(|(f, _)| takes(f)).map(|(f, v)| (f.clone(), v.clone())));
|
||||
m.insert("boundVariables".into(), Value::Object(bound));
|
||||
}
|
||||
crate::cmd::props::apply(cmd, doc, id, &m)
|
||||
}
|
||||
|
||||
/// The key of the properties [`copy_props_of`] copies that sets what a variable bound to `field`
|
||||
/// sets: a corner's radius is `cornerRadius`, a side's stroke weight `strokeWeight`, the font
|
||||
/// weight `fontStyle`, a layout grid's field `grids` and a paint's or effect's field its list.
|
||||
fn pasted_key(field: &str) -> &str {
|
||||
match field {
|
||||
"topLeftRadius" | "topRightRadius" | "bottomRightRadius" | "bottomLeftRadius" => "cornerRadius",
|
||||
f if crate::cmd::props::STROKE_SIDES.contains(&f) => "strokeWeight",
|
||||
"fontWeight" => "fontStyle",
|
||||
f => match f.split_once('/') {
|
||||
Some(("layoutGrids", _)) => "grids",
|
||||
Some((list, _)) => list,
|
||||
None => f,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a variable bound to `field` goes with the properties [`copy_props_of`] copies: not a
|
||||
/// size, auto layout spacing, visibility or text content.
|
||||
fn copied_binding(field: &str) -> bool {
|
||||
!matches!(
|
||||
field,
|
||||
"width"
|
||||
| "height"
|
||||
| "minWidth"
|
||||
| "maxWidth"
|
||||
| "minHeight"
|
||||
| "maxHeight"
|
||||
| "gap"
|
||||
| "columnGap"
|
||||
| "rowGap"
|
||||
| "crossGap"
|
||||
| "padding"
|
||||
| "paddingHorizontal"
|
||||
| "paddingVertical"
|
||||
| "paddingTop"
|
||||
| "paddingRight"
|
||||
| "paddingBottom"
|
||||
| "paddingLeft"
|
||||
| "visible"
|
||||
| "characters"
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) fn paste_props(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let props = s.clipboard.props.clone().ok_or_else(|| EngineError::Disabled("edit.pasteProperties".into(), "no copied properties".into()))?;
|
||||
let mut props = s.clipboard.props.clone().ok_or_else(|| EngineError::Disabled("edit.pasteProperties".into(), "no copied properties".into()))?;
|
||||
if s.ds()?.uid != s.clipboard.props_source_doc {
|
||||
props = without_links(props);
|
||||
}
|
||||
let ids = req_targets("edit.pasteProperties", s, p)?;
|
||||
let doc = s.doc_mut()?;
|
||||
for i in ids {
|
||||
|
||||
@@ -268,12 +268,13 @@ pub(super) fn stroke_brush(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
ok()
|
||||
}
|
||||
|
||||
pub(super) fn reparent(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids = req_targets("node.reparent", s, p)?;
|
||||
let parent = req_id("node.reparent", p, "parent")?;
|
||||
let index = opt_index("node.reparent", p, "index")?;
|
||||
pub(super) fn reparent(s: &mut Session, p: &Value, cmd: &str, keep_order: bool) -> Result<Value> {
|
||||
let ids = req_targets(cmd, s, p)?;
|
||||
let parent = req_id(cmd, p, "parent")?;
|
||||
let index = opt_index(cmd, p, "index")?;
|
||||
let doc = s.doc_mut()?;
|
||||
let ids = z_sorted(doc, &roots(doc, &ids));
|
||||
let roots = roots(doc, &ids);
|
||||
let ids = if keep_order { roots } else { z_sorted(doc, &roots) };
|
||||
// `index` is where the first moved layer ends up among the parent's children (bottom first),
|
||||
// counted after the move, the way `node.reorder` counts it. The layers land together, keeping
|
||||
// their order, under the sibling that stays put and ends up just after them (none: on top).
|
||||
@@ -445,20 +446,58 @@ fn paint_set_in(s: &mut Session, p: &Value, fills: bool, to_regions: bool) -> Re
|
||||
}
|
||||
};
|
||||
if let Some((id, regions)) = fill_regions(s, cmd, p, &ids)?.filter(|_| fills && to_regions) {
|
||||
let (nw, nh) = s.doc().ok().and_then(|d| d.node(id)).map_or((100.0, 100.0), |n| (n.width, n.height));
|
||||
let image_dims = s.doc().ok().and_then(|d| match &new_paint {
|
||||
Some(figcraft_color::Paint { kind: figcraft_color::PaintKind::Image(img), .. })
|
||||
if img.scale_mode == figcraft_color::ImageScaleMode::Crop =>
|
||||
{
|
||||
d.images.get(&img.image).map(|data| (f64::from(data.width), f64::from(data.height)))
|
||||
}
|
||||
_ => None,
|
||||
});
|
||||
edit_region_fills(s.doc_mut()?, id, ®ions, |list| {
|
||||
if list.is_empty() {
|
||||
list.push(figcraft_color::Paint::solid(figcraft_color::Color::DEFAULT_SHAPE));
|
||||
}
|
||||
let at = idx.unwrap_or(list.len().saturating_sub(1));
|
||||
let Some(slot) = list.get_mut(at) else { return Err(bad(cmd, format!("no paint at index {at}"))) };
|
||||
let old = slot.clone();
|
||||
edit_slot(slot);
|
||||
if let Some((iw, ih)) = image_dims
|
||||
&& let figcraft_color::PaintKind::Image(img) = &mut slot.kind
|
||||
&& img.scale_mode == figcraft_color::ImageScaleMode::Crop
|
||||
{
|
||||
match &old.kind {
|
||||
figcraft_color::PaintKind::Image(old_img) if old_img.image == img.image => {
|
||||
if old_img.rotation != img.rotation {
|
||||
img.crop = None;
|
||||
img.crop = Some(img.placement_crop(iw, ih, nw, nh));
|
||||
} else if img.crop.is_none() {
|
||||
img.crop = Some(old_img.placement_crop(iw, ih, nw, nh));
|
||||
} else if regions.len() > 1 && old_img.scale_mode == figcraft_color::ImageScaleMode::Crop {
|
||||
img.crop = old_img.crop;
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
if img.crop.is_none() {
|
||||
img.crop = Some(img.placement_crop(iw, ih, nw, nh));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
return ok();
|
||||
}
|
||||
let image_dims = s.doc().ok().and_then(|d| match &new_paint {
|
||||
Some(figcraft_color::Paint { kind: figcraft_color::PaintKind::Image(img), .. }) if img.scale_mode == figcraft_color::ImageScaleMode::Crop => {
|
||||
d.images.get(&img.image).map(|data| (f64::from(data.width), f64::from(data.height)))
|
||||
}
|
||||
_ => None,
|
||||
});
|
||||
let doc = s.doc_mut()?;
|
||||
for i in ids {
|
||||
let n = doc.get_mut(i)?;
|
||||
for i in &ids {
|
||||
let n = doc.get_mut(*i)?;
|
||||
if fills {
|
||||
crate::cmd::lists::take_character_fills(n);
|
||||
}
|
||||
@@ -470,6 +509,28 @@ fn paint_set_in(s: &mut Session, p: &Value, fills: bool, to_regions: bool) -> Re
|
||||
let Some(slot) = list.get_mut(at) else { return Err(bad(cmd, format!("no paint at index {at}"))) };
|
||||
let old = slot.clone();
|
||||
edit_slot(slot);
|
||||
if let Some((iw, ih)) = image_dims
|
||||
&& let figcraft_color::PaintKind::Image(img) = &mut slot.kind
|
||||
&& img.scale_mode == figcraft_color::ImageScaleMode::Crop
|
||||
{
|
||||
match &old.kind {
|
||||
figcraft_color::PaintKind::Image(old_img) if old_img.image == img.image => {
|
||||
if old_img.rotation != img.rotation {
|
||||
img.crop = None;
|
||||
img.crop = Some(img.placement_crop(iw, ih, n.width, n.height));
|
||||
} else if img.crop.is_none() {
|
||||
img.crop = Some(old_img.placement_crop(iw, ih, n.width, n.height));
|
||||
} else if ids.len() > 1 && old_img.scale_mode == figcraft_color::ImageScaleMode::Crop {
|
||||
img.crop = old_img.crop;
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
if img.crop.is_none() {
|
||||
img.crop = Some(img.placement_crop(iw, ih, n.width, n.height));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
crate::cmd::lists::rebind_edited_paint(n, fills, at, &old);
|
||||
if fills {
|
||||
n.styles.fill = None;
|
||||
|
||||
@@ -154,7 +154,7 @@ pub(super) fn cut_selection(s: &mut Session, sel: EditSelection) -> Result<Value
|
||||
}
|
||||
let cut = sel.parts.len();
|
||||
let segments = copy_parts(s, "edit.cut", &sel)?;
|
||||
vectoredit::delete_selection(s, sel.delete, false)?;
|
||||
vectoredit::delete_selection(s, sel.delete, false, false)?;
|
||||
Ok(json!({"cut": cut, "segments": segments}))
|
||||
}
|
||||
|
||||
|
||||
@@ -462,6 +462,7 @@ fn close(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let uid = ds.uid;
|
||||
let active_uid = s.docs.get(s.active).map(|d| d.uid);
|
||||
s.remember_view(i);
|
||||
s.remove_tabs(|d| d.uid == uid);
|
||||
// Removing a tab before the active one shifts its index; keep the same document selected.
|
||||
s.active = active_uid.and_then(|a| s.docs.iter().position(|d| d.uid == a)).unwrap_or(i.min(s.docs.len().saturating_sub(1)));
|
||||
|
||||
@@ -107,6 +107,7 @@ pub(crate) fn open(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
ds.on_disk = on_disk.filter(|_| native);
|
||||
s.docs.push(ds);
|
||||
s.active = s.docs.len() - 1;
|
||||
s.restore_view();
|
||||
let mut out = json!({"index": s.active, "summary": summary});
|
||||
out[if warnings { "warnings" } else { "repairs" }] = json!(loaded.issues);
|
||||
Ok(out)
|
||||
|
||||
@@ -173,7 +173,8 @@ fn wants_data(p: &Value) -> bool {
|
||||
|
||||
/// Save the file of the active tab (the main file for a branch tab, with its branches), or export
|
||||
/// the active document as an experimental `.fig` copy without changing its native save state.
|
||||
/// Without a path the file comes back as base64 `data` for the caller to deliver (#969).
|
||||
/// Without a path the file comes back as base64 `data` for the caller to deliver (#969). Saved
|
||||
/// to another file, the document takes that file's name, as its tab does.
|
||||
fn save_to(s: &mut Session, path: Option<String>) -> Result<Value> {
|
||||
if let Some(path) = path.as_deref().filter(|p| ext(p) == "fig") {
|
||||
return export_fig(s, &json!({"path": path}));
|
||||
@@ -185,9 +186,7 @@ fn save_to(s: &mut Session, path: Option<String>) -> Result<Value> {
|
||||
refuse_dropping_images(ds, path)?;
|
||||
}
|
||||
let mut snapshot = FileSnapshot::of(ds);
|
||||
let follows_path = ds.path.as_deref().map_or(ds.doc.name == "Untitled", |old| ds.doc.name == file_stem(old));
|
||||
if let Some(path) = path.as_deref()
|
||||
&& follows_path
|
||||
&& ds.path.as_deref() != Some(path)
|
||||
{
|
||||
Arc::make_mut(&mut snapshot.doc).name = file_stem(path);
|
||||
|
||||
@@ -234,6 +234,9 @@ fn crop(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// Like any paint edit, the layer leaves its paint style.
|
||||
n.styles.fill = None;
|
||||
}
|
||||
if s.ds()?.vector_edit.is_some() {
|
||||
crate::vectoredit::end(s)?;
|
||||
}
|
||||
s.request_ui(cmd, json!({"id": id, "index": index}));
|
||||
Ok(json!({"id": id, "index": index}))
|
||||
}
|
||||
|
||||
@@ -642,7 +642,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
spec!(
|
||||
"text.edit.key",
|
||||
"Text key",
|
||||
"{key: Backspace|Delete|Left|Right|Up|Down|Home|End|Enter|Tab|Escape|SelectAll, shift?, alt?, cmd?} in a list, Tab nests the item and Shift+Tab, Enter on an empty item or Backspace at its start move it out; in a code block, Tab types two spaces and Enter keeps the line's indent",
|
||||
"{key: Backspace|Delete|Left|Right|Up|Down|Home|End|Enter|Tab|Escape|SelectAll, shift?, alt?, cmd?} in a list, Tab nests the item and Shift+Tab, Enter on an empty item or Backspace at its start move it out; in a code block, Tab types two spaces and Enter keeps the line's indent; elsewhere Tab and Shift+Tab edit the next or previous text layer of the frame in reading order (rows top to bottom, each left to right), all of it selected, and do nothing at the last and the first (in a board object or a widget's field Tab types a tab)",
|
||||
true,
|
||||
|s, p| {
|
||||
let k = req_string("text.edit.key", p, "key")?;
|
||||
|
||||
@@ -298,3 +298,207 @@ 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}");
|
||||
}
|
||||
}
|
||||
|
||||
/// 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);
|
||||
}
|
||||
@@ -115,6 +115,7 @@ fn copying_a_variant_pastes_an_instance_but_copying_its_set_keeps_the_components
|
||||
let (set, _, hover) = button_set(&mut s);
|
||||
ex(&mut s, "select.set", json!({"ids": [hover]}));
|
||||
ex(&mut s, "edit.copy", json!({}));
|
||||
ex(&mut s, "select.set", json!({"ids": []}));
|
||||
let pasted = crate::params::id_of(&ex(&mut s, "edit.paste", json!({}))["ids"][0]).unwrap();
|
||||
assert_eq!(component_of(&s, pasted), hover);
|
||||
assert_eq!(node(&s, pasted).name, node(&s, set).name);
|
||||
@@ -241,6 +242,108 @@ fn alt_dragging_a_main_component_copies_an_instance() {
|
||||
healthy(&s);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pasting_a_variant_with_its_set_selected_adds_a_variant_below_the_others() {
|
||||
let mut s = Session::new();
|
||||
let (set, _, hover) = button_set(&mut s);
|
||||
let bounds = |s: &Session, i: NodeId| s.doc().unwrap().world_bounds(i).unwrap();
|
||||
let named = |s: &Session, i: NodeId, name: &str| kids(s, i).into_iter().find(|c| node(s, *c).name == name).unwrap();
|
||||
ex(&mut s, "select.set", json!({"ids": [hover]}));
|
||||
ex(&mut s, "edit.copy", json!({}));
|
||||
let bottom = kids(&s, set).iter().map(|k| bounds(&s, *k).y1).fold(f64::MIN, f64::max);
|
||||
let pasted = crate::params::id_of(&ex(&mut s, "edit.paste", json!({}))["ids"][0]).unwrap();
|
||||
assert!(matches!(node(&s, pasted).kind, NodeKind::Component { .. }));
|
||||
assert_eq!(node(&s, pasted).parent, Some(set));
|
||||
assert_eq!(kids(&s, set).len(), 3);
|
||||
assert_eq!(chars(&s, named(&s, pasted, "Label")), "Hover");
|
||||
let (b, h) = (bounds(&s, pasted), bounds(&s, hover));
|
||||
assert_eq!((b.x0, b.y0), (h.x0, bottom + 20.0));
|
||||
assert!(bounds(&s, set).y1 >= b.y1, "the set grows to hold it");
|
||||
|
||||
let label = named(&s, hover, "Label");
|
||||
ex(&mut s, "select.set", json!({"ids": [label]}));
|
||||
let second = crate::params::id_of(&ex(&mut s, "edit.paste", json!({}))["ids"][0]).unwrap();
|
||||
assert_eq!(node(&s, second).parent, Some(set), "a layer inside a variant selected");
|
||||
assert_eq!(bounds(&s, second).y0, b.y1 + 20.0);
|
||||
ex(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(kids(&s, set).len(), 3);
|
||||
healthy(&s);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_variant_pasted_into_its_set_after_the_set_moved_lands_under_the_variant() {
|
||||
let mut s = Session::new();
|
||||
let (set, _, hover) = button_set(&mut s);
|
||||
let bounds = |s: &Session, i: NodeId| s.doc().unwrap().world_bounds(i).unwrap();
|
||||
ex(&mut s, "select.set", json!({"ids": [hover]}));
|
||||
ex(&mut s, "edit.copy", json!({}));
|
||||
let x = bounds(&s, set).x0;
|
||||
ex(&mut s, "node.set", json!({"id": set, "props": {"x": x + 1000.0}}));
|
||||
let pasted = crate::params::id_of(&ex(&mut s, "edit.paste", json!({}))["ids"][0]).unwrap();
|
||||
let (b, h, sb) = (bounds(&s, pasted), bounds(&s, hover), bounds(&s, set));
|
||||
assert_eq!(b.x0, h.x0, "under the copied variant where it is now, not where it was copied");
|
||||
assert!(sb.x0 <= b.x0 && sb.x1 >= b.x1 && sb.y1 >= b.y1, "inside the set");
|
||||
healthy(&s);
|
||||
}
|
||||
|
||||
/// Copy `main`, select `selected` and run `command` with `params`; the first pasted layer.
|
||||
fn copy_then(s: &mut Session, main: NodeId, selected: &[NodeId], command: &str, params: Value) -> NodeId {
|
||||
ex(s, "select.set", json!({"ids": [main]}));
|
||||
ex(s, "edit.copy", json!({}));
|
||||
ex(s, "select.set", json!({"ids": selected}));
|
||||
crate::params::id_of(&ex(s, command, params)["ids"][0]).unwrap()
|
||||
}
|
||||
|
||||
// Only a plain paste with the copied variants' own set, or a layer in it, selected makes new
|
||||
// variants. Every other paste of a copied main into a set makes an instance of it there, as
|
||||
// before: the tests below.
|
||||
|
||||
#[test]
|
||||
fn a_variant_pasted_with_another_set_selected_is_an_instance() {
|
||||
let mut s = Session::new();
|
||||
let (set, _, hover) = button_set(&mut s);
|
||||
let (other, ..) = button_set(&mut s);
|
||||
ex(&mut s, "node.set", json!({"id": other, "props": {"y": 300}}));
|
||||
let pasted = copy_then(&mut s, hover, &[other], "edit.paste", json!({}));
|
||||
assert_eq!(component_of(&s, pasted), hover);
|
||||
assert_eq!(node(&s, pasted).parent, Some(other));
|
||||
assert_eq!((kids(&s, set).len(), kids(&s, other).len()), (2, 3));
|
||||
healthy(&s);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_main_that_is_no_variant_pasted_with_a_set_selected_is_an_instance() {
|
||||
let mut s = Session::new();
|
||||
let (set, ..) = button_set(&mut s);
|
||||
let k = kit(&mut s);
|
||||
let pasted = copy_then(&mut s, k.card, &[set], "edit.paste", json!({}));
|
||||
assert_eq!(component_of(&s, pasted), k.card);
|
||||
assert_eq!(node(&s, pasted).parent, Some(set));
|
||||
healthy(&s);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_variant_pasted_with_its_own_set_as_an_explicit_parent_is_an_instance() {
|
||||
let mut s = Session::new();
|
||||
let (set, _, hover) = button_set(&mut s);
|
||||
let pasted = copy_then(&mut s, hover, &[hover], "edit.paste", json!({"parent": set}));
|
||||
assert_eq!(component_of(&s, pasted), hover);
|
||||
assert_eq!(node(&s, pasted).parent, Some(set));
|
||||
healthy(&s);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pasting_over_or_replacing_a_variant_makes_an_instance_of_the_copied_variant() {
|
||||
for command in ["edit.pasteOver", "edit.pasteReplace"] {
|
||||
let mut s = Session::new();
|
||||
let (set, default, hover) = button_set(&mut s);
|
||||
let pasted = copy_then(&mut s, hover, &[default], command, json!({}));
|
||||
assert_eq!(component_of(&s, pasted), hover, "{command} on a variant of the copied variant's set");
|
||||
assert_eq!(node(&s, pasted).parent, Some(set), "{command}");
|
||||
healthy(&s);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicating_a_variant_adds_a_variant_to_its_set() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -407,3 +407,29 @@ fn a_join_stopped_at_its_budget_says_so() {
|
||||
let (some, complete) = crate::design_context::referenced(s.doc().unwrap(), &start, &none, 3);
|
||||
assert_eq!((some.len(), complete), (3, false), "{some:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn code_links_keep_their_value_names_and_carry_source_and_notes() {
|
||||
let mut s = session();
|
||||
let variants: Vec<_> = ["small", "extra_large"]
|
||||
.iter()
|
||||
.map(|v| {
|
||||
let f = node(&mut s, json!({"type": "frame", "name": format!("Size={v}"), "width": 80, "height": 32}));
|
||||
id(&s.execute("component.create", &json!({"ids": [f]})).unwrap())
|
||||
})
|
||||
.collect();
|
||||
let set = id(&s.execute("component.combineVariants", &json!({"ids": variants})).unwrap());
|
||||
s.execute(
|
||||
"codeConnect.set",
|
||||
&json!({"id": set, "name": "Button", "template": "<Button size={Size} />", "source": "src/button.tsx",
|
||||
"notes": "Use for main actions", "values": {"Size": {"extra_large": "xl"}}}),
|
||||
)
|
||||
.unwrap();
|
||||
let instance = id(&s.execute("instance.create", &json!({"component": variants[1]})).unwrap());
|
||||
let v = context(&mut s, json!({"ids": [instance]}));
|
||||
let link = &v["components"][set.to_string()]["codeLinks"][0];
|
||||
assert_eq!(link["values"]["Size"]["extra_large"], "xl", "a design value keeps its name: {link}");
|
||||
let code = &only(&v)["code"][0];
|
||||
assert_eq!((code["source"].as_str(), code["notes"].as_str()), (Some("src/button.tsx"), Some("Use for main actions")), "{code}");
|
||||
assert!(code["code"].as_str().unwrap().contains("xl"), "{code}");
|
||||
}
|
||||
@@ -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,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 {
|
||||
// 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.
|
||||
@@ -391,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
|
||||
@@ -454,6 +461,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 +482,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 +522,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 +545,12 @@ 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 !c.params.iter().any(|p| p.prop == *prop) && !unknown.iter().any(|u| u == prop) {
|
||||
unknown.push(prop.clone());
|
||||
}
|
||||
}
|
||||
Ok(unknown)
|
||||
}
|
||||
|
||||
@@ -557,12 +593,103 @@ 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 = link_fields(l);
|
||||
v["component"] = json!(component);
|
||||
v
|
||||
}
|
||||
|
||||
/// A link's own fields, as the connect file and `inspect.designContext` give them: its keys are
|
||||
/// the file's, and a mapping's property names and values stay as written.
|
||||
pub(crate) fn link_fields(l: &CodeLink) -> Value {
|
||||
let mut v = json!({"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_fields(l);
|
||||
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 +705,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 +743,34 @@ 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; 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";
|
||||
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 = 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());
|
||||
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 +790,18 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
]
|
||||
}
|
||||
|
||||
/// 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 Ok(serde_json::Map::new());
|
||||
}
|
||||
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"))),
|
||||
}
|
||||
}
|
||||
|
||||
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 +840,24 @@ fn import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
));
|
||||
continue;
|
||||
};
|
||||
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(),
|
||||
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() {
|
||||
|
||||
@@ -384,6 +384,10 @@ fn stroke_color(n: &Node) -> Option<Color> {
|
||||
/// The CSS borders a solid stroke makes: one `border`, or with individual stroke sides a border
|
||||
/// on each side that has a weight.
|
||||
fn css_borders(doc: &Document, n: &Node, t: &mut Tokens) -> Vec<(String, String)> {
|
||||
// A vector's stroke belongs to its path, not to a rectangle around its bounding box.
|
||||
if matches!(n.kind, NodeKind::Vector { .. }) {
|
||||
return Vec::new();
|
||||
}
|
||||
let Some(c) = stroke_color(n) else { return Vec::new() };
|
||||
let Some(sides) = n.stroke.sides else {
|
||||
let weight = tok(doc, n, &["strokeWeight"], format!("{}px", num(n.stroke.weight)), t);
|
||||
@@ -573,6 +577,126 @@ mod tests {
|
||||
assert!(!css.contains("gradient"), "{css}");
|
||||
}
|
||||
|
||||
fn embedded_svgs(code: &str) -> Vec<String> {
|
||||
use base64::Engine as _;
|
||||
code.split("data:image/svg+xml;base64,")
|
||||
.skip(1)
|
||||
.map(|rest| {
|
||||
let b64 = rest.split('"').next().unwrap();
|
||||
String::from_utf8(base64::engine::general_purpose::STANDARD.decode(b64).unwrap()).unwrap()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vector_code_uses_its_svg_asset_not_a_box_border() {
|
||||
let mut s = Session::new();
|
||||
let icon =
|
||||
id_of(&s.execute("frame.create", &json!({"name": "icon", "width": 24, "height": 24, "props": {"fill": "none"}})).unwrap()["id"]).unwrap();
|
||||
let check = id_of(&s.execute("vector.create", &json!({"path": "M4 12 L10 18 L20 6", "parent": icon, "name": "check", "props": {"fill": "none", "stroke": "#1F3A68", "strokeWeight": 2}})).unwrap()["id"]).unwrap();
|
||||
s.doc_mut().unwrap().get_mut(check).unwrap().fills = vec![Paint::solid(Color::WHITE)];
|
||||
let doc = s.doc().unwrap();
|
||||
let html = code_for(doc, icon, CodeLang::Html);
|
||||
assert!(html.contains("<div class=\"check\">"), "node wrapper: {html}");
|
||||
assert!(html.contains("<img class=\"check-asset\" src=\"data:image/svg+xml;base64,"), "{html}");
|
||||
assert!(html.contains("alt=\"check\""), "{html}");
|
||||
assert!(!html.contains("border: 2px solid"), "{html}");
|
||||
assert!(!html.contains("background:"), "the vector's fill belongs to its SVG, not its box: {html}");
|
||||
let opaque = embedded_svgs(&html);
|
||||
assert_eq!(opaque.len(), 1, "{html}");
|
||||
assert!(opaque[0].contains("<path") && opaque[0].contains("#1F3A68"), "{:?}", opaque[0]);
|
||||
for lang in [CodeLang::React, CodeLang::Vue, CodeLang::Leptos, CodeLang::Tailwind] {
|
||||
let code = code_for(doc, icon, lang);
|
||||
assert!(code.contains("<img") && code.contains("src=\"data:image/svg+xml;base64,"), "{}: {code}", lang.id());
|
||||
assert!(!code.contains("border: 2px solid") && !code.contains("border-[2px]"), "{}: {code}", lang.id());
|
||||
}
|
||||
let css = code_for(doc, icon, CodeLang::Css);
|
||||
assert!(!css.contains("border: 2px solid"), "{css}");
|
||||
let swift = code_for(doc, icon, CodeLang::SwiftUi);
|
||||
assert!(swift.contains("Image(\"check\")"), "{swift}");
|
||||
assert!(!swift.contains(".overlay(RoundedRectangle"), "{swift}");
|
||||
let ark = code_for(doc, icon, CodeLang::ArkUi);
|
||||
assert!(!ark.contains(".border({"), "{ark}");
|
||||
|
||||
// CSS owns the node's rotation and opacity, so the embedded asset must not bake them in.
|
||||
s.doc_mut().unwrap().get_mut(check).unwrap().opacity = 0.5;
|
||||
s.doc_mut().unwrap().get_mut(check).unwrap().transform = figcraft_geom::Affine::rotate(30f64.to_radians());
|
||||
let transformed = code_for(s.doc().unwrap(), icon, CodeLang::Html);
|
||||
assert!(transformed.contains("opacity: 0.5;"), "{transformed}");
|
||||
assert!(transformed.contains("transform: rotate("), "{transformed}");
|
||||
assert_eq!(embedded_svgs(&transformed), opaque, "the asset stays node-local and opaque: {transformed}");
|
||||
|
||||
let rectangle =
|
||||
id_of(&s.execute("shape.rectangle", &json!({"parent": icon, "props": {"stroke": "#1F3A68", "strokeWeight": 2}})).unwrap()["id"]).unwrap();
|
||||
assert!(code_for(s.doc().unwrap(), rectangle, CodeLang::Css).contains("border: 2px solid"), "box strokes remain");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vector_assets_are_self_contained_and_leptos_literals_escape() {
|
||||
let mut s = Session::new();
|
||||
let icon = id_of(&s.execute("frame.create", &json!({"name": "Icons", "width": 24, "height": 24})).unwrap()["id"]).unwrap();
|
||||
for name in ["Check Icon", "Check Icon", r"icon\q", "check#dark"] {
|
||||
s.execute("vector.create", &json!({"path": "M4 12 L10 18 L20 6", "parent": icon, "name": name, "props": {"fill": "none"}})).unwrap();
|
||||
}
|
||||
let html = code_for(s.doc().unwrap(), icon, CodeLang::Html);
|
||||
assert_eq!(embedded_svgs(&html).len(), 4, "nested vectors need no separate filesystem export: {html}");
|
||||
assert!(!html.contains("src=\"check#dark.svg\""), "{html}");
|
||||
let leptos = code_for(s.doc().unwrap(), icon, CodeLang::Leptos);
|
||||
assert!(leptos.contains("alt=\"icon\\\\q\""), "{leptos}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vector_asset_keeps_stroke_overflow_inside_a_node_sized_wrapper() {
|
||||
let mut s = Session::new();
|
||||
let badge = id_of(
|
||||
&s.execute(
|
||||
"vector.create",
|
||||
&json!({"path": "M0 0 H24 V24 H0 Z", "name": "badge", "props": {"fill": "none", "stroke": "#1F3A68", "strokeWeight": 2}}),
|
||||
)
|
||||
.unwrap()["id"],
|
||||
)
|
||||
.unwrap();
|
||||
s.doc_mut().unwrap().get_mut(badge).unwrap().stroke.miter_limit = 1.0;
|
||||
let html = code_for(s.doc().unwrap(), badge, CodeLang::Html);
|
||||
assert!(html.contains("<div class=\"badge\">"), "node-sized wrapper: {html}");
|
||||
assert!(html.contains("<img class=\"badge-asset\""), "inner asset: {html}");
|
||||
assert!(html.contains("overflow: visible;"), "stroke is not clipped: {html}");
|
||||
assert!(html.contains("left: -2px;") && html.contains("top: -2px;"), "asset offset: {html}");
|
||||
assert!(html.contains("width: 28px;") && html.contains("height: 28px;"), "asset keeps its bounds: {html}");
|
||||
assert!(html.contains("max-width: none;"), "the wrapper cannot shrink the asset: {html}");
|
||||
let svg = embedded_svgs(&html);
|
||||
assert_eq!(svg.len(), 1, "{html}");
|
||||
assert!(svg[0].contains("width=\"28\" height=\"28\""), "{}", svg[0]);
|
||||
let tailwind = code_for(s.doc().unwrap(), badge, CodeLang::Tailwind);
|
||||
assert!(tailwind.contains("overflow-visible") && tailwind.contains("max-w-none"), "{tailwind}");
|
||||
assert!(tailwind.contains("w-7") && tailwind.contains("h-7"), "28px on the spacing scale: {tailwind}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vector_markup_does_not_duplicate_svg_effects() {
|
||||
let mut s = Session::new();
|
||||
let vector = id_of(
|
||||
&s.execute("vector.create", &json!({"path": "M0 0 H24 V24 H0 Z", "name": "effect icon", "props": {"fill": "#FFFFFF"}})).unwrap()["id"],
|
||||
)
|
||||
.unwrap();
|
||||
s.doc_mut().unwrap().get_mut(vector).unwrap().effects = vec![
|
||||
figcraft_doc::Effect { kind: EffectKind::LayerBlur(figcraft_doc::Blur::uniform(8.0)), visible: true },
|
||||
figcraft_doc::Effect { kind: EffectKind::DropShadow(Shadow { radius: 4.0, offset: (3.0, 4.0), ..Default::default() }), visible: true },
|
||||
];
|
||||
let html = code_for(s.doc().unwrap(), vector, CodeLang::Html);
|
||||
assert!(!html.contains("filter: blur(") && !html.contains("box-shadow:"), "the SVG owns these effects: {html}");
|
||||
let svg = embedded_svgs(&html);
|
||||
assert_eq!(svg.len(), 1, "{html}");
|
||||
assert!(svg[0].contains("feGaussianBlur") && svg[0].contains("feOffset"), "{}", svg[0]);
|
||||
let standalone = code_for(s.doc().unwrap(), vector, CodeLang::Css);
|
||||
assert!(standalone.contains("filter: blur(4px)") && standalone.contains("box-shadow:"), "standalone CSS is unchanged: {standalone}");
|
||||
|
||||
let rectangle = id_of(&s.execute("shape.rectangle", &json!({"name": "ordinary", "width": 24, "height": 24})).unwrap()["id"]).unwrap();
|
||||
s.doc_mut().unwrap().get_mut(rectangle).unwrap().effects = s.doc().unwrap().node(vector).unwrap().effects.clone();
|
||||
let ordinary = code_for(s.doc().unwrap(), rectangle, CodeLang::Html);
|
||||
assert!(ordinary.contains("filter: blur(4px)") && ordinary.contains("box-shadow:"), "ordinary shapes keep CSS effects: {ordinary}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn swiftui_and_compose_for_an_auto_layout_card() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -216,7 +216,7 @@ fn arkui_layer(ctx: &Ctx, n: &Node, depth: usize, out: &mut String, extra: &[Str
|
||||
}
|
||||
}
|
||||
// Ellipses take their stroke as a shape attribute (above).
|
||||
if !matches!(n.kind, NodeKind::Ellipse { .. })
|
||||
if !matches!(n.kind, NodeKind::Ellipse { .. } | NodeKind::Vector { .. })
|
||||
&& let Some(c) = stroke_color(n)
|
||||
{
|
||||
mods.push(format!(".border({{ width: {}, color: {} }})", num(n.stroke.weight), ark_color(c)));
|
||||
|
||||
@@ -126,6 +126,16 @@ pub(super) fn css(doc: &Document, id: NodeId) -> String {
|
||||
/// The CSS declarations for `n`'s own look and size, one per line; `hug` leaves out the width
|
||||
/// and/or height (they follow the content). Bound variables become `var(--name, value)`.
|
||||
pub(crate) fn css_decls(doc: &Document, n: &Node, t: &mut Tokens, hug: (bool, bool)) -> String {
|
||||
css_decls_impl(doc, n, t, hug, false)
|
||||
}
|
||||
|
||||
/// The declarations around an embedded vector image: its SVG owns shadows and layer blur, so
|
||||
/// only the markup wrapper omits those. Standalone CSS and ordinary shapes keep them.
|
||||
pub(crate) fn css_decls_for_markup(doc: &Document, n: &Node, t: &mut Tokens, hug: (bool, bool)) -> String {
|
||||
css_decls_impl(doc, n, t, hug, true)
|
||||
}
|
||||
|
||||
fn css_decls_impl(doc: &Document, n: &Node, t: &mut Tokens, hug: (bool, bool), vector_svg: bool) -> String {
|
||||
let px = |v: f64| format!("{}px", num(v));
|
||||
let mut out = String::new();
|
||||
let mut put = |key: &str, value: String| out.push_str(&format!("{key}: {value};\n"));
|
||||
@@ -188,7 +198,12 @@ pub(crate) fn css_decls(doc: &Document, n: &Node, t: &mut Tokens, hug: (bool, bo
|
||||
// One `background` with every visible fill as a layer, top first (a document's fills run
|
||||
// bottom to top, as the renderer paints them). CSS allows a plain colour only as the last
|
||||
// layer, so a solid above another fill becomes a one-colour gradient.
|
||||
let visible: Vec<(usize, &figcraft_color::Paint)> = n.fills.iter().enumerate().filter(|(_, p)| p.visible).collect();
|
||||
let visible: Vec<(usize, &figcraft_color::Paint)> = if matches!(n.kind, NodeKind::Vector { .. }) {
|
||||
// The SVG carries the path's fills; an image's box must not get a rectangular one.
|
||||
Vec::new()
|
||||
} else {
|
||||
n.fills.iter().enumerate().filter(|(_, p)| p.visible).collect()
|
||||
};
|
||||
let layers: Vec<String> = visible
|
||||
.iter()
|
||||
.enumerate()
|
||||
@@ -217,7 +232,7 @@ pub(crate) fn css_decls(doc: &Document, n: &Node, t: &mut Tokens, hug: (bool, bo
|
||||
for (key, value) in css_borders(doc, n, t) {
|
||||
put(&key, value);
|
||||
}
|
||||
effect_decls(n, &mut put);
|
||||
effect_decls(n, &mut put, vector_svg && matches!(n.kind, NodeKind::Vector { .. }));
|
||||
if let NodeKind::Text(tx) = &n.kind {
|
||||
text_decls(doc, n, tx, t, &mut put);
|
||||
}
|
||||
@@ -274,12 +289,14 @@ fn layout_decls(doc: &Document, n: &Node, l: &figcraft_doc::AutoLayout, t: &mut
|
||||
}
|
||||
}
|
||||
|
||||
/// Shadows and blurs of `n`.
|
||||
fn effect_decls(n: &Node, put: &mut impl FnMut(&str, String)) {
|
||||
/// Shadows and blurs of `n`. `svg_owned` leaves shadows and layer blur to the embedded SVG;
|
||||
/// backdrop filters stay in CSS because the self-contained asset has no outer page behind it.
|
||||
fn effect_decls(n: &Node, put: &mut impl FnMut(&str, String), svg_owned: bool) {
|
||||
let shadows: Vec<String> = n
|
||||
.effects
|
||||
.iter()
|
||||
.filter(|e| e.visible)
|
||||
.filter(|e| !(svg_owned && matches!(e.kind, EffectKind::DropShadow(_) | EffectKind::InnerShadow(_))))
|
||||
.filter_map(|e| match &e.kind {
|
||||
EffectKind::DropShadow(s) => {
|
||||
Some(format!("{}px {}px {}px {}px {}", num(s.offset.0), num(s.offset.1), num(s.radius), num(s.spread), s.color.to_css()))
|
||||
@@ -296,7 +313,7 @@ fn effect_decls(n: &Node, put: &mut impl FnMut(&str, String)) {
|
||||
for e in n.effects.iter().filter(|e| e.visible) {
|
||||
match e.kind {
|
||||
// CSS blurs are uniform: a progressive blur has no CSS equivalent and is left out.
|
||||
EffectKind::LayerBlur(ref b) if !b.is_progressive() => put("filter", format!("blur({}px)", num(b.radius / 2.0))),
|
||||
EffectKind::LayerBlur(ref b) if !svg_owned && !b.is_progressive() => put("filter", format!("blur({}px)", num(b.radius / 2.0))),
|
||||
EffectKind::BackgroundBlur(ref b) if !b.is_progressive() => put("backdrop-filter", format!("blur({}px)", num(b.radius / 2.0))),
|
||||
// CSS has no refraction: the frost is the nearest.
|
||||
EffectKind::Glass(ref g) => put("backdrop-filter", format!("blur({}px)", num(g.sanitized().frost / 2.0))),
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
use super::css::{Tokens, css_decls};
|
||||
use base64::Engine as _;
|
||||
|
||||
use super::css::{Tokens, css_decls_for_markup};
|
||||
use super::{CodeLang, Ctx, Document, LayoutMode, Node, NodeId, NodeKind, Param, Sizing, indent, num, with_v_if};
|
||||
|
||||
// ------------------------------------------------------------------ HTML and React markup
|
||||
@@ -85,6 +87,24 @@ fn html_escape(s: &str) -> String {
|
||||
s.replace('&', "&").replace('<', "<").replace('>', ">").replace('\n', "<br>")
|
||||
}
|
||||
|
||||
/// A layer name in a quoted markup attribute, with line breaks flattened.
|
||||
fn attr_escape(s: &str) -> String {
|
||||
s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """).replace(['\n', '\r'], " ")
|
||||
}
|
||||
|
||||
/// A vector as a self-contained SVG asset and its local painted bounds. CSS owns the node's
|
||||
/// placement and opacity, so the embedded geometry is node-local and fully opaque. No filesystem
|
||||
/// export or URL escaping is needed, and nested vectors work exactly like top-level ones.
|
||||
fn vector_data_uri(doc: &mut Document, n: &Node) -> Option<(String, figcraft_geom::Rect)> {
|
||||
let node = doc.get_mut(n.id).ok()?;
|
||||
node.parent = None;
|
||||
node.transform = figcraft_geom::Affine::IDENTITY;
|
||||
node.opacity = 1.0;
|
||||
let bounds = figcraft_render::export_bounds(doc, n.id)?;
|
||||
let svg = figcraft_svg::export_svg(doc, &[n.id], &Default::default())?;
|
||||
Some((format!("data:image/svg+xml;base64,{}", base64::engine::general_purpose::STANDARD.encode(svg)), bounds))
|
||||
}
|
||||
|
||||
/// Text as JSX children: HTML escapes, braces as expressions, line breaks as `<br />`.
|
||||
fn jsx_text(s: &str) -> String {
|
||||
let mut out = String::new();
|
||||
@@ -147,6 +167,8 @@ pub(crate) struct Markup<'c, 'a> {
|
||||
/// With `fluid`, other layers at least this share of the root's width are fluid too (a
|
||||
/// divider, a banner image); smaller ones (icons) keep their size. Default: none.
|
||||
pub fluid_leaves: f64,
|
||||
/// Lazily cloned once for node-local SVG assets, not once per vector.
|
||||
asset_doc: Option<Document>,
|
||||
}
|
||||
|
||||
/// How `n` sits in its parent: in the flex flow, or placed at its position.
|
||||
@@ -175,6 +197,18 @@ fn placement_decls(n: &Node, parent: Option<&Node>, root: bool, in_flow: bool) -
|
||||
decls
|
||||
}
|
||||
|
||||
/// Extra declarations around an embedded vector image. The inner SVG can be larger than the
|
||||
/// node box, so the wrapper must establish positioning in flex flow and leave overflow visible.
|
||||
fn vector_wrapper_decls(n: &Node, in_flow: bool, own: &mut String) {
|
||||
if !matches!(n.kind, NodeKind::Vector { .. }) {
|
||||
return;
|
||||
}
|
||||
own.push_str("overflow: visible;\n");
|
||||
if in_flow {
|
||||
own.push_str("position: relative;\n");
|
||||
}
|
||||
}
|
||||
|
||||
impl<'c, 'a> Markup<'c, 'a> {
|
||||
pub fn new(ctx: &'c Ctx<'a>, lang: CodeLang) -> Self {
|
||||
Markup {
|
||||
@@ -192,6 +226,7 @@ impl<'c, 'a> Markup<'c, 'a> {
|
||||
inline: false,
|
||||
fluid: false,
|
||||
fluid_leaves: f64::INFINITY,
|
||||
asset_doc: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -290,6 +325,30 @@ impl<'c, 'a> Markup<'c, 'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A node-sized wrapper and its inner SVG image. The inner rule uses the exported bounds,
|
||||
/// so strokes and effects keep their size and can overflow the wrapper without clipping.
|
||||
fn vector_element(&mut self, n: &Node, depth: usize, path: &str, class: &str, attr: &str, pad: &str, attrs: &str) {
|
||||
let root_doc = self.ctx.doc;
|
||||
let asset = vector_data_uri(self.asset_doc.get_or_insert_with(|| root_doc.clone()), n);
|
||||
let bounds = asset.as_ref().map(|(_, b)| *b).unwrap_or_else(|| n.local_rect());
|
||||
let asset_class = class_name(&format!("{class} asset"), "asset", &mut self.used);
|
||||
let asset_decls = format!(
|
||||
"display: block;\nposition: absolute;\nleft: {}px;\ntop: {}px;\nwidth: {}px;\nheight: {}px;\nmax-width: none;\n",
|
||||
num(bounds.x0),
|
||||
num(bounds.y0),
|
||||
num(bounds.width()),
|
||||
num(bounds.height())
|
||||
);
|
||||
self.rule(&format!("{path}/$svg"), &asset_class, asset_decls);
|
||||
// Leptos attributes are Rust string literals; the other targets use HTML escaping.
|
||||
let lang = self.lang;
|
||||
let quote = |value: &str| if lang == CodeLang::Leptos { format!("{value:?}") } else { format!("\"{}\"", attr_escape(value)) };
|
||||
let src = asset.map(|(uri, _)| format!(" src={}", quote(&uri))).unwrap_or_default();
|
||||
let alt = quote(&n.name);
|
||||
let inner = self.pad(depth + 1);
|
||||
self.markup.push_str(&format!("{pad}<div {attr}=\"{class}\"{attrs}>\n{inner}<img {attr}=\"{asset_class}\"{src} alt={alt} />\n{pad}</div>\n"));
|
||||
}
|
||||
|
||||
fn element(&mut self, n: &Node, parent: Option<&Node>, depth: usize, path: &str) {
|
||||
let doc = self.ctx.doc;
|
||||
let root = n.id == self.ctx.root;
|
||||
@@ -319,7 +378,7 @@ impl<'c, 'a> Markup<'c, 'a> {
|
||||
}
|
||||
let hugs = n.layout.is_some() || matches!(n.kind, NodeKind::Text(_));
|
||||
let hug = (hugs && n.child_layout.sizing_h == Sizing::Hug, hugs && n.child_layout.sizing_v == Sizing::Hug);
|
||||
let mut own = css_decls(doc, n, &mut self.tokens, hug);
|
||||
let mut own = css_decls_for_markup(doc, n, &mut self.tokens, hug);
|
||||
let page = self.ctx.doc.node(self.ctx.root).map_or(f64::INFINITY, |r| r.width);
|
||||
if self.fluid && (n.layout.is_some() || matches!(n.kind, NodeKind::Text(_)) || (!root && n.width >= page * self.fluid_leaves)) {
|
||||
// Full width, or sized by the flex row (`flex: 1`): no cap needed.
|
||||
@@ -328,6 +387,7 @@ impl<'c, 'a> Markup<'c, 'a> {
|
||||
if n.layout.is_none() && !n.children.is_empty() && !root && in_flow {
|
||||
own.push_str("position: relative;\n");
|
||||
}
|
||||
vector_wrapper_decls(n, in_flow, &mut own);
|
||||
decls.push_str(&own);
|
||||
self.rule(path, &class, decls);
|
||||
// The root's variant attributes, and a Vue `v-if` guard, ride on the open tag.
|
||||
@@ -339,6 +399,7 @@ impl<'c, 'a> Markup<'c, 'a> {
|
||||
}
|
||||
let open = |tag: &str| format!("{pad}<{tag} {attr}=\"{class}\"{attrs}>");
|
||||
match &n.kind {
|
||||
NodeKind::Vector { .. } => self.vector_element(n, depth, path, &class, attr, &pad, &attrs),
|
||||
NodeKind::Text(t) => {
|
||||
let body = self.text_body(n, t);
|
||||
self.markup.push_str(&format!("{}{body}</p>\n", open("p")));
|
||||
|
||||
@@ -192,7 +192,9 @@ fn swift_layer(ctx: &Ctx, n: &Node, depth: usize, out: &mut String, extra: &[Str
|
||||
mods.push(format!(".frame(width: {w}, height: {h})"));
|
||||
}
|
||||
}
|
||||
if let Some(c) = stroke_color(n) {
|
||||
if !matches!(n.kind, NodeKind::Vector { .. })
|
||||
&& let Some(c) = stroke_color(n)
|
||||
{
|
||||
mods.push(format!(
|
||||
".overlay(RoundedRectangle(cornerRadius: {corner}).stroke({}, lineWidth: {}))",
|
||||
bound(&["stroke"], swift_color(c)),
|
||||
|
||||
@@ -178,7 +178,14 @@ fn code(doc: &Document, id: NodeId) -> Vec<Value> {
|
||||
.filter_map(|l| {
|
||||
let lang = CodeLang::from_id(&l.language)?;
|
||||
let snippet = code_connect::connected_code(doc, id, lang, l)?;
|
||||
Some(json!({"language": l.language, "importPath": l.import_path, "name": l.name, "code": snippet}))
|
||||
// The snippet already holds the template and the values it maps.
|
||||
let mut v = code_connect::link_fields(l);
|
||||
if let Some(o) = v.as_object_mut() {
|
||||
o.remove("template");
|
||||
o.remove("values");
|
||||
}
|
||||
v["code"] = json!(snippet);
|
||||
Some(v)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -355,7 +362,7 @@ fn components_json(doc: &Document, ids: &BTreeSet<NodeId>) -> Value {
|
||||
v["description"] = json!(description);
|
||||
}
|
||||
if !n.code_links.is_empty() {
|
||||
v["codeLinks"] = camel(serde_json::to_value(&n.code_links).unwrap_or(Value::Null));
|
||||
v["codeLinks"] = json!(n.code_links.iter().map(code_connect::link_fields).collect::<Vec<_>>());
|
||||
}
|
||||
out.insert(id.to_string(), v);
|
||||
}
|
||||
|
||||
@@ -274,8 +274,10 @@ fn decl(key: &str, value: &str) -> Vec<(String, String)> {
|
||||
("width", "100%") => kw("w-full"),
|
||||
("width", v) => one(spacing("w", v)),
|
||||
("height", v) => one(spacing("h", v)),
|
||||
("max-width", "none") => kw("max-w-none"),
|
||||
("max-width", v) => one(format!("max-w-{}", arb(v))),
|
||||
("min-height", v) => one(format!("min-h-{}", arb(v))),
|
||||
("overflow", "visible") => kw("overflow-visible"),
|
||||
("margin-inline", "auto") => kw("mx-auto"),
|
||||
("gap", v) => one(spacing("gap", v)),
|
||||
("padding", v) => padding(v),
|
||||
|
||||
@@ -119,6 +119,9 @@ pub struct DocState {
|
||||
/// Where each page's view was left in this session (its centre and zoom; see
|
||||
/// [`Self::open_page`]; not saved).
|
||||
page_views: BTreeMap<NodeId, (f64, f64, f64)>,
|
||||
/// The canvas fits the page's content when it first gets its size. Off when the view was
|
||||
/// restored from where the file was left ([`Session::restore_view`]).
|
||||
pub fit_when_sized: bool,
|
||||
}
|
||||
|
||||
/// A version shown on the canvas in place of the document: read-only until it's restored or the
|
||||
@@ -184,6 +187,7 @@ impl DocState {
|
||||
images_left_in_file: None,
|
||||
on_disk: None,
|
||||
page_views: BTreeMap::new(),
|
||||
fit_when_sized: true,
|
||||
};
|
||||
st.zoom_to_fit();
|
||||
st
|
||||
@@ -332,6 +336,29 @@ impl DocState {
|
||||
}
|
||||
}
|
||||
|
||||
/// Each page's view as left: the one shown now at its current view, the others shown in this
|
||||
/// session at theirs.
|
||||
pub(crate) fn page_views(&self) -> impl Iterator<Item = (NodeId, (f64, f64, f64))> + '_ {
|
||||
let shown = (self.page, (self.view.cx, self.view.cy, self.view.zoom));
|
||||
self.page_views.iter().filter(|(p, _)| **p != self.page).map(|(p, v)| (*p, *v)).chain(std::iter::once(shown))
|
||||
}
|
||||
|
||||
/// Take `views` as where their pages were left, and show `page` (or the page shown now) at
|
||||
/// its view. With one, the canvas keeps it instead of fitting the page when it gets its size.
|
||||
pub(crate) fn show_views(&mut self, page: Option<NodeId>, views: impl IntoIterator<Item = (NodeId, (f64, f64, f64))>) {
|
||||
self.page_views.extend(views);
|
||||
if let Some(page) = page {
|
||||
self.page = page;
|
||||
}
|
||||
match self.page_views.get(&self.page) {
|
||||
Some(&(cx, cy, zoom)) => {
|
||||
(self.view.cx, self.view.cy, self.view.zoom) = (cx, cy, zoom);
|
||||
self.fit_when_sized = false;
|
||||
}
|
||||
None => self.zoom_to_fit(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn zoom_to_fit(&mut self) {
|
||||
match self.doc.page_content_bounds(self.page) {
|
||||
Some(b) => self.view.fit(b, 1.0),
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
//! Files open again where they were left: when a file's tab closes or the app quits, the page it
|
||||
//! showed and each page's view (its centre and zoom) are kept for that file, and opening it again
|
||||
//! shows them, as Figma opens a file where you were. They live in the preferences, not in the
|
||||
//! file, so looking around never changes a file.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{NodeId, Session, ViewState};
|
||||
|
||||
/// How many files' views are kept, the most recently left first.
|
||||
pub const MAX_FILE_VIEWS: usize = 100;
|
||||
|
||||
/// Where a file was left.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct FileView {
|
||||
pub path: String,
|
||||
/// The page shown.
|
||||
pub page: NodeId,
|
||||
/// The view of each page shown while it was open.
|
||||
pub pages: Vec<PageView>,
|
||||
}
|
||||
|
||||
/// A page's view: the page point at the canvas's centre, and the zoom.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct PageView {
|
||||
pub page: NodeId,
|
||||
pub cx: f64,
|
||||
pub cy: f64,
|
||||
pub zoom: f64,
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Keep where tab `i`'s file is left. A tab without a file of its own (a new or imported file,
|
||||
/// a branch) keeps nothing.
|
||||
pub(crate) fn remember_view(&mut self, i: usize) {
|
||||
let Some(ds) = self.docs.get(i).filter(|d| d.branch_of.is_none()) else { return };
|
||||
let Some(path) = ds.path.clone() else { return };
|
||||
let pages = ds.page_views().map(|(page, (cx, cy, zoom))| PageView { page, cx, cy, zoom }).collect();
|
||||
let view = FileView { path, page: ds.page, pages };
|
||||
let views = &mut self.prefs.file_views;
|
||||
views.retain(|v| v.path != view.path);
|
||||
views.insert(0, view);
|
||||
views.truncate(MAX_FILE_VIEWS);
|
||||
self.prefs_unsaved = true;
|
||||
}
|
||||
|
||||
/// [`remember_view`](Self::remember_view) for every open tab, before the app quits.
|
||||
pub fn remember_views(&mut self) {
|
||||
for i in 0..self.docs.len() {
|
||||
self.remember_view(i);
|
||||
}
|
||||
}
|
||||
|
||||
/// Show the active tab's file where it was left, if it was: its page, if the file still has
|
||||
/// it as a page that isn't a divider, at its view, and each other page at its view when it is
|
||||
/// shown. A view that isn't a finite centre with a zoom the canvas takes is left out.
|
||||
pub(crate) fn restore_view(&mut self) {
|
||||
let Ok(ds) = self.ds() else { return };
|
||||
let Some(kept) = ds.path.as_deref().and_then(|p| self.prefs.file_views.iter().find(|v| v.path == p)).cloned() else { return };
|
||||
let Ok(ds) = self.ds_mut() else { return };
|
||||
let doc = ds.doc.clone();
|
||||
let views = kept
|
||||
.pages
|
||||
.iter()
|
||||
.filter(|v| doc.pages.contains(&v.page) && [v.cx, v.cy, v.zoom].iter().all(|x| x.is_finite()))
|
||||
.filter(|v| (ViewState::MIN_ZOOM..=ViewState::MAX_ZOOM).contains(&v.zoom))
|
||||
.map(|v| (v.page, (v.cx, v.cy, v.zoom)));
|
||||
let page = Some(kept.page).filter(|p| doc.pages.contains(p) && !doc.is_divider(*p));
|
||||
ds.show_views(page, views);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,136 @@
|
||||
//! Files open again where they were left.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::*;
|
||||
|
||||
fn ex(s: &mut Session, cmd: &str, p: Value) -> Value {
|
||||
s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd} {p}: {e}"))
|
||||
}
|
||||
|
||||
/// A test's folder, removed when the test ends, a failing one too.
|
||||
struct Dir(std::path::PathBuf);
|
||||
|
||||
impl std::ops::Deref for Dir {
|
||||
type Target = std::path::Path;
|
||||
fn deref(&self) -> &std::path::Path {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Dir {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
fn dir(name: &str) -> Dir {
|
||||
let d = std::env::temp_dir().join(format!("figcraft-file-views-{}-{name}", std::process::id()));
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
Dir(d)
|
||||
}
|
||||
|
||||
/// A saved file at `path` with two pages, each holding a rectangle, the first page shown.
|
||||
fn two_pages(s: &mut Session, path: &str) -> (NodeId, NodeId) {
|
||||
ex(s, "file.new", json!({}));
|
||||
ex(s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 100, "height": 100}));
|
||||
ex(s, "page.add", json!({"name": "Second"}));
|
||||
let pages = s.doc().unwrap().pages.clone();
|
||||
ex(s, "page.select", json!({"id": pages[1].0}));
|
||||
ex(s, "shape.rectangle", json!({"x": 2000, "y": 2000, "width": 50, "height": 50}));
|
||||
ex(s, "page.select", json!({"id": pages[0].0}));
|
||||
ex(s, "file.saveAs", json!({"path": path}));
|
||||
(pages[0], pages[1])
|
||||
}
|
||||
|
||||
fn view(s: &Session) -> (NodeId, f64, f64, f64) {
|
||||
let ds = s.ds().unwrap();
|
||||
(ds.page, ds.view.cx, ds.view.cy, ds.view.zoom)
|
||||
}
|
||||
|
||||
fn look(s: &mut Session, cx: f64, cy: f64, zoom: f64) {
|
||||
let v = &mut s.ds_mut().unwrap().view;
|
||||
(v.cx, v.cy, v.zoom) = (cx, cy, zoom);
|
||||
}
|
||||
|
||||
/// Closed and opened again, a file shows the page it showed, at its view, and its other page at
|
||||
/// the view that page was left at; looking around leaves the file unchanged.
|
||||
#[test]
|
||||
fn a_file_opens_again_where_it_was_left() {
|
||||
let d = dir("left");
|
||||
let path = d.join("two.figcraft").to_string_lossy().into_owned();
|
||||
let mut s = Session::new();
|
||||
let (first, second) = two_pages(&mut s, &path);
|
||||
let saved = std::fs::read(&path).unwrap();
|
||||
look(&mut s, 40.0, 60.0, 2.5);
|
||||
ex(&mut s, "page.select", json!({"id": second.0}));
|
||||
look(&mut s, 2010.0, 2020.0, 0.5);
|
||||
assert!(!s.ds().unwrap().is_dirty(), "looking around is no change to the file");
|
||||
ex(&mut s, "file.close", json!({}));
|
||||
assert_eq!(std::fs::read(&path).unwrap(), saved, "nothing written to the file");
|
||||
assert!(s.prefs_unsaved, "kept in the preferences");
|
||||
ex(&mut s, "file.open", json!({"path": path}));
|
||||
assert_eq!(view(&s), (second, 2010.0, 2020.0, 0.5));
|
||||
assert!(!s.ds().unwrap().fit_when_sized, "the canvas keeps the view instead of fitting");
|
||||
ex(&mut s, "page.select", json!({"id": first.0}));
|
||||
assert_eq!(view(&s), (first, 40.0, 60.0, 2.5));
|
||||
// Through the preferences file, as the next start reads them.
|
||||
let prefs: crate::Prefs = serde_json::from_value(serde_json::to_value(&s.prefs).unwrap()).unwrap();
|
||||
let mut next = Session::new();
|
||||
next.prefs = prefs;
|
||||
ex(&mut next, "file.open", json!({"path": path}));
|
||||
assert_eq!(view(&next), (second, 2010.0, 2020.0, 0.5));
|
||||
}
|
||||
|
||||
/// Quitting keeps every open file's view; a file never saved keeps none.
|
||||
#[test]
|
||||
fn quitting_keeps_each_open_files_view() {
|
||||
let d = dir("quit");
|
||||
let (a, b) = (d.join("a.figcraft").to_string_lossy().into_owned(), d.join("b.figcraft").to_string_lossy().into_owned());
|
||||
let mut s = Session::new();
|
||||
let (a_page, _) = two_pages(&mut s, &a);
|
||||
look(&mut s, 1.0, 2.0, 3.0);
|
||||
let (b_page, _) = two_pages(&mut s, &b);
|
||||
look(&mut s, 4.0, 5.0, 0.25);
|
||||
ex(&mut s, "file.new", json!({}));
|
||||
s.remember_views();
|
||||
let kept: Vec<&str> = s.prefs.file_views.iter().map(|v| v.path.as_str()).collect();
|
||||
assert_eq!(kept.len(), 2, "{kept:?}");
|
||||
let mut next = Session::new();
|
||||
next.prefs = s.prefs.clone();
|
||||
ex(&mut next, "file.open", json!({"path": a}));
|
||||
assert_eq!(view(&next), (a_page, 1.0, 2.0, 3.0));
|
||||
ex(&mut next, "file.open", json!({"path": b}));
|
||||
assert_eq!(view(&next), (b_page, 4.0, 5.0, 0.25));
|
||||
}
|
||||
|
||||
/// A kept page the file no longer has, or a view the canvas can't show, is left out: the file
|
||||
/// opens fitted as before.
|
||||
#[test]
|
||||
fn a_view_that_no_longer_fits_the_file_is_left_out() {
|
||||
let d = dir("stale");
|
||||
let path = d.join("one.figcraft").to_string_lossy().into_owned();
|
||||
let mut s = Session::new();
|
||||
let (first, _) = two_pages(&mut s, &path);
|
||||
ex(&mut s, "file.close", json!({}));
|
||||
s.prefs.file_views[0].page = NodeId(999_999);
|
||||
s.prefs.file_views[0].pages = vec![PageView { page: first, cx: f64::NAN, cy: 0.0, zoom: 1.0 }];
|
||||
ex(&mut s, "file.open", json!({"path": path}));
|
||||
let ds = s.ds().unwrap();
|
||||
assert_eq!(ds.page, first);
|
||||
assert!(ds.fit_when_sized, "fitted as a file never left");
|
||||
assert!(ds.view.cx.is_finite());
|
||||
}
|
||||
|
||||
/// The views kept are bounded, the most recently left first.
|
||||
#[test]
|
||||
fn the_most_recently_left_files_are_kept() {
|
||||
let mut s = Session::new();
|
||||
for k in 0..MAX_FILE_VIEWS + 5 {
|
||||
ex(&mut s, "file.new", json!({}));
|
||||
s.ds_mut().unwrap().path = Some(format!("/nowhere/{k}.figcraft"));
|
||||
ex(&mut s, "file.close", json!({"force": true}));
|
||||
}
|
||||
assert_eq!(s.prefs.file_views.len(), MAX_FILE_VIEWS);
|
||||
assert_eq!(s.prefs.file_views[0].path, format!("/nowhere/{}.figcraft", MAX_FILE_VIEWS + 4));
|
||||
}
|
||||
@@ -368,6 +368,7 @@ pub static GESTURES: &[(Group, &str, &str, &str)] = &[
|
||||
(Selection, "Pick select: next or previous layer", "⇥ / ⇧⇥", "Tab / Shift+Tab"),
|
||||
(Selection, "Pick select: into a layer, out to its parent", "↵ / ⇧↵", "Enter / Shift+Enter"),
|
||||
(Selection, "Pick select: select the picked layer", "Space", "Space"),
|
||||
(Text, "While editing text: next or previous text layer", "⇥ / ⇧⇥", "Tab / Shift+Tab"),
|
||||
(Edit, "Duplicate by dragging", "⌥ drag", "Alt+drag"),
|
||||
(Transform, "Nudge (Shift: big nudge)", "← ↑ → ↓", "← ↑ → ↓"),
|
||||
(Transform, "Resize by the nudge amount", "⌘ arrows", "Ctrl+arrows"),
|
||||
|
||||
@@ -107,13 +107,16 @@ use serde_json::{Value, json};
|
||||
mod derived;
|
||||
mod doc_state;
|
||||
mod error;
|
||||
mod file_views;
|
||||
mod prefs;
|
||||
mod reopen;
|
||||
mod session;
|
||||
mod view_state;
|
||||
|
||||
pub use derived::{changed_nodes, normalize};
|
||||
pub use doc_state::{DocState, History, HistoryEntry, Interaction, PREVIEW_READ_ONLY, Preedit, TextEdit, VersionPreview};
|
||||
pub use error::{EngineError, Result, bad};
|
||||
pub use file_views::{FileView, MAX_FILE_VIEWS, PageView};
|
||||
pub use prefs::{Clipboard, DefaultProps, MAX_RECENT_ACTIONS, Prefs, UI_SCALE_MAX, UI_SCALE_MIN, UI_SCALE_SIZES, UiRequest, clamp_ui_scale};
|
||||
pub use session::Forward;
|
||||
pub use view_state::ViewState;
|
||||
@@ -489,6 +492,8 @@ mod panels_behaviour_tests;
|
||||
#[cfg(test)]
|
||||
mod paste_missing_image_tests;
|
||||
#[cfg(test)]
|
||||
mod paste_over_tests;
|
||||
#[cfg(test)]
|
||||
mod paste_sibling_tests;
|
||||
#[cfg(test)]
|
||||
mod path_read_caps_tests;
|
||||
@@ -549,6 +554,8 @@ mod proto_run_tests;
|
||||
#[cfg(test)]
|
||||
mod proto_tail_tests;
|
||||
#[cfg(test)]
|
||||
mod reopen_tests;
|
||||
#[cfg(test)]
|
||||
mod rest_slot_tests;
|
||||
#[cfg(test)]
|
||||
mod retained_walk_tests;
|
||||
@@ -625,6 +632,8 @@ mod text_motion_tests;
|
||||
#[cfg(test)]
|
||||
mod text_style_picker_tests;
|
||||
#[cfg(test)]
|
||||
mod text_tab_tests;
|
||||
#[cfg(test)]
|
||||
mod text_tail_tests;
|
||||
#[cfg(test)]
|
||||
mod text_weight_step_tests;
|
||||
@@ -698,6 +707,8 @@ mod export_bounds_tests;
|
||||
#[cfg(test)]
|
||||
mod page_view_tests;
|
||||
#[cfg(test)]
|
||||
mod paste_properties_tests;
|
||||
#[cfg(test)]
|
||||
mod selection_reorder_tests;
|
||||
#[cfg(test)]
|
||||
mod selection_spacing_tests;
|
||||
@@ -0,0 +1,95 @@
|
||||
//! Shift+Cmd/Ctrl+V with several layers selected pastes after the last of them as seen.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::Session;
|
||||
use crate::params::id_of;
|
||||
use figcraft_doc::NodeId;
|
||||
|
||||
fn id(v: &Value) -> NodeId {
|
||||
id_of(&v["id"]).unwrap()
|
||||
}
|
||||
|
||||
fn frame(s: &mut Session, x: f64, y: f64) -> NodeId {
|
||||
id(&s.execute("frame.create", &json!({"x": x, "y": y, "width": 200, "height": 100})).unwrap())
|
||||
}
|
||||
|
||||
fn kids(s: &Session, parent: NodeId) -> Vec<NodeId> {
|
||||
s.doc().unwrap().node(parent).unwrap().children.clone()
|
||||
}
|
||||
|
||||
fn paste_over(s: &mut Session, sel: Vec<NodeId>) -> Vec<NodeId> {
|
||||
s.set_selection(sel);
|
||||
s.execute("edit.pasteOver", &json!({})).unwrap()["ids"].as_array().unwrap().iter().filter_map(id_of).collect()
|
||||
}
|
||||
|
||||
fn top_left(s: &Session, n: NodeId) -> (f64, f64) {
|
||||
let b = s.doc().unwrap().world_bounds(n).unwrap();
|
||||
(b.x0, b.y0)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn several_rows_of_an_auto_layout_selected_get_the_copy_after_the_last_row() {
|
||||
let mut s = Session::new();
|
||||
let rows: Vec<NodeId> =
|
||||
(0..4).map(|k| id(&s.execute("shape.rectangle", &json!({"x": 0, "y": k * 30, "width": 40, "height": 20})).unwrap())).collect();
|
||||
let r = s.execute("layout.add", &json!({"ids": rows, "direction": "vertical"})).unwrap();
|
||||
let list = id_of(&r["ids"][0]).unwrap();
|
||||
assert_eq!(kids(&s, list), rows);
|
||||
s.execute("edit.copy", &json!({"ids": [rows[0]]})).unwrap();
|
||||
// Clicked from the middle down and back: the click order isn't the order on screen.
|
||||
let pasted = paste_over(&mut s, vec![rows[1], rows[3], rows[2]]);
|
||||
assert_eq!(pasted.len(), 1);
|
||||
assert_eq!(kids(&s, list), vec![rows[0], rows[1], rows[2], rows[3], pasted[0]], "after the last selected row");
|
||||
assert_eq!(s.selection(), pasted);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn several_artboards_in_a_column_get_the_copy_below_the_lowest_with_their_gap() {
|
||||
let mut s = Session::new();
|
||||
let (a, b, c) = (frame(&mut s, 0.0, 0.0), frame(&mut s, 0.0, 140.0), frame(&mut s, 0.0, 280.0));
|
||||
let source = frame(&mut s, 1000.0, 0.0);
|
||||
s.execute("edit.copy", &json!({"ids": [source]})).unwrap();
|
||||
let pasted = paste_over(&mut s, vec![a, c, b]);
|
||||
assert_eq!(pasted.len(), 1);
|
||||
assert_eq!(top_left(&s, pasted[0]), (0.0, 420.0), "below the lowest artboard, 40 below it like the others");
|
||||
let page = s.doc().unwrap().node(c).unwrap().parent.unwrap();
|
||||
let order = kids(&s, page);
|
||||
let at = |n: NodeId| order.iter().position(|i| *i == n).unwrap();
|
||||
assert_eq!(at(pasted[0]), at(c) + 1, "just above the lowest artboard");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn several_artboards_in_a_row_get_the_copy_right_of_the_rightmost_with_their_gap() {
|
||||
let mut s = Session::new();
|
||||
let (a, b, c) = (frame(&mut s, 0.0, 0.0), frame(&mut s, 260.0, 0.0), frame(&mut s, 520.0, 0.0));
|
||||
let source = frame(&mut s, 0.0, 1000.0);
|
||||
s.execute("edit.copy", &json!({"ids": [source]})).unwrap();
|
||||
let pasted = paste_over(&mut s, vec![b, a, c]);
|
||||
assert_eq!(top_left(&s, pasted[0]), (780.0, 0.0), "right of the rightmost, 60 from it like the others");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn several_overlapping_layers_get_the_copy_right_under_the_lowest() {
|
||||
let mut s = Session::new();
|
||||
let (a, b) = (frame(&mut s, 0.0, 0.0), frame(&mut s, 50.0, 30.0));
|
||||
let source = frame(&mut s, 1000.0, 0.0);
|
||||
s.execute("edit.copy", &json!({"ids": [source]})).unwrap();
|
||||
let pasted = paste_over(&mut s, vec![b, a]);
|
||||
assert_eq!(top_left(&s, pasted[0]), (50.0, 130.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn several_absolute_layers_of_an_auto_layout_get_the_copy_below_the_lowest() {
|
||||
let mut s = Session::new();
|
||||
let rows: Vec<NodeId> =
|
||||
(0..3).map(|k| id(&s.execute("shape.rectangle", &json!({"x": 0, "y": k * 30, "width": 40, "height": 20})).unwrap())).collect();
|
||||
s.execute("layout.add", &json!({"ids": rows, "direction": "vertical"})).unwrap();
|
||||
s.execute("node.set", &json!({"ids": rows, "props": {"absolute": true}})).unwrap();
|
||||
s.execute("edit.copy", &json!({"ids": [rows[0]]})).unwrap();
|
||||
let (x, y0) = top_left(&s, rows[1]);
|
||||
let (_, y1) = top_left(&s, rows[2]);
|
||||
let pasted = paste_over(&mut s, vec![rows[2], rows[0], rows[1]]);
|
||||
assert_eq!(pasted.len(), 1);
|
||||
assert_eq!(top_left(&s, pasted[0]), (x, y1 + 20.0 + (y1 - y0 - 20.0)), "the layout doesn't place them, so below the lowest");
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
//! Copy properties and Paste properties (Alt+Cmd/Ctrl+C and V) carry what a layer's look comes
|
||||
//! from as well as its values: its colour, effect and grid styles, the variables bound to what is
|
||||
//! copied and a frame's layout grids. A link the file pasted into doesn't have is left out.
|
||||
|
||||
use figcraft_doc::{LayoutGrid, NodeId};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::Session;
|
||||
|
||||
fn id(v: Value) -> NodeId {
|
||||
NodeId(v["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
fn frame(s: &mut Session, x: f64) -> NodeId {
|
||||
id(s.execute("frame.create", &json!({"x": x, "y": 0, "width": 100, "height": 100})).unwrap())
|
||||
}
|
||||
|
||||
fn copy_onto(s: &mut Session, from: NodeId, to: NodeId) {
|
||||
s.execute("edit.copyProperties", &json!({"id": from})).unwrap();
|
||||
s.execute("edit.pasteProperties", &json!({"ids": [to]})).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_frame_pastes_its_styles_variables_and_layout_grids() {
|
||||
let mut s = Session::new();
|
||||
let (a, b, c) = (frame(&mut s, 0.0), frame(&mut s, 200.0), frame(&mut s, 400.0));
|
||||
s.execute("variable.createCollection", &json!({"name": "Tokens"})).unwrap();
|
||||
for (name, value) in [("surface", "#FF0000"), ("other", "#0000FF")] {
|
||||
s.execute("variable.create", &json!({"collection": "Tokens", "name": name, "type": "color", "value": value})).unwrap();
|
||||
}
|
||||
s.execute("variable.create", &json!({"collection": "Tokens", "name": "radius", "type": "number", "value": 16})).unwrap();
|
||||
s.execute("variable.bind", &json!({"ids": [a], "field": "fills/0/color", "variable": "surface"})).unwrap();
|
||||
s.execute("variable.bind", &json!({"ids": [a], "field": "cornerRadius", "variable": "radius"})).unwrap();
|
||||
s.execute("node.set", &json!({"ids": [a], "props": {"grids": [serde_json::to_value(LayoutGrid::default()).unwrap()]}})).unwrap();
|
||||
// B is bound to another colour, which the paste replaces.
|
||||
s.execute("variable.bind", &json!({"ids": [b], "field": "fills/0/color", "variable": "other"})).unwrap();
|
||||
let shadow = s.execute("style.create", &json!({"type": "effect", "name": "Shadow", "value": [{"type": "dropShadow"}]})).unwrap()["id"].clone();
|
||||
let green = s.execute("style.create", &json!({"type": "paint", "name": "Green", "value": "#00FF00"})).unwrap()["id"].clone();
|
||||
s.execute("style.apply", &json!({"ids": [c], "style": green})).unwrap();
|
||||
s.execute("style.apply", &json!({"ids": [c], "style": shadow})).unwrap();
|
||||
|
||||
copy_onto(&mut s, a, b);
|
||||
let (na, nb) = (s.doc().unwrap().node(a).unwrap().clone(), s.doc().unwrap().node(b).unwrap().clone());
|
||||
assert_eq!(nb.bound.get("fills/0/color"), na.bound.get("fills/0/color"), "the fill follows the same variable");
|
||||
assert_eq!(nb.bound.get("cornerRadius"), na.bound.get("cornerRadius"), "and so do the corners");
|
||||
assert_eq!(nb.corners.radii, [16.0; 4]);
|
||||
assert_eq!(nb.grids, na.grids, "a frame's layout grids come along");
|
||||
|
||||
copy_onto(&mut s, c, a);
|
||||
let (na, nc) = (s.doc().unwrap().node(a).unwrap().clone(), s.doc().unwrap().node(c).unwrap().clone());
|
||||
assert_eq!(na.styles.fill, nc.styles.fill, "the fill style is linked");
|
||||
assert!(nc.styles.effect.is_some() && na.styles.effect == nc.styles.effect, "the effect style too");
|
||||
assert!(!na.bound.contains_key("fills/0/color"), "the style replaces the fill's variable");
|
||||
assert!(!na.bound.contains_key("cornerRadius"), "C's corners aren't bound, so A's aren't any more");
|
||||
assert!(na.grids.is_empty(), "nor has it layout grids");
|
||||
assert_eq!(na.fills, nc.fills);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn links_another_file_lacks_paste_as_values() {
|
||||
let mut s = Session::new();
|
||||
let a = frame(&mut s, 0.0);
|
||||
s.execute("variable.createCollection", &json!({"name": "Tokens"})).unwrap();
|
||||
s.execute("variable.create", &json!({"collection": "Tokens", "name": "surface", "type": "color", "value": "#FF0000"})).unwrap();
|
||||
s.execute("variable.bind", &json!({"ids": [a], "field": "fills/0/color", "variable": "surface"})).unwrap();
|
||||
let st = s.execute("style.create", &json!({"type": "paint", "name": "Line", "value": "#00FF00"})).unwrap()["id"].clone();
|
||||
s.execute("node.set", &json!({"ids": [a], "props": {"strokes": [{"type": "solid", "color": "#000000"}]}})).unwrap();
|
||||
s.execute("style.apply", &json!({"ids": [a], "style": st, "target": "stroke"})).unwrap();
|
||||
s.execute("edit.copyProperties", &json!({"id": a})).unwrap();
|
||||
let copied = s.doc().unwrap().node(a).unwrap().clone();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let b = frame(&mut s, 0.0);
|
||||
// This file's own style and variable come out with the copied ids: they are not the copied ones.
|
||||
s.execute("variable.createCollection", &json!({"name": "Theirs"})).unwrap();
|
||||
s.execute("variable.create", &json!({"collection": "Theirs", "name": "ink", "type": "color", "value": "#0000FF"})).unwrap();
|
||||
s.execute("style.create", &json!({"type": "paint", "name": "Ink", "value": "#0000FF"})).unwrap();
|
||||
let doc = s.doc().unwrap();
|
||||
let vid = copied.bound["fills/0/color"].as_str();
|
||||
assert!(doc.style(st.as_str().unwrap()).is_some() && doc.variables.get_by_id(vid).is_some(), "the ids are taken here");
|
||||
s.execute("edit.pasteProperties", &json!({"ids": [b]})).unwrap();
|
||||
let nb = s.doc().unwrap().node(b).unwrap();
|
||||
assert_eq!((nb.fills.clone(), nb.strokes.clone()), (copied.fills, copied.strokes), "the values arrive");
|
||||
assert!(nb.bound.is_empty() && nb.styles.fill.is_none() && nb.styles.stroke.is_none(), "{:?} {:?}", nb.bound, nb.styles);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_style_unlinks_the_layers_own() {
|
||||
let mut s = Session::new();
|
||||
let (a, b) = (frame(&mut s, 0.0), frame(&mut s, 200.0));
|
||||
// B's own style gives the same colour, so the paste changes no value that would unlink it.
|
||||
let gone = s.execute("style.create", &json!({"type": "paint", "name": "Gone", "value": "#00FF00"})).unwrap()["id"].clone();
|
||||
let own = s.execute("style.create", &json!({"type": "paint", "name": "Own", "value": "#00FF00"})).unwrap()["id"].clone();
|
||||
s.execute("style.apply", &json!({"ids": [a], "style": gone, "target": "stroke"})).unwrap();
|
||||
s.execute("style.apply", &json!({"ids": [b], "style": own, "target": "stroke"})).unwrap();
|
||||
s.execute("edit.copyProperties", &json!({"id": a})).unwrap();
|
||||
s.execute("style.delete", &json!({"style": gone})).unwrap();
|
||||
|
||||
s.execute("edit.pasteProperties", &json!({"ids": [b]})).unwrap();
|
||||
let nb = s.doc().unwrap().node(b).unwrap();
|
||||
assert!(nb.styles.stroke.is_none(), "A's strokes had no style here, so B's aren't linked: {:?}", nb.styles);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_binding_on_what_the_copy_doesnt_carry_stays() {
|
||||
let mut s = Session::new();
|
||||
let a = frame(&mut s, 0.0);
|
||||
let t = id(s.execute("text.create", &json!({"text": "Hi", "x": 0, "y": 200})).unwrap());
|
||||
s.execute("variable.createCollection", &json!({"name": "Tokens"})).unwrap();
|
||||
s.execute("variable.create", &json!({"collection": "Tokens", "name": "body", "type": "number", "value": 18})).unwrap();
|
||||
s.execute("variable.bind", &json!({"ids": [t], "field": "fontSize", "variable": "body"})).unwrap();
|
||||
let before = s.doc().unwrap().node(t).unwrap().bound.get("fontSize").cloned();
|
||||
|
||||
copy_onto(&mut s, a, t);
|
||||
let nt = s.doc().unwrap().node(t).unwrap();
|
||||
assert!(before.is_some() && nt.bound.get("fontSize") == before.as_ref(), "a frame carries no font size: {:?}", nt.bound);
|
||||
}
|
||||
@@ -63,7 +63,8 @@ pub struct Prefs {
|
||||
/// Files that have a path are saved by themselves a few seconds after they change (the app's
|
||||
/// timer; off: only File ▸ Save writes them).
|
||||
pub auto_save: bool,
|
||||
/// The desktop app starts on the Home screen instead of in a new file.
|
||||
/// The desktop app starts on the Home screen instead of reopening the files open when it last
|
||||
/// quit.
|
||||
pub start_on_home: bool,
|
||||
/// `figcraft://` invite links open this app (`collab.registerLinks`); `None`: on for installed
|
||||
/// builds, off for development builds.
|
||||
@@ -85,6 +86,18 @@ pub struct Prefs {
|
||||
/// Recently opened or saved files, newest first (File ▸ Open recent; at most
|
||||
/// [`cmd::file::MAX_RECENT`]).
|
||||
pub recent_files: Vec<String>,
|
||||
/// The files open when the desktop app last quit, in tab order: the next start opens them again
|
||||
/// ([`Session::reopen_files`](crate::Session::reopen_files)).
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub open_files: Vec<String>,
|
||||
/// Which of [`open_files`](Self::open_files) was in front.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub front_file: Option<String>,
|
||||
/// Where each file was left when its tab closed or the app quit, the most recently left first,
|
||||
/// at most [`MAX_FILE_VIEWS`](crate::MAX_FILE_VIEWS): opening it again shows that page at that
|
||||
/// view ([`Session::remember_views`](crate::Session::remember_views)).
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub file_views: Vec<crate::FileView>,
|
||||
/// The files you put on a server without its key, with their owner tokens (passwords: see
|
||||
/// [`online`]), most recently opened first, at most [`online::MAX_ONLINE_FILES`].
|
||||
#[serde(skip_serializing_if = "Vec::is_empty", deserialize_with = "online::read")]
|
||||
@@ -158,6 +171,9 @@ impl Default for Prefs {
|
||||
plugin_directory: None,
|
||||
publish_server: live::DEFAULT_SERVER.into(),
|
||||
recent_files: Vec::new(),
|
||||
open_files: Vec::new(),
|
||||
front_file: None,
|
||||
file_views: Vec::new(),
|
||||
online_files: Vec::new(),
|
||||
getting_started_dismissed: false,
|
||||
link_notice_skipped: false,
|
||||
@@ -201,6 +217,9 @@ pub struct Clipboard {
|
||||
pub images: std::collections::BTreeMap<String, figcraft_doc::ImageData>,
|
||||
/// Copied properties (Copy properties / Paste properties).
|
||||
pub props: Option<Value>,
|
||||
/// The file the copied properties came from: their style and variable ids name its styles and
|
||||
/// variables, and in another file the same ids can name unrelated ones.
|
||||
pub props_source_doc: u64,
|
||||
/// A copied fill or stroke row (`fill.copy`, `stroke.copy`): whether it's a fill, and the paint.
|
||||
pub paint: Option<(bool, figcraft_color::Paint)>,
|
||||
/// The stroke settings (`weight`, alignment, sides…) copied with a stroke's paint.
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
//! The files open when the desktop app quit open again at its next start, in their tabs' order
|
||||
//! with the same one in front, as Figma's desktop app reopens its tabs.
|
||||
|
||||
use serde_json::json;
|
||||
|
||||
use crate::{EngineError, Session};
|
||||
|
||||
impl Session {
|
||||
/// Keep the open files to reopen at the next start: each tab's file that has a path, in tab
|
||||
/// order, and the one in front. Files without one (new, imported, joined from a live session)
|
||||
/// and branch tabs are left out.
|
||||
pub fn remember_open_files(&mut self) {
|
||||
let path = |i: usize| self.docs.get(i).filter(|d| d.branch_of.is_none()).and_then(|d| d.path.clone());
|
||||
self.prefs.open_files = (0..self.docs.len()).filter_map(path).collect();
|
||||
self.prefs.front_file = path(self.active);
|
||||
}
|
||||
|
||||
/// Open the files [`remember_open_files`](Self::remember_open_files) kept, then bring the one
|
||||
/// that was in front forward. A file that is no longer there is skipped; the others that don't
|
||||
/// open come back with why. A file already open (a recovered copy, one named at start) keeps
|
||||
/// its tab.
|
||||
pub fn reopen_files(&mut self) -> Vec<(String, EngineError)> {
|
||||
let mut failed = Vec::new();
|
||||
for path in self.prefs.open_files.clone() {
|
||||
if !crate::file_access::exists(&path) {
|
||||
continue;
|
||||
}
|
||||
if let Err(e) = self.execute("file.open", &json!({"path": path})) {
|
||||
failed.push((path, e));
|
||||
}
|
||||
}
|
||||
let front = self.prefs.front_file.as_deref();
|
||||
if let Some(i) = self.docs.iter().position(|d| front.is_some() && d.path.as_deref() == front) {
|
||||
self.active = i;
|
||||
}
|
||||
failed
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
//! The files open when the desktop app quit open again at its next start.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use serde_json::json;
|
||||
|
||||
use crate::Session;
|
||||
|
||||
/// A fresh folder for a test's files, removed when the test ends, a failing one too.
|
||||
struct Folder(PathBuf);
|
||||
|
||||
impl std::ops::Deref for Folder {
|
||||
type Target = Path;
|
||||
fn deref(&self) -> &Path {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Folder {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
fn folder(name: &str) -> Folder {
|
||||
let dir = std::env::temp_dir().join(format!("figcraft-reopen-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
Folder(dir)
|
||||
}
|
||||
|
||||
fn saved(s: &mut Session, dir: &Path, name: &str) -> String {
|
||||
let path = dir.join(format!("{name}.figcraft")).to_string_lossy().into_owned();
|
||||
s.execute("file.new", &json!({"name": name})).unwrap();
|
||||
s.execute("file.save", &json!({"path": path})).unwrap();
|
||||
path
|
||||
}
|
||||
|
||||
fn paths(s: &Session) -> Vec<Option<String>> {
|
||||
s.docs.iter().map(|d| d.path.clone()).collect()
|
||||
}
|
||||
|
||||
/// The next start: the preferences the last run kept, nothing open yet.
|
||||
fn next_start(last: &Session) -> Session {
|
||||
let mut s = Session::empty();
|
||||
s.prefs = last.prefs.clone();
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_files_open_at_quit_reopen_in_their_order_with_the_same_one_in_front() {
|
||||
let dir = folder("order");
|
||||
let mut s = Session::empty();
|
||||
let a = saved(&mut s, &dir, "A");
|
||||
s.execute("file.new", &json!({"name": "Untitled"})).unwrap();
|
||||
let b = saved(&mut s, &dir, "B");
|
||||
let c = saved(&mut s, &dir, "C");
|
||||
s.execute("doc.switch", &json!({"index": 2})).unwrap();
|
||||
s.remember_open_files();
|
||||
assert_eq!(s.prefs.open_files, vec![a.clone(), b.clone(), c.clone()], "the new file without a path is left out");
|
||||
assert_eq!(s.prefs.front_file.as_deref(), Some(b.as_str()));
|
||||
|
||||
let mut t = next_start(&s);
|
||||
assert!(t.reopen_files().is_empty());
|
||||
assert_eq!(paths(&t), vec![Some(a), Some(b.clone()), Some(c)]);
|
||||
assert_eq!(t.docs[t.active].path.as_deref(), Some(b.as_str()), "B is in front again");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_gone_since_is_skipped_and_one_that_wont_open_says_why() {
|
||||
let dir = folder("gone");
|
||||
let mut s = Session::empty();
|
||||
let kept = saved(&mut s, &dir, "Kept");
|
||||
let gone = saved(&mut s, &dir, "Gone");
|
||||
let broken = saved(&mut s, &dir, "Broken");
|
||||
s.remember_open_files();
|
||||
std::fs::remove_file(&gone).unwrap();
|
||||
std::fs::write(&broken, b"not a figcraft file").unwrap();
|
||||
|
||||
let mut t = next_start(&s);
|
||||
let failed = t.reopen_files();
|
||||
assert_eq!(failed.iter().map(|(p, _)| p.clone()).collect::<Vec<_>>(), vec![broken]);
|
||||
assert_eq!(paths(&t), vec![Some(kept)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_already_open_at_start_keeps_its_one_tab() {
|
||||
let dir = folder("twice");
|
||||
let mut s = Session::empty();
|
||||
let a = saved(&mut s, &dir, "A");
|
||||
let b = saved(&mut s, &dir, "B");
|
||||
s.execute("doc.switch", &json!({"index": 0})).unwrap();
|
||||
s.remember_open_files();
|
||||
|
||||
// B was named on the command line (or came back as a recovered copy).
|
||||
let mut t = next_start(&s);
|
||||
t.execute("file.open", &json!({"path": b})).unwrap();
|
||||
assert!(t.reopen_files().is_empty());
|
||||
assert_eq!(paths(&t), vec![Some(b), Some(a.clone())]);
|
||||
assert_eq!(t.docs[t.active].path.as_deref(), Some(a.as_str()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quitting_with_nothing_open_leaves_nothing_to_reopen() {
|
||||
let dir = folder("none");
|
||||
let mut s = Session::empty();
|
||||
saved(&mut s, &dir, "A");
|
||||
s.remember_open_files();
|
||||
s.execute("file.close", &json!({"index": 0})).unwrap();
|
||||
s.remember_open_files();
|
||||
assert!(s.prefs.open_files.is_empty());
|
||||
assert_eq!(s.prefs.front_file, None);
|
||||
let saved = serde_json::to_value(&s.prefs).unwrap();
|
||||
assert!(saved.get("open_files").is_none() && saved.get("front_file").is_none(), "not written when empty");
|
||||
}
|
||||
@@ -94,7 +94,7 @@ fn assert_save_state_unchanged(s: &Session, before: &DocState, recent: &[String]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_native_save_uses_chosen_filename_for_an_untitled_document() {
|
||||
fn saving_to_another_file_names_the_document_after_it() {
|
||||
let mut files = SaveFiles::new();
|
||||
let path = files.path("Redis.figcraft");
|
||||
let copy = files.path("Redis copy.figcraft");
|
||||
@@ -111,9 +111,19 @@ fn first_native_save_uses_chosen_filename_for_an_untitled_document() {
|
||||
|
||||
s.execute("file.saveAs", &json!({"path": copy.to_string_lossy()})).unwrap();
|
||||
assert_eq!(s.ds().unwrap().doc.name, "Redis copy");
|
||||
s.execute("file.rename", &json!({"name": "Chosen title"})).unwrap();
|
||||
s.execute("file.rename", &json!({"name": "Chosen: title"})).unwrap();
|
||||
s.execute("file.save", &json!({})).unwrap();
|
||||
assert_eq!(s.ds().unwrap().doc.name, "Chosen: title", "saving to the same file keeps a name given here");
|
||||
s.execute("file.saveAs", &json!({"path": manual_copy.to_string_lossy()})).unwrap();
|
||||
assert_eq!(s.ds().unwrap().doc.name, "Chosen title");
|
||||
assert_eq!(s.ds().unwrap().doc.name, "Other", "a name given here too");
|
||||
assert_eq!(figcraft_format::load_bytes(&std::fs::read(&manual_copy).unwrap()).unwrap().0.name, "Other");
|
||||
|
||||
// A file without one on disk yet: imported, here with its source's name.
|
||||
let imported = files.path("Imported.figcraft");
|
||||
let mut i = Session::new();
|
||||
i.execute("file.rename", &json!({"name": "ШИМ"})).unwrap();
|
||||
i.execute("file.saveAs", &json!({"path": imported.to_string_lossy()})).unwrap();
|
||||
assert_eq!(i.ds().unwrap().doc.name, "Imported");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
//! Tab and Shift+Tab while editing a text layer move editing to the next or previous text layer
|
||||
//! of the same top-level frame, in reading order (rows top to bottom, each left to right), with
|
||||
//! all of its text selected; hidden and locked text is passed over, and at either end the key
|
||||
//! does nothing.
|
||||
|
||||
use figcraft_doc::NodeId;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::Session;
|
||||
use crate::params::id_of;
|
||||
|
||||
fn ex(s: &mut Session, cmd: &str, p: Value) -> Value {
|
||||
s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}"))
|
||||
}
|
||||
|
||||
fn text(s: &mut Session, chars: &str, x: f64, y: f64, parent: NodeId) -> NodeId {
|
||||
id_of(&ex(s, "text.create", json!({"text": chars, "x": x, "y": y, "parent": parent}))["id"]).unwrap()
|
||||
}
|
||||
|
||||
fn frame(s: &mut Session, x: f64, y: f64) -> NodeId {
|
||||
id_of(&ex(s, "frame.create", json!({"x": x, "y": y, "width": 400, "height": 300}))["id"]).unwrap()
|
||||
}
|
||||
|
||||
fn tab(s: &mut Session, shift: bool) {
|
||||
ex(s, "text.edit.key", json!({"key": "Tab", "shift": shift}));
|
||||
}
|
||||
|
||||
/// The text being edited and whether all of it is selected.
|
||||
fn editing(s: &Session) -> (NodeId, bool) {
|
||||
let te = s.ds().unwrap().text_edit.clone().expect("still editing");
|
||||
let n = s.doc().unwrap().node(te.id).unwrap().kind.text().unwrap().char_count();
|
||||
(te.id, te.anchor.min(te.caret) == 0 && te.anchor.max(te.caret) == n)
|
||||
}
|
||||
|
||||
fn chars(s: &Session, id: NodeId) -> String {
|
||||
s.doc().unwrap().node(id).unwrap().kind.text().unwrap().characters.clone()
|
||||
}
|
||||
|
||||
/// A frame with a row of three texts whose tops differ by a few pixels, out of order in the
|
||||
/// layer list, and a second row below; a text in another frame beside it.
|
||||
fn two_rows(s: &mut Session) -> Vec<NodeId> {
|
||||
let f = frame(s, 0.0, 0.0);
|
||||
let b = text(s, "B", 150.0, 12.0, f);
|
||||
let a = text(s, "A", 10.0, 10.0, f);
|
||||
let e = text(s, "E", 150.0, 100.0, f);
|
||||
let c = text(s, "C", 290.0, 6.0, f);
|
||||
let d = text(s, "D", 10.0, 101.0, f);
|
||||
let other = frame(s, 500.0, 0.0);
|
||||
text(s, "Elsewhere", 10.0, 10.0, other);
|
||||
vec![a, b, c, d, e]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tab_reads_a_row_left_to_right_then_the_next_row() {
|
||||
let mut s = Session::new();
|
||||
let order = two_rows(&mut s);
|
||||
ex(&mut s, "text.edit.begin", json!({"id": order[0], "caret": 0}));
|
||||
for want in &order[1..] {
|
||||
tab(&mut s, false);
|
||||
assert_eq!(editing(&s), (*want, true), "on to {} with all of it selected", chars(&s, *want));
|
||||
}
|
||||
assert!(order.iter().all(|t| !chars(&s, *t).contains('\t')), "no tab typed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shift_tab_goes_back() {
|
||||
let mut s = Session::new();
|
||||
let order = two_rows(&mut s);
|
||||
ex(&mut s, "text.edit.begin", json!({"id": order[4], "caret": 0}));
|
||||
for want in order[..4].iter().rev() {
|
||||
tab(&mut s, true);
|
||||
assert_eq!(editing(&s).0, *want, "back to {}", chars(&s, *want));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tab_on_the_last_text_keeps_editing_it() {
|
||||
let mut s = Session::new();
|
||||
let order = two_rows(&mut s);
|
||||
let undo = s.ds().unwrap().history.undo.len();
|
||||
ex(&mut s, "text.edit.begin", json!({"id": order[4], "caret": 1}));
|
||||
tab(&mut s, false);
|
||||
let te = s.ds().unwrap().text_edit.clone().expect("still editing");
|
||||
assert_eq!((te.id, te.caret, te.anchor), (order[4], 1, 1), "the last one: nothing moves");
|
||||
assert_eq!(chars(&s, order[4]), "E", "and nothing is typed");
|
||||
// Shift+Tab on the first one does nothing either.
|
||||
ex(&mut s, "text.edit.end", json!({}));
|
||||
ex(&mut s, "text.edit.begin", json!({"id": order[0], "caret": 0}));
|
||||
tab(&mut s, true);
|
||||
assert_eq!(editing(&s).0, order[0]);
|
||||
ex(&mut s, "text.edit.end", json!({}));
|
||||
assert_eq!(s.ds().unwrap().history.undo.len(), undo, "no undo step for it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hidden_and_locked_text_is_skipped() {
|
||||
let mut s = Session::new();
|
||||
let f = frame(&mut s, 0.0, 0.0);
|
||||
let first = text(&mut s, "First", 10.0, 10.0, f);
|
||||
let hidden = text(&mut s, "Hidden", 10.0, 50.0, f);
|
||||
ex(&mut s, "node.set", json!({"id": hidden, "props": {"visible": false}}));
|
||||
let locked = text(&mut s, "Locked", 10.0, 90.0, f);
|
||||
ex(&mut s, "node.set", json!({"id": locked, "props": {"locked": true}}));
|
||||
let inner = id_of(&ex(&mut s, "frame.create", json!({"x": 10, "y": 130, "width": 200, "height": 60, "parent": f}))["id"]).unwrap();
|
||||
text(&mut s, "In a locked frame", 0.0, 0.0, inner);
|
||||
ex(&mut s, "node.set", json!({"id": inner, "props": {"locked": true}}));
|
||||
let last = text(&mut s, "Last", 10.0, 220.0, f);
|
||||
ex(&mut s, "text.edit.begin", json!({"id": first, "caret": 0}));
|
||||
tab(&mut s, false);
|
||||
assert_eq!(editing(&s).0, last, "past the hidden text, the locked one and the text in a locked frame");
|
||||
tab(&mut s, true);
|
||||
assert_eq!(editing(&s).0, first);
|
||||
}
|
||||
@@ -221,11 +221,11 @@ fn list_keys_at_list_items() {
|
||||
2,
|
||||
"Tab",
|
||||
false,
|
||||
"a\n\tb",
|
||||
"a\nb",
|
||||
vec![(B, 0), (P, 1)],
|
||||
"a plain paragraph at a level isn't an item: Tab types a tab",
|
||||
"a plain paragraph at a level isn't an item: Tab leaves the list alone (and moves to the next text, none here)",
|
||||
),
|
||||
("a\nb", vec![(P, 0), (P, 0)], 3, "Tab", false, "a\nb\t", vec![(P, 0), (P, 0)], "outside a list Tab types a tab"),
|
||||
("a\nb", vec![(P, 0), (P, 0)], 3, "Tab", false, "a\nb", vec![(P, 0), (P, 0)], "outside a list Tab types no tab"),
|
||||
("a", vec![(B, 8)], 1, "Tab", false, "a", vec![(B, 8)], "silent: nesting stops at 8 levels"),
|
||||
];
|
||||
for (chars, before, caret, k, shift, after, want, why) in cases {
|
||||
|
||||
@@ -217,6 +217,124 @@ fn ordinary_resize_and_scale_keep_image_fill_settings() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crop_mode_image_resizing_without_cmd_morphs_and_with_cmd_crops() {
|
||||
use figcraft_doc::color::{ImageScaleMode, PaintKind};
|
||||
let mut s = session();
|
||||
let layer = image_layer(&mut s);
|
||||
// Set the image fill mode to Crop without an explicit crop: fill.set initializes placement crop.
|
||||
let mut fills = s.doc().unwrap().node(layer).unwrap().fills.clone();
|
||||
let PaintKind::Image(img) = &mut fills[0].kind else { panic!("image fill") };
|
||||
img.scale_mode = ImageScaleMode::Crop;
|
||||
img.crop = None;
|
||||
ex(&mut s, "fill.set", json!({"ids": [layer], "index": 0, "paint": fills[0]}));
|
||||
|
||||
// Verify fill.set initialized img.crop with placement crop.
|
||||
let initial_node = s.doc().unwrap().node(layer).unwrap().clone();
|
||||
let PaintKind::Image(img) = &initial_node.fills[0].kind else { panic!("image fill") };
|
||||
let Some(initial_crop) = img.crop else { panic!("crop initialized") };
|
||||
|
||||
let before = figcraft_render::render_node(s.doc().unwrap(), layer, 1.0).unwrap();
|
||||
assert_eq!((before.width(), before.height()), (200, 100));
|
||||
|
||||
// 1. Resize without Cmd (normal resize from bottom edge: 100 -> 50).
|
||||
// The layer height shrinks to 50, but img.crop stays unchanged, stretching/squishing the image.
|
||||
s.pointer(&ev(PointerKind::Down, Point::new(100.0, 100.0), NONE)).unwrap();
|
||||
s.pointer(&ev(PointerKind::Move, Point::new(100.0, 50.0), NONE)).unwrap();
|
||||
s.pointer(&ev(PointerKind::Up, Point::new(100.0, 50.0), NONE)).unwrap();
|
||||
assert_eq!(size(&s, layer), (200.0, 50.0));
|
||||
|
||||
let n = s.doc().unwrap().node(layer).unwrap().clone();
|
||||
let PaintKind::Image(img) = &n.fills[0].kind else { panic!("image fill") };
|
||||
assert_eq!(img.crop, Some(initial_crop), "normal resize leaves crop transform unchanged");
|
||||
|
||||
let morphed = figcraft_render::render_node(s.doc().unwrap(), layer, 1.0).unwrap();
|
||||
assert_eq!((morphed.width(), morphed.height()), (200, 50));
|
||||
|
||||
// 2. Resize with Cmd from right edge: 200 -> 100.
|
||||
// The layer width shrinks to 100, and img.crop is updated so the pixels stay stationary on page (cropping).
|
||||
s.pointer(&ev(PointerKind::Down, Point::new(200.0, 25.0), CMD)).unwrap();
|
||||
s.pointer(&ev(PointerKind::Move, Point::new(100.0, 25.0), CMD)).unwrap();
|
||||
s.pointer(&ev(PointerKind::Up, Point::new(100.0, 25.0), CMD)).unwrap();
|
||||
assert_eq!(size(&s, layer), (100.0, 50.0));
|
||||
|
||||
let n = s.doc().unwrap().node(layer).unwrap().clone();
|
||||
let PaintKind::Image(img) = &n.fills[0].kind else { panic!("image fill") };
|
||||
assert_ne!(img.crop, Some(initial_crop), "Cmd resize updates crop transform");
|
||||
|
||||
let cropped = figcraft_render::render_node(s.doc().unwrap(), layer, 1.0).unwrap();
|
||||
assert_eq!((cropped.width(), cropped.height()), (100, 50));
|
||||
// The remaining 100x50 pixels match the top-left 100x50 of morphed (pixels stayed still in layer space).
|
||||
for y in 0..50usize {
|
||||
assert_eq!(&cropped.data()[y * 400..(y + 1) * 400], &morphed.data()[y * 800..y * 800 + 400], "row {y}: stationary cropped pixels");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multi_layer_crop_mode_selection_computes_placement_per_node() {
|
||||
use figcraft_doc::color::{ImageScaleMode, PaintKind};
|
||||
let mut s = session();
|
||||
let layer1 = image_layer(&mut s); // 200 x 100
|
||||
let layer2 = id(&ex(&mut s, "shape.rectangle", json!({"x": 300, "y": 0, "width": 100, "height": 100})));
|
||||
|
||||
// Choose Crop mode on both layers simultaneously via fill.set with crop: None (as the picker does).
|
||||
let mut fill = s.doc().unwrap().node(layer1).unwrap().fills[0].clone();
|
||||
let PaintKind::Image(img) = &mut fill.kind else { panic!("image fill") };
|
||||
img.scale_mode = ImageScaleMode::Crop;
|
||||
img.crop = None;
|
||||
ex(&mut s, "fill.set", json!({"ids": [layer1, layer2], "index": 0, "paint": fill}));
|
||||
|
||||
// Verify both layers received crop transforms tailored to their own dimensions, not stretched.
|
||||
let n1 = s.doc().unwrap().node(layer1).unwrap().clone();
|
||||
let n2 = s.doc().unwrap().node(layer2).unwrap().clone();
|
||||
let PaintKind::Image(img1) = &n1.fills[0].kind else { panic!("image fill") };
|
||||
let PaintKind::Image(img2) = &n2.fills[0].kind else { panic!("image fill") };
|
||||
|
||||
let crop1 = img1.crop.expect("layer1 crop initialized");
|
||||
let crop2 = img2.crop.expect("layer2 crop initialized");
|
||||
|
||||
// layer1 (200x100) and layer2 (100x100) have different aspect ratios, so their crop transforms must differ.
|
||||
assert_ne!(crop1, crop2, "differently sized layers must have distinct crop transforms");
|
||||
|
||||
// Both should match expected placement crop for their respective dimensions (iw=200, ih=100 from image_layer):
|
||||
assert_eq!(crop1, [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]);
|
||||
assert_eq!(crop2, [0.5, 0.0, 0.0, 1.0, 0.25, 0.0]);
|
||||
|
||||
// Rotate 90° on the multi-selection (as the picker's Rotate button does):
|
||||
let mut rot_fill = n1.fills[0].clone();
|
||||
let PaintKind::Image(img) = &mut rot_fill.kind else { panic!("image fill") };
|
||||
img.rotation = 1;
|
||||
ex(&mut s, "fill.set", json!({"ids": [layer1, layer2], "index": 0, "paint": rot_fill}));
|
||||
|
||||
let n1_rot = s.doc().unwrap().node(layer1).unwrap().clone();
|
||||
let n2_rot = s.doc().unwrap().node(layer2).unwrap().clone();
|
||||
let PaintKind::Image(img1_rot) = &n1_rot.fills[0].kind else { panic!("image fill") };
|
||||
let PaintKind::Image(img2_rot) = &n2_rot.fills[0].kind else { panic!("image fill") };
|
||||
|
||||
let crop1_rot = img1_rot.crop.expect("layer1 rotated crop initialized");
|
||||
let crop2_rot = img2_rot.crop.expect("layer2 rotated crop initialized");
|
||||
assert_ne!(crop1_rot, crop2_rot, "differently sized layers must have distinct rotated crop transforms");
|
||||
assert_eq!(crop1_rot, [1.0, 0.0, 0.0, 0.25, 0.0, 0.375]);
|
||||
assert_eq!(crop2_rot, [1.0, 0.0, 0.0, 0.5, 0.0, 0.25]);
|
||||
|
||||
// Shared filter edit on multi-selection in Crop mode (e.g. Exposure slider):
|
||||
let mut filter_fill = n1_rot.fills[0].clone();
|
||||
let PaintKind::Image(img) = &mut filter_fill.kind else { panic!("image fill") };
|
||||
img.filters.exposure = 0.5;
|
||||
ex(&mut s, "fill.set", json!({"ids": [layer1, layer2], "index": 0, "paint": filter_fill}));
|
||||
|
||||
let n1_filt = s.doc().unwrap().node(layer1).unwrap().clone();
|
||||
let n2_filt = s.doc().unwrap().node(layer2).unwrap().clone();
|
||||
let PaintKind::Image(img1_filt) = &n1_filt.fills[0].kind else { panic!("image fill") };
|
||||
let PaintKind::Image(img2_filt) = &n2_filt.fills[0].kind else { panic!("image fill") };
|
||||
|
||||
// Both layers keep their distinct crop transforms; neither is overwritten by the other.
|
||||
assert_eq!(img1_filt.crop, Some(crop1_rot));
|
||||
assert_eq!(img2_filt.crop, Some(crop2_rot));
|
||||
assert_eq!(img1_filt.filters.exposure, 0.5);
|
||||
assert_eq!(img2_filt.filters.exposure, 0.5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn command_crop_preserves_each_image_fill_and_leaves_tiles() {
|
||||
use figcraft_doc::color::{Color, ImageScaleMode, Paint, PaintKind};
|
||||
@@ -242,43 +360,134 @@ fn command_crop_preserves_each_image_fill_and_leaves_tiles() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn command_resize_leaves_fills_when_text_or_auto_layout_recomputes_the_box() {
|
||||
for case in ["text", "child", "frame"] {
|
||||
fn command_resize_leaves_a_texts_fills() {
|
||||
let mut s = session();
|
||||
let image = image_layer(&mut s);
|
||||
let fills = s.doc().unwrap().node(image).unwrap().fills.clone();
|
||||
let layer = id(&ex(
|
||||
&mut s,
|
||||
"text.create",
|
||||
json!({"text": "hello world hello world hello world", "props": {
|
||||
"width": 200, "height": 100, "fontSize": 24, "textAutoResize": "none", "fills": fills
|
||||
}}),
|
||||
));
|
||||
ex(&mut s, "select.set", json!({"ids": [layer]}));
|
||||
let doc = s.doc().unwrap();
|
||||
let world = doc.world_transform(layer);
|
||||
let n = doc.node(layer).unwrap();
|
||||
let (from, to) = (world * Point::new(n.width, n.height / 2.0), world * Point::new(10.0, n.height / 2.0));
|
||||
drag(&mut s, from, to, CMD);
|
||||
assert_eq!(s.doc().unwrap().node(layer).unwrap().fills, fills, "a text reflows: keep the existing resize behaviour");
|
||||
}
|
||||
|
||||
fn image_units_per_layer_unit(s: &Session, layer: NodeId) -> (f64, f64, f64, f64) {
|
||||
use figcraft_doc::color::PaintKind;
|
||||
let doc = s.doc().unwrap();
|
||||
let n = doc.node(layer).unwrap();
|
||||
let PaintKind::Image(img) = &n.fills[0].kind else { panic!("image fill") };
|
||||
let data = doc.images.get(&img.image).unwrap();
|
||||
let c = img.effective_crop(f64::from(data.width), f64::from(data.height), n.width, n.height);
|
||||
(c[0] / n.width, c[3] / n.height, c[4], c[5])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn command_resize_crops_in_auto_layout_against_the_box_layout_leaves() {
|
||||
use figcraft_doc::color::{ImageScaleMode, PaintKind};
|
||||
for case in ["child", "child with a minimum width", "auto layout frame"] {
|
||||
let mut s = session();
|
||||
let image = image_layer(&mut s);
|
||||
let fills = s.doc().unwrap().node(image).unwrap().fills.clone();
|
||||
let layer = match case {
|
||||
"text" => id(&ex(
|
||||
&mut s,
|
||||
"text.create",
|
||||
json!({"text": "hello world hello world hello world", "props": {
|
||||
"width": 200, "height": 100, "fontSize": 24, "textAutoResize": "none", "fills": fills
|
||||
}}),
|
||||
)),
|
||||
let frame = id(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 240, "height": 140})));
|
||||
set(&mut s, &[frame], json!({"layout": "horizontal", "padding": 20}));
|
||||
let (layer, to_x, width) = match case {
|
||||
"auto layout frame" => {
|
||||
set(&mut s, &[frame], json!({"fills": fills}));
|
||||
(frame, 10.0, 40.0)
|
||||
}
|
||||
_ => {
|
||||
let frame = id(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 200, "height": 100})));
|
||||
set(&mut s, &[frame], json!({"layout": "horizontal", "padding": 20}));
|
||||
ex(&mut s, "node.reparent", json!({"ids": [image], "parent": frame}));
|
||||
if case == "child" {
|
||||
ex(&mut s, "node.reparent", json!({"ids": [image], "parent": frame}));
|
||||
set(&mut s, &[image], json!({"minWidth": 150}));
|
||||
image
|
||||
(image, 150.0, 150.0)
|
||||
} else {
|
||||
set(&mut s, &[frame], json!({"fills": fills}));
|
||||
frame
|
||||
set(&mut s, &[image], json!({"minWidth": 150}));
|
||||
(image, 10.0, 150.0)
|
||||
}
|
||||
}
|
||||
};
|
||||
ex(&mut s, "select.set", json!({"ids": [layer]}));
|
||||
let before = image_units_per_layer_unit(&s, layer);
|
||||
let doc = s.doc().unwrap();
|
||||
let world = doc.world_transform(layer);
|
||||
let n = doc.node(layer).unwrap();
|
||||
let from = world * Point::new(n.width, n.height / 2.0);
|
||||
let to = world * Point::new(10.0, n.height / 2.0);
|
||||
let (from, to) = (world * Point::new(n.width, n.height / 2.0), world * Point::new(to_x, n.height / 2.0));
|
||||
drag(&mut s, from, to, CMD);
|
||||
assert_eq!(s.doc().unwrap().node(layer).unwrap().fills, fills, "{case}: keep the existing resize behaviour");
|
||||
let n = s.doc().unwrap().node(layer).unwrap().clone();
|
||||
assert!(near(n.width, width), "{case}: {} wide, as auto layout leaves it", n.width);
|
||||
let PaintKind::Image(img) = &n.fills[0].kind else { panic!("image fill") };
|
||||
assert_eq!(img.scale_mode, ImageScaleMode::Crop, "{case}: cropped");
|
||||
let after = image_units_per_layer_unit(&s, layer);
|
||||
assert!(near(after.0, before.0) && near(after.1, before.1), "{case}: the image keeps its scale, not stretched: {before:?} -> {after:?}");
|
||||
assert!(near(after.2, before.2) && near(after.3, before.3), "{case}: its left edge stays where it was in the layer: {before:?} -> {after:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A minimum width can give a layer back the width its left side was dragged in by: the crop then
|
||||
/// slides back along the image instead of running past its right edge.
|
||||
#[test]
|
||||
fn command_crop_slides_back_onto_the_image_when_layout_widens_the_layer() {
|
||||
use figcraft_doc::color::{ImagePaint, PaintKind};
|
||||
let mut s = session();
|
||||
let image = image_layer(&mut s);
|
||||
let frame = id(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 240, "height": 140})));
|
||||
set(&mut s, &[frame], json!({"layout": "horizontal", "padding": 20}));
|
||||
ex(&mut s, "node.reparent", json!({"ids": [image], "parent": frame}));
|
||||
set(&mut s, &[image], json!({"minWidth": 150}));
|
||||
ex(&mut s, "select.set", json!({"ids": [image]}));
|
||||
let before = image_units_per_layer_unit(&s, image);
|
||||
let world = s.doc().unwrap().world_transform(image);
|
||||
drag(&mut s, world * Point::new(0.0, 50.0), world * Point::new(190.0, 50.0), CMD);
|
||||
let doc = s.doc().unwrap();
|
||||
let n = doc.node(image).unwrap();
|
||||
assert!(near(n.width, 150.0), "{} wide, as the minimum width leaves it", n.width);
|
||||
let PaintKind::Image(img) = &n.fills[0].kind else { panic!("image fill") };
|
||||
let data = doc.images.get(&img.image).unwrap();
|
||||
let crop = img.effective_crop(f64::from(data.width), f64::from(data.height), n.width, n.height);
|
||||
let (x0, _, x1, _) = ImagePaint::crop_rect(crop);
|
||||
assert!(x0 <= 1e-9 && x1 >= 1.0 - 1e-9, "the image covers the layer: {x0}..{x1}");
|
||||
let after = image_units_per_layer_unit(&s, image);
|
||||
assert!(near(after.0, before.0) && near(after.1, before.1), "the image keeps its scale: {before:?} -> {after:?}");
|
||||
}
|
||||
|
||||
/// Where the image's edge stops a crop, Shift still keeps the ratio (both axes stop together) and
|
||||
/// Alt still keeps the box centred (both sides stop together).
|
||||
#[test]
|
||||
fn command_crop_stopped_by_the_image_keeps_the_ratio_with_shift_and_the_centre_with_alt() {
|
||||
let mut s = session();
|
||||
let layer = image_layer(&mut s);
|
||||
ex(&mut s, "select.set", json!({"ids": [layer]}));
|
||||
drag(&mut s, Point::new(200.0, 100.0), Point::new(150.0, 80.0), CMD);
|
||||
assert_eq!(size(&s, layer), (150.0, 80.0));
|
||||
drag(&mut s, Point::new(150.0, 80.0), Point::new(240.0, 128.0), Mods { shift: true, alt: false, cmd: true });
|
||||
assert!(
|
||||
near_rect(bounds(&s, layer), Rect::new(0.0, 0.0, 187.5, 100.0)),
|
||||
"the bottom stops at the image, the right side with it: {:?}",
|
||||
bounds(&s, layer)
|
||||
);
|
||||
|
||||
let mut s = session();
|
||||
let layer = image_layer(&mut s);
|
||||
ex(&mut s, "select.set", json!({"ids": [layer]}));
|
||||
drag(&mut s, Point::new(0.0, 50.0), Point::new(20.0, 50.0), CMD);
|
||||
drag(&mut s, Point::new(200.0, 50.0), Point::new(150.0, 50.0), CMD);
|
||||
assert!(near_rect(bounds(&s, layer), Rect::new(20.0, 0.0, 150.0, 100.0)), "{:?}", bounds(&s, layer));
|
||||
drag(&mut s, Point::new(150.0, 50.0), Point::new(190.0, 50.0), Mods { shift: false, alt: true, cmd: true });
|
||||
assert!(
|
||||
near_rect(bounds(&s, layer), Rect::new(0.0, 0.0, 170.0, 100.0)),
|
||||
"the left side stops at the image, the right side as far: {:?}",
|
||||
bounds(&s, layer)
|
||||
);
|
||||
}
|
||||
|
||||
/// A resize is an explicit edit of the size: a size bound to a variable lets go of it (#809), so
|
||||
/// Cmd/Ctrl crops a bound layer's image as any other's; other bindings stay.
|
||||
#[test]
|
||||
@@ -795,6 +1004,73 @@ fn snapping_to_layers_wins_over_the_pixel_grid() {
|
||||
assert_eq!(size(&s, b), (100.0, 151.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn frames_land_on_whole_pixels_whatever_they_snap_to() {
|
||||
// Figma's help: frames, sections and components "always snap to the pixel grid, even if Snap
|
||||
// to pixel grid is disabled". Other layers follow the setting.
|
||||
let frame = |s: &mut Session, x: f64, y: f64| id(&ex(s, "frame.create", json!({"x": x, "y": y, "width": 100, "height": 100})));
|
||||
let whole = |r: Rect| [r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.fract() == 0.0);
|
||||
let mut s = Session::new();
|
||||
// A neighbour off the pixel grid, as a scaled or imported layer leaves one: its right edge at
|
||||
// 100.4.
|
||||
rect(&mut s, 0.4, 0.0, 100.0, 100.0, None);
|
||||
let f = frame(&mut s, 300.0, 300.0);
|
||||
let r = rect(&mut s, 300.0, 600.0, 100.0, 100.0, None);
|
||||
// Moved next to it, a rectangle snaps onto 100.4 and the frame to the whole pixel there.
|
||||
ex(&mut s, "select.set", json!({"ids": [r]}));
|
||||
drag(&mut s, Point::new(350.0, 650.0), Point::new(151.5, 650.0), Mods::default());
|
||||
assert!(near(bounds(&s, r).x0, 100.4), "{:?}", bounds(&s, r));
|
||||
ex(&mut s, "select.set", json!({"ids": [f]}));
|
||||
drag(&mut s, Point::new(350.0, 350.0), Point::new(151.5, 350.0), Mods::default());
|
||||
assert_eq!(bounds(&s, f).origin(), Point::new(100.0, 300.0), "moved by the snap, onto the whole pixel");
|
||||
// With Snap to pixel grid off, frames still move, resize and draw on whole pixels.
|
||||
ex(&mut s, "view.snapPixel", json!({"on": false}));
|
||||
ex(&mut s, "view.snapObjects", json!({"on": false}));
|
||||
drag(&mut s, Point::new(150.0, 350.0), Point::new(160.3, 360.6), Mods::default());
|
||||
assert_eq!(bounds(&s, f).origin(), Point::new(110.0, 311.0), "moved");
|
||||
drag(&mut s, Point::new(210.0, 411.0), Point::new(250.4, 450.6), Mods::default());
|
||||
assert_eq!(size(&s, f), (140.0, 140.0), "resized");
|
||||
ex(&mut s, "tool.set", json!({"tool": "frame"}));
|
||||
drag(&mut s, Point::new(500.3, 500.6), Point::new(560.6, 540.2), Mods::default());
|
||||
let drawn = s.selection()[0];
|
||||
assert!(whole(bounds(&s, drawn)), "drawn: {:?}", bounds(&s, drawn));
|
||||
// A frame already off the pixel grid lands on it once moved.
|
||||
ex(&mut s, "tool.set", json!({"tool": "move"}));
|
||||
let off = frame(&mut s, 800.4, 800.7);
|
||||
ex(&mut s, "select.set", json!({"ids": [off]}));
|
||||
drag(&mut s, Point::new(850.0, 850.0), Point::new(860.0, 850.0), Mods::default());
|
||||
assert!(whole(bounds(&s, off)), "{:?}", bounds(&s, off));
|
||||
// A rectangle follows the pointer.
|
||||
ex(&mut s, "select.set", json!({"ids": [r]}));
|
||||
drag(&mut s, Point::new(150.0, 650.0), Point::new(160.3, 650.0), Mods::default());
|
||||
assert!(near(bounds(&s, r).x0, 110.7), "{:?}", bounds(&s, r));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn frames_resized_together_each_land_on_whole_pixels() {
|
||||
let mut s = session();
|
||||
let frame = |s: &mut Session, x: f64| id(&ex(s, "frame.create", json!({"x": x, "y": 0, "width": 100, "height": 100})));
|
||||
let (a, b) = (frame(&mut s, 0.0), frame(&mut s, 200.0));
|
||||
ex(&mut s, "select.set", json!({"ids": [a, b]}));
|
||||
// 300 wide to 400: a third more, so each frame alone would be 133.33 wide.
|
||||
drag(&mut s, Point::new(300.0, 100.0), Point::new(400.0, 100.0), Mods::default());
|
||||
assert_eq!(bounds(&s, a), Rect::new(0.0, 0.0, 133.0, 100.0));
|
||||
assert_eq!(bounds(&s, b), Rect::new(267.0, 0.0, 400.0, 100.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_frame_dropped_into_a_frame_off_the_pixel_grid_lands_on_its_whole_pixels() {
|
||||
let mut s = session();
|
||||
let target = id(&ex(&mut s, "frame.create", json!({"x": 300.5, "y": 0.5, "width": 300, "height": 300})));
|
||||
let f = id(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 50, "height": 50})));
|
||||
ex(&mut s, "select.set", json!({"ids": [f]}));
|
||||
drag(&mut s, Point::new(25.0, 25.0), Point::new(425.0, 125.0), Mods::default());
|
||||
let n = s.doc().unwrap().node(f).unwrap().clone();
|
||||
assert_eq!(n.parent, Some(target));
|
||||
let [.., x, y] = n.transform.as_coeffs();
|
||||
assert_eq!((x.fract(), y.fract()), (0.0, 0.0), "at {x}, {y} in the frame");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corner_cursors_stay_diagonal_whatever_the_proportions() {
|
||||
let mut s = session();
|
||||
@@ -856,3 +1132,19 @@ fn the_transform_box_and_its_handles() {
|
||||
// At a larger zoom the same layer is big enough on screen for its handles inside it.
|
||||
assert_eq!(handle_at(s.doc().unwrap(), &[tiny], Point::new(320.2, 10.2), 20.0), Some(Handle::Corner(0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn command_crop_changes_a_locked_ratio_and_stops_at_the_images_edges() {
|
||||
let mut s = session();
|
||||
let layer = image_layer(&mut s);
|
||||
set(&mut s, &[layer], json!({"constrainProportions": true}));
|
||||
ex(&mut s, "select.set", json!({"ids": [layer]}));
|
||||
drag(&mut s, Point::new(200.0, 50.0), Point::new(150.0, 50.0), CMD);
|
||||
assert_eq!(size(&s, layer), (150.0, 100.0), "a side changes the ratio, lock or not");
|
||||
drag(&mut s, Point::new(150.0, 50.0), Point::new(260.0, 50.0), CMD);
|
||||
assert_eq!(size(&s, layer), (200.0, 100.0), "the side stops at the image's edge");
|
||||
drag(&mut s, Point::new(100.0, 0.0), Point::new(100.0, -40.0), CMD);
|
||||
assert!(near_rect(bounds(&s, layer), Rect::new(0.0, 0.0, 200.0, 100.0)), "the top stops at the image's top: {:?}", bounds(&s, layer));
|
||||
drag(&mut s, Point::new(200.0, 50.0), Point::new(100.0, 50.0), Mods { shift: true, alt: false, cmd: true });
|
||||
assert_eq!(size(&s, layer), (100.0, 50.0), "Shift keeps the ratio");
|
||||
}
|
||||
@@ -700,6 +700,31 @@ fn deleting_points_vs_delete_and_heal() {
|
||||
assert_eq!((n.vertices.len(), n.segments.len()), (4, 3), "deleting a segment leaves its points");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deleting_a_point_selects_the_next_one_on_its_path() {
|
||||
let mut s = Session::new();
|
||||
let id = id_of(&ex(&mut s, "vector.create", json!({"path": "M0 0 L100 0 L200 0 L300 0"}))["id"]).unwrap();
|
||||
ex(&mut s, "vector.edit.begin", json!({"id": id}));
|
||||
let selected = |s: &Session| editing(s).unwrap().vertices.iter().map(|v| page_pos(s, id, *v)).collect::<Vec<_>>();
|
||||
let second = point_at(&s, id, (100.0, 0.0));
|
||||
ex(&mut s, "vector.edit.select", json!({"vertices": [second]}));
|
||||
key(&mut s, "Delete", true);
|
||||
assert_eq!(selected(&s), [Point::new(200.0, 0.0)], "the point after the deleted one");
|
||||
key(&mut s, "Delete", true);
|
||||
assert_eq!(selected(&s), [Point::new(300.0, 0.0)], "so Delete again walks along the path");
|
||||
key(&mut s, "Delete", true);
|
||||
assert_eq!(selected(&s), [Point::new(0.0, 0.0)], "past the path's end, the point before it");
|
||||
|
||||
let mut s = Session::new();
|
||||
let id = square(&mut s, true);
|
||||
let tr = point_at(&s, id, (100.0, 0.0));
|
||||
ex(&mut s, "vector.edit.select", json!({"vertices": [tr]}));
|
||||
key(&mut s, "Delete", false);
|
||||
let after = selected(&s);
|
||||
assert_eq!(after.len(), 1, "one point selected after a plain Delete: {after:?}");
|
||||
assert!([Point::new(100.0, 100.0), Point::new(0.0, 0.0)].contains(&after[0]), "a neighbour of the deleted corner: {after:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn handles_follow_their_mirroring() {
|
||||
// A smooth middle point at (100, 0) on an open path; one handle is dragged to (+30, 10).
|
||||
|
||||
@@ -102,6 +102,8 @@ pub const TOOL_NAMES: &[&str] = &[
|
||||
"get_node",
|
||||
"design_context",
|
||||
"export_assets",
|
||||
"component_mappings",
|
||||
"sync_mappings",
|
||||
"select",
|
||||
"export",
|
||||
"screenshot",
|
||||
@@ -126,6 +128,8 @@ const DOCUMENT_TOOLS: &[&str] = &[
|
||||
"get_node",
|
||||
"design_context",
|
||||
"export_assets",
|
||||
"component_mappings",
|
||||
"sync_mappings",
|
||||
"select",
|
||||
"export",
|
||||
"screenshot",
|
||||
@@ -286,6 +290,33 @@ fn tools() -> Vec<Value> {
|
||||
),
|
||||
false,
|
||||
),
|
||||
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",
|
||||
@@ -490,6 +521,26 @@ fn export_assets(b: &mut dyn Backend, a: &Map<String, Value>) -> Result<ToolResu
|
||||
exec(b, "file.exportAssets", Value::Object(params)).map(|v| ToolResult::json(&v))
|
||||
}
|
||||
|
||||
/// `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))
|
||||
}
|
||||
@@ -637,6 +688,8 @@ pub fn call_tool(b: &mut dyn Backend, name: &str, args: &Value) -> ToolResult {
|
||||
"get_node" => get_node(b, &a),
|
||||
"design_context" => design_context(b, &a),
|
||||
"export_assets" => export_assets(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)]
|
||||
|
||||
@@ -102,6 +102,7 @@ name = "English"
|
||||
"All comments" = "All comments"
|
||||
"All components" = "All components"
|
||||
"All fonts" = "All fonts"
|
||||
"All libraries" = "All libraries"
|
||||
"All objects" = "All objects"
|
||||
"All supported properties" = "All supported properties"
|
||||
"All the fonts this file uses are installed" = "All the fonts this file uses are installed"
|
||||
@@ -392,6 +393,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"
|
||||
@@ -1469,6 +1473,8 @@ name = "English"
|
||||
"Small caps" = "Small caps"
|
||||
"Smart animate" = "Smart animate"
|
||||
"Snap to pixel grid" = "Snap to pixel grid"
|
||||
"Snap to pixel grid off" = "Snap to pixel grid off"
|
||||
"Snap to pixel grid on" = "Snap to pixel grid on"
|
||||
"Social and slides" = "Social and slides"
|
||||
"Social media" = "Social media"
|
||||
"Social post sizes" = "Social post sizes"
|
||||
@@ -1759,6 +1765,7 @@ name = "English"
|
||||
"What it's for" = "What it's for"
|
||||
"What this changed from isn't known: it changed before FigCraft kept a copy of ready-for-dev frames. Resolve the change (or mark it ready again) to compare from now on." = "What this changed from isn't known: it changed before FigCraft kept a copy of ready-for-dev frames. Resolve the change (or mark it ready again) to compare from now on."
|
||||
"When marked ready" = "When marked ready"
|
||||
"While editing text: next or previous text layer" = "While editing text: next or previous text layer"
|
||||
"While hovering" = "While hovering"
|
||||
"While pressing" = "While pressing"
|
||||
"White" = "White"
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -99,6 +99,7 @@ name = "Русский"
|
||||
"All comments" = "Все комментарии"
|
||||
"All components" = "Все компоненты"
|
||||
"All fonts" = "Все шрифты"
|
||||
"All libraries" = "Все библиотеки"
|
||||
"All objects" = "Все объекты"
|
||||
"All supported properties" = "Все поддерживаемые свойства"
|
||||
"All the fonts this file uses are installed" = "Все шрифты, которые использует этот файл, установлены"
|
||||
@@ -1346,6 +1347,8 @@ name = "Русский"
|
||||
"Small caps" = "Капитель"
|
||||
"Smart animate" = "Smart animate"
|
||||
"Snap to pixel grid" = "Привязка к пиксельной сетке"
|
||||
"Snap to pixel grid off" = "Привязка к пиксельной сетке выключена"
|
||||
"Snap to pixel grid on" = "Привязка к пиксельной сетке включена"
|
||||
"Social and slides" = "Соцсети и слайды"
|
||||
"Social media" = "Соцсети"
|
||||
"Social post sizes" = "Размеры публикаций для соцсетей"
|
||||
@@ -1864,6 +1867,183 @@ name = "Русский"
|
||||
"⌘ click" = "⌘ нажатие"
|
||||
"⌘ scroll" = "⌘ прокрутка"
|
||||
"⌥ drag" = "⌥ перетаскивание"
|
||||
"1 year" = "1 год"
|
||||
"30 days" = "30 дней"
|
||||
"90 days" = "90 дней"
|
||||
"A layer in an auto layout frame is placed by its frame" = "Слой в Frame с автолейаутом размещается своим Frame"
|
||||
"Allow and download" = "Разрешить и загрузить"
|
||||
"Allow downloading fonts?" = "Разрешить загрузку шрифтов?"
|
||||
"Alt+double-click an edge of an auto layout child" = "Alt+двойное нажатие по краю дочернего объекта автолейаута"
|
||||
"Android Vector Drawable" = "Android Vector Drawable"
|
||||
"Annotation" = "Аннотация"
|
||||
"Anyone on your network with this code can look at the file, not change it, while this app stays open." = "Все в вашей сети с этим кодом могут смотреть файл, но не менять его, пока это приложение открыто."
|
||||
"Auto: as many words as fit on each line" = "Авто: столько слов, сколько помещается в строке"
|
||||
"Auto: by the first letter with a direction" = "Авто: по первой букве, у которой есть направление"
|
||||
"Balance" = "Баланс"
|
||||
"Balance: every line close to the same length" = "Баланс: все строки примерно одной длины"
|
||||
"Best effort" = "По возможности"
|
||||
"Board grid" = "Сетка доски"
|
||||
"Calculated from other variables; it follows them" = "Вычисляется из других переменных и следует за ними"
|
||||
"Changed {date}" = "Изменено {date}"
|
||||
"Check for Updates" = "Проверить обновления"
|
||||
"Check for updates…" = "Проверить обновления…"
|
||||
"Compare with" = "Сравнить с"
|
||||
"Compatibility" = "Совместимость"
|
||||
"Copied comments for AI" = "Комментарии скопированы для ИИ"
|
||||
"Copy browser link" = "Копировать ссылку для браузера"
|
||||
"Copy effect" = "Копировать эффект"
|
||||
"Copy fill" = "Копировать заливку"
|
||||
"Copy for AI" = "Копировать для ИИ"
|
||||
"Copy link to page" = "Копировать ссылку на страницу"
|
||||
"Copy stroke" = "Копировать обводку"
|
||||
"Couldn't download {name}" = "Не удалось загрузить {name}"
|
||||
"Couldn't reach {server} for its team list." = "Не удалось связаться с {server}, чтобы получить список команды."
|
||||
"Crop image" = "Обрезать изображение"
|
||||
"Ctrl+Alt+← ↑ → ↓" = "Ctrl+Alt+← ↑ → ↓"
|
||||
"Ctrl+click a padding field" = "Ctrl+нажатие по полю внутреннего отступа"
|
||||
"Dart constants for Flutter…" = "Константы Dart для Flutter…"
|
||||
"Delete {n} variables" = { one = "Удалить {n} переменную", few = "Удалить {n} переменные", many = "Удалить {n} переменных", other = "Удалить {n} переменных" }
|
||||
"Detach calculation" = "Отвязать вычисление"
|
||||
"Developer Mode only inspects: switch to Design (Shift+D) to edit" = "Режим разработчика только просматривает: чтобы редактировать, перейдите в «Дизайн» (Shift+D)"
|
||||
"Disconnected. Reconnecting…" = "Соединение разорвано. Повторное подключение…"
|
||||
"Disconnected. Your edits stay here and sync when the connection returns. Reconnecting…" = "Соединение разорвано. Ваши правки остаются здесь и синхронизируются, когда связь восстановится. Повторное подключение…"
|
||||
"Dismiss" = "Закрыть"
|
||||
"Don't show this again" = "Больше не показывать"
|
||||
"Double-click an edge of an auto layout frame" = "Двойное нажатие по краю Frame с автолейаутом"
|
||||
"Download" = "Загрузить"
|
||||
"Downloading… {percent}%" = "Загрузка… {percent}%"
|
||||
"Drop to use this image" = "Перетащите, чтобы использовать это изображение"
|
||||
"Duplicate group" = "Дублировать группу"
|
||||
"Edit padding on all sides" = "Изменить внутренние отступы со всех сторон"
|
||||
"Edit variables" = "Редактировать переменные"
|
||||
"Enter / Shift+Enter" = "Enter / Shift+Enter"
|
||||
"Everyone who reaches this server can open these files while they are shared." = "Все, кто имеет доступ к этому серверу, могут открывать эти файлы, пока они опубликованы."
|
||||
"Exact only" = "Только точные"
|
||||
"Expand the interface" = "Развернуть интерфейс"
|
||||
"Exported {name}; {n} kinds of content were changed or left out" = { one = "Файл {name} экспортирован; {n} тип содержимого изменён или пропущен", few = "Файл {name} экспортирован; {n} типа содержимого изменены или пропущены", many = "Файл {name} экспортирован; {n} типов содержимого изменены или пропущены", other = "Файл {name} экспортирован; {n} типов содержимого изменены или пропущены" }
|
||||
"Exported {n} files; some content was changed or left out" = { one = "Экспортирован {n} файл; часть содержимого изменена или пропущена", few = "Экспортировано {n} файла; часть содержимого изменена или пропущена", many = "Экспортировано {n} файлов; часть содержимого изменена или пропущена", other = "Экспортировано {n} файлов; часть содержимого изменена или пропущена" }
|
||||
"Extra large" = "Очень крупный"
|
||||
"FigCraft stopped because of an internal error." = "FigCraft остановился из-за внутренней ошибки."
|
||||
"Format" = "Формат"
|
||||
"Free fonts come from Google Fonts and Noto, through jsDelivr and GitHub. Each file is checked against the font index before it is installed into the font folder the Craft apps share. Nothing is downloaded until you allow it." = "Бесплатные шрифты поступают из Google Fonts и Noto через jsDelivr и GitHub. Каждый файл сверяется с указателем шрифтов, прежде чем будет установлен в общую папку шрифтов программ Craft. Ничего не загружается, пока вы это не разрешите."
|
||||
"Graph paper" = "Бумага в клетку"
|
||||
"Hide UI" = "Скрыть интерфейс"
|
||||
"Huge" = "Огромный"
|
||||
"Ignore unsupported" = "Пропускать неподдерживаемое"
|
||||
"Invert zoom direction" = "Инвертировать направление масштабирования"
|
||||
"Joining live session…" = "Подключение к сеансу…"
|
||||
"Large" = "Крупный"
|
||||
"Leaving the prototype" = "Выход из прототипа"
|
||||
"Left to right" = "Слева направо"
|
||||
"Link copied: it opens the file in FigCraft" = "Ссылка скопирована: она открывает файл в FigCraft"
|
||||
"Link copied: it opens the file in the browser" = "Ссылка скопирована: она открывает файл в браузере"
|
||||
"Medium" = "Средний"
|
||||
"Move out of any group" = "Вынести из любой группы"
|
||||
"Move to group {group}" = "Переместить в группу {group}"
|
||||
"Move up or down while dragging its label" = "Перемещать вверх или вниз, перетаскивая подпись"
|
||||
"New from selection" = "Создать из выделения"
|
||||
"No comments to copy" = "Нет комментариев для копирования"
|
||||
"No scope is shared by all the selected variables" = "У выделенных переменных нет общей области применения"
|
||||
"Nobody shares a file there now." = "Сейчас там никто не публикует файл."
|
||||
"Not connected: {reason}. Your work is still in this tab." = "Нет соединения: {reason}. Ваша работа остаётся в этой вкладке."
|
||||
"Not now" = "Не сейчас"
|
||||
"Nothing changed since this version." = "С этой версии ничего не изменилось."
|
||||
"Nothing counted yet" = "Пока ничего не подсчитано"
|
||||
"Nothing to pick: the page is empty" = "Нечего выбрать: страница пуста"
|
||||
"Past 30 days" = "За 30 дней"
|
||||
"Past 90 days" = "За 90 дней"
|
||||
"Past year" = "За год"
|
||||
"Paste effect" = "Вставить эффект"
|
||||
"Paste fill" = "Вставить заливку"
|
||||
"Paste stroke" = "Вставить обводку"
|
||||
"Pick select: Tab and Shift+Tab move between layers, Enter goes into one, Shift+Enter out, Space selects, Escape cancels" = "Выбор указанием: Tab и Shift+Tab переходят между слоями, Enter входит в слой, Shift+Enter выходит, Space выделяет, Escape отменяет"
|
||||
"Pick select: into a layer, out to its parent" = "Выбор указанием: войти в слой, выйти к родителю"
|
||||
"Pick select: next or previous layer" = "Выбор указанием: следующий или предыдущий слой"
|
||||
"Pick select: select the picked layer" = "Выбор указанием: выделить указанный слой"
|
||||
"Pretty" = "Аккуратно"
|
||||
"Pretty: full lines, no one word alone on the last" = "Аккуратно: полные строки, без одного слова в последней"
|
||||
"Reload the page to get back the unsaved files the browser had room for." = "Перезагрузите страницу, чтобы вернуть несохранённые файлы, для которых в браузере хватило места."
|
||||
"Reload the page to get your unsaved files back." = "Перезагрузите страницу, чтобы вернуть несохранённые файлы."
|
||||
"Reload the page to start again." = "Перезагрузите страницу, чтобы начать снова."
|
||||
"Remove all auto layout" = "Убрать весь автолейаут"
|
||||
"Removed since this version" = "Удалено с этой версии"
|
||||
"Reset grid" = "Сбросить сетку"
|
||||
"Retry now" = "Повторить сейчас"
|
||||
"Right to left" = "Справа налево"
|
||||
"Rotate a degree (Shift: 15)" = "Повернуть на градус (Shift: на 15)"
|
||||
"Same as file ({profile})" = "Как в файле ({profile})"
|
||||
"Save a copy…" = "Сохранить копию…"
|
||||
"Scope" = "Область применения"
|
||||
"Scope: all supported properties" = "Область применения: все поддерживаемые свойства"
|
||||
"Scope: hidden from pickers" = "Область применения: скрыто в списках выбора"
|
||||
"Scope: only {scope}" = "Область применения: только {scope}"
|
||||
"Scrub a field faster (2x) or slower (1/2, 1/4)" = "Менять значение поля быстрее (2x) или медленнее (1/2, 1/4)"
|
||||
"Scrubbing at 1/2" = "Изменение со скоростью 1/2"
|
||||
"Scrubbing at 1/4" = "Изменение со скоростью 1/4"
|
||||
"Scrubbing at 1x" = "Изменение со скоростью 1x"
|
||||
"Scrubbing at 2x" = "Изменение со скоростью 2x"
|
||||
"Select a row, a column or a full grid of three or more layers, outside an auto layout flow" = "Выделите строку, столбец или полную сетку из трёх и более слоёв вне потока автолейаута"
|
||||
"Selection box: switch to pick select" = "Рамка выделения: переключиться на выбор указанием"
|
||||
"Server key" = "Ключ сервера"
|
||||
"Set as opening page" = "Сделать стартовой страницей"
|
||||
"Set corner smoothing to 60%" = "Задать сглаживание углов 60%"
|
||||
"Set fill container" = "Задать: заполнить контейнер"
|
||||
"Set hug contents" = "Задать: по размеру содержимого"
|
||||
"Shared by your team on {server}" = "Опубликовано вашей командой на {server}"
|
||||
"Show and move the placement crosshair (its tool chosen, nothing selected)" = "Показать и перемещать перекрестие размещения (когда выбран его инструмент и ничего не выделено)"
|
||||
"Small" = "Мелкий"
|
||||
"Space" = "Space"
|
||||
"Strong line every" = "Жирная линия каждые"
|
||||
"Subscript" = "Нижний индекс"
|
||||
"Superscript" = "Верхний индекс"
|
||||
"Tab or Ctrl+Space again" = "Tab или Ctrl+Space ещё раз"
|
||||
"Text direction" = "Направление текста"
|
||||
"Text on a path" = "Текст по контуру"
|
||||
"The bars are hidden. {shortcut} shows them again" = "Панели скрыты. {shortcut} показывает их снова"
|
||||
"This link opens a website outside the prototype:" = "Эта ссылка открывает сайт вне прототипа:"
|
||||
"This link opens your mail app to write a message:" = "Эта ссылка открывает почтовую программу, чтобы написать сообщение:"
|
||||
"This server doesn't count detached instances" = "Этот сервер не считает отвязанные экземпляры"
|
||||
"This server doesn't count insertions" = "Этот сервер не считает вставки"
|
||||
"This server doesn't count styles and variables" = "Этот сервер не считает стили и переменные"
|
||||
"This variant's value" = "Значение этого варианта"
|
||||
"This version can't be read." = "Эту версию не удалось прочитать."
|
||||
"This version doesn't have it: all of it is new." = "В этой версии этого нет: всё появилось позже."
|
||||
"Update check is not supported in the web browser." = "Проверка обновлений в браузере не поддерживается."
|
||||
"Upload from computer" = "Загрузить с компьютера"
|
||||
"What changed since a saved version" = "Что изменилось с сохранённой версии"
|
||||
"When marked ready" = "Когда отмечено готовым"
|
||||
"Wrap style" = "Стиль переноса"
|
||||
"Your unsaved files were too large for the browser to keep." = "Несохранённые файлы оказались слишком большими, чтобы браузер их сохранил."
|
||||
"connector labels without a saved snapshot are centred on the line, without their background" = "подписи соединителей без сохранённого снимка центрируются на линии, без фона"
|
||||
"elbowed and curved connectors without a saved path are routed afresh" = "ломаные и кривые соединители без сохранённого контура прокладываются заново"
|
||||
"instance swap properties whose default component was past the layer limit were skipped" = "свойства замены экземпляра, у которых компонент по умолчанию выходил за предел слоёв, пропущены"
|
||||
"instances whose component was past the layer limit were imported as frames" = "экземпляры, чей компонент выходил за предел слоёв, импортированы как Frame"
|
||||
"invalid vector region fill paint list; layer fill used" = "недопустимый список заливок векторной области; использована заливка слоя"
|
||||
"invalid vector region paints were skipped" = "недопустимые заливки векторной области пропущены"
|
||||
"linked vector region fill styles keep resolved appearance; live style links were left out" = "связанные стили заливки векторной области сохраняют вычисленное оформление; живые связи стилей опущены"
|
||||
"note or shape generated child has invalid bounds; child skipped" = "у сгенерированного потомка заметки или фигуры недопустимые границы; потомок пропущен"
|
||||
"note or shape generated child is missing its style or bounds; child skipped" = "у сгенерированного потомка заметки или фигуры нет стиля или границ; потомок пропущен"
|
||||
"note or shape generated children exceed the layer or nesting limit; remaining children skipped" = "сгенерированные потомки заметки или фигуры превышают предел слоёв или вложенности; остальные потомки пропущены"
|
||||
"note or shape generated layout is missing or unsupported; using its outer frame" = "сгенерированная вёрстка заметки или фигуры отсутствует или не поддерживается; использован внешний Frame"
|
||||
"shape generated outline is missing or damaged; using its rectangle" = "сгенерированный контур фигуры отсутствует или повреждён; использован её прямоугольник"
|
||||
"sticky layers import as frames with their text" = "слои стикеров импортируются как Frame вместе со своим текстом"
|
||||
"swapped instances whose previous component isn't in the file took the new component's look" = "заменённые экземпляры, чей прежний компонент отсутствует в файле, получили вид нового компонента"
|
||||
"variable-bound vector region paints keep resolved appearance; live bindings were left out" = "привязанные к переменным заливки векторной области сохраняют вычисленное оформление; живые привязки опущены"
|
||||
"vector region paint data exceeded import limits and was skipped" = "данные заливки векторной области превысили пределы импорта и пропущены"
|
||||
"vector region references a missing fill style; layer fill used" = "векторная область ссылается на отсутствующий стиль заливки; использована заливка слоя"
|
||||
"{count} in it now · Changed {date}" = "Сейчас в нём {count} · Изменено {date}"
|
||||
"{insertions} · {detachments}" = "{insertions} · {detachments}"
|
||||
"{name}, disconnected from its live session" = "{name}, отключён от сеанса"
|
||||
"{n} detached" = { one = "{n} отвязан", few = "{n} отвязаны", many = "{n} отвязано", other = "{n} отвязано" }
|
||||
"{n} inserted" = { one = "{n} вставлен", few = "{n} вставлены", many = "{n} вставлено", other = "{n} вставлено" }
|
||||
"{period}: {counts}" = "{period}: {counts}"
|
||||
"{used} · {detached}" = "{used} · {detached}"
|
||||
"{used} · {inserted}" = "{used} · {inserted}"
|
||||
"↵ / ⇧↵" = "↵ / ⇧↵"
|
||||
"⇥ or ⌥ Space again" = "⇥ или ⌥ Space ещё раз"
|
||||
"⌘ click a padding field" = "⌘ нажатие по полю внутреннего отступа"
|
||||
"⌥ double-click an edge of an auto layout child" = "⌥ двойное нажатие по краю дочернего объекта автолейаута"
|
||||
"⌥⌘ ← ↑ → ↓" = "⌥⌘ ← ↑ → ↓"
|
||||
|
||||
[commands]
|
||||
"align.bottom" = "Выровнять по нижнему краю"
|
||||
@@ -2479,6 +2659,44 @@ name = "Русский"
|
||||
"window.focus" = "Вывести окно на передний план"
|
||||
"window.new" = "Новое окно"
|
||||
"template.list" = "Список шаблонов"
|
||||
"board.grid" = "Сетка доски"
|
||||
"board.reshape" = "Изменить форму соединителя"
|
||||
"collab.reconnect" = "Переподключить сеанс"
|
||||
"comment.prompt" = "Копировать комментарии для ИИ"
|
||||
"data.fill" = "Заполнить копии данными"
|
||||
"effect.copy" = "Копировать эффект"
|
||||
"effect.paste" = "Вставить эффект"
|
||||
"file.fontReport" = "Проверить шрифты документа"
|
||||
"file.markSaved" = "Отметить как сохранённый"
|
||||
"fill.copy" = "Копировать заливку"
|
||||
"fill.paste" = "Вставить заливку"
|
||||
"font.download" = "Загрузить шрифт"
|
||||
"font.downloads" = "Загрузки шрифтов"
|
||||
"image.crop" = "Обрезать изображение"
|
||||
"image.replace" = "Заменить изображение"
|
||||
"layout.removeAll" = "Убрать весь автолейаут"
|
||||
"library.check" = "Проверить обновления библиотек команды"
|
||||
"pref.invertZoom" = "Инвертировать направление масштабирования"
|
||||
"pref.uiScaleDown" = "Меньший интерфейс"
|
||||
"pref.uiScaleReset" = "Размер интерфейса по умолчанию"
|
||||
"pref.uiScaleUp" = "Больший интерфейс"
|
||||
"proto.linkNotice" = "Уведомление перед переходом по ссылке"
|
||||
"selection.createColorStyle" = "Создать стиль цвета из выделения"
|
||||
"stroke.copy" = "Копировать обводку"
|
||||
"stroke.paste" = "Вставить обводку"
|
||||
"text.direction" = "Направление текста"
|
||||
"text.directionAuto" = "Направление текста: авто"
|
||||
"text.directionLtr" = "Направление текста: слева направо"
|
||||
"text.directionRtl" = "Направление текста: справа налево"
|
||||
"text.fit" = "Вписать текст в блок"
|
||||
"text.openLink" = "Открыть ссылку"
|
||||
"text.wrapStyle" = "Стиль переноса"
|
||||
"tool.annotation" = "Аннотация"
|
||||
"tool.crosshair" = "Переместить перекрестие размещения"
|
||||
"tool.textOnPath" = "Текст по контуру"
|
||||
"variable.extendCollection" = "Расширить коллекцию"
|
||||
"view.minimize" = "Свернуть интерфейс"
|
||||
"widget.hover" = "Виджет наведения"
|
||||
|
||||
[menu]
|
||||
"bool.exclude" = "Исключение"
|
||||
@@ -2512,3 +2730,6 @@ name = "Русский"
|
||||
"view.themeDark" = "Тёмная"
|
||||
"view.themeLight" = "Светлая"
|
||||
"view.themeSystem" = "Системная"
|
||||
"text.directionAuto" = "Авто"
|
||||
"text.directionLtr" = "Слева направо"
|
||||
"text.directionRtl" = "Справа налево"
|
||||
@@ -1815,6 +1815,235 @@ name = "Türkçe"
|
||||
"⌘ scroll" = "⌘ kaydırma"
|
||||
"⌥ drag" = "⌥ sürükle"
|
||||
|
||||
"1 year" = "1 yıl"
|
||||
"30 days" = "30 gün"
|
||||
"90 days" = "90 gün"
|
||||
"A layer in an auto layout frame is placed by its frame" = "Otomatik yerleşim çerçevesindeki bir katman, çerçevesi tarafından yerleştirilir"
|
||||
"A layer on its own aligns to its frame: select more layers, or one in a frame" = "Tek başına bir katman çerçevesine hizalanır: daha fazla katman veya çerçeve içindeki bir katmanı seçin"
|
||||
"Adding to {name}" = "{name} öğesine ekleniyor"
|
||||
"All the fonts this file uses are installed" = "Bu dosyanın kullandığı tüm yazı tipleri yüklü"
|
||||
"Allow and download" = "İzin ver ve indir"
|
||||
"Allow downloading fonts?" = "Yazı tiplerinin indirilmesine izin verilsin mi?"
|
||||
"Alt+double-click an edge of an auto layout child" = "Otomatik yerleşim alt öğesinin bir kenarına Alt+çift tıklayın"
|
||||
"Android Vector Drawable" = "Android Vector Drawable"
|
||||
"Annotation" = "Ek açıklama"
|
||||
"Anyone on your network with this code can look at the file, not change it, while this app stays open." = "Ağınızdaki bu koda sahip herkes, bu uygulama açık kaldığı sürece dosyayı değiştirmeden görüntüleyebilir."
|
||||
"Auto: as many words as fit on each line" = "Otomatik: her satıra sığdığı kadar sözcük"
|
||||
"Auto: by the first letter with a direction" = "Otomatik: yönü olan ilk harfe göre"
|
||||
"Balance" = "Dengeli"
|
||||
"Balance: every line close to the same length" = "Dengeli: her satır yaklaşık aynı uzunlukta"
|
||||
"Best effort" = "En iyi uyum"
|
||||
"Board grid" = "Pano ızgarası"
|
||||
"Bottom padding" = "Alt iç boşluk"
|
||||
"Calculated from other variables; it follows them" = "Diğer değişkenlerden hesaplanır; onları izler"
|
||||
"Changed {date}" = "{date} tarihinde değiştirildi"
|
||||
"Check for Updates" = "Güncellemeleri Denetle"
|
||||
"Check for updates…" = "Güncellemeleri denetle…"
|
||||
"Checking the fonts installed on this computer…" = "Bu bilgisayarda yüklü yazı tipleri denetleniyor…"
|
||||
"Compare with" = "Şununla karşılaştır"
|
||||
"Compatibility" = "Uyumluluk"
|
||||
"Convert to frame" = "Çerçeveye dönüştür"
|
||||
"Convert to section" = "Bölüme dönüştür"
|
||||
"Copied comments for AI" = "Yorumlar yapay zeka için kopyalandı"
|
||||
"Copy browser link" = "Tarayıcı bağlantısını kopyala"
|
||||
"Copy effect" = "Efekti kopyala"
|
||||
"Copy fill" = "Dolguyu kopyala"
|
||||
"Copy for AI" = "Yapay zeka için kopyala"
|
||||
"Copy link to page" = "Sayfa bağlantısını kopyala"
|
||||
"Copy stroke" = "Konturu kopyala"
|
||||
"Couldn't download the variables" = "Değişkenler indirilemedi"
|
||||
"Couldn't download {name}" = "{name} indirilemedi"
|
||||
"Couldn't reach {server} for its team list." = "Ekip listesi için {server} sunucusuna ulaşılamadı."
|
||||
"Couldn't save automatically: {error}" = "Otomatik olarak kaydedilemedi: {error}"
|
||||
"Crop image" = "Görseli kırp"
|
||||
"Ctrl+Alt+← ↑ → ↓" = "Ctrl+Alt+← ↑ → ↓"
|
||||
"Ctrl+click a padding field" = "Bir iç boşluk alanına Ctrl+tıklayın"
|
||||
"Dart constants for Flutter…" = "Flutter için Dart sabitleri…"
|
||||
"Delete {n} variables" = { other = "{n} değişkeni sil" }
|
||||
"Detach calculation" = "Hesaplamayı ayır"
|
||||
"Developer Mode only inspects: switch to Design (Shift+D) to edit" = "Geliştirici Modu yalnızca inceler: düzenlemek için Tasarım (Shift+D) moduna geçin"
|
||||
"Disconnected. Reconnecting…" = "Bağlantı kesildi. Yeniden bağlanılıyor…"
|
||||
"Disconnected. Your edits stay here and sync when the connection returns. Reconnecting…" = "Bağlantı kesildi. Düzenlemeleriniz burada kalır ve bağlantı geri geldiğinde eşitlenir. Yeniden bağlanılıyor…"
|
||||
"Dismiss" = "Kapat"
|
||||
"Don't show this again" = "Bunu bir daha gösterme"
|
||||
"Double-click an edge of an auto layout frame" = "Otomatik yerleşim çerçevesinin bir kenarına çift tıklayın"
|
||||
"Download" = "İndir"
|
||||
"Downloading… {percent}%" = "İndiriliyor… %{percent}"
|
||||
"Drop a .figcraft, .fig, .jam, .sketch, .json, .svg or image file." = "Bir .figcraft, .fig, .jam, .sketch, .json, .svg veya görsel dosyası bırakın."
|
||||
"Drop to import" = "İçe aktarmak için bırakın"
|
||||
"Drop to open" = "Açmak için bırakın"
|
||||
"Drop to use this image" = "Bu görseli kullanmak için bırakın"
|
||||
"Duplicate group" = "Grubu çoğalt"
|
||||
"Edit padding on all sides" = "Tüm kenarlardaki iç boşluğu düzenle"
|
||||
"Edit variables" = "Değişkenleri düzenle"
|
||||
"Enter / Shift+Enter" = "Enter / Shift+Enter"
|
||||
"Everyone who reaches this server can open these files while they are shared." = "Bu sunucuya erişebilen herkes, paylaşıldıkları sürece bu dosyaları açabilir."
|
||||
"Exact only" = "Yalnızca birebir"
|
||||
"Expand the interface" = "Arayüzü genişlet"
|
||||
"Exported {name}; {n} kinds of content were changed or left out" = { other = "{name} dışa aktarıldı; {n} tür içerik değiştirildi veya dışarıda bırakıldı" }
|
||||
"Exported {n} files; some content was changed or left out" = { other = "{n} dosya dışa aktarıldı; bazı içerikler değiştirildi veya dışarıda bırakıldı" }
|
||||
"Extra large" = "Çok büyük"
|
||||
"FigCraft couldn't open its window: {error}" = "FigCraft penceresini açamadı: {error}"
|
||||
"FigCraft stopped because of an internal error." = "FigCraft bir iç hata nedeniyle durdu."
|
||||
"FigCraft tried {apis}, then again with lower requirements on the power-saving GPU. Updating the graphics driver often helps." = "FigCraft {apis} ile denedi, ardından güç tasarruflu GPU üzerinde daha düşük gereksinimlerle yeniden denedi. Grafik sürücüsünü güncellemek genellikle yardımcı olur."
|
||||
"Format" = "Biçim"
|
||||
"Free fonts come from Google Fonts and Noto, through jsDelivr and GitHub. Each file is checked against the font index before it is installed into the font folder the Craft apps share. Nothing is downloaded until you allow it." = "Ücretsiz yazı tipleri, jsDelivr ve GitHub aracılığıyla Google Fonts ve Noto'dan sağlanır. Her dosya, Craft uygulamalarının ortak kullandığı yazı tipi klasörüne yüklenmeden önce yazı tipi diziniyle karşılaştırılarak denetlenir. Siz izin verene kadar hiçbir şey indirilmez."
|
||||
"Graph paper" = "Milimetrik kâğıt"
|
||||
"Hide UI" = "Arayüzü gizle"
|
||||
"Huge" = "Devasa"
|
||||
"If it keeps happening, please report it at {link} with this message." = "Sorun devam ederse lütfen bu mesajla birlikte {link} adresinden bildirin."
|
||||
"Ignore unsupported" = "Desteklenmeyenleri yoksay"
|
||||
"Individual padding" = "Ayrı ayrı iç boşluk"
|
||||
"Interface size" = "Arayüz boyutu"
|
||||
"Invert zoom direction" = "Yakınlaştırma yönünü tersine çevir"
|
||||
"Joining live session…" = "Canlı oturuma katılınıyor…"
|
||||
"Large" = "Büyük"
|
||||
"Leaving the prototype" = "Prototipten çıkılıyor"
|
||||
"Left padding" = "Sol iç boşluk"
|
||||
"Left to right" = "Soldan sağa"
|
||||
"Link copied: it opens the file in FigCraft" = "Bağlantı kopyalandı: dosyayı FigCraft'ta açar"
|
||||
"Link copied: it opens the file in the browser" = "Bağlantı kopyalandı: dosyayı tarayıcıda açar"
|
||||
"Medium" = "Orta"
|
||||
"Missing fonts" = "Eksik yazı tipleri"
|
||||
"Move out of any group" = "Tüm grupların dışına taşı"
|
||||
"Move to group {group}" = "{group} grubuna taşı"
|
||||
"Move up or down while dragging its label" = "Etiketini sürüklerken yukarı veya aşağı hareket ettirin"
|
||||
"New from selection" = "Seçimden yeni oluştur"
|
||||
"No comments to copy" = "Kopyalanacak yorum yok"
|
||||
"No files or templates match your search" = "Aramanızla eşleşen dosya veya şablon yok"
|
||||
"No other pages" = "Başka sayfa yok"
|
||||
"No scope is shared by all the selected variables" = "Seçili tüm değişkenlerin paylaştığı bir kapsam yok"
|
||||
"Nobody shares a file there now." = "Şu anda orada kimse dosya paylaşmıyor."
|
||||
"Not connected: {reason}. Your work is still in this tab." = "Bağlı değil: {reason}. Çalışmanız hâlâ bu sekmede."
|
||||
"Not now" = "Şimdi değil"
|
||||
"Nothing changed since this version." = "Bu sürümden bu yana hiçbir şey değişmedi."
|
||||
"Nothing counted yet" = "Henüz sayılan bir şey yok"
|
||||
"Nothing to pick: the page is empty" = "Seçilecek bir şey yok: sayfa boş"
|
||||
"Opening the file…" = "Dosya açılıyor…"
|
||||
"Opening {n} files as new files" = { other = "{n} dosya yeni dosya olarak açılıyor" }
|
||||
"Other" = "Diğer"
|
||||
"Past 30 days" = "Son 30 gün"
|
||||
"Past 90 days" = "Son 90 gün"
|
||||
"Past year" = "Son 1 yıl"
|
||||
"Paste effect" = "Efekti yapıştır"
|
||||
"Paste fill" = "Dolguyu yapıştır"
|
||||
"Paste stroke" = "Konturu yapıştır"
|
||||
"Pick select: Tab and Shift+Tab move between layers, Enter goes into one, Shift+Enter out, Space selects, Escape cancels" = "Katman seçici: Tab ve Shift+Tab katmanlar arasında gezinir, Enter katmanın içine girer, Shift+Enter dışına çıkar, Space seçer, Escape iptal eder"
|
||||
"Pick select: into a layer, out to its parent" = "Katman seçici: katmanın içine gir, üst katmana çık"
|
||||
"Pick select: next or previous layer" = "Katman seçici: sonraki veya önceki katman"
|
||||
"Pick select: select the picked layer" = "Katman seçici: işaretlenen katmanı seç"
|
||||
"Plugin" = "Eklenti"
|
||||
"Plugins & widgets" = "Eklentiler ve widget'lar"
|
||||
"Pretty" = "Düzenli"
|
||||
"Pretty: full lines, no one word alone on the last" = "Dengeli: tam satırlar, son satırda tek sözcük kalmaz"
|
||||
"Relative to your system's display scaling (100% is the system's own size). Document zoom is separate." = "Sisteminizin ekran ölçeklendirmesine göredir (%100 sistemin kendi boyutudur). Belge yakınlaştırması ayrıdır."
|
||||
"Reload the page to get back the unsaved files the browser had room for." = "Tarayıcının yer ayırabildiği kaydedilmemiş dosyaları geri almak için sayfayı yeniden yükleyin."
|
||||
"Reload the page to get your unsaved files back." = "Kaydedilmemiş dosyalarınızı geri almak için sayfayı yeniden yükleyin."
|
||||
"Reload the page to start again." = "Yeniden başlamak için sayfayı yeniden yükleyin."
|
||||
"Remove all auto layout" = "Tüm otomatik yerleşimleri kaldır"
|
||||
"Remove {name} from session" = "{name} adlı kişiyi oturumdan kaldır"
|
||||
"Removed since this version" = "Bu sürümden bu yana kaldırıldı"
|
||||
"Reorder selection" = "Seçimi yeniden sırala"
|
||||
"Reset grid" = "Izgarayı sıfırla"
|
||||
"Retry now" = "Şimdi yeniden dene"
|
||||
"Right padding" = "Sağ iç boşluk"
|
||||
"Right to left" = "Sağdan sola"
|
||||
"Rotate a degree (Shift: 15)" = "Bir derece döndür (Shift: 15)"
|
||||
"Same as file ({profile})" = "Dosyayla aynı ({profile})"
|
||||
"Save a copy…" = "Kopyasını kaydet…"
|
||||
"Save files automatically" = "Dosyaları otomatik kaydet"
|
||||
"Scope" = "Kapsam"
|
||||
"Scope: all supported properties" = "Kapsam: desteklenen tüm özellikler"
|
||||
"Scope: hidden from pickers" = "Kapsam: seçicilerden gizli"
|
||||
"Scope: only {scope}" = "Kapsam: yalnızca {scope}"
|
||||
"Scrub a field faster (2x) or slower (1/2, 1/4)" = "Bir alanı daha hızlı (2x) veya daha yavaş (1/2, 1/4) kaydırarak ayarlayın"
|
||||
"Scrubbing at 1/2" = "1/2 hızında kaydırma"
|
||||
"Scrubbing at 1/4" = "1/4 hızında kaydırma"
|
||||
"Scrubbing at 1x" = "1x hızında kaydırma"
|
||||
"Scrubbing at 2x" = "2x hızında kaydırma"
|
||||
"Search files and templates" = "Dosya ve şablonlarda ara"
|
||||
"Search pages" = "Sayfalarda ara"
|
||||
"Search results" = "Arama sonuçları"
|
||||
"Select a row, a column or a full grid of three or more layers, outside an auto layout flow" = "Otomatik yerleşim akışı dışında üç veya daha fazla katmandan oluşan bir satır, sütun veya tam ızgara seçin"
|
||||
"Selection box: switch to pick select" = "Seçim kutusu: tıklayarak seçime geç"
|
||||
"Server key" = "Sunucu anahtarı"
|
||||
"Set as opening page" = "Açılış sayfası olarak ayarla"
|
||||
"Set corner smoothing to 60%" = "Köşe yumuşatmayı %60 olarak ayarla"
|
||||
"Set fill container" = "Kapsayıcıyı doldur olarak ayarla"
|
||||
"Set hug contents" = "İçeriği sar olarak ayarla"
|
||||
"Shared by your team on {server}" = "{server} üzerinde ekibiniz tarafından paylaşıldı"
|
||||
"Show and move the placement crosshair (its tool chosen, nothing selected)" = "Yerleştirme artı işaretini göster ve taşı (aracı seçiliyken, hiçbir şey seçili değilken)"
|
||||
"Small" = "Küçük"
|
||||
"Space" = "Boşluk"
|
||||
"Start on the Home screen" = "Ana ekranda başlat"
|
||||
"Strong line every" = "Kalın çizgi aralığı"
|
||||
"Subscript" = "Alt simge"
|
||||
"Superscript" = "Üst simge"
|
||||
"Tab or Ctrl+Space again" = "Tekrar Tab veya Ctrl+Space"
|
||||
"Text direction" = "Metin yönü"
|
||||
"Text on a path" = "Yol üzerinde metin"
|
||||
"The bars are hidden. {shortcut} shows them again" = "Çubuklar gizli. {shortcut} bunları yeniden gösterir"
|
||||
"The destination document is unavailable. Nothing was imported." = "Hedef belge kullanılamıyor. Hiçbir şey içe aktarılmadı."
|
||||
"The destination document was closed. Nothing was imported." = "Hedef belge kapatılmış. Hiçbir şey içe aktarılmadı."
|
||||
"The destination page was removed. Nothing was imported." = "Hedef sayfa kaldırılmış. Hiçbir şey içe aktarılmadı."
|
||||
"The window is too small for {size}%, so the interface is drawn at {drawn}%. Make the window larger to use {size}%." = "Pencere %{size} için çok küçük olduğundan arayüz %{drawn} olarak çiziliyor. %{size} kullanmak için pencereyi büyütün."
|
||||
"This file is too large to join here (up to {mb} MB)" = "Bu dosya buraya eklenmek için çok büyük (en fazla {mb} MB)"
|
||||
"This file uses fonts that aren't installed on this computer. Their text is drawn in a fallback font until you install them." = "Bu dosya, bu bilgisayarda yüklü olmayan yazı tiplerini kullanıyor. Siz yükleyene kadar ilgili metinler yedek bir yazı tipiyle çizilir."
|
||||
"This link opens a website outside the prototype:" = "Bu bağlantı prototip dışında bir web sitesi açar:"
|
||||
"This link opens your mail app to write a message:" = "Bu bağlantı ileti yazmak için e-posta uygulamanızı açar:"
|
||||
"This server doesn't count detached instances" = "Bu sunucu ayrılmış örnekleri saymaz"
|
||||
"This server doesn't count insertions" = "Bu sunucu eklemeleri saymaz"
|
||||
"This server doesn't count styles and variables" = "Bu sunucu stilleri ve değişkenleri saymaz"
|
||||
"This variant's value" = "Bu varyantın değeri"
|
||||
"This version can't be read." = "Bu sürüm okunamıyor."
|
||||
"This version doesn't have it: all of it is new." = "Bu sürümde yok: tamamı yeni."
|
||||
"Top padding" = "Üst iç boşluk"
|
||||
"Try another search, or browse templates." = "Başka bir arama deneyin veya şablonlara göz atın."
|
||||
"Update check is not supported in the web browser." = "Güncelleme denetimi web tarayıcısında desteklenmiyor."
|
||||
"Updating the graphics driver often helps. To use OpenGL only, start FigCraft from a Command Prompt with:" = "Grafik sürücüsünü güncellemek genellikle işe yarar. Yalnızca OpenGL kullanmak için FigCraft'ı Komut İstemi'nden şu komutla başlatın:"
|
||||
"Updating the graphics driver often helps. WGPU_BACKEND (vulkan, gl, metal) names another graphics API to try." = "Grafik sürücüsünü güncellemek genellikle işe yarar. WGPU_BACKEND (vulkan, gl, metal) denenecek başka bir grafik API'sini belirtir."
|
||||
"Upload from computer" = "Bilgisayardan yükle"
|
||||
"Use your browser's zoom to change the interface size." = "Arayüz boyutunu değiştirmek için tarayıcınızın yakınlaştırma ayarını kullanın."
|
||||
"WGPU_BACKEND is set and names the graphics API to use; unsetting it lets FigCraft choose." = "WGPU_BACKEND ayarlı ve kullanılacak grafik API'sini belirtiyor; bu ayarı kaldırmak seçimi FigCraft'a bırakır."
|
||||
"What changed since a saved version" = "Kaydedilmiş bir sürümden bu yana değişenler"
|
||||
"When marked ready" = "Hazır olarak işaretlendiğinde"
|
||||
"Widget" = "Widget"
|
||||
"Wrap style" = "Satır kaydırma stili"
|
||||
"Your unsaved files were too large for the browser to keep." = "Kaydedilmemiş dosyalarınız tarayıcının saklayabileceği boyuttan büyüktü."
|
||||
"connector labels without a saved snapshot are centred on the line, without their background" = "kaydedilmiş anlık görüntüsü olmayan bağlayıcı etiketleri, arka planları olmadan çizginin ortasına hizalandı"
|
||||
"elbowed and curved connectors without a saved path are routed afresh" = "kaydedilmiş yolu olmayan dirsekli ve kavisli bağlayıcılar yeniden yönlendirildi"
|
||||
"instance swap properties whose default component was past the layer limit were skipped" = "varsayılan bileşeni katman sınırını aşan örnek değiştirme özellikleri atlandı"
|
||||
"instances whose component was past the layer limit were imported as frames" = "bileşeni katman sınırını aşan örnekler çerçeve olarak içe aktarıldı"
|
||||
"invalid vector region fill paint list; layer fill used" = "geçersiz vektör bölgesi dolgu boyası listesi; katman dolgusu kullanıldı"
|
||||
"invalid vector region paints were skipped" = "geçersiz vektör bölgesi boyaları atlandı"
|
||||
"linked vector region fill styles keep resolved appearance; live style links were left out" = "bağlı vektör bölgesi dolgu stilleri çözümlenmiş görünümü korur; canlı stil bağlantıları dışarıda bırakıldı"
|
||||
"note or shape generated child has invalid bounds; child skipped" = "not veya şekil tarafından oluşturulan alt öğenin sınırları geçersiz; alt öğe atlandı"
|
||||
"note or shape generated child is missing its style or bounds; child skipped" = "not veya şekil tarafından oluşturulan alt öğenin stili veya sınırları eksik; alt öğe atlandı"
|
||||
"note or shape generated children exceed the layer or nesting limit; remaining children skipped" = "not veya şekil tarafından oluşturulan alt öğeler katman veya iç içe geçme sınırını aşıyor; kalan alt öğeler atlandı"
|
||||
"note or shape generated layout is missing or unsupported; using its outer frame" = "not veya şekil tarafından oluşturulan yerleşim eksik veya desteklenmiyor; dış çerçevesi kullanılıyor"
|
||||
"only in a text style or variable" = "yalnızca bir metin stilinde veya değişkende"
|
||||
"shape generated outline is missing or damaged; using its rectangle" = "şekil tarafından oluşturulan dış hat eksik veya bozuk; dikdörtgeni kullanılıyor"
|
||||
"slot layers without a matching slot property were imported as frames" = "eşleşen yuva özelliği olmayan yuva katmanları çerçeve olarak içe aktarıldı"
|
||||
"sticky layers import as frames with their text" = "yapışkan not katmanları metinleriyle birlikte çerçeve olarak içe aktarılır"
|
||||
"swapped instances whose previous component isn't in the file took the new component's look" = "önceki bileşeni dosyada bulunmayan değiştirilmiş örnekler yeni bileşenin görünümünü aldı"
|
||||
"variable-bound vector region paints keep resolved appearance; live bindings were left out" = "değişkene bağlı vektör bölgesi boyaları çözümlenmiş görünümü korur; canlı bağlamalar dışarıda bırakıldı"
|
||||
"vector region paint data exceeded import limits and was skipped" = "vektör bölgesi boya verileri içe aktarma sınırlarını aştığı için atlandı"
|
||||
"vector region references a missing fill style; layer fill used" = "vektör bölgesi eksik bir dolgu stiline başvuruyor; katman dolgusu kullanıldı"
|
||||
"{count} in it now · Changed {date}" = "Şu anda {count} · Değiştirilme: {date}"
|
||||
"{insertions} · {detachments}" = "{insertions} · {detachments}"
|
||||
"{name}, disconnected from its live session" = "{name}, canlı oturum bağlantısı kesildi"
|
||||
"{n} detached" = { other = "{n} ayrıldı" }
|
||||
"{n} inserted" = { other = "{n} eklendi" }
|
||||
"{n} text layers" = { other = "{n} metin katmanı" }
|
||||
"{percent}%" = "%{percent}"
|
||||
"{period}: {counts}" = "{period}: {counts}"
|
||||
"{used} · {detached}" = "{used} · {detached}"
|
||||
"{used} · {inserted}" = "{used} · {inserted}"
|
||||
"↵ / ⇧↵" = "↵ / ⇧↵"
|
||||
"⇥ or ⌥ Space again" = "Tekrar ⇥ veya ⌥ Space"
|
||||
"⌘ click a padding field" = "⌘ tuşuyla bir iç boşluk alanına tıklayın"
|
||||
"⌥ double-click an edge of an auto layout child" = "⌥ tuşuyla otomatik yerleşim alt öğesinin bir kenarına çift tıklayın"
|
||||
"⌥⌘ ← ↑ → ↓" = "⌥⌘ ← ↑ → ↓"
|
||||
[commands]
|
||||
"align.bottom" = "Alta hizala"
|
||||
"align.hcenter" = "Yatay merkezleri hizala"
|
||||
@@ -2420,6 +2649,60 @@ name = "Türkçe"
|
||||
"window.new" = "Yeni pencere"
|
||||
"template.list" = "Şablonları listele"
|
||||
|
||||
"arrange.reorder" = "Yeniden sırala"
|
||||
"board.codeBlock" = "Kod bloğu"
|
||||
"board.grid" = "Pano ızgarası"
|
||||
"board.mindMap" = "Zihin haritası"
|
||||
"board.mindMapAdd" = "Zihin haritası düğümü ekle"
|
||||
"board.reshape" = "Panoyu yeniden şekillendir"
|
||||
"board.setLanguage" = "Kod dili"
|
||||
"collab.reconnect" = "Yeniden bağlan"
|
||||
"collab.removePerson" = "Kişiyi oturumdan kaldır"
|
||||
"comment.prompt" = "Yorumları yapay zeka için kopyala"
|
||||
"data.fill" = "Veri doldur"
|
||||
"effect.copy" = "Efekti kopyala"
|
||||
"effect.paste" = "Efekti yapıştır"
|
||||
"file.fontReport" = "Yazı tipi raporu"
|
||||
"file.markSaved" = "Kaydedildi olarak işaretle"
|
||||
"fill.copy" = "Dolguyu kopyala"
|
||||
"fill.paste" = "Dolguyu yapıştır"
|
||||
"font.download" = "Yazı tipini indir"
|
||||
"font.downloads" = "Yazı tipi indirmeleri"
|
||||
"image.crop" = "Görseli kırp"
|
||||
"image.replace" = "Görseli değiştir"
|
||||
"inspect.designContext" = "Tasarım bağlamı"
|
||||
"layout.removeAll" = "Tüm yerleşimleri kaldır"
|
||||
"library.check" = "Kitaplığı denetle"
|
||||
"object.convertToSection" = "Bölüme dönüştür"
|
||||
"page.setOpening" = "Açılış sayfası olarak ayarla"
|
||||
"pref.autoSave" = "Otomatik kaydet"
|
||||
"pref.invertZoom" = "Yakınlaştırmayı ters çevir"
|
||||
"pref.startOnHome" = "Ana sayfada başlat"
|
||||
"pref.uiScale" = "Arayüz ölçeği"
|
||||
"pref.uiScaleDown" = "Arayüz ölçeğini küçült"
|
||||
"pref.uiScaleReset" = "Arayüz ölçeğini sıfırla"
|
||||
"pref.uiScaleUp" = "Arayüz ölçeğini büyüt"
|
||||
"proto.linkNotice" = "Prototip bağlantı bildirimi"
|
||||
"selection.createColorStyle" = "Seçimden renk stili oluştur"
|
||||
"stroke.copy" = "Konturu kopyala"
|
||||
"stroke.paste" = "Konturu yapıştır"
|
||||
"text.direction" = "Metin yönü"
|
||||
"text.directionAuto" = "Metin yönü: Otomatik"
|
||||
"text.directionLtr" = "Metin yönü: Soldan sağa"
|
||||
"text.directionRtl" = "Metin yönü: Sağdan sola"
|
||||
"text.fit" = "Metni sığdır"
|
||||
"text.loadFont" = "Yazı tipini yükle"
|
||||
"text.missingFonts" = "Eksik yazı tipleri"
|
||||
"text.openLink" = "Bağlantıyı aç"
|
||||
"text.refit" = "Metni yeniden sığdır"
|
||||
"text.rescanFonts" = "Yazı tiplerini yeniden tara"
|
||||
"text.wrapStyle" = "Metin kaydırma stili"
|
||||
"tool.annotation" = "Ek açıklama aracı"
|
||||
"tool.crosshair" = "Artı işareti aracı"
|
||||
"tool.textOnPath" = "Yol üzerinde metin aracı"
|
||||
"variable.extendCollection" = "Değişken koleksiyonunu genişlet"
|
||||
"view.minimize" = "Simge durumuna küçült"
|
||||
"widget.hover" = "Araç takımı üzerine gelme"
|
||||
[menu]
|
||||
"bool.exclude" = "Hariç tut"
|
||||
"bool.flatten" = "Düzleştir"
|
||||
@@ -2452,3 +2735,6 @@ name = "Türkçe"
|
||||
"view.themeDark" = "Koyu"
|
||||
"view.themeLight" = "Açık"
|
||||
"view.themeSystem" = "Sistemi izle"
|
||||
"text.directionAuto" = "Otomatik"
|
||||
"text.directionLtr" = "Soldan sağa"
|
||||
"text.directionRtl" = "Sağdan sola"
|
||||
@@ -22,9 +22,23 @@ impl FigApp {
|
||||
// `file.open`/`file.close`). Record that presentation before returning, so an in-flight
|
||||
// screenshot admitted on the old file cannot accept pixels from the new one.
|
||||
self.observe_presentation();
|
||||
if let Ok(v) = &r {
|
||||
self.note_snapping(id, v);
|
||||
}
|
||||
r.map_err(|e| self.failed(id, &e)).ok()
|
||||
}
|
||||
|
||||
/// Snap to pixel grid turned on or off says which at the bottom, as in Figma: its shortcut
|
||||
/// (Shift+Cmd/Ctrl+') changes nothing on the canvas until the next drag.
|
||||
fn note_snapping(&mut self, id: &str, result: &Value) {
|
||||
let msg = match (id, result.get("on").and_then(Value::as_bool)) {
|
||||
("view.snapPixel", Some(true)) => crate::i18n::tr("Snap to pixel grid on"),
|
||||
("view.snapPixel", Some(false)) => crate::i18n::tr("Snap to pixel grid off"),
|
||||
_ => return,
|
||||
};
|
||||
self.toast(msg);
|
||||
}
|
||||
|
||||
/// A programmatic command that changed the engine clipboard never wrote the system clipboard:
|
||||
/// forget the old system mirror so a later user paste does not trust it as our own copy.
|
||||
/// `before` is the layers generation captured before the command ran.
|
||||
@@ -321,6 +335,7 @@ impl FigApp {
|
||||
self.autosave_tick(ctx, now);
|
||||
self.auto_save_tick(ctx, now);
|
||||
updates_ui::tick(self, ctx);
|
||||
crate::assets_panel::refresh_libraries(self, ctx);
|
||||
self.logic_ticked = true;
|
||||
}
|
||||
}
|
||||
@@ -72,6 +72,44 @@ impl FigApp {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the colour picker is being used right now for the selected layers' own look (a
|
||||
/// paint, an effect, a text range or Selection colors): a drag on its value controls (the
|
||||
/// palette, the hue and alpha sliders, a number field, the gradient bar and its stops), the
|
||||
/// keyboard in one of its fields, the eyedropper sampling, or a drag of the canvas handles it
|
||||
/// owns (gradient stops and handles, image crop). Only then does the canvas hide the selection
|
||||
/// frame and a text's coloured selection, so the colour being chosen shows against the page.
|
||||
/// Merely having the picker open, or pressing a button, a menu or a swatch, leaves it visible.
|
||||
pub(crate) fn picker_hides_selection(&self, ctx: &egui::Context) -> bool {
|
||||
let edits_selection = matches!(
|
||||
self.ui.picker,
|
||||
Some(
|
||||
crate::colorpicker::PickerTarget::Paint { .. }
|
||||
| crate::colorpicker::PickerTarget::Effect { .. }
|
||||
| crate::colorpicker::PickerTarget::TextRange { .. }
|
||||
| crate::colorpicker::PickerTarget::SelectionColor { .. }
|
||||
)
|
||||
);
|
||||
if !edits_selection {
|
||||
return false;
|
||||
}
|
||||
// The picker draws after the canvas, so its card comes from the previous frame.
|
||||
let card = self.ui.picker_popover.as_ref();
|
||||
// A drag changes the colour live; a press alone does not. Buttons, menus, swatches and the
|
||||
// paint-type switches are clicks and must not hide the selection while held (they used to,
|
||||
// which flickered it). Dragging the card by its header moves the popover, not the colour.
|
||||
let header_drag = card.map(|c| c.header_drag_id());
|
||||
let dragging = ctx.dragged_id().is_some_and(|id| header_drag != Some(id))
|
||||
&& ctx.input(|i| i.pointer.any_down() && i.pointer.press_origin().is_some_and(|p| card.is_some_and(|c| c.rect.contains(p))));
|
||||
// A value field keeps the keyboard after its click: hide until focus leaves the picker.
|
||||
// Only a text edit counts: every clicked control takes focus in egui, and a focused
|
||||
// palette square or swatch must not keep the selection hidden after the drag.
|
||||
let typing = ctx.text_edit_focused()
|
||||
&& ctx
|
||||
.memory(|m| m.focused())
|
||||
.is_some_and(|id| ctx.read_response(id).is_some_and(|r| card.is_some_and(|c| c.rect.contains_rect(r.rect))));
|
||||
dragging || typing || self.session.tool.pick_only || crate::handles::gradient_dragging(ctx) || crate::handles::crop_dragging(ctx)
|
||||
}
|
||||
|
||||
/// Leaving Design ends a pen path as Escape does and goes back to Move: Prototype and Inspect
|
||||
/// don't draw (#307). Checked as the frame starts (the control channel) and after the panels
|
||||
/// and shortcuts (the mode switcher, the tabs, Shift+E/Shift+D), before the canvas sees more.
|
||||
|
||||
@@ -21,7 +21,7 @@ mod drag_sprite;
|
||||
mod input;
|
||||
pub(crate) use input::release_fields_for_press;
|
||||
mod outline;
|
||||
mod overlays;
|
||||
pub(crate) mod overlays;
|
||||
mod render;
|
||||
mod rulers;
|
||||
|
||||
@@ -280,8 +280,9 @@ fn pointer_event(app: &FigApp, kind: PointerKind, pos: Pos2, m: &egui::Modifiers
|
||||
sy: f64::from(pos.y),
|
||||
shift: m.shift,
|
||||
alt: m.alt,
|
||||
// Crop mode: resizing the layer crops it, as Cmd/Ctrl-resizing does.
|
||||
cmd: m.command || app.ui.crop.is_some(),
|
||||
// Crop mode: resizing the layer crops it, as Cmd/Ctrl-resizing does (not while its points
|
||||
// are being edited, where Cmd/Ctrl bends a segment).
|
||||
cmd: m.command || (app.ui.crop.is_some() && app.session.ds().is_ok_and(|d| d.vector_edit.is_none())),
|
||||
ctrl: m.ctrl,
|
||||
zoom,
|
||||
pressure: app.canvas.pressure,
|
||||
@@ -326,7 +327,7 @@ pub fn show(app: &mut FigApp, ui: &mut Ui, worker: &mut Worker) {
|
||||
// Otherwise keep the centre.
|
||||
ds.view.vw = f64::from(rect.width());
|
||||
ds.view.vh = f64::from(rect.height());
|
||||
if first {
|
||||
if first && ds.fit_when_sized {
|
||||
ds.zoom_to_fit();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -529,9 +529,10 @@ fn draw_crop(app: &FigApp, painter: &egui::Painter, id: NodeId, img: &ImagePaint
|
||||
|
||||
/// Draw the handles.
|
||||
pub fn draw(app: &mut FigApp, painter: &egui::Painter) {
|
||||
// Crop mode ends when a colour picker opens, or when its layer leaves the selection or its fill
|
||||
// is no longer a Crop image (an undo).
|
||||
if app.ui.crop.is_some() && (app.ui.picker.is_some() || crop_target(app).is_none()) {
|
||||
// Crop mode ends when a colour picker opens, when its layer leaves the selection or its fill
|
||||
// is no longer a Crop image (an undo), or when the layer's points are being edited.
|
||||
let editing_points = app.session.ds().is_ok_and(|d| d.vector_edit.is_some());
|
||||
if app.ui.crop.is_some() && (app.ui.picker.is_some() || crop_target(app).is_none() || editing_points) {
|
||||
app.ui.crop = None;
|
||||
}
|
||||
let app = &*app;
|
||||
@@ -697,8 +698,8 @@ pub fn input(app: &mut FigApp, ctx: &egui::Context, pos: Pos2) -> Input {
|
||||
}
|
||||
}
|
||||
if let Some((id, fills, index, _, rect)) = crop_target(app) {
|
||||
// Crop mode: the layer's own resize handles crop it (the pointer events carry Cmd/Ctrl).
|
||||
if app.ui.crop.is_some() && on_resize_handle(app, pos) {
|
||||
// The layer's own resize handles resize/crop the layer, not the crop handles.
|
||||
if on_resize_handle(app, pos) {
|
||||
return Input::Ignored;
|
||||
}
|
||||
let Some(c) = crop_corners(app, id, rect) else { return Input::Ignored };
|
||||
@@ -821,13 +822,13 @@ fn apply(app: &mut FigApp, drag: &Drag, pos: Pos2, modifiers: egui::Modifiers) {
|
||||
let (dx, dy) = (u.0 - start.0, u.1 - start.1);
|
||||
(x0 + dx, y0 + dy, x1 + dx, y1 + dy)
|
||||
} else {
|
||||
// Scale about the opposite corner, keeping the image's aspect ratio unless Shift.
|
||||
// Scale about the opposite corner, keeping the image's aspect ratio with Shift.
|
||||
let corners = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)];
|
||||
let (ax, ay) = corners.get((*which + 2) % 4).copied().unwrap_or((x0, y0));
|
||||
let (cx, cy) = corners.get(*which).copied().unwrap_or((x1, y1));
|
||||
let (ow, oh) = (cx - ax, cy - ay);
|
||||
let (mut nw, mut nh) = (u.0 - ax, u.1 - ay);
|
||||
if !modifiers.shift {
|
||||
if modifiers.shift {
|
||||
// Node aspect matters: the unit box is not square in pixels.
|
||||
let Some(n) = app.session.doc().ok().and_then(|d| d.node(*id)).cloned() else { return };
|
||||
let k = ((nw * n.width).abs() / (ow * n.width).abs().max(1e-9)).max((nh * n.height).abs() / (oh * n.height).abs().max(1e-9));
|
||||
|
||||
@@ -321,6 +321,9 @@ pub(super) fn input(app: &mut FigApp, ui: &mut Ui, resp: &egui::Response) -> boo
|
||||
open_context_menu(app, pos, mods.command);
|
||||
return true;
|
||||
}
|
||||
if crop_mode_multi_click(app, resp, pos, &mods) {
|
||||
return true;
|
||||
}
|
||||
// A third quick click is counted as a triple, not a double (a click elsewhere in between still
|
||||
// leaves its time in the sequence): it means the same here — edit, enter, open — unless a
|
||||
// vector or text is being edited, where a triple already has its own meaning. A triple on
|
||||
@@ -432,6 +435,18 @@ fn pan_past_edge(app: &mut FigApp, ctx: &egui::Context, mods: &egui::Modifiers)
|
||||
}
|
||||
}
|
||||
|
||||
/// A double- or triple-click in crop mode stays in crop mode (it would edit the points), and is
|
||||
/// taken here. Its last press may have begun a resize on a side of the layer: its release ends that.
|
||||
fn crop_mode_multi_click(app: &mut FigApp, resp: &egui::Response, pos: Pos2, mods: &egui::Modifiers) -> bool {
|
||||
if app.ui.crop.is_none() || !(resp.double_clicked() || resp.triple_clicked()) {
|
||||
return false;
|
||||
}
|
||||
if std::mem::take(&mut app.canvas.dragging) {
|
||||
send(app, PointerKind::Up, pos, mods);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fn send(app: &mut FigApp, kind: PointerKind, pos: Pos2, m: &egui::Modifiers) {
|
||||
let ev = pointer_event(app, kind, pos, m);
|
||||
// A hover where nothing changed since the last one finds what that one found (the state is
|
||||
|
||||
@@ -170,14 +170,29 @@ pub(super) fn outline_path(doc: &Document, n: &figcraft_doc::Node) -> Option<fig
|
||||
figcraft_render::node_outline(doc, n).map(|(p, _)| p)
|
||||
}
|
||||
|
||||
/// How far, in screen points, the flattened outline of a path with `curves` curved segments may
|
||||
/// stray from it. Up to [`SMOOTH_CURVES`] curves it is 0.02, so the outline bends smoothly. Above
|
||||
/// that it grows with the count, up to 0.5 at 25 times as many. The outline is flattened again each
|
||||
/// frame the view moves or the layer is hovered, and egui tessellates every point each frame, so a
|
||||
/// heavy vector keeps about as many points as at 0.5.
|
||||
pub(super) fn outline_tolerance(curves: usize) -> f64 {
|
||||
(0.02 * curves as f64 / SMOOTH_CURVES as f64).clamp(0.02, 0.5)
|
||||
}
|
||||
|
||||
/// The most curved segments an outline flattens at the smooth 0.02 pt ([`outline_tolerance`]).
|
||||
pub(super) const SMOOTH_CURVES: usize = 200;
|
||||
|
||||
/// [`outline_path`] on screen, flattened into polylines.
|
||||
fn outline_shape(app: &FigApp, doc: &Document, id: NodeId) -> Option<Vec<Vec<Pos2>>> {
|
||||
use figcraft_geom::kurbo::PathEl;
|
||||
let n = doc.node(id)?;
|
||||
let path = outline_path(doc, n)?;
|
||||
let w = doc.world_transform(id);
|
||||
let mut out = Vec::new();
|
||||
let mut cur: Vec<Pos2> = Vec::new();
|
||||
figcraft_geom::kurbo::flatten(path.iter(), 0.5 / app.session.ds().map(|d| d.view.zoom).unwrap_or(1.0), |el| {
|
||||
let curves = path.elements().iter().filter(|el| matches!(el, PathEl::QuadTo(..) | PathEl::CurveTo(..))).count();
|
||||
let zoom = app.session.ds().map(|d| d.view.zoom).unwrap_or(1.0);
|
||||
figcraft_geom::kurbo::flatten(path.iter(), outline_tolerance(curves) / zoom, |el| {
|
||||
use figcraft_geom::kurbo::PathEl::*;
|
||||
match el {
|
||||
MoveTo(p) => {
|
||||
|
||||
@@ -46,3 +46,82 @@ fn square_corners_keep_the_box() {
|
||||
let id = layer(&mut s, "rectangle", json!({"stroke": "#000000", "strokeWeight": 4, "strokeAlign": "outside"}));
|
||||
assert!(path_of(s.doc().unwrap(), id).is_none());
|
||||
}
|
||||
|
||||
/// How far, in screen points, layer `id`'s outline strays from its path: the largest distance from
|
||||
/// the middle of one of its straight pieces to the path.
|
||||
fn largest_stray(u: &crate::layers_drag_tests::Ui, id: NodeId) -> f64 {
|
||||
use figcraft_geom::kurbo::ParamCurveNearest;
|
||||
let doc = u.app.session.doc().unwrap().clone();
|
||||
let path = path_of(&doc, id).unwrap();
|
||||
let to_local = doc.world_transform(id).inverse();
|
||||
let zoom = u.app.session.ds().unwrap().view.zoom;
|
||||
let mut largest: f64 = 0.0;
|
||||
for shape in super::outline::outline_shapes(&u.app, &doc, id, egui::Stroke::new(1.0, egui::Color32::WHITE)) {
|
||||
let egui::Shape::Path(line) = shape else { panic!("a polyline outline") };
|
||||
for piece in line.points.windows(2) {
|
||||
let middle = to_local * u.app.to_page(piece[0] + (piece[1] - piece[0]) * 0.5);
|
||||
let d = path.segments().map(|seg| seg.nearest(middle, 1e-9).distance_sq).fold(f64::MAX, f64::min).sqrt();
|
||||
largest = largest.max(d * zoom);
|
||||
}
|
||||
}
|
||||
largest
|
||||
}
|
||||
|
||||
/// The outline is flattened to 0.02 pt on screen at any zoom, so its straight pieces don't show:
|
||||
/// each stays well within 0.1 pt of the curve (0.5 pt left straight pieces visible on an ellipse).
|
||||
#[test]
|
||||
fn a_selected_ellipses_outline_stays_on_the_curve_at_any_zoom() {
|
||||
let mut s = Session::new();
|
||||
let ellipse =
|
||||
NodeId(s.execute("node.create", &json!({"type": "ellipse", "x": 0, "y": 0, "width": 65, "height": 50})).unwrap()["id"].as_u64().unwrap());
|
||||
let mut u = crate::layers_drag_tests::Ui::new(s);
|
||||
for zoom in [1.0, 3.5, 16.0] {
|
||||
u.app.session.execute("view.set", &json!({"zoom": zoom, "cx": 30, "cy": 25})).unwrap();
|
||||
u.frame(vec![]);
|
||||
let stray = largest_stray(&u, ellipse);
|
||||
assert!(stray < 0.1, "at {zoom}x the outline strays {stray:.3} pt from the curve");
|
||||
}
|
||||
}
|
||||
|
||||
/// A vector of `rows` closed bands, each `waves` cubic waves 10 pt wide along its top.
|
||||
fn waves(rows: usize, waves: usize) -> String {
|
||||
let mut d = String::new();
|
||||
for r in 0..rows {
|
||||
let y = r as f64 * 10.0;
|
||||
d += &format!("M0 {y} ");
|
||||
for k in 0..waves {
|
||||
let x = k as f64 * 10.0;
|
||||
d += &format!("C{} {} {} {} {} {y} ", x + 3.3, y - 8.0, x + 6.6, y + 8.0, x + 10.0);
|
||||
}
|
||||
d += &format!("L{} {} L0 {} Z ", waves as f64 * 10.0, y + 6.0, y + 6.0);
|
||||
}
|
||||
d
|
||||
}
|
||||
|
||||
/// Heavy vectors are flattened coarser, so hovering, panning and zooming them stays as cheap as
|
||||
/// before: a vector of 5,000 curves keeps the points 0.5 pt gave it (0.02 pt gives about five times
|
||||
/// as many), and one of 200 still bends as smoothly as an ellipse.
|
||||
#[test]
|
||||
fn a_heavy_vectors_outline_keeps_the_points_it_had() {
|
||||
use super::outline::{SMOOTH_CURVES, outline_shapes, outline_tolerance};
|
||||
let mut s = Session::new();
|
||||
let vector = |s: &mut Session, d: String| {
|
||||
NodeId(s.execute("node.create", &json!({"type": "vector", "path": d, "closed": true, "x": 0, "y": 0})).unwrap()["id"].as_u64().unwrap())
|
||||
};
|
||||
let heavy = vector(&mut s, waves(50, 100));
|
||||
let light = vector(&mut s, waves(2, SMOOTH_CURVES / 2));
|
||||
let u = crate::layers_drag_tests::Ui::new(s);
|
||||
let doc = u.app.session.doc().unwrap().clone();
|
||||
let points = |id: NodeId| -> usize {
|
||||
outline_shapes(&u.app, &doc, id, egui::Stroke::new(1.0, egui::Color32::WHITE))
|
||||
.iter()
|
||||
.map(|shape| if let egui::Shape::Path(line) = shape { line.points.len() } else { 0 })
|
||||
.sum()
|
||||
};
|
||||
let zoom = u.app.session.ds().unwrap().view.zoom;
|
||||
let mut before = 0;
|
||||
figcraft_geom::kurbo::flatten(path_of(&doc, heavy).unwrap().iter(), 0.5 / zoom, |_| before += 1);
|
||||
assert!(points(heavy) <= before, "{} points, {before} at 0.5 pt", points(heavy));
|
||||
assert_eq!(outline_tolerance(SMOOTH_CURVES), 0.02);
|
||||
assert!(largest_stray(&u, light) < 0.1, "{SMOOTH_CURVES} curves bend smoothly");
|
||||
}
|
||||
@@ -124,7 +124,10 @@ pub(super) fn overlays(app: &FigApp, painter: &egui::Painter, t: &Tokens) -> Vec
|
||||
}
|
||||
// Selection.
|
||||
let editing = ds.text_edit.clone();
|
||||
if !sel.is_empty() && editing.is_none() && ds.vector_edit.is_none() {
|
||||
// While the colour picker is being used on the selection, hide its frame and handles so the
|
||||
// colour being picked shows on the layer itself (a text's coloured selection would hide it
|
||||
// too).
|
||||
if !sel.is_empty() && editing.is_none() && ds.vector_edit.is_none() && !app.picker_hides_selection(painter.ctx()) {
|
||||
size_label = selection_overlay(app, painter, ds, &doc, &sel, zoom);
|
||||
}
|
||||
if app.session.tool.tool == ToolId::ShapeBuilder
|
||||
@@ -171,22 +174,27 @@ pub(super) fn overlays(app: &FigApp, painter: &egui::Painter, t: &Tokens) -> Vec
|
||||
labels
|
||||
}
|
||||
|
||||
/// The pixel grid's lines: one screen pixel wide, a light grey at a fifth of its strength, so
|
||||
/// they darken white and lighten a dark canvas or fill alike. Measured in Figma (2026-11-24):
|
||||
/// 242 on white and 78 on a grey of 50, which this grey gives.
|
||||
pub(crate) const PIXEL_GRID: Color32 = Color32::from_rgba_unmultiplied_const(190, 190, 190, 51);
|
||||
|
||||
/// Pixel grid at high zoom.
|
||||
fn pixel_grid(app: &FigApp, painter: &egui::Painter) {
|
||||
let r = app.canvas.rect;
|
||||
let p0 = app.to_page(r.min);
|
||||
let p1 = app.to_page(r.max);
|
||||
let col = Color32::from_black_alpha(18);
|
||||
let line = stroke(PIXEL_GRID, 1.0 / painter.pixels_per_point());
|
||||
let mut x = p0.x.floor();
|
||||
while x <= p1.x {
|
||||
let s = app.to_screen(x, 0.0).x;
|
||||
painter.line_segment([pos2(s, r.min.y), pos2(s, r.max.y)], stroke(col, 1.0));
|
||||
let s = painter.round_to_pixel_center(app.to_screen(x, 0.0).x);
|
||||
painter.line_segment([pos2(s, r.min.y), pos2(s, r.max.y)], line);
|
||||
x += 1.0;
|
||||
}
|
||||
let mut y = p0.y.floor();
|
||||
while y <= p1.y {
|
||||
let s = app.to_screen(0.0, y).y;
|
||||
painter.line_segment([pos2(r.min.x, s), pos2(r.max.x, s)], stroke(col, 1.0));
|
||||
let s = painter.round_to_pixel_center(app.to_screen(0.0, y).y);
|
||||
painter.line_segment([pos2(r.min.x, s), pos2(r.max.x, s)], line);
|
||||
y += 1.0;
|
||||
}
|
||||
}
|
||||
@@ -268,12 +276,16 @@ fn text_edit_overlay(app: &FigApp, painter: &egui::Painter, t: &Tokens, doc: &Do
|
||||
let preedit = app.preedit_view();
|
||||
let edoc: &Document = preedit.map(|p| &*p.doc).unwrap_or(doc);
|
||||
let Some(text) = TextOnScreen::of(edoc, te.id) else { return };
|
||||
// While the colour picker is being used on this text, its frame and coloured selection hide
|
||||
// too: the selection colour tinted the very characters whose colour is being chosen. The
|
||||
// caret stays.
|
||||
let picking = app.picker_hides_selection(painter.ctx());
|
||||
let layout = &text.layout;
|
||||
if let Some(q) = node_quad(app, edoc, te.id) {
|
||||
if !picking && let Some(q) = node_quad(app, edoc, te.id) {
|
||||
quad(painter, q, stroke(accent(painter), 1.0));
|
||||
}
|
||||
let (a, b) = (te.caret.min(te.anchor), te.caret.max(te.anchor));
|
||||
if a != b && preedit.is_none() {
|
||||
if a != b && preedit.is_none() && !picking {
|
||||
for q in text.selection(app, a, b) {
|
||||
painter.add(Shape::convex_polygon(q.to_vec(), accent(painter).gamma_multiply(0.3), Stroke::NONE));
|
||||
}
|
||||
|
||||
@@ -131,6 +131,11 @@ fn shows(code: &str, web: bool) -> bool {
|
||||
// Arabic; keep the catalog out until an embedded Arabic fallback is supplied.
|
||||
return figcraft_text::face_with_char('ع', &["Noto Sans Arabic"]).is_some();
|
||||
}
|
||||
if code.split(['-', '_']).next().is_some_and(|b| b.eq_ignore_ascii_case("he") || b.eq_ignore_ascii_case("iw")) {
|
||||
// Desktop draws Hebrew with a system face (or bundled craft-fonts); the web leaves it out
|
||||
// unless Noto Sans Hebrew is embedded (FIGCRAFT_EMBED_SCRIPTS=Hebr).
|
||||
return figcraft_text::face_with_char('א', &["Noto Sans Hebrew"]).is_some();
|
||||
}
|
||||
if code.split('-').next() == Some("ta") {
|
||||
// Desktop draws Tamil with a system face (#2018); the web has none until craft-fonts
|
||||
// carries Noto Sans Tamil.
|
||||
@@ -233,6 +238,15 @@ mod tests {
|
||||
assert_eq!(shows("ar-SA", true), face);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_web_offers_hebrew_only_with_its_face() {
|
||||
assert!(shows("he", false), "desktop always lists Hebrew");
|
||||
let face = figcraft_text::face_with_char('א', &["Noto Sans Hebrew"]).is_some();
|
||||
assert_eq!(shows("he", true), face);
|
||||
assert_eq!(shows("he-IL", true), face);
|
||||
assert_eq!(shows("iw-IL", true), face);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_web_offers_tamil_only_with_its_face() {
|
||||
assert!(shows("ta", false), "desktop always lists Tamil");
|
||||
|
||||
@@ -372,3 +372,172 @@ fn a_gradient_drag_whose_gesture_closes_under_the_held_button_stops_editing() {
|
||||
u.button(u.app.to_screen(180.0, 200.0), false);
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `shape` is painted in `col`, as a fill or a stroke.
|
||||
fn painted_in(shape: &egui::Shape, col: egui::Color32) -> bool {
|
||||
use egui::epaint::ColorMode;
|
||||
match shape {
|
||||
egui::Shape::Path(p) => p.fill == col || matches!(p.stroke.color, ColorMode::Solid(c) if c == col),
|
||||
egui::Shape::Rect(r) => r.fill == col || r.stroke.color == col,
|
||||
egui::Shape::LineSegment { stroke, .. } => stroke.color == col,
|
||||
egui::Shape::Circle(c) => c.fill == col || c.stroke.color == col,
|
||||
egui::Shape::Vec(v) => v.iter().any(|s| painted_in(s, col)),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// How many shapes painted in `col` this frame draws inside `area`. On the page those are the
|
||||
/// selection's frame, its handles and a text's coloured selection.
|
||||
fn painted_around(out: &egui::FullOutput, area: egui::Rect, col: egui::Color32) -> usize {
|
||||
out.shapes.iter().filter(|c| painted_in(&c.shape, col) && c.shape.visual_bounding_rect().intersects(area)).count()
|
||||
}
|
||||
|
||||
/// A text layer's box on screen, with room for its handles.
|
||||
fn text_area(u: &Ui, id: NodeId) -> egui::Rect {
|
||||
let b = u.app.session.doc().unwrap().world_bounds(id).unwrap();
|
||||
egui::Rect::from_two_pos(u.app.to_screen(b.x0, b.y0), u.app.to_screen(b.x1, b.y1)).expand(20.0)
|
||||
}
|
||||
|
||||
fn selected_text(s: &mut Session) -> NodeId {
|
||||
let id =
|
||||
NodeId(s.execute("text.create", &json!({"text": "Hello", "x": 300, "y": 200, "props": {"fontSize": 48}})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
id
|
||||
}
|
||||
|
||||
// The colour picker only hides the selection while it is being used: opening it leaves the frame in
|
||||
// view, and the press/drag on its controls hides it. A text makes this matter: its frame runs
|
||||
// through the glyphs and its selection is tinted.
|
||||
#[test]
|
||||
fn a_selected_texts_frame_hides_only_while_its_colour_picker_is_used() {
|
||||
let mut s = Session::new();
|
||||
let text = selected_text(&mut s);
|
||||
let mut u = Ui::new(s);
|
||||
let area = text_area(&u, text);
|
||||
let accent = crate::theme::canvas_accent(&u.ctx);
|
||||
assert!(painted_around(&u.frame_output(vec![]), area, accent) > 0, "the selected text's frame shows");
|
||||
|
||||
let target = PickerTarget::Paint { fills: true, index: 0, ids: vec![text] };
|
||||
u.app.open_picker(target.clone(), None);
|
||||
for _ in 0..3 {
|
||||
u.frame(vec![]);
|
||||
}
|
||||
assert_eq!(u.app.ui.picker, Some(target.clone()), "the picker is open");
|
||||
assert!(painted_around(&u.frame_output(vec![]), area, accent) > 0, "an open picker alone leaves the frame in view");
|
||||
|
||||
// A press alone changes nothing; dragging the saturation/value square uses the picker.
|
||||
let square = u.ctx.read_response(egui::Id::unique("cp_sv")).expect("the saturation/value square").rect;
|
||||
let from = square.center();
|
||||
let to = from + egui::vec2(12.0, 8.0);
|
||||
u.button(from, true);
|
||||
assert!(painted_around(&u.frame_output(vec![]), area, accent) > 0, "holding the palette still leaves the frame");
|
||||
u.frame(vec![egui::Event::PointerMoved(to)]);
|
||||
assert_eq!(painted_around(&u.frame_output(vec![]), area, accent), 0, "dragging the palette hides the frame");
|
||||
u.button(to, false);
|
||||
assert_eq!(u.app.ui.picker, Some(target), "releasing does not close the picker");
|
||||
assert!(painted_around(&u.frame_output(vec![]), area, accent) > 0, "releasing brings the frame back");
|
||||
|
||||
// A button in the picker (the blend dropdown) is a click, not a value drag.
|
||||
let button = egui::pos2(square.center().x, square.min.y - 30.0);
|
||||
u.button(button, true);
|
||||
assert!(painted_around(&u.frame_output(vec![]), area, accent) > 0, "holding a picker button leaves the frame");
|
||||
u.button(button, false);
|
||||
}
|
||||
|
||||
// The picker's header is its drag handle: moving the card is not choosing a colour.
|
||||
#[test]
|
||||
fn dragging_the_picker_by_its_header_does_not_hide_the_selection() {
|
||||
let mut s = Session::new();
|
||||
let text = selected_text(&mut s);
|
||||
let mut u = Ui::new(s);
|
||||
let area = text_area(&u, text);
|
||||
let accent = crate::theme::canvas_accent(&u.ctx);
|
||||
u.app.open_picker(PickerTarget::Paint { fills: true, index: 0, ids: vec![text] }, None);
|
||||
for _ in 0..3 {
|
||||
u.frame(vec![]);
|
||||
}
|
||||
let header = u.app.ui.picker_popover.as_ref().expect("the picker is open").header.center();
|
||||
let before = u.app.ui.picker_popover.as_ref().unwrap().rect;
|
||||
u.button(header, true);
|
||||
for k in 1..=5 {
|
||||
u.frame(vec![egui::Event::PointerMoved(header - egui::vec2(0.0, 6.0 * k as f32))]);
|
||||
}
|
||||
assert!(u.app.ui.picker_popover.as_ref().unwrap().rect.min.y < before.min.y - 10.0, "the header drag moved the picker");
|
||||
assert!(painted_around(&u.frame_output(vec![]), area, accent) > 0, "moving the picker leaves the frame in view");
|
||||
u.button(header - egui::vec2(0.0, 30.0), false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_texts_coloured_selection_hides_only_while_its_colour_picker_is_used() {
|
||||
let mut s = Session::new();
|
||||
let text = selected_text(&mut s);
|
||||
// Select all of it: the selection highlight the colour picker's own layer would otherwise wear.
|
||||
figcraft_engine::textedit::begin(&mut s, text, None, false).unwrap();
|
||||
let mut u = Ui::new(s);
|
||||
let area = text_area(&u, text);
|
||||
let tint = crate::theme::canvas_accent(&u.ctx).gamma_multiply(0.3);
|
||||
assert!(painted_around(&u.frame_output(vec![]), area, tint) > 0, "the text selection is tinted");
|
||||
|
||||
u.app.open_picker(PickerTarget::Paint { fills: true, index: 0, ids: vec![text] }, None);
|
||||
for _ in 0..3 {
|
||||
u.frame(vec![]);
|
||||
}
|
||||
assert!(painted_around(&u.frame_output(vec![]), area, tint) > 0, "an open picker alone leaves it tinted");
|
||||
|
||||
let square = u.ctx.read_response(egui::Id::unique("cp_sv")).expect("the saturation/value square").rect;
|
||||
let from = square.center();
|
||||
let to = from + egui::vec2(10.0, 6.0);
|
||||
u.button(from, true);
|
||||
assert!(painted_around(&u.frame_output(vec![]), area, tint) > 0, "holding the palette still leaves the tint");
|
||||
u.frame(vec![egui::Event::PointerMoved(to)]);
|
||||
assert_eq!(painted_around(&u.frame_output(vec![]), area, tint), 0, "dragging the palette hides the tint");
|
||||
u.button(to, false);
|
||||
assert!(painted_around(&u.frame_output(vec![]), area, tint) > 0, "releasing brings the tint back");
|
||||
}
|
||||
|
||||
// Typing a colour value counts as using the picker even when no mouse button is down.
|
||||
#[test]
|
||||
fn a_focused_colour_field_hides_the_selection_while_it_is_edited() {
|
||||
let mut s = Session::new();
|
||||
let text = selected_text(&mut s);
|
||||
let mut u = Ui::new(s);
|
||||
let area = text_area(&u, text);
|
||||
let accent = crate::theme::canvas_accent(&u.ctx);
|
||||
u.app.open_picker(PickerTarget::Paint { fills: true, index: 0, ids: vec![text] }, None);
|
||||
for _ in 0..3 {
|
||||
u.frame(vec![]);
|
||||
}
|
||||
assert!(painted_around(&u.frame_output(vec![]), area, accent) > 0, "the frame shows while the picker is idle");
|
||||
|
||||
let hex = u.ctx.read_response(egui::Id::unique("cp_hex").with("click")).expect("the Hex field").rect;
|
||||
u.button(hex.center(), true);
|
||||
u.button(hex.center(), false);
|
||||
for _ in 0..2 {
|
||||
u.frame(vec![]);
|
||||
}
|
||||
assert_eq!(painted_around(&u.frame_output(vec![]), area, accent), 0, "a focused value field hides the frame");
|
||||
u.frame(vec![egui::Event::Text("0".into())]);
|
||||
assert_eq!(painted_around(&u.frame_output(vec![]), area, accent), 0, "and typing in it keeps the frame hidden");
|
||||
}
|
||||
|
||||
// egui gives every clicked control the keyboard, a palette square and a swatch included. Only a
|
||||
// text field means the picker is being used: a square that keeps focus must not keep the
|
||||
// selection hidden after its drag ends.
|
||||
#[test]
|
||||
fn a_focused_palette_square_does_not_hide_the_selection() {
|
||||
let mut s = Session::new();
|
||||
let text = selected_text(&mut s);
|
||||
let mut u = Ui::new(s);
|
||||
let area = text_area(&u, text);
|
||||
let accent = crate::theme::canvas_accent(&u.ctx);
|
||||
u.app.open_picker(PickerTarget::Paint { fills: true, index: 0, ids: vec![text] }, None);
|
||||
for _ in 0..3 {
|
||||
u.frame(vec![]);
|
||||
}
|
||||
// What egui does to a clicked square.
|
||||
u.ctx.memory_mut(|m| m.request_focus(egui::Id::unique("cp_sv")));
|
||||
for _ in 0..2 {
|
||||
u.frame(vec![]);
|
||||
}
|
||||
assert!(painted_around(&u.frame_output(vec![]), area, accent) > 0, "focus on a palette square leaves the frame in view");
|
||||
}
|
||||
@@ -141,11 +141,11 @@ fn choose_mode(u: &mut Ui, shown: &str, item: &str) {
|
||||
u.frame(vec![]);
|
||||
}
|
||||
|
||||
/// Crop chosen as the image fill's mode in the colour picker enters crop mode, as Crop image does
|
||||
/// (#2150): the picker closes, the picture keeps its place, and a corner handle then crops it
|
||||
/// with the layer still selected. The other modes only set the mode.
|
||||
/// Crop chosen as the image fill's mode in the colour picker sets the mode with a placement crop
|
||||
/// (#2499): the picker stays open, crop mode on the canvas does not start, and dragging a corner
|
||||
/// handle without Cmd resizes the layer and morphs/squishes the image.
|
||||
#[test]
|
||||
fn crop_chosen_in_the_colour_picker_enters_crop_mode() {
|
||||
fn crop_chosen_in_the_colour_picker_sets_mode_and_morphs_on_resize() {
|
||||
let (mut u, layer, _) = setup();
|
||||
u.app.ui.picker = Some(crate::colorpicker::PickerTarget::Paint { fills: true, index: 0, ids: vec![layer] });
|
||||
for _ in 0..4 {
|
||||
@@ -155,8 +155,8 @@ fn crop_chosen_in_the_colour_picker_enters_crop_mode() {
|
||||
assert_eq!(mode(&u, layer), (ImageScaleMode::Fit, None));
|
||||
assert!(u.app.ui.picker.is_some() && u.app.ui.crop.is_none(), "Fit is only a mode");
|
||||
choose_mode(&mut u, "Fit", "Crop");
|
||||
assert_eq!(u.app.ui.crop, Some((layer, 0)), "crop mode on the image fill");
|
||||
assert!(u.app.ui.picker.is_none(), "crop mode takes the canvas from the picker");
|
||||
assert_eq!(u.app.ui.crop, None, "Crop in picker does not enter canvas crop mode");
|
||||
assert!(u.app.ui.picker.is_some(), "picker stays open");
|
||||
// The picture keeps its place: the crop is the one Crop image makes of the fitted image.
|
||||
let (m, Some(before)) = mode(&u, layer) else { panic!("a crop where the picture was") };
|
||||
assert_eq!(m, ImageScaleMode::Crop);
|
||||
@@ -169,29 +169,18 @@ fn crop_chosen_in_the_colour_picker_enters_crop_mode() {
|
||||
assert_eq!(mode(&menu, other), (ImageScaleMode::Fit, None));
|
||||
menu.app.run("image.crop", json!({}));
|
||||
assert_eq!(mode(&menu, other), (ImageScaleMode::Crop, Some(before)));
|
||||
// The bottom right corner, dragged in, crops the picture to the top left 3/4 of the layer.
|
||||
// Close the picker to drag the canvas resize handles.
|
||||
u.app.ui.picker = None;
|
||||
u.frame(vec![]);
|
||||
// Dragging the bottom right corner without Cmd resizes the layer to 150x75 and morphs/squishes the image.
|
||||
let (from, to) = (u.app.to_screen(200.0, 100.0), u.app.to_screen(150.0, 75.0));
|
||||
u.drag_to(from, to);
|
||||
u.button(to, false);
|
||||
assert_eq!(u.app.session.selection(), vec![layer], "the layer stays selected");
|
||||
assert_eq!(u.app.ui.crop, Some((layer, 0)), "still cropping");
|
||||
let n = u.app.session.doc().unwrap().node(layer).unwrap().clone();
|
||||
assert!((n.width - 150.0).abs() < 1e-6 && (n.height - 75.0).abs() < 1e-6, "{} x {}", n.width, n.height);
|
||||
let (_, Some(after)) = mode(&u, layer) else { panic!("a crop") };
|
||||
assert!((after[0] - before[0] * 0.75).abs() < 1e-9 && (after[3] - before[3] * 0.75).abs() < 1e-9, "{before:?} -> {after:?}");
|
||||
assert!((after[4] - before[4]).abs() < 1e-9 && (after[5] - before[5]).abs() < 1e-9, "the top left stays: {before:?} -> {after:?}");
|
||||
// The picture's own corner, now outside the layer at (200, 100), scales the picture inside the
|
||||
// layer, which keeps its size and its selection.
|
||||
let (from, to) = (u.app.to_screen(200.0, 100.0), u.app.to_screen(240.0, 120.0));
|
||||
u.drag_to(from, to);
|
||||
u.button(to, false);
|
||||
assert_eq!(u.app.session.selection(), vec![layer], "the layer stays selected");
|
||||
assert_eq!(u.app.ui.crop, Some((layer, 0)), "still cropping");
|
||||
let n = u.app.session.doc().unwrap().node(layer).unwrap().clone();
|
||||
assert!((n.width - 150.0).abs() < 1e-6 && (n.height - 75.0).abs() < 1e-6, "the layer keeps its size: {} x {}", n.width, n.height);
|
||||
let (_, Some(scaled)) = mode(&u, layer) else { panic!("a crop") };
|
||||
// The picture grew from 200 x 100 to 240 x 120: the layer shows 5/6 of what it showed.
|
||||
assert!((scaled[0] - after[0] * 5.0 / 6.0).abs() < 1e-6 && (scaled[3] - after[3] * 5.0 / 6.0).abs() < 1e-6, "{after:?} -> {scaled:?}");
|
||||
assert_eq!(after, before, "normal resize without Cmd leaves crop transform unchanged to morph/squish");
|
||||
}
|
||||
|
||||
/// The reporter's sequence (#2307): the colour picker open on an image fill held in Crop mode
|
||||
@@ -206,12 +195,7 @@ fn crop_from_the_colour_picker_then_a_drag_on_the_image_moves_the_crop_not_the_l
|
||||
u.frame(vec![]);
|
||||
}
|
||||
choose_mode(&mut u, "Fill", "Crop");
|
||||
// Crop mode on the canvas ended (a click away from the image); the picker opens on the Crop fill.
|
||||
u.app.ui.crop = None;
|
||||
u.app.ui.picker = Some(crate::colorpicker::PickerTarget::Paint { fills: true, index: 0, ids: vec![layer] });
|
||||
for _ in 0..4 {
|
||||
u.frame(vec![]);
|
||||
}
|
||||
assert!(u.app.ui.picker.is_some());
|
||||
let (_, Some(before)) = mode(&u, layer) else { panic!("a crop") };
|
||||
let at = u.app.session.doc().unwrap().node(layer).unwrap().transform.as_coeffs();
|
||||
let from = u.app.to_screen(100.0, 50.0);
|
||||
@@ -267,7 +251,7 @@ fn image_at(u: &Ui, id: NodeId, fills: bool, region: Option<usize>) -> figcraft_
|
||||
/// fill have nothing for Crop image to crop either.
|
||||
#[test]
|
||||
fn crop_in_the_colour_picker_only_sets_the_mode_where_crop_image_does_not_apply() {
|
||||
use crate::colorpicker::{PickerTarget, crop_on_canvas};
|
||||
use crate::colorpicker::PickerTarget;
|
||||
let picture = |u: &Ui, id: NodeId| u.app.session.doc().unwrap().node(id).unwrap().fills[0].clone();
|
||||
// Opens the picker on `target`, chooses Crop and checks crop mode stays off.
|
||||
let crop_only_sets_the_mode = |u: &mut Ui, target: PickerTarget, what: &str| {
|
||||
@@ -288,7 +272,7 @@ fn crop_in_the_colour_picker_only_sets_the_mode_where_crop_image_does_not_apply(
|
||||
assert_eq!(image_at(&u, layer, false, None).scale_mode, ImageScaleMode::Crop);
|
||||
assert_eq!(mode(&u, layer), (ImageScaleMode::Fill, None), "the fill is untouched");
|
||||
|
||||
// Two image layers at once: both take the mode.
|
||||
// Two image layers at once: both take the mode, with each layer's crop sized to its own dimensions.
|
||||
let (mut u, layer, rect) = setup();
|
||||
let paint = picture(&u, layer);
|
||||
u.app.run("fill.set", json!({"ids": [rect], "index": 0, "paint": paint}));
|
||||
@@ -296,6 +280,8 @@ fn crop_in_the_colour_picker_only_sets_the_mode_where_crop_image_does_not_apply(
|
||||
crop_only_sets_the_mode(&mut u, PickerTarget::Paint { fills: true, index: 0, ids: vec![layer, rect] }, "two layers");
|
||||
assert_eq!(mode(&u, layer).0, ImageScaleMode::Crop);
|
||||
assert_eq!(mode(&u, rect).0, ImageScaleMode::Crop);
|
||||
let (crop1, crop2) = (mode(&u, layer).1.unwrap(), mode(&u, rect).1.unwrap());
|
||||
assert_ne!(crop1, crop2, "differently sized layers must have distinct placement crops without stretching");
|
||||
|
||||
// A region's own image fill in vector edit mode: the region's mode is set, the layer's image
|
||||
// fill is untouched.
|
||||
@@ -313,12 +299,133 @@ fn crop_in_the_colour_picker_only_sets_the_mode_where_crop_image_does_not_apply(
|
||||
crop_only_sets_the_mode(&mut u, PickerTarget::Paint { fills: true, index: 0, ids: vec![vector] }, "a region");
|
||||
assert_eq!(image_at(&u, vector, true, Some(1)).scale_mode, ImageScaleMode::Crop);
|
||||
assert_eq!(u.app.session.doc().unwrap().node(vector).unwrap().fills, layer_fills, "the layer's fills are untouched");
|
||||
}
|
||||
|
||||
// A fill that isn't an image, and targets that aren't a layer's paint, have no crop on the canvas.
|
||||
let (u, layer, rect) = setup();
|
||||
assert_eq!(crop_on_canvas(&u.app, &PickerTarget::Paint { fills: true, index: 0, ids: vec![layer] }), Some((layer, 0)));
|
||||
assert_eq!(crop_on_canvas(&u.app, &PickerTarget::Paint { fills: true, index: 0, ids: vec![rect] }), None, "a solid fill");
|
||||
assert_eq!(crop_on_canvas(&u.app, &PickerTarget::Paint { fills: true, index: 1, ids: vec![layer] }), None, "no fill there");
|
||||
assert_eq!(crop_on_canvas(&u.app, &PickerTarget::PageBackground), None);
|
||||
assert_eq!(crop_on_canvas(&u.app, &PickerTarget::Style { id: "S:1".into(), index: 0 }), None);
|
||||
#[test]
|
||||
fn in_crop_mode_the_edges_of_an_image_in_auto_layout_crop_it_too() {
|
||||
let (mut u, layer, _) = setup();
|
||||
let column = id(&u.app.session.execute("frame.create", &json!({"x": 0, "y": 0, "width": 200, "height": 100})).unwrap());
|
||||
u.app.run("node.reparent", json!({"ids": [layer], "parent": column}));
|
||||
u.app.run("node.set", json!({"ids": [column], "props": {"layout": "vertical", "sizingV": "hug"}}));
|
||||
u.app.run("select.set", json!({"ids": [layer]}));
|
||||
u.app.run("image.crop", json!({}));
|
||||
u.frame(vec![]);
|
||||
let (_, Some(before)) = mode(&u, layer) else { panic!("a crop") };
|
||||
let (from, to) = (u.app.to_screen(100.0, 100.0), u.app.to_screen(100.0, 60.0));
|
||||
u.drag_to(from, to);
|
||||
u.button(to, false);
|
||||
let n = u.app.session.doc().unwrap().node(layer).unwrap().clone();
|
||||
assert!((n.height - 60.0).abs() < 1e-6 && (n.width - 200.0).abs() < 1e-6, "the bottom edge moved up: {} x {}", n.width, n.height);
|
||||
let (m, Some(after)) = mode(&u, layer) else { panic!("a crop") };
|
||||
assert_eq!(m, ImageScaleMode::Crop);
|
||||
assert!((after[3] - before[3] * 0.6).abs() < 1e-9 && (after[0] - before[0]).abs() < 1e-9, "cropped, not squashed: {before:?} -> {after:?}");
|
||||
assert!((after[5] - before[5]).abs() < 1e-9, "the top stays: {before:?} -> {after:?}");
|
||||
assert_eq!(u.app.ui.crop, Some((layer, 0)), "still cropping");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_double_click_in_crop_mode_keeps_cropping_and_vector_edit_ends_crop_mode() {
|
||||
let (mut u, layer, _) = setup();
|
||||
u.app.run("image.crop", json!({}));
|
||||
u.frame(vec![]);
|
||||
let at = u.app.to_screen(100.0, 50.0);
|
||||
for _ in 0..2 {
|
||||
u.button(at, true);
|
||||
u.button(at, false);
|
||||
}
|
||||
u.frame(vec![]);
|
||||
assert!(u.app.session.ds().unwrap().vector_edit.is_none(), "a double-click while cropping doesn't edit the points");
|
||||
assert_eq!(u.app.ui.crop, Some((layer, 0)), "still cropping");
|
||||
let (from, to) = (u.app.to_screen(200.0, 50.0), u.app.to_screen(150.0, 50.0));
|
||||
u.drag_to(from, to);
|
||||
u.button(to, false);
|
||||
let n = u.app.session.doc().unwrap().node(layer).unwrap().clone();
|
||||
assert!((n.width - 150.0).abs() < 1e-6 && matches!(n.kind, figcraft_doc::NodeKind::Rectangle), "the side crops; the layer stays a rectangle");
|
||||
u.app.run("vector.edit.begin", json!({"id": layer}));
|
||||
u.frame(vec![]);
|
||||
assert_eq!(u.app.ui.crop, None, "editing the points ends crop mode");
|
||||
u.app.run("image.crop", json!({}));
|
||||
u.frame(vec![]);
|
||||
assert!(u.app.session.ds().unwrap().vector_edit.is_none(), "cropping ends editing the points");
|
||||
assert_eq!(u.app.ui.crop, Some((layer, 0)));
|
||||
}
|
||||
|
||||
/// The second press of a double-click on a side of the layer begins a resize; its release, which
|
||||
/// is the double-click, ends it, and crop mode stays.
|
||||
#[test]
|
||||
fn a_double_click_on_a_side_in_crop_mode_leaves_no_resize_open() {
|
||||
let (mut u, layer, _) = setup();
|
||||
u.app.run("image.crop", json!({}));
|
||||
u.frame(vec![]);
|
||||
let at = u.app.to_screen(200.0, 50.0);
|
||||
for _ in 0..2 {
|
||||
u.button(at, true);
|
||||
u.button(at, false);
|
||||
}
|
||||
u.frame(vec![]);
|
||||
assert!(u.app.session.ds().unwrap().interaction.is_none(), "the resize the second press began is over");
|
||||
assert_eq!(u.app.ui.crop, Some((layer, 0)), "still cropping");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn in_crop_mode_the_images_corners_scale_freely_and_with_shift_in_proportion() {
|
||||
let image_size = |u: &Ui, layer: NodeId| {
|
||||
let n = u.app.session.doc().unwrap().node(layer).unwrap().clone();
|
||||
let (_, Some(c)) = mode(u, layer) else { panic!("a crop") };
|
||||
let (x0, y0, x1, y1) = figcraft_color::ImagePaint::crop_rect(c);
|
||||
((x1 - x0) * n.width, (y1 - y0) * n.height)
|
||||
};
|
||||
for shift in [false, true] {
|
||||
let (mut u, layer, _) = setup();
|
||||
u.app.run("image.crop", json!({}));
|
||||
u.frame(vec![]);
|
||||
let (from, to) = (u.app.to_screen(200.0, 50.0), u.app.to_screen(150.0, 50.0));
|
||||
u.drag_to(from, to);
|
||||
u.button(to, false);
|
||||
let (w0, h0) = image_size(&u, layer);
|
||||
let modifiers = if shift { Modifiers::SHIFT } else { Modifiers::NONE };
|
||||
let (from, to) = (u.app.to_screen(200.0, 100.0), u.app.to_screen(260.0, 110.0));
|
||||
u.frame_with(
|
||||
vec![Event::PointerMoved(from), Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers }],
|
||||
modifiers,
|
||||
);
|
||||
for k in 1..=10 {
|
||||
u.frame_with(vec![Event::PointerMoved(from + (to - from) * (k as f32 / 10.0))], modifiers);
|
||||
}
|
||||
u.frame_with(vec![Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers }], modifiers);
|
||||
let (w1, h1) = image_size(&u, layer);
|
||||
let kept = (w1 / h1 - w0 / h0).abs() < 1e-6;
|
||||
assert!(w1 > w0, "the corner scaled the image: {w0}x{h0} -> {w1}x{h1}");
|
||||
assert_eq!(kept, shift, "Shift {shift}: {w0}x{h0} -> {w1}x{h1}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn in_auto_layout_a_side_dragged_past_the_image_leaves_no_empty_strip() {
|
||||
let mut s = Session::new();
|
||||
let image = image::RgbaImage::from_fn(300, 200, |x, y| image::Rgba([(x % 255) as u8, (y % 255) as u8, 120, 255]));
|
||||
let mut png = std::io::Cursor::new(Vec::new());
|
||||
image.write_to(&mut png, image::ImageFormat::Png).unwrap();
|
||||
let data = base64::engine::general_purpose::STANDARD.encode(png.into_inner());
|
||||
let content = id(&s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 1092, "height": 1400})).unwrap());
|
||||
id(&s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 300, "height": 160, "parent": content})).unwrap());
|
||||
let layer = id(&s.execute("image.place", &json!({"data": data, "x": 0, "y": 300, "width": 804, "height": 969})).unwrap());
|
||||
s.execute("node.reparent", &json!({"ids": [layer], "parent": content})).unwrap();
|
||||
s.execute("node.set", &json!({"ids": [content], "props": {"layout": "vertical", "sizingV": "hug", "padding": [112, 0, 100, 0]}})).unwrap();
|
||||
s.execute("node.set", &json!({"ids": [layer], "props": {"constrainProportions": true}})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [layer]})).unwrap();
|
||||
let mut u = Ui::new(s);
|
||||
u.app.run("view.set", json!({"zoom": 0.5, "cx": 546, "cy": 700}));
|
||||
u.app.run("image.crop", json!({}));
|
||||
u.frame(vec![]);
|
||||
let b = u.app.session.doc().unwrap().world_bounds(layer).unwrap();
|
||||
let (from, to) = (u.app.to_screen(400.0, b.y0), u.app.to_screen(400.0, b.y0 - 120.0));
|
||||
u.drag_to(from, to);
|
||||
u.button(to, false);
|
||||
let n = u.app.session.doc().unwrap().node(layer).unwrap().clone();
|
||||
let (_, Some(c)) = mode(&u, layer) else { panic!("a crop") };
|
||||
let (x0, y0, x1, y1) = figcraft_color::ImagePaint::crop_rect(c);
|
||||
assert!(x0 <= 1e-9 && y0 <= 1e-9 && x1 >= 1.0 - 1e-9 && y1 >= 1.0 - 1e-9, "the image covers the layer: {:?}", (x0, y0, x1, y1));
|
||||
assert!(n.width >= 1.0 && n.height >= 1.0, "{} x {}", n.width, n.height);
|
||||
assert!(u.app.session.ds().unwrap().vector_edit.is_none());
|
||||
}
|
||||
@@ -348,13 +348,17 @@ pub fn show(app: &mut FigApp, ctx: &Context) {
|
||||
let selected = langs().find(|(code, _)| on(code)).map_or(tr("System"), |(_, name)| name);
|
||||
let resp = crate::widgets::dropdown(ui, selected, 220.0, None);
|
||||
let mut pick = None;
|
||||
crate::right::menu_popup(&resp).show(|ui| {
|
||||
for (code, name) in langs() {
|
||||
if crate::right::menu_check(ui, on(code), name, "") {
|
||||
pick = Some(code);
|
||||
ui.close();
|
||||
// Vertical-only fallback: keep the menu anchored to the dropdown's start edge.
|
||||
let alt = if ui.style().right_to_left { &[egui::RectAlign::TOP_END] } else { &[egui::RectAlign::TOP_START] };
|
||||
crate::right::menu_popup(&resp).align_alternatives(alt).show(|ui| {
|
||||
egui::ScrollArea::vertical().max_height(320.0).show(ui, |ui| {
|
||||
for (code, name) in langs() {
|
||||
if crate::right::menu_check(ui, on(code), name, "") {
|
||||
pick = Some(code);
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
if let Some(code) = pick {
|
||||
app.run("pref.language", json!({"language": code}));
|
||||
|
||||
@@ -683,6 +683,7 @@ fn create_collection(app: &mut FigApp, vars: &Variables, st: &mut Editor) {
|
||||
{
|
||||
st.library = None;
|
||||
st.collection = Some(id.clone());
|
||||
st.group = None;
|
||||
start_rename(st, Rename::Collection(id));
|
||||
}
|
||||
}
|
||||
@@ -896,7 +897,11 @@ fn var_row(app: &mut FigApp, ui: &mut Ui, view: &View, coll: &Collection, v: &Va
|
||||
// An inherited variable is named (and deleted) in the collection it extends.
|
||||
let inherited = v.extends.is_some();
|
||||
if editable && st.rename.as_ref() == Some(&target) {
|
||||
if let Some(name) = rename_field(ui, st, &target, &v.name, name_r, regular(11.0)) {
|
||||
// The row shows the name's last part: the field edits that and keeps the group. A name of
|
||||
// slashes and spaces alone is ignored, as the group would swallow it and drop the variable.
|
||||
let (group, short) = v.name.rsplit_once('/').unwrap_or(("", &v.name));
|
||||
if let Some(typed) = rename_field(ui, st, &target, short, name_r, regular(11.0)).filter(|n| n.split('/').any(|p| !p.trim().is_empty())) {
|
||||
let name = if group.is_empty() { typed } else { format!("{group}/{typed}") };
|
||||
app.run("variable.update", json!({"variable": v.id, "name": name}));
|
||||
}
|
||||
} else {
|
||||
@@ -1160,7 +1165,9 @@ fn create_row(app: &mut FigApp, ui: &mut Ui, view: &View, coll: &Collection, st:
|
||||
VariableType::Boolean => tr_noop("Boolean"),
|
||||
};
|
||||
if menu_item(ui, tr(label), "") {
|
||||
let name = unique(label, |n| view.in_collection(&coll.id).any(|v| v.name == n));
|
||||
// Made in the group shown, so the table showing it lists it.
|
||||
let base = st.group.as_ref().map_or_else(|| label.to_string(), |g| format!("{g}/{label}"));
|
||||
let name = unique(&base, |n| view.in_collection(&coll.id).any(|v| v.name == n));
|
||||
let params = json!({"collection": coll.id, "name": name, "type": kind.id()});
|
||||
if let Some(id) = app.run("variable.create", params).and_then(|r| r["id"].as_str().map(str::to_string)) {
|
||||
st.query.clear();
|
||||
|
||||
+53
-24
@@ -102,9 +102,6 @@ pub(crate) fn file_row(ui: &Ui, t: &Tokens, r: Rect, resp: &Response, row: &File
|
||||
if resp.hovered() {
|
||||
ui.painter().rect_filled(r, CornerRadius::same(5), t.hover);
|
||||
}
|
||||
if let Some((icon, tint)) = row.mark {
|
||||
icons::paint(ui.painter(), Rect::from_min_size(pos2(r.min.x + 8.0, r.center().y - 8.0), vec2(16.0, 16.0)), icon, tint);
|
||||
}
|
||||
let (name_font, detail_font) = (regular(12.0), regular(row.detail_size));
|
||||
let width = |s: &str, font: &egui::FontId| ui.painter().layout_no_wrap(s.to_string(), font.clone(), Color32::WHITE).size().x;
|
||||
let room = (r.width() - 40.0).max(0.0);
|
||||
@@ -120,8 +117,19 @@ pub(crate) fn file_row(ui: &Ui, t: &Tokens, r: Rect, resp: &Response, row: &File
|
||||
widgets::elide_start_font(ui, row.detail, detail_room, detail_font.clone())
|
||||
};
|
||||
let cut = name != row.name || detail != row.detail;
|
||||
ui.painter().text(pos2(r.min.x + 32.0, r.center().y), Align2::LEFT_CENTER, name, name_font, row.ink);
|
||||
ui.painter().text(pos2(r.max.x - 8.0, r.center().y), Align2::RIGHT_CENTER, detail, detail_font, row.detail_ink);
|
||||
if crate::i18n::right_to_left() {
|
||||
if let Some((icon, tint)) = row.mark {
|
||||
icons::paint(ui.painter(), Rect::from_min_size(pos2(r.max.x - 24.0, r.center().y - 8.0), vec2(16.0, 16.0)), icon, tint);
|
||||
}
|
||||
ui.painter().text(pos2(r.max.x - 32.0, r.center().y), Align2::RIGHT_CENTER, name, name_font, row.ink);
|
||||
ui.painter().text(pos2(r.min.x + 8.0, r.center().y), Align2::LEFT_CENTER, detail, detail_font, row.detail_ink);
|
||||
} else {
|
||||
if let Some((icon, tint)) = row.mark {
|
||||
icons::paint(ui.painter(), Rect::from_min_size(pos2(r.min.x + 8.0, r.center().y - 8.0), vec2(16.0, 16.0)), icon, tint);
|
||||
}
|
||||
ui.painter().text(pos2(r.min.x + 32.0, r.center().y), Align2::LEFT_CENTER, name, name_font, row.ink);
|
||||
ui.painter().text(pos2(r.max.x - 8.0, r.center().y), Align2::RIGHT_CENTER, detail, detail_font, row.detail_ink);
|
||||
}
|
||||
cut
|
||||
}
|
||||
|
||||
@@ -144,30 +152,40 @@ pub fn show(app: &mut FigApp, ui: &mut Ui) {
|
||||
dropped(app, ui.ctx());
|
||||
egui::CentralPanel::default().frame(egui::Frame::NONE.fill(t.panel)).show(ui, |ui| {
|
||||
let rect = ui.max_rect();
|
||||
let left = Rect::from_min_size(rect.min, vec2(SIDEBAR, rect.height()));
|
||||
ui.painter().line_segment([left.right_top(), left.right_bottom()], Stroke::new(1.0, t.border));
|
||||
sidebar(app, ui, &t, left);
|
||||
let rtl = crate::i18n::right_to_left();
|
||||
let side = if rtl {
|
||||
Rect::from_min_size(pos2(rect.max.x - SIDEBAR, rect.min.y), vec2(SIDEBAR, rect.height()))
|
||||
} else {
|
||||
Rect::from_min_size(rect.min, vec2(SIDEBAR, rect.height()))
|
||||
};
|
||||
let border_x = if rtl { side.left() } else { side.right() };
|
||||
ui.painter().line_segment([pos2(border_x, side.top()), pos2(border_x, side.bottom())], Stroke::new(1.0, t.border));
|
||||
sidebar(app, ui, &t, side);
|
||||
let main =
|
||||
if rtl { Rect::from_min_max(rect.min, pos2(side.min.x, rect.max.y)) } else { Rect::from_min_max(pos2(side.max.x, rect.min.y), rect.max) };
|
||||
if app.ui.home_view.file_query.trim().is_empty() && app.ui.home_view.section == Section::Online {
|
||||
// Your online files lay themselves out in the area (and scroll their own list).
|
||||
let area = Rect::from_min_max(pos2(left.max.x + 40.0, rect.min.y + 24.0), rect.max - vec2(40.0, 24.0));
|
||||
let area = main.shrink2(vec2(40.0, 24.0));
|
||||
crate::online::section(app, ui, area, &t);
|
||||
opened_join(app);
|
||||
return;
|
||||
}
|
||||
let main = Rect::from_min_max(pos2(left.max.x, rect.min.y), rect.max);
|
||||
ui.scope_builder(egui::UiBuilder::new().max_rect(main), |ui| {
|
||||
egui::ScrollArea::vertical().id_salt("home").auto_shrink([false, false]).show(ui, |ui| {
|
||||
egui::Frame::NONE.inner_margin(egui::Margin::symmetric(40, 24)).show(ui, |ui| {
|
||||
ui.spacing_mut().item_spacing = vec2(GAP, 0.0);
|
||||
if app.ui.home_view.file_query.trim().is_empty() {
|
||||
match app.ui.home_view.section {
|
||||
Section::Templates => templates(app, ui, &t),
|
||||
_ => recents(app, ui, &t),
|
||||
let align = if rtl { egui::Align::Max } else { egui::Align::Min };
|
||||
ui.with_layout(egui::Layout::top_down(align), |ui| {
|
||||
ui.spacing_mut().item_spacing = vec2(GAP, 0.0);
|
||||
if app.ui.home_view.file_query.trim().is_empty() {
|
||||
match app.ui.home_view.section {
|
||||
Section::Templates => templates(app, ui, &t),
|
||||
_ => recents(app, ui, &t),
|
||||
}
|
||||
} else {
|
||||
search_results(app, ui, &t);
|
||||
opened_join(app);
|
||||
}
|
||||
} else {
|
||||
search_results(app, ui, &t);
|
||||
opened_join(app);
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -221,8 +239,13 @@ fn sidebar(app: &mut FigApp, ui: &mut Ui, t: &Tokens, left: Rect) {
|
||||
ui.painter().rect_filled(r, CornerRadius::same(5), if current { t.selected_row } else { t.hover });
|
||||
}
|
||||
focus_ring(ui, t, r, &resp, 5);
|
||||
icons::paint(ui.painter(), Rect::from_min_size(pos2(r.min.x + 10.0, r.center().y - 8.0), vec2(16.0, 16.0)), icon, t.icon);
|
||||
ui.painter().text(pos2(r.min.x + 36.0, r.center().y), Align2::LEFT_CENTER, tr(label), regular(12.0), t.text);
|
||||
if crate::i18n::right_to_left() {
|
||||
icons::paint(ui.painter(), Rect::from_min_size(pos2(r.max.x - 26.0, r.center().y - 8.0), vec2(16.0, 16.0)), icon, t.icon);
|
||||
ui.painter().text(pos2(r.max.x - 36.0, r.center().y), Align2::RIGHT_CENTER, tr(label), regular(12.0), t.text);
|
||||
} else {
|
||||
icons::paint(ui.painter(), Rect::from_min_size(pos2(r.min.x + 10.0, r.center().y - 8.0), vec2(16.0, 16.0)), icon, t.icon);
|
||||
ui.painter().text(pos2(r.min.x + 36.0, r.center().y), Align2::LEFT_CENTER, tr(label), regular(12.0), t.text);
|
||||
}
|
||||
if resp.clicked() {
|
||||
app.ui.home_view.section = section;
|
||||
app.ui.home_view.file_query.clear();
|
||||
@@ -241,10 +264,16 @@ fn sidebar(app: &mut FigApp, ui: &mut Ui, t: &Tokens, left: Rect) {
|
||||
ui.painter().rect_filled(r, CornerRadius::same(5), if current { t.selected_row } else { t.hover });
|
||||
}
|
||||
focus_ring(ui, t, r, &resp, 5);
|
||||
icons::paint(ui.painter(), Rect::from_min_size(pos2(r.min.x + 10.0, r.center().y - 8.0), vec2(16.0, 16.0)), Icon::Adjust, t.icon);
|
||||
ui.painter().text(pos2(r.min.x + 36.0, r.center().y), Align2::LEFT_CENTER, tr("Preferences"), regular(12.0), t.text);
|
||||
let key_label = figcraft_engine::keymap::display("Cmd+,", crate::shortcuts::platform());
|
||||
ui.painter().text(pos2(r.max.x - 8.0, r.center().y), Align2::RIGHT_CENTER, &key_label, regular(11.0), t.text_secondary);
|
||||
if crate::i18n::right_to_left() {
|
||||
icons::paint(ui.painter(), Rect::from_min_size(pos2(r.max.x - 26.0, r.center().y - 8.0), vec2(16.0, 16.0)), Icon::Adjust, t.icon);
|
||||
ui.painter().text(pos2(r.max.x - 36.0, r.center().y), Align2::RIGHT_CENTER, tr("Preferences"), regular(12.0), t.text);
|
||||
ui.painter().text(pos2(r.min.x + 8.0, r.center().y), Align2::LEFT_CENTER, &key_label, regular(11.0), t.text_secondary);
|
||||
} else {
|
||||
icons::paint(ui.painter(), Rect::from_min_size(pos2(r.min.x + 10.0, r.center().y - 8.0), vec2(16.0, 16.0)), Icon::Adjust, t.icon);
|
||||
ui.painter().text(pos2(r.min.x + 36.0, r.center().y), Align2::LEFT_CENTER, tr("Preferences"), regular(12.0), t.text);
|
||||
ui.painter().text(pos2(r.max.x - 8.0, r.center().y), Align2::RIGHT_CENTER, &key_label, regular(11.0), t.text_secondary);
|
||||
}
|
||||
resp = resp.on_hover_text(format!("{} ({})", tr("Preferences"), key_label));
|
||||
if resp.clicked() {
|
||||
app.ui.preferences = !app.ui.preferences;
|
||||
|
||||
@@ -95,7 +95,9 @@ const LATIN_AMERICA: &[&str] =
|
||||
/// language the UI can't draw (CJK on the web without CJK faces built in) doesn't count.
|
||||
fn resolve_one(want: &str) -> Option<usize> {
|
||||
let tag = want.trim().split(['.', '@']).next().unwrap_or("").replace('_', "-");
|
||||
let base = tag.split('-').next().unwrap_or("");
|
||||
let raw_base = tag.split('-').next().unwrap_or("");
|
||||
// Map the obsolete ISO 639-1 tag `iw` (still emitted by older Java/Android locales) to `he`.
|
||||
let base = if raw_base.eq_ignore_ascii_case("iw") { "he" } else { raw_base };
|
||||
let has = |subtags: &[&str]| tag.split('-').skip(1).any(|t| subtags.iter().any(|s| s.eq_ignore_ascii_case(t)));
|
||||
let zh = |code: &str| {
|
||||
LANGS.iter().position(|l| l.code.eq_ignore_ascii_case(code)).filter(|i| LANGS.get(*i).is_some_and(|l| crate::cjk::can_show(l.code)))
|
||||
|
||||
@@ -584,11 +584,51 @@ fn right_to_left_languages_mirror_the_window() {
|
||||
for code in ["en", "", "es-419", "zh-Hans", "tr", "ru", "arn", "hey"] {
|
||||
assert!(!writes_right_to_left(code), "{code}");
|
||||
}
|
||||
// Every catalog that mirrors is one of them, and the Arabic one does.
|
||||
// Every catalog that mirrors is one of them, and the Arabic and Hebrew ones do.
|
||||
assert!(LANGS.iter().any(|l| l.code == "ar" && writes_right_to_left(l.code)));
|
||||
assert!(LANGS.iter().any(|l| l.code == "he" && writes_right_to_left(l.code)));
|
||||
assert!(!writes_right_to_left(LANGS[0].code), "English reads left to right");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hebrew_tags_and_plurals() {
|
||||
let he = LANGS.iter().position(|l| l.code == "he").expect("locales/he.toml is baked in");
|
||||
assert_eq!(LANGS[he].name, "עברית");
|
||||
for tag in ["he", "he-IL", "he_IL.UTF-8", "iw", "iw-IL", "iw_IL.UTF-8"] {
|
||||
assert_eq!(resolve(tag, None), he, "{tag}");
|
||||
assert_eq!(resolve("system", Some(tag)), he, "{tag}");
|
||||
}
|
||||
assert!(!plural_one(he, 0) && plural_one(he, 1) && !plural_one(he, 2) && !plural_one(he, 5));
|
||||
let singular = fill(counted(he, "{n} layers", 1), &[("n", &1)]);
|
||||
let dual = fill(counted(he, "{n} layers", 2), &[("n", &2)]);
|
||||
assert_eq!(singular, "1 שכבה");
|
||||
assert_eq!(dual, "2 שכבות");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_built_in_hebrew_face_draws_the_hebrew_catalog() {
|
||||
if !figcraft_text::CRAFT_FONTS.iter().any(|f| f.family == "Noto Sans Hebrew" && f.style == "Regular") {
|
||||
eprintln!("built without craft-fonts' Noto Sans Hebrew; skipping");
|
||||
return;
|
||||
}
|
||||
let Some(face) = figcraft_text::face_with_char('א', &["Noto Sans Hebrew"]) else {
|
||||
panic!("the supplied Noto Sans Hebrew face must draw Hebrew");
|
||||
};
|
||||
let he = &LANGS[LANGS.iter().position(|l| l.code == "he").unwrap()];
|
||||
let letters: BTreeSet<char> = he
|
||||
.ui
|
||||
.iter()
|
||||
.chain(he.commands)
|
||||
.chain(he.menu)
|
||||
.flat_map(|(_, t)| forms(t))
|
||||
.flat_map(str::chars)
|
||||
.filter(|c| matches!(u32::from(*c), 0x05D0..=0x05EA))
|
||||
.collect();
|
||||
assert!(letters.len() >= 27);
|
||||
let missing: String = letters.iter().filter(|c| !face.has_char(**c)).collect();
|
||||
assert!(missing.is_empty(), "Hebrew catalog glyphs missing from the embedded face: {missing:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_built_in_arabic_face_draws_the_arabic_catalog() {
|
||||
if !figcraft_text::CRAFT_FONTS.iter().any(|f| f.family == "Noto Sans Arabic" && f.style == "Regular") {
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
use egui::accesskit::{Node, Role};
|
||||
use figcraft_doc::{NodeId, NodeKind};
|
||||
use figcraft_engine::Session;
|
||||
use serde_json::json;
|
||||
|
||||
use crate::component_swap_default_tests::{centre, click, tree};
|
||||
use crate::layers_drag_tests::Ui;
|
||||
|
||||
fn id(v: serde_json::Value) -> NodeId {
|
||||
NodeId(v["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
fn combos(nodes: &[Node]) -> Vec<String> {
|
||||
nodes.iter().filter(|n| n.role() == Role::ComboBox).filter_map(|n| n.value().map(str::to_string)).collect()
|
||||
}
|
||||
|
||||
fn small_and_large_instances_selected(with_a_rectangle: bool) -> (Ui, Vec<(String, NodeId)>, Vec<NodeId>) {
|
||||
let mut s = Session::new();
|
||||
let mut variants = Vec::new();
|
||||
for (k, name) in ["Size=S, State=Default", "Size=L, State=Default", "Size=S, State=Hover", "Size=L, State=Hover"].iter().enumerate() {
|
||||
let f = id(s.execute("frame.create", &json!({"x": 0, "y": 20 + k * 44, "width": 80, "height": 30, "name": name})).unwrap());
|
||||
variants.push((name.to_string(), id(s.execute("component.create", &json!({"ids": [f]})).unwrap())));
|
||||
}
|
||||
s.execute("component.combineVariants", &json!({"ids": variants.iter().map(|v| v.1).collect::<Vec<_>>()})).unwrap();
|
||||
let small = id(s.execute("instance.create", &json!({"component": variants[0].1, "x": 300, "y": 20})).unwrap());
|
||||
let large = id(s.execute("instance.create", &json!({"component": variants[1].1, "x": 300, "y": 80})).unwrap());
|
||||
let mut selected = vec![small, large];
|
||||
if with_a_rectangle {
|
||||
selected.push(id(s.execute("shape.rectangle", &json!({"x": 500, "y": 20, "width": 20, "height": 20})).unwrap()));
|
||||
}
|
||||
s.execute("select.set", &json!({"ids": selected})).unwrap();
|
||||
let u = Ui::new(s);
|
||||
u.ctx.enable_accesskit();
|
||||
(u, variants, vec![small, large])
|
||||
}
|
||||
|
||||
fn main_of(u: &Ui, instance: NodeId) -> NodeId {
|
||||
match &u.app.session.doc().unwrap().node(instance).unwrap().kind {
|
||||
NodeKind::Instance { component, .. } => *component,
|
||||
_ => panic!("not an instance"),
|
||||
}
|
||||
}
|
||||
|
||||
fn pick(u: &mut Ui, shown: &str, value: &str) {
|
||||
let nodes = tree(u);
|
||||
let dropdown = nodes.iter().find(|n| n.role() == Role::ComboBox && n.value() == Some(shown)).unwrap_or_else(|| panic!("a {shown} dropdown"));
|
||||
click(u, centre(dropdown));
|
||||
let nodes = tree(u);
|
||||
let item = nodes
|
||||
.iter()
|
||||
.find(|n| n.label() == Some(value) && !matches!(n.role(), Role::ComboBox | Role::TextInput) && n.bounds().is_some())
|
||||
.unwrap_or_else(|| panic!("{value} in the menu"));
|
||||
click(u, centre(item));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_selected_instances_show_their_shared_variant_properties_and_set_them_together() {
|
||||
let (mut u, variants, instances) = small_and_large_instances_selected(false);
|
||||
let variant = |name: &str| variants.iter().find(|v| v.0 == name).unwrap().1;
|
||||
|
||||
let shown = combos(&tree(&mut u));
|
||||
assert!(shown.contains(&"Mixed".to_string()), "Size differs between them: {shown:?}");
|
||||
assert!(shown.contains(&"Default".to_string()), "State is the same: {shown:?}");
|
||||
|
||||
pick(&mut u, "Mixed", "L");
|
||||
assert_eq!(instances.iter().map(|i| main_of(&u, *i)).collect::<Vec<_>>(), [variant("Size=L, State=Default"); 2]);
|
||||
|
||||
pick(&mut u, "Default", "Hover");
|
||||
assert_eq!(instances.iter().map(|i| main_of(&u, *i)).collect::<Vec<_>>(), [variant("Size=L, State=Hover"); 2]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn instances_selected_with_a_plain_layer_show_no_instance_properties() {
|
||||
let (mut u, _, _) = small_and_large_instances_selected(true);
|
||||
let shown = combos(&tree(&mut u));
|
||||
assert!(!shown.iter().any(|v| v == "Mixed" || v == "Default"), "no property rows: {shown:?}");
|
||||
}
|
||||
@@ -134,6 +134,97 @@ fn setup() -> (Ui, NodeId, NodeId, NodeId) {
|
||||
(u, frame, child, rect)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vertical_auto_layout_layers_follow_the_canvas_before_and_after_a_drop() {
|
||||
let mut s = Session::new();
|
||||
let frame = id(s.execute("node.create", &json!({"type": "frame", "width": 180, "height": 160, "props": {"layout": "vertical"}})).unwrap());
|
||||
let rect = |s: &mut Session, name: &str| {
|
||||
id(s.execute("node.create", &json!({"type": "rectangle", "parent": frame, "width": 80, "height": 30, "name": name})).unwrap())
|
||||
};
|
||||
let first = rect(&mut s, "First");
|
||||
let second = rect(&mut s, "Second");
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let mut u = Ui::new(s);
|
||||
u.app.ui.expanded.insert(frame);
|
||||
let canvas_top = |u: &Ui, id: NodeId| u.app.session.doc().unwrap().world_bounds(id).unwrap().y0;
|
||||
assert!(canvas_top(&u, first) < canvas_top(&u, second));
|
||||
let (top, bottom) = (u.row_at(first), u.row_at(second));
|
||||
assert!(top.y < bottom.y, "the Layers panel follows the vertical flow");
|
||||
|
||||
let above_first = top - vec2(0.0, 4.0);
|
||||
u.drag_to(bottom, above_first);
|
||||
u.button(above_first, false);
|
||||
assert!(canvas_top(&u, second) < canvas_top(&u, first), "dropping above moves it up on the canvas");
|
||||
assert!(u.row_at(second).y < u.row_at(first).y, "the Layers order follows the drop");
|
||||
|
||||
u.app.run("select.set", json!({"ids": [second]}));
|
||||
u.ctx.enable_accesskit();
|
||||
u.frame(vec![]);
|
||||
let press = |u: &mut Ui, key| {
|
||||
u.frame(
|
||||
[true, false]
|
||||
.into_iter()
|
||||
.map(|pressed| Event::Key { key, physical_key: None, pressed, repeat: false, modifiers: Default::default() })
|
||||
.collect(),
|
||||
);
|
||||
};
|
||||
for _ in 0..4 {
|
||||
press(&mut u, egui::Key::F6);
|
||||
if u.app.ui.nav.region == crate::a11y::Region::Layers {
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert_eq!(u.app.ui.nav.region, crate::a11y::Region::Layers);
|
||||
press(&mut u, egui::Key::ArrowDown);
|
||||
u.frame(vec![]);
|
||||
assert_eq!(u.app.session.selection(), vec![first]);
|
||||
assert_eq!(crate::a11y::focused_name(&u.ctx), "First");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grouped_drop_between_vertical_and_stacked_rows_keeps_the_visible_order() {
|
||||
for source_vertical in [true, false] {
|
||||
let mut s = Session::new();
|
||||
let container = |s: &mut Session, x, vertical| {
|
||||
let props = if vertical { json!({"layout": "vertical"}) } else { json!({}) };
|
||||
id(s.execute("node.create", &json!({"type": "frame", "x": x, "width": 180, "height": 160, "props": props})).unwrap())
|
||||
};
|
||||
let source = container(&mut s, 0, source_vertical);
|
||||
let target = container(&mut s, 240, !source_vertical);
|
||||
let rect = |s: &mut Session, parent, name| {
|
||||
id(s.execute("node.create", &json!({"type": "rectangle", "parent": parent, "width": 80, "height": 30, "name": name})).unwrap())
|
||||
};
|
||||
let (a, b) = if source_vertical {
|
||||
(rect(&mut s, source, "A"), rect(&mut s, source, "B"))
|
||||
} else {
|
||||
let b = rect(&mut s, source, "B");
|
||||
(rect(&mut s, source, "A"), b)
|
||||
};
|
||||
let c = rect(&mut s, target, "C");
|
||||
s.execute("select.set", &json!({"ids": [b, a]})).unwrap();
|
||||
let mut u = Ui::new(s);
|
||||
u.app.ui.expanded.extend([source, target]);
|
||||
let top = u.row_at(a);
|
||||
assert!(top.y < u.row_at(b).y);
|
||||
let above_c = u.row_at(c) - vec2(0.0, 4.0);
|
||||
u.drag_to(top, above_c);
|
||||
u.button(above_c, false);
|
||||
|
||||
let (a_row, b_row, c_row) = (u.row_at(a), u.row_at(b), u.row_at(c));
|
||||
assert!(a_row.y < b_row.y && b_row.y < c_row.y, "A, B, C in the destination (source vertical: {source_vertical})");
|
||||
let doc = u.app.session.doc().unwrap();
|
||||
assert!(doc.node(source).unwrap().children.is_empty());
|
||||
let want = if source_vertical { vec![c, b, a] } else { vec![a, b, c] };
|
||||
assert_eq!(doc.node(target).unwrap().children, want);
|
||||
|
||||
u.app.run("edit.undo", json!({}));
|
||||
let doc = u.app.session.doc().unwrap();
|
||||
assert_eq!(doc.node(a).unwrap().parent, Some(source));
|
||||
assert_eq!(doc.node(b).unwrap().parent, Some(source));
|
||||
assert_eq!(doc.node(target).unwrap().children, vec![c]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn holding_over_a_collapsed_frame_opens_it_and_dropping_moves_the_layer_in() {
|
||||
let (mut u, frame, child, rect) = setup();
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Arrow keys in the layers panel once a row has been clicked: up/down through the rows (Shift
|
||||
//! extends), left/right to collapse, expand, and go to the parent or first child; a press on the
|
||||
//! canvas gives arrows back to nudging. Delete after a click in the Pages list deletes the page.
|
||||
//! Arrow keys in the layers panel once F6 has put the keyboard on its rows: up/down through the
|
||||
//! rows (Shift extends), left/right to collapse, expand, and go to the parent or first child. After
|
||||
//! a click on a row the arrows nudge the layer, as on the canvas. Delete after a click in the Pages
|
||||
//! list deletes the page.
|
||||
|
||||
use egui::{Event, Key, Modifiers, Pos2, pos2, vec2};
|
||||
use figcraft_doc::NodeId;
|
||||
@@ -46,10 +47,29 @@ fn click_row(u: &mut Ui, id: NodeId) {
|
||||
assert_eq!(sel(u), vec![id]);
|
||||
}
|
||||
|
||||
/// Presses F6 until the keyboard is on the layers panel, as a keyboard user gets there.
|
||||
fn keyboard_into_the_layers(u: &mut Ui) {
|
||||
for _ in 0..crate::a11y::Region::ALL.len() {
|
||||
key(u, Key::F6, false);
|
||||
u.frame(vec![]);
|
||||
if u.app.ui.nav.region == crate::a11y::Region::Layers {
|
||||
return;
|
||||
}
|
||||
}
|
||||
panic!("F6 never reached the layers panel");
|
||||
}
|
||||
|
||||
/// Selects `id` and moves the keyboard onto its row with F6.
|
||||
fn keyboard_to_the_row(u: &mut Ui, id: NodeId) {
|
||||
u.app.run("select.set", json!({"ids": [id]}));
|
||||
u.frame(vec![]);
|
||||
keyboard_into_the_layers(u);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn up_and_down_walk_the_rows_and_shift_extends() {
|
||||
let (mut u, a, frame, _, c) = setup();
|
||||
click_row(&mut u, c);
|
||||
keyboard_to_the_row(&mut u, c);
|
||||
key(&mut u, Key::ArrowDown, false);
|
||||
assert_eq!(sel(&u), vec![frame]);
|
||||
key(&mut u, Key::ArrowDown, false);
|
||||
@@ -103,6 +123,7 @@ fn a_keyboard_shift_range_keeps_an_anchor_covered_by_a_selected_frame() {
|
||||
let mut want = vec![rect4, frame1];
|
||||
want.sort();
|
||||
assert_eq!(got, want, "the pointer range keeps the frame");
|
||||
keyboard_into_the_layers(&mut u);
|
||||
// Rows: Frame 2, Rect 4, Frame 1, Rect 3, Rect 2. Shift+Down runs from Rect 2 (the anchor).
|
||||
key(&mut u, Key::ArrowDown, true);
|
||||
let mut got = sel(&u);
|
||||
@@ -115,7 +136,7 @@ fn a_keyboard_shift_range_keeps_an_anchor_covered_by_a_selected_frame() {
|
||||
#[test]
|
||||
fn left_and_right_open_close_and_move_between_levels() {
|
||||
let (mut u, _, frame, child, _) = setup();
|
||||
click_row(&mut u, frame);
|
||||
keyboard_to_the_row(&mut u, frame);
|
||||
key(&mut u, Key::ArrowRight, false);
|
||||
assert!(u.app.ui.expanded.contains(&frame), "Right opens a closed row");
|
||||
assert_eq!(sel(&u), vec![frame]);
|
||||
@@ -129,21 +150,38 @@ fn left_and_right_open_close_and_move_between_levels() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_canvas_press_gives_arrows_back_to_nudging() {
|
||||
fn a_clicked_row_leaves_the_arrows_to_the_canvas() {
|
||||
let (mut u, _, _, _, c) = setup();
|
||||
click_row(&mut u, c);
|
||||
assert!(u.app.ui.layers_focus);
|
||||
// Press on empty canvas (deselects), then select c from the canvas side and nudge it.
|
||||
let p = pos2(900.0, 700.0);
|
||||
u.button(p, true);
|
||||
u.button(p, false);
|
||||
assert!(!u.app.ui.layers_focus);
|
||||
u.app.run("select.set", json!({"ids": [c]}));
|
||||
key(&mut u, Key::ArrowRight, false);
|
||||
assert_eq!(sel(&u), vec![c]);
|
||||
let doc = u.app.session.doc().unwrap();
|
||||
assert_eq!(doc.node(c).unwrap().transform.translation().x, 201.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn down_on_a_clicked_row_moves_it_one_place_in_a_vertical_auto_layout() {
|
||||
let mut s = Session::new();
|
||||
let column = id(s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 100, "height": 200, "name": "Column"})).unwrap());
|
||||
let rows: Vec<NodeId> = (0..3)
|
||||
.map(|i| id(s.execute("shape.rectangle", &json!({"x": 0, "y": i * 30, "width": 80, "height": 20, "parent": column})).unwrap()))
|
||||
.collect();
|
||||
s.execute("layout.add", &json!({"ids": [column], "direction": "vertical"})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let mut u = Ui::new(s);
|
||||
u.app.ui.expanded.insert(column);
|
||||
u.frame(vec![]);
|
||||
click_row(&mut u, rows[1]);
|
||||
key(&mut u, Key::ArrowDown, false);
|
||||
let order = u.app.session.doc().unwrap().node(column).unwrap().children.clone();
|
||||
assert_eq!(order, [rows[0], rows[2], rows[1]]);
|
||||
assert_eq!(sel(&u), vec![rows[1]]);
|
||||
key(&mut u, Key::ArrowUp, false);
|
||||
key(&mut u, Key::ArrowUp, false);
|
||||
let order = u.app.session.doc().unwrap().node(column).unwrap().children.clone();
|
||||
assert_eq!(order, [rows[1], rows[0], rows[2]]);
|
||||
}
|
||||
|
||||
/// The middle of `page`'s row in the Pages list, found by clicking down the list until it opens;
|
||||
/// then back to `back`.
|
||||
fn page_row(u: &mut Ui, page: NodeId, back: NodeId) -> Pos2 {
|
||||
|
||||
@@ -157,6 +157,8 @@ mod import_report_tests;
|
||||
#[cfg(test)]
|
||||
mod inspect_fields_tests;
|
||||
#[cfg(test)]
|
||||
mod instances_shared_props_tests;
|
||||
#[cfg(test)]
|
||||
mod layers_behaviour_tests;
|
||||
#[cfg(test)]
|
||||
mod layers_component_rows_tests;
|
||||
@@ -203,6 +205,8 @@ mod menu_input_tests;
|
||||
#[cfg(test)]
|
||||
mod menu_overflow_tests;
|
||||
#[cfg(test)]
|
||||
mod menu_scroll_tests;
|
||||
#[cfg(test)]
|
||||
mod mirror_tests;
|
||||
#[cfg(test)]
|
||||
mod missing_fonts_tests;
|
||||
@@ -232,6 +236,8 @@ mod pen_mode_tests;
|
||||
#[cfg(test)]
|
||||
mod perf_tests;
|
||||
#[cfg(test)]
|
||||
mod pixel_grid_tests;
|
||||
#[cfg(test)]
|
||||
mod plugin_panel_tests;
|
||||
#[cfg(test)]
|
||||
mod plugin_save_ui_tests;
|
||||
@@ -293,6 +299,8 @@ mod text_link_tests;
|
||||
#[cfg(test)]
|
||||
mod text_mixed_fill_tests;
|
||||
#[cfg(test)]
|
||||
mod text_paste_style_tests;
|
||||
#[cfg(test)]
|
||||
mod tidy_tests;
|
||||
#[cfg(test)]
|
||||
mod titlebar_tests;
|
||||
@@ -307,6 +315,8 @@ mod variable_picker_tests;
|
||||
#[cfg(test)]
|
||||
mod variables_export_ui_tests;
|
||||
#[cfg(test)]
|
||||
mod variables_group_create_tests;
|
||||
#[cfg(test)]
|
||||
mod variables_rename_tests;
|
||||
#[cfg(test)]
|
||||
mod variables_select_tests;
|
||||
@@ -560,8 +570,9 @@ pub struct UiState {
|
||||
pub layer_search: bool,
|
||||
pub layer_filter: String,
|
||||
pub layer_anchor: Option<NodeId>,
|
||||
/// The layers panel has the keyboard: arrow keys move through its rows instead of nudging
|
||||
/// (set by a click on a row, cleared by a press on the canvas).
|
||||
/// A layer row was clicked last: Shift+F10 opens the context menu at its row (set by a click on
|
||||
/// a row, cleared by a press on the canvas). Arrow keys still nudge; they move through the rows
|
||||
/// only once F6 has put the keyboard on the layers panel.
|
||||
pub layers_focus: bool,
|
||||
/// The file (its `uid`) whose pages list has the keyboard: Delete with no layers selected deletes
|
||||
/// its current page (set by a click on a page row or the add-page button, cleared by a click on a
|
||||
@@ -638,6 +649,9 @@ pub struct UiState {
|
||||
/// copy changes the engine clipboard without writing the OS clipboard; the generation then
|
||||
/// no longer matches, so the stale mirror is not mistaken for the user's own copy.
|
||||
pub last_copy_generation: u64,
|
||||
/// The formatting of the characters last copied as text: a paste into a text edit of those
|
||||
/// same characters keeps it.
|
||||
pub text_copy: Option<figcraft_engine::textedit::RichText>,
|
||||
/// The fill, stroke or effect row highlighted in the Design panel: Cmd/Ctrl+C copies it.
|
||||
pub property_row: Option<property_rows::Highlight>,
|
||||
/// A paint or effect copied from its row: Cmd/Ctrl+V pastes it while it's the last copy.
|
||||
@@ -786,6 +800,7 @@ impl Default for UiState {
|
||||
|
||||
last_copy: None,
|
||||
last_copy_generation: 0,
|
||||
text_copy: None,
|
||||
property_row: None,
|
||||
property_copy: None,
|
||||
after_field: None,
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
//! A panel menu taller than the window scrolls, so its last rows can be reached and picked: the
|
||||
//! page's variable mode menu of a collection with more modes than fit.
|
||||
|
||||
use egui::{Event, Modifiers, MouseWheelUnit, PointerButton, Pos2, TouchPhase, vec2};
|
||||
use figcraft_engine::Session;
|
||||
use serde_json::json;
|
||||
|
||||
use crate::layers_drag_tests::Ui;
|
||||
use crate::live_tests::{flat, text_center, texts};
|
||||
|
||||
/// A click at `p`, and the frames that follow; what the last frame drew.
|
||||
fn click(u: &mut Ui, p: Pos2) -> Vec<egui::Shape> {
|
||||
for _ in 0..5 {
|
||||
u.frame(vec![Event::PointerMoved(p)]);
|
||||
}
|
||||
let mut shapes = Vec::new();
|
||||
for pressed in [Some(true), Some(false)].into_iter().chain(std::iter::repeat_n(None, 20)) {
|
||||
let events = pressed.map(|pressed| Event::PointerButton { pos: p, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE });
|
||||
shapes = flat(&u.frame_output(events.into_iter().collect()).shapes);
|
||||
}
|
||||
shapes
|
||||
}
|
||||
|
||||
/// Where `label` is drawn, if it is.
|
||||
fn at(shapes: &[egui::Shape], label: &str) -> Option<Pos2> {
|
||||
texts(shapes).into_iter().find(|(t, ..)| t == label).map(|(_, p, size)| p + size / 2.0)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_menu_taller_than_the_window_scrolls_to_its_last_row() {
|
||||
let modes: Vec<String> = (0..60).map(|k| format!("Mode {k}")).collect();
|
||||
let mut s = Session::new();
|
||||
s.execute("variable.createCollection", &json!({"name": "Theme", "modes": modes})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": []})).unwrap();
|
||||
let mut u = Ui::new(s);
|
||||
let shapes = flat(&u.frame_output(vec![]).shapes);
|
||||
let menu = click(&mut u, text_center(&shapes, "Auto (Mode 0)"));
|
||||
let first = at(&menu, " Mode 0").expect("the menu is open");
|
||||
assert!(at(&menu, " Mode 59").is_none_or(|p| p.y > 900.0), "the last row starts below the window");
|
||||
let wheel = Event::MouseWheel {
|
||||
unit: MouseWheelUnit::Point,
|
||||
source: egui::MouseWheelSource::Unknown,
|
||||
delta: vec2(0.0, -5000.0),
|
||||
phase: TouchPhase::Move,
|
||||
modifiers: Modifiers::NONE,
|
||||
};
|
||||
u.frame(vec![Event::PointerMoved(first), wheel]);
|
||||
for _ in 0..30 {
|
||||
u.frame(vec![]);
|
||||
}
|
||||
let shapes = flat(&u.frame_output(vec![]).shapes);
|
||||
let last = at(&shapes, " Mode 59").expect("scrolled to the last row");
|
||||
assert!(last.y < 900.0, "inside the window: {last:?}");
|
||||
click(&mut u, last);
|
||||
let page = u.app.session.page().unwrap();
|
||||
let doc = u.app.session.doc().unwrap();
|
||||
let coll = &doc.variables.collections[0];
|
||||
let picked = coll.modes.iter().find(|m| m.name == "Mode 59").unwrap().id.clone();
|
||||
assert_eq!(doc.node(page).unwrap().var_modes.get(&coll.id), Some(&picked), "the last mode is picked");
|
||||
}
|
||||
|
||||
/// The page's variable mode menu of a collection with `n` modes, opened; what it drew.
|
||||
fn mode_menu(n: usize) -> (Ui, Vec<egui::Shape>) {
|
||||
let modes: Vec<String> = (0..n).map(|k| format!("Mode {k}")).collect();
|
||||
let mut s = Session::new();
|
||||
s.execute("variable.createCollection", &json!({"name": "Theme", "modes": modes})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": []})).unwrap();
|
||||
let mut u = Ui::new(s);
|
||||
let shapes = flat(&u.frame_output(vec![]).shapes);
|
||||
let menu = click(&mut u, text_center(&shapes, "Auto (Mode 0)"));
|
||||
(u, menu)
|
||||
}
|
||||
|
||||
/// A press and release of `key`, and a frame after it.
|
||||
fn key(u: &mut Ui, key: egui::Key) {
|
||||
for pressed in [true, false] {
|
||||
u.frame(vec![Event::Key { key, physical_key: None, pressed, repeat: false, modifiers: Modifiers::NONE }]);
|
||||
}
|
||||
u.frame(vec![]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_click_on_the_scroll_bar_track_keeps_the_menu_open() {
|
||||
let (mut u, menu) = mode_menu(60);
|
||||
let first = at(&menu, " Mode 0").expect("the menu is open");
|
||||
u.ctx.enable_accesskit();
|
||||
let out = u.frame_output(vec![Event::PointerMoved(first)]);
|
||||
let nodes = out.platform_output.accesskit_update.expect("an AccessKit update").nodes;
|
||||
let bar = nodes
|
||||
.iter()
|
||||
.filter(|(_, n)| n.role() == egui::accesskit::Role::ScrollBar)
|
||||
.filter_map(|(_, n)| n.bounds())
|
||||
.find(|b| b.x0 as f32 > first.x && (b.y0..b.y1).contains(&f64::from(first.y)))
|
||||
.expect("the menu's scroll bar");
|
||||
let shapes = click(&mut u, Pos2::new(((bar.x0 + bar.x1) / 2.0) as f32, (bar.y1 - 10.0) as f32));
|
||||
assert!(texts(&shapes).iter().any(|(t, ..)| t.starts_with(" Mode ")), "the menu is still open");
|
||||
assert!(at(&shapes, " Mode 0").is_none_or(|p| p.y < first.y), "the click on the track scrolled the rows");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_keyboard_stays_on_its_row_when_the_window_shrinks_until_the_menu_scrolls_and_grows_back() {
|
||||
let (mut u, _) = mode_menu(25);
|
||||
for _ in 0..3 {
|
||||
key(&mut u, egui::Key::ArrowDown);
|
||||
}
|
||||
let row = u.ctx.memory(|m| m.focused()).expect("a row has the keyboard");
|
||||
for height in [400.0, 900.0] {
|
||||
u.screen = vec2(1440.0, height);
|
||||
for _ in 0..10 {
|
||||
u.frame(vec![]);
|
||||
}
|
||||
assert_eq!(u.ctx.memory(|m| m.focused()), Some(row), "the same row has the keyboard at a window {height} pt tall");
|
||||
}
|
||||
}
|
||||
@@ -209,6 +209,7 @@ pub fn invoke(app: &mut FigApp, id: &str) {
|
||||
.ok()
|
||||
.and_then(|d| d.vector_edit.as_ref())
|
||||
.is_some_and(|ve| ve.parts().iter().any(|p| !p.vertices.is_empty() || !p.segments.is_empty()));
|
||||
let rich = doc.filter(|_| !partial).and_then(|d| figcraft_engine::textedit::layers_rich_text(d, &ids));
|
||||
let mirror = doc.filter(|_| !partial).and_then(|d| text_layers_text(d, &ids).or_else(|| figcraft_svg_export(d, &ids)));
|
||||
let ran = app.run(id, json!({}));
|
||||
// A partial copy put temporary layers on the engine clipboard; mirror their SVG.
|
||||
@@ -223,6 +224,7 @@ pub fn invoke(app: &mut FigApp, id: &str) {
|
||||
app.clipboard_set_text(&text);
|
||||
app.ui.last_copy = Some(text);
|
||||
app.ui.last_copy_generation = app.session.clipboard.layers_generation;
|
||||
app.ui.text_copy = rich;
|
||||
}
|
||||
}
|
||||
"edit.paste" => paste(app, None, None),
|
||||
|
||||
@@ -37,9 +37,9 @@ const MAX_THUMBS: usize = 600;
|
||||
const THUMBS_PER_FRAME: usize = 8;
|
||||
/// Layers compared per component when checking whether its thumbnail is stale.
|
||||
const MAX_COMPARED: usize = 20_000;
|
||||
/// Look for changed library files this often (seconds) while the panel shows.
|
||||
/// Look for changed library files this often (seconds).
|
||||
const LIBRARY_REFRESH: f64 = 2.0;
|
||||
/// Ask team libraries' servers for newer versions this often (seconds) while the panel shows.
|
||||
/// Ask team libraries' servers for newer versions this often (seconds).
|
||||
// shortcut: polled (a few bytes when nothing changed); a server push needs a connection per
|
||||
// library, worth it once libraries are used beyond the Assets panel.
|
||||
const SERVER_REFRESH: f64 = 30.0;
|
||||
@@ -278,33 +278,42 @@ fn build_listing(app: &FigApp, doc: &Document, q: &str, key: (u64, String, u64))
|
||||
Listing { key, local: foldered("", local), local_styles, libraries, updates }
|
||||
}
|
||||
|
||||
/// Re-read enabled library files that changed on disk (throttled).
|
||||
fn refresh_libraries(app: &mut FigApp, ui: &Ui) {
|
||||
/// Re-read enabled library files that changed on disk (throttled), every logic tick whether or not
|
||||
/// the Assets panel shows, so the style pickers list library styles too. A library this file
|
||||
/// hasn't tried to read yet (just opened or added) is read at once.
|
||||
pub(crate) fn refresh_libraries(app: &mut FigApp, ctx: &egui::Context) {
|
||||
let Ok(doc) = app.session.doc() else { return };
|
||||
if doc.libraries.enabled.is_empty() {
|
||||
return;
|
||||
}
|
||||
let paths: Vec<String> = doc.libraries.enabled.iter().map(|l| l.path.clone()).collect();
|
||||
let id = Id::unique("asset_libraries_checked");
|
||||
let now = ui.input(|i| i.time);
|
||||
let last: Option<f64> = ui.data(|d| d.get_temp(id));
|
||||
if last.is_none_or(|l| now - l >= LIBRARY_REFRESH) {
|
||||
// The paths the last read tried: one that was refused (too large, not on this computer) is
|
||||
// never cached, and would otherwise be tried again every frame.
|
||||
let tried_id = Id::unique("asset_libraries_tried");
|
||||
let now = ctx.input(|i| i.time);
|
||||
let last: Option<f64> = ctx.data(|d| d.get_temp(id));
|
||||
let tried: Vec<String> = ctx.data(|d| d.get_temp(tried_id)).unwrap_or_default();
|
||||
let unread_here = paths.iter().any(|p| !is_server_link(p) && app.session.libraries.cached(p).is_none() && !tried.contains(p));
|
||||
if unread_here || last.is_none_or(|l| now - l >= LIBRARY_REFRESH) {
|
||||
for p in &paths {
|
||||
let _ = app.session.libraries.load(p);
|
||||
}
|
||||
ui.data_mut(|d| d.insert_temp(id, now));
|
||||
ctx.data_mut(|d| {
|
||||
d.insert_temp(id, now);
|
||||
d.insert_temp(tried_id, paths.clone());
|
||||
});
|
||||
// Team libraries: in the background, at once for one not fetched yet.
|
||||
let sid = Id::unique("asset_server_libraries_checked");
|
||||
let fetched: Option<f64> = ui.data(|d| d.get_temp(sid));
|
||||
let fetched: Option<f64> = ctx.data(|d| d.get_temp(sid));
|
||||
// Only the ones you added or checked: a file can't make the app contact a server (#1097).
|
||||
let team: Vec<&String> = paths.iter().filter(|p| is_server_link(p) && app.session.library_allowed(p)).collect();
|
||||
let unread = team.iter().any(|p| app.session.libraries.cached(p).is_none());
|
||||
if !team.is_empty() && (unread || fetched.is_none_or(|l| now - l >= SERVER_REFRESH)) {
|
||||
app.session.refresh_server_libraries();
|
||||
ui.data_mut(|d| d.insert_temp(sid, now));
|
||||
ctx.data_mut(|d| d.insert_temp(sid, now));
|
||||
}
|
||||
}
|
||||
ui.ctx().request_repaint_after(std::time::Duration::from_secs_f64(LIBRARY_REFRESH));
|
||||
}
|
||||
|
||||
/// The search field with the libraries button; returns the lowercase query.
|
||||
@@ -577,12 +586,15 @@ fn render_thumbs(ui: &Ui, w: f32, thumbs: &mut Thumbs, wanted: &[(Source, NodeId
|
||||
}
|
||||
}
|
||||
|
||||
/// Draw the Assets panel: refresh libraries, switch to the libraries view when asked,
|
||||
/// otherwise cache a listing keyed by revision, query and library state, render local and
|
||||
/// Draw the Assets panel: repaint every `LIBRARY_REFRESH` while the file has libraries (so a
|
||||
/// library changed on disk shows; the app's tick reads it), switch to the libraries view when
|
||||
/// asked, otherwise cache a listing keyed by revision, query and library state, render local and
|
||||
/// enabled-library assets with reused thumbnails, and dispatch place, style, hide, toggle
|
||||
/// and drag actions.
|
||||
pub fn show(app: &mut FigApp, ui: &mut Ui) {
|
||||
refresh_libraries(app, ui);
|
||||
if app.session.doc().is_ok_and(|d| !d.libraries.enabled.is_empty()) {
|
||||
ui.ctx().request_repaint_after(std::time::Duration::from_secs_f64(LIBRARY_REFRESH));
|
||||
}
|
||||
if app.ui.libraries {
|
||||
libraries_view(app, ui);
|
||||
return;
|
||||
|
||||
@@ -31,6 +31,7 @@ use crate::widgets;
|
||||
pub fn instance_section(app: &mut FigApp, ui: &mut Ui, doc: &Document, sel: &[NodeId]) {
|
||||
let [id] = sel else {
|
||||
combine_ui(app, ui, doc, sel);
|
||||
instances_ui(app, ui, doc, sel);
|
||||
return;
|
||||
};
|
||||
let Some(n) = doc.node(*id) else { return };
|
||||
@@ -712,7 +713,7 @@ fn instance_ui(app: &mut FigApp, ui: &mut Ui, doc: &Document, n: &Node) {
|
||||
}
|
||||
});
|
||||
}
|
||||
instance_props(app, ui, doc, n, &comps);
|
||||
instance_props(app, ui, doc, &[n.id], &comps);
|
||||
// Exposed nested instances: their properties, under their names.
|
||||
if !nested {
|
||||
for c in figcraft_engine::components::exposed_copies(doc, id) {
|
||||
@@ -722,7 +723,7 @@ fn instance_ui(app: &mut FigApp, ui: &mut Ui, doc: &Document, n: &Node) {
|
||||
icons::paint(ui.painter(), r, Icon::Instance, crate::theme::COMPONENT);
|
||||
ui.label(egui::RichText::new(&cn.name).font(semibold(11.0)).color(t.text));
|
||||
});
|
||||
instance_props(app, ui, doc, cn, &comps);
|
||||
instance_props(app, ui, doc, &[cn.id], &comps);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -732,38 +733,120 @@ fn nested_in_main(doc: &Document, id: NodeId) -> bool {
|
||||
!inside_instance(doc, id) && figcraft_engine::components::owning_component(doc, id).is_some_and(|c| c != id)
|
||||
}
|
||||
|
||||
/// Variant and component property controls for instance `n`.
|
||||
fn instance_props(app: &mut FigApp, ui: &mut Ui, doc: &Document, n: &Node, comps: &[(NodeId, String)]) {
|
||||
let NodeKind::Instance { component, props } = &n.kind else { return };
|
||||
let id = n.id;
|
||||
let set = variant_set(doc, *component);
|
||||
let slots = slots_of(doc, id);
|
||||
/// The Instance section for a selection of two or more instances: the properties they share. A
|
||||
/// selection with any other layer shows nothing.
|
||||
fn instances_ui(app: &mut FigApp, ui: &mut Ui, doc: &Document, sel: &[NodeId]) {
|
||||
if sel.len() < 2 || !sel.iter().all(|id| matches!(doc.node(*id).map(|n| &n.kind), Some(NodeKind::Instance { .. }))) {
|
||||
return;
|
||||
}
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let comps = local_components(app, ui, doc);
|
||||
widgets::separator(ui);
|
||||
row(ui, 36.0, |ui| {
|
||||
ui.label(egui::RichText::new(tr("Instance")).font(semibold(11.0)).color(t.text));
|
||||
});
|
||||
instance_props(app, ui, doc, sel, &comps);
|
||||
}
|
||||
|
||||
/// A variant property the selected instances share: the values every one of their sets has, and
|
||||
/// the current value, None when it differs between them (Mixed).
|
||||
struct SharedVariantProp {
|
||||
name: String,
|
||||
values: Vec<String>,
|
||||
current: Option<String>,
|
||||
}
|
||||
|
||||
/// A boolean, text, instance-swap or slot property the selected instances share, by name and type:
|
||||
/// its definition (the first instance's) and the value, None when it differs between them (Mixed).
|
||||
struct SharedProp {
|
||||
name: String,
|
||||
def: PropDef,
|
||||
value: Option<Value>,
|
||||
}
|
||||
|
||||
/// The variant and other properties of instance `id` with its own values (a property it doesn't
|
||||
/// set has its default). None when `id` isn't an instance.
|
||||
fn own_props(doc: &Document, id: NodeId) -> Option<(Vec<SharedVariantProp>, Vec<SharedProp>)> {
|
||||
let Some(NodeKind::Instance { component, props }) = doc.node(id).map(|n| &n.kind) else { return None };
|
||||
let current = doc.node(*component).map(|c| variant_props(&c.name)).unwrap_or_default();
|
||||
let variants = variant_set(doc, *component)
|
||||
.map(|set| variant_options(doc, set))
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.map(|(name, values)| SharedVariantProp { current: Some(current.get(&name).cloned().unwrap_or_default()), name, values })
|
||||
.collect();
|
||||
let others = instance_prop_list(doc, *component)
|
||||
.into_iter()
|
||||
.map(|(name, def)| {
|
||||
let value = props.get(&name).cloned().unwrap_or_else(|| figcraft_engine::components::prop_default_value(&def));
|
||||
SharedProp { name, def, value: Some(value) }
|
||||
})
|
||||
.collect();
|
||||
Some((variants, others))
|
||||
}
|
||||
|
||||
/// The properties every instance in `ids` has, in the first one's order, with the values they share;
|
||||
/// nothing when any of `ids` isn't an instance.
|
||||
fn shared_props(doc: &Document, ids: &[NodeId]) -> (Vec<SharedVariantProp>, Vec<SharedProp>) {
|
||||
let Some((first, rest)) = ids.split_first() else { return Default::default() };
|
||||
let Some((mut variants, mut others)) = own_props(doc, *first) else { return Default::default() };
|
||||
for id in rest {
|
||||
let Some((own_variants, own_others)) = own_props(doc, *id) else { return Default::default() };
|
||||
variants.retain_mut(|shared| {
|
||||
let Some(own) = own_variants.iter().find(|o| o.name == shared.name) else { return false };
|
||||
shared.values.retain(|v| own.values.contains(v));
|
||||
if shared.current != own.current {
|
||||
shared.current = None;
|
||||
}
|
||||
true
|
||||
});
|
||||
others.retain_mut(|shared| {
|
||||
let Some(own) =
|
||||
own_others.iter().find(|o| o.name == shared.name && std::mem::discriminant(&o.def) == std::mem::discriminant(&shared.def))
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
if shared.value != own.value {
|
||||
shared.value = None;
|
||||
}
|
||||
true
|
||||
});
|
||||
}
|
||||
(variants, others)
|
||||
}
|
||||
|
||||
/// Variant and component property controls for instances `ids`: the properties they share, set on
|
||||
/// all of them at once. Slots show only for a single instance.
|
||||
fn instance_props(app: &mut FigApp, ui: &mut Ui, doc: &Document, ids: &[NodeId], comps: &[(NodeId, String)]) {
|
||||
let (variants, others) = shared_props(doc, ids);
|
||||
let slots = match ids {
|
||||
[id] => slots_of(doc, *id),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
// Variant properties.
|
||||
if let Some(set) = set {
|
||||
let current = doc.node(*component).map(|c| variant_props(&c.name)).unwrap_or_default();
|
||||
for (k, vals) in variant_options(doc, set) {
|
||||
let cur = current.get(&k).cloned().unwrap_or_default();
|
||||
row(ui, 32.0, |ui| {
|
||||
prop_label(ui, &k, Icon::ComponentSet);
|
||||
let w = ui.available_width().max(60.0);
|
||||
// A string variable naming one of the values can choose it.
|
||||
crate::variable_ui::bindable(app, ui, &[id], &format!("{PROP_BINDING}{k}"), VariableType::String, w, |app, ui| {
|
||||
let resp = widgets::dropdown(ui, &cur, w, None);
|
||||
menu_popup(&resp).show(|ui| {
|
||||
for v in &vals {
|
||||
if menu_item(ui, v, "") {
|
||||
app.run("instance.setProperties", json!({"ids": [id], "properties": {k.clone(): v}}));
|
||||
ui.close();
|
||||
}
|
||||
for SharedVariantProp { name: k, values: vals, current } in variants {
|
||||
row(ui, 32.0, |ui| {
|
||||
prop_label(ui, &k, Icon::ComponentSet);
|
||||
let w = ui.available_width().max(60.0);
|
||||
// A string variable naming one of the values can choose it.
|
||||
crate::variable_ui::bindable(app, ui, ids, &format!("{PROP_BINDING}{k}"), VariableType::String, w, |app, ui| {
|
||||
let resp = widgets::dropdown(ui, current.as_deref().unwrap_or(tr("Mixed")), w, None);
|
||||
menu_popup(&resp).show(|ui| {
|
||||
for v in &vals {
|
||||
if menu_item(ui, v, "") {
|
||||
app.run("instance.setProperties", json!({"ids": ids, "properties": {k.clone(): v}}));
|
||||
ui.close();
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
// Boolean, text and instance-swap properties.
|
||||
for (k, d) in instance_prop_list(doc, *component) {
|
||||
let v = props.get(&k).cloned().unwrap_or_else(|| figcraft_engine::components::prop_default_value(&d));
|
||||
for SharedProp { name: k, def: d, value } in others {
|
||||
if matches!(d, PropDef::Slot { .. }) && !slots.iter().any(|(_, name)| *name == k) {
|
||||
continue;
|
||||
}
|
||||
row(ui, 32.0, |ui| {
|
||||
prop_label(ui, &k, type_icon(&d));
|
||||
let w = ui.available_width().max(60.0);
|
||||
@@ -771,26 +854,28 @@ fn instance_props(app: &mut FigApp, ui: &mut Ui, doc: &Document, n: &Node, comps
|
||||
let bind_field = format!("{PROP_BINDING}{k}");
|
||||
match d {
|
||||
PropDef::Boolean { .. } => {
|
||||
crate::variable_ui::bindable(app, ui, &[id], &bind_field, VariableType::Boolean, w, |app, ui| {
|
||||
let on = v.as_bool().unwrap_or(false);
|
||||
if widgets::checkbox(ui, on, "") {
|
||||
app.run("instance.setProperties", json!({"ids": [id], "properties": {k.clone(): !on}}));
|
||||
crate::variable_ui::bindable(app, ui, ids, &bind_field, VariableType::Boolean, w, |app, ui| {
|
||||
let state = value.as_ref().map(|v| v.as_bool().unwrap_or(false));
|
||||
if widgets::checkbox_tri(ui, state, "") {
|
||||
app.run("instance.setProperties", json!({"ids": ids, "properties": {k.clone(): !state.unwrap_or(false)}}));
|
||||
}
|
||||
});
|
||||
}
|
||||
PropDef::Text { .. } => {
|
||||
crate::variable_ui::bindable(app, ui, &[id], &bind_field, VariableType::String, w, |app, ui| {
|
||||
let cur = v.as_str().unwrap_or_default().to_string();
|
||||
if let Some(ns) = widgets::text_field(ui, Id::unique(("iprop", id, k.as_str())), &cur, w, "")
|
||||
crate::variable_ui::bindable(app, ui, ids, &bind_field, VariableType::String, w, |app, ui| {
|
||||
let cur = value.as_ref().and_then(Value::as_str).unwrap_or_default().to_string();
|
||||
let placeholder = if value.is_some() { "" } else { tr("Mixed") };
|
||||
if let Some(ns) = widgets::text_field(ui, Id::unique(("iprop", ids, k.as_str())), &cur, w, placeholder)
|
||||
&& ns != cur
|
||||
{
|
||||
app.run("instance.setProperties", json!({"ids": [id], "properties": {k.clone(): ns}}));
|
||||
app.run("instance.setProperties", json!({"ids": ids, "properties": {k.clone(): ns}}));
|
||||
}
|
||||
});
|
||||
}
|
||||
PropDef::InstanceSwap { preferred, .. } => {
|
||||
if let Some(c) = swap_dropdown(ui, doc, figcraft_engine::params::id_of(&v), &preferred, comps, w, &k).1 {
|
||||
app.run("instance.setProperties", json!({"ids": [id], "properties": {k.clone(): c.0}}));
|
||||
let cur = value.as_ref().and_then(figcraft_engine::params::id_of);
|
||||
if let Some(c) = swap_dropdown(ui, doc, cur, value.is_none(), &preferred, comps, w, &k).1 {
|
||||
app.run("instance.setProperties", json!({"ids": ids, "properties": {k.clone(): c.0}}));
|
||||
}
|
||||
}
|
||||
PropDef::Variant { .. } => {}
|
||||
@@ -806,18 +891,24 @@ fn instance_props(app: &mut FigApp, ui: &mut Ui, doc: &Document, n: &Node, comps
|
||||
|
||||
/// The dropdown of an instance-swap property showing component `cur`: its menu lists the
|
||||
/// property's preferred components first (when it has any), then every component in the file. The
|
||||
/// dropdown, and the component picked (picking the current one picks nothing). `name` labels it for
|
||||
/// assistive technology.
|
||||
/// dropdown, and the component picked (picking the current one picks nothing). Without `cur` it reads
|
||||
/// "Mixed" when `mixed` (the selected instances swap in different components), else "None". `name`
|
||||
/// labels it for assistive technology.
|
||||
pub(crate) fn swap_dropdown(
|
||||
ui: &mut Ui,
|
||||
doc: &Document,
|
||||
cur: Option<NodeId>,
|
||||
mixed: bool,
|
||||
preferred: &[NodeId],
|
||||
comps: &[(NodeId, String)],
|
||||
w: f32,
|
||||
name: &str,
|
||||
) -> (egui::Response, Option<NodeId>) {
|
||||
let label = cur.and_then(|c| doc.node(c)).map(|c| c.name.clone()).unwrap_or_else(|| tr("None").into());
|
||||
let label = match cur.and_then(|c| doc.node(c)) {
|
||||
Some(c) => c.name.clone(),
|
||||
None if mixed => tr("Mixed").into(),
|
||||
None => tr("None").into(),
|
||||
};
|
||||
let resp = widgets::dropdown(ui, &label, w, Some(Icon::Instance));
|
||||
if !name.is_empty() {
|
||||
crate::a11y::combo(&resp, name, &label, crate::a11y::menu_open(&resp));
|
||||
|
||||
@@ -404,7 +404,8 @@ pub fn playground_section(app: &mut FigApp, ui: &mut Ui, doc: &Document, id: Nod
|
||||
widgets::label(ui, name, t.text_secondary);
|
||||
let preferred: Vec<NodeId> = p["preferred"].as_array().into_iter().flatten().filter_map(figcraft_engine::params::id_of).collect();
|
||||
let w = ui.available_width().max(60.0);
|
||||
if let Some(c) = crate::component_panel::swap_dropdown(ui, doc, figcraft_engine::params::id_of(value), &preferred, &comps, w, name).1
|
||||
if let Some(c) =
|
||||
crate::component_panel::swap_dropdown(ui, doc, figcraft_engine::params::id_of(value), false, &preferred, &comps, w, name).1
|
||||
{
|
||||
set = Some((name.to_string(), json!(c.0)));
|
||||
}
|
||||
@@ -481,11 +482,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 +510,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
|
||||
|
||||
@@ -617,12 +617,22 @@ fn hides_children(n: &figcraft_doc::Node, dimmed: bool) -> bool {
|
||||
dimmed || !n.visible || n.hides_contents()
|
||||
}
|
||||
|
||||
fn vertical_flow(n: &figcraft_doc::Node) -> bool {
|
||||
n.layout.as_ref().is_some_and(|layout| layout.mode == figcraft_doc::LayoutMode::Vertical)
|
||||
}
|
||||
|
||||
/// Follow a vertical flow from top to bottom; elsewhere start at the top of the stacking order.
|
||||
fn panel_children(n: &figcraft_doc::Node) -> impl Iterator<Item = &NodeId> {
|
||||
let mut children = n.children.iter();
|
||||
let forward = vertical_flow(n);
|
||||
std::iter::from_fn(move || if forward { children.next() } else { children.next_back() })
|
||||
}
|
||||
|
||||
fn collect(doc: &Document, id: NodeId, depth: usize, dimmed: bool, locked: bool, expanded: &BTreeSet<NodeId>, out: &mut Vec<Row>) {
|
||||
let Some(n) = doc.node(id) else { return };
|
||||
let dim_kids = !n.is_page() && hides_children(n, dimmed);
|
||||
let lock_kids = locked || n.locked;
|
||||
// Layers panel lists top of the stack first.
|
||||
for c in n.children.iter().rev() {
|
||||
for c in panel_children(n) {
|
||||
let Some(cn) = doc.node(*c) else { continue };
|
||||
let has_kids = !cn.children.is_empty() || matches!(cn.kind, NodeKind::BooleanOp { .. });
|
||||
out.push(Row { id: *c, depth, has_kids, dimmed: dim_kids, locked_above: lock_kids });
|
||||
@@ -632,10 +642,10 @@ fn collect(doc: &Document, id: NodeId, depth: usize, dimmed: bool, locked: bool,
|
||||
}
|
||||
}
|
||||
|
||||
/// Layers whose name contains `q` (lowercase), top of the stack first, as a flat list.
|
||||
/// Layers whose name contains `q` (lowercase), in panel order as a flat list.
|
||||
fn matching(doc: &Document, id: NodeId, q: &str, out: &mut Vec<Row>) {
|
||||
let Some(n) = doc.node(id) else { return };
|
||||
for c in n.children.iter().rev() {
|
||||
for c in panel_children(n) {
|
||||
let Some(cn) = doc.node(*c) else { continue };
|
||||
let name = if cn.name.is_empty() { cn.kind.label() } else { cn.name.as_str() };
|
||||
if name.to_lowercase().contains(q) {
|
||||
@@ -984,26 +994,29 @@ fn select_clicked(app: &mut FigApp, rows: &[Row], sel: &[NodeId], id: NodeId, m:
|
||||
|
||||
/// Drops `moving` on `target` (`zone`: 0 into it, -1 above, 1 below), unless Dev Mode refuses
|
||||
/// (a drag started in the design can end after a switch to it).
|
||||
fn drop_layers(app: &mut FigApp, doc: &Document, moving: &[NodeId], target: NodeId, zone: i8) {
|
||||
fn drop_layers(app: &mut FigApp, doc: &Document, rows: &[Row], moving: &[NodeId], target: NodeId, zone: i8) {
|
||||
if crate::menus::dev_mode_refuses(app, "node.reparent") {
|
||||
return;
|
||||
}
|
||||
let ids = moving.to_vec();
|
||||
match zone {
|
||||
0 => {
|
||||
app.run("node.reparent", json!({"ids": ids, "parent": target}));
|
||||
}
|
||||
z => {
|
||||
// Above in the list = higher z = after the target among siblings.
|
||||
if let Some(parent) = doc.node(target).and_then(|n| n.parent) {
|
||||
let idx = doc.index_in_parent(target).unwrap_or(0);
|
||||
let gap = if z < 0 { idx + 1 } else { idx };
|
||||
// `index` is the final position: the dragged layers below the gap leave it.
|
||||
let below = doc.node(parent).map_or(0, |p| p.children.iter().take(gap).filter(|c| ids.contains(c)).count());
|
||||
app.run("node.reparent", json!({"ids": ids, "parent": parent, "index": gap - below}));
|
||||
}
|
||||
}
|
||||
let parent = if zone == 0 { Some(target) } else { doc.node(target).and_then(|n| n.parent) };
|
||||
let Some(parent) = parent.and_then(|id| doc.node(id)) else { return };
|
||||
let forward = vertical_flow(parent);
|
||||
let mut pending: BTreeSet<_> = moving.iter().copied().collect();
|
||||
let index = (zone != 0).then(|| {
|
||||
let idx = doc.index_in_parent(target).unwrap_or(0);
|
||||
// Above means before the target in a vertical flow, after it in a stack.
|
||||
let gap = if (zone < 0) != forward { idx + 1 } else { idx };
|
||||
// `index` is the final position: the dragged layers below the gap leave it.
|
||||
let below = parent.children.iter().take(gap).filter(|c| pending.contains(c)).count();
|
||||
gap - below
|
||||
});
|
||||
// Keep the displayed order of the moved rows. A selection can include a layer outside
|
||||
// the current list (for example, under a collapsed row); include it after the listed rows.
|
||||
let mut ids: Vec<_> = rows.iter().map(|row| row.id).chain(moving.iter().copied()).filter(|id| pending.remove(id)).collect();
|
||||
if !forward {
|
||||
ids.reverse();
|
||||
}
|
||||
app.run("layers.reparent", json!({"ids": ids, "parent": parent.id, "index": index}));
|
||||
}
|
||||
|
||||
/// The eye and padlock's span on a row (`rr`, the row inset 8 pt from each side) wider than the view:
|
||||
@@ -1447,7 +1460,7 @@ fn layers(app: &mut FigApp, ui: &mut Ui) {
|
||||
d.remove::<(NodeId, f64)>(Id::unique("layer_drag_hold"));
|
||||
});
|
||||
if let (Some(_), Some((target, zone))) = (dragging, drop) {
|
||||
drop_layers(app, &doc, &moving, target, zone);
|
||||
drop_layers(app, &doc, &rows, &moving, target, zone);
|
||||
}
|
||||
}
|
||||
if let Ok(ds) = app.session.ds_mut() {
|
||||
|
||||
@@ -44,22 +44,87 @@ pub(crate) fn preview_blend(app: &mut FigApp, ctx: &egui::Context, ids: &[NodeId
|
||||
/// (else its 600 px default area width) and keeps the size measured; rows ([`menu_row`]) take the
|
||||
/// larger of that width and their content, so the menu fits its content. Chain `.width(w)` for a
|
||||
/// menu at least `w` wide.
|
||||
pub fn menu_popup(anchor: &egui::Response) -> egui::Popup<'static> {
|
||||
egui::Popup::menu(anchor).width(anchor.rect.width().max(MENU_MIN_W)).style(menu_style)
|
||||
pub fn menu_popup(anchor: &egui::Response) -> Menu {
|
||||
Menu(egui::Popup::menu(anchor).width(anchor.rect.width().max(MENU_MIN_W)).style(menu_style))
|
||||
}
|
||||
|
||||
/// A context menu (secondary click on `resp`) sized like [`menu_popup`].
|
||||
pub fn context_popup(resp: &egui::Response) -> egui::Popup<'static> {
|
||||
egui::Popup::context_menu(resp).width(MENU_MIN_W).style(menu_style)
|
||||
pub fn context_popup(resp: &egui::Response) -> Menu {
|
||||
Menu(egui::Popup::context_menu(resp).width(MENU_MIN_W).style(menu_style))
|
||||
}
|
||||
|
||||
/// A context menu for a property row: a secondary click anywhere over `rect` opens it, even over
|
||||
/// the row's fields (which would otherwise take the click), like the incumbent's row menus.
|
||||
pub(super) fn row_context_menu(ui: &Ui, rect: Rect, id: Id) -> egui::Popup<'static> {
|
||||
pub(super) fn row_context_menu(ui: &Ui, rect: Rect, id: Id) -> Menu {
|
||||
let resp = ui.interact(rect, id, Sense::hover());
|
||||
let open = ui.rect_contains_pointer(rect) && ui.input(|i| i.pointer.secondary_clicked());
|
||||
let at_pointer = egui::Popup::menu(&resp).width(MENU_MIN_W).style(menu_style).at_pointer_fixed();
|
||||
at_pointer.open_memory(open.then_some(egui::SetOpenCommand::Bool(true)))
|
||||
Menu(at_pointer.open_memory(open.then_some(egui::SetOpenCommand::Bool(true))))
|
||||
}
|
||||
|
||||
/// The gap a menu taller than the window keeps from the window's top and bottom edges.
|
||||
const MENU_WINDOW_GAP: f32 = 8.0;
|
||||
|
||||
/// A popup menu ([`menu_popup`], [`context_popup`]) whose rows scroll when it would be taller
|
||||
/// than the window. egui keeps a popup inside the window by moving it, but one taller than the
|
||||
/// window runs off its edge, and rows past it can't be reached.
|
||||
#[must_use]
|
||||
pub struct Menu(egui::Popup<'static>);
|
||||
|
||||
impl Menu {
|
||||
/// At least `width` wide.
|
||||
pub fn width(self, width: f32) -> Self {
|
||||
Self(self.0.width(width))
|
||||
}
|
||||
|
||||
/// Open and closed under `id` instead of the anchor's.
|
||||
pub fn id(self, id: Id) -> Self {
|
||||
Self(self.0.id(id))
|
||||
}
|
||||
|
||||
pub fn close_behavior(self, behavior: egui::PopupCloseBehavior) -> Self {
|
||||
Self(self.0.close_behavior(behavior))
|
||||
}
|
||||
|
||||
/// Show the menu while it is open. Its rows `content` scroll with the wheel or the scroll bar
|
||||
/// once they were taller than the window last frame, as the main menu's do (#2217); a menu
|
||||
/// that fits is laid out as it is, so it still grows with its rows (a scroll area in a popup
|
||||
/// would keep the popup's last height). A click on the scroll bar scrolls and leaves the menu
|
||||
/// open. The rows have the same ids scrolling or not, so the row the keyboard is on keeps it
|
||||
/// when the window's height changes which of the two the menu does.
|
||||
pub fn show<R>(self, content: impl FnOnce(&mut Ui) -> R) -> Option<egui::InnerResponse<R>> {
|
||||
let rows = self.0.get_id().with("menu_rows");
|
||||
let bar_key = rows.with("scroll_bar");
|
||||
let ctx = self.0.ctx().clone();
|
||||
let bar_clicked = ctx.data(|d| d.get_temp::<Id>(bar_key)).is_some_and(|bar| ctx.interaction_snapshot(|i| i.clicked == Some(bar)));
|
||||
let popup = if bar_clicked { self.0.close_behavior(egui::PopupCloseBehavior::IgnoreClicks) } else { self.0 };
|
||||
let rows_ui = egui::UiBuilder::new().scope_id(rows);
|
||||
popup.show(|ui| {
|
||||
let window = ui.ctx().content_rect().height();
|
||||
let max_height = (window - ui.style().spacing.menu_margin.sum().y - 2.0 * MENU_WINDOW_GAP).max(0.0);
|
||||
let rows_height = ui.scope_id().with("menu_rows_height");
|
||||
let last = ui.data(|d| d.get_temp::<f32>(rows_height)).unwrap_or(0.0);
|
||||
let (inner, height) = if last > max_height {
|
||||
let out = egui::ScrollArea::vertical()
|
||||
.id_salt("menu_rows")
|
||||
.max_height(max_height)
|
||||
.scroll_source(egui::scroll_area::ScrollSource::MOUSE_WHEEL | egui::scroll_area::ScrollSource::SCROLL_BAR)
|
||||
.show(ui, |ui| ui.scope_builder(rows_ui, content).inner);
|
||||
// egui's id for a scroll area's vertical bar (a test in `menu_scroll_tests` clicks it).
|
||||
ui.data_mut(|d| d.insert_temp(bar_key, out.id.with(1_usize)));
|
||||
(out.inner, out.content_size.y)
|
||||
} else {
|
||||
let inner = ui.scope_builder(rows_ui, content).inner;
|
||||
let height = ui.min_rect().height();
|
||||
if height > max_height {
|
||||
ui.ctx().request_repaint();
|
||||
}
|
||||
(inner, height)
|
||||
};
|
||||
ui.data_mut(|d| d.insert_temp(rows_height, height));
|
||||
inner
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn menu_item(ui: &mut Ui, label: &str, shortcut: &str) -> bool {
|
||||
@@ -116,12 +181,23 @@ fn lit_row(
|
||||
// These menus sit on the theme's popup fill (white in the light theme), not on the dark
|
||||
// `t.menu` of the menu bar: the theme's text, white only on the green highlight (#972).
|
||||
let col = if hovered { t.menu_text } else { t.text };
|
||||
ui.painter().galley(pos2(r.min.x + MENU_PAD + lead, r.center().y - text.size().y / 2.0), text, col);
|
||||
if let Some(k) = keys {
|
||||
let at = pos2(r.max.x - MENU_PAD - k.size().x, r.center().y - k.size().y / 2.0);
|
||||
ui.painter().galley(at, k, if hovered { t.menu_text } else { t.text_secondary });
|
||||
let rtl = crate::widgets::rtl(ui);
|
||||
if rtl {
|
||||
ui.painter().galley(pos2(r.max.x - MENU_PAD - lead - text.size().x, r.center().y - text.size().y / 2.0), text, col);
|
||||
if let Some(k) = keys {
|
||||
let at = pos2(r.min.x + MENU_PAD, r.center().y - k.size().y / 2.0);
|
||||
ui.painter().galley(at, k, if hovered { t.menu_text } else { t.text_secondary });
|
||||
}
|
||||
} else {
|
||||
ui.painter().galley(pos2(r.min.x + MENU_PAD + lead, r.center().y - text.size().y / 2.0), text, col);
|
||||
if let Some(k) = keys {
|
||||
let at = pos2(r.max.x - MENU_PAD - k.size().x, r.center().y - k.size().y / 2.0);
|
||||
ui.painter().galley(at, k, if hovered { t.menu_text } else { t.text_secondary });
|
||||
}
|
||||
}
|
||||
art(ui.painter(), r, col);
|
||||
// In RTL, anchor right-aligned trailing artwork near the reading end (left) so it stays opposite the label.
|
||||
let art_r = if rtl && art_w > 0.0 { Rect::from_min_max(r.min, pos2((r.min.x + art_w + MENU_PAD).min(r.max.x), r.max.y)) } else { r };
|
||||
art(ui.painter(), art_r, col);
|
||||
resp
|
||||
}
|
||||
|
||||
@@ -196,16 +272,54 @@ const CHECK_COL: f32 = 14.0;
|
||||
/// `Some(true)`) is drawn in its own column ahead of the icon, so a checked entry's label does
|
||||
/// not move against the unchecked ones.
|
||||
pub fn menu_icon_item(ui: &mut Ui, icon: Option<crate::icons::Icon>, on: Option<bool>, label: &str, shortcut: &str) -> bool {
|
||||
let rtl = crate::widgets::rtl(ui);
|
||||
let paint = |p: &egui::Painter, r: Rect, col: Color32| {
|
||||
if on == Some(true) {
|
||||
let mark = p.layout_no_wrap("✓".to_owned(), regular(11.5), col);
|
||||
p.galley(pos2(r.min.x + MENU_PAD, r.center().y - mark.size().y / 2.0), mark, col);
|
||||
let x = if rtl { r.max.x - MENU_PAD - mark.size().x } else { r.min.x + MENU_PAD };
|
||||
p.galley(pos2(x, r.center().y - mark.size().y / 2.0), mark, col);
|
||||
}
|
||||
if let Some(icon) = icon {
|
||||
crate::icons::paint(p, Rect::from_min_size(pos2(r.min.x + MENU_PAD + CHECK_COL, r.center().y - 8.0), vec2(16.0, 16.0)), icon, col);
|
||||
let x = if rtl { r.max.x - MENU_PAD - CHECK_COL - 16.0 } else { r.min.x + MENU_PAD + CHECK_COL };
|
||||
crate::icons::paint(p, Rect::from_min_size(pos2(x, r.center().y - 8.0), vec2(16.0, 16.0)), icon, col);
|
||||
}
|
||||
};
|
||||
let resp = lit_row(ui, label, shortcut, 0.0, CHECK_COL + 22.0, paint, false);
|
||||
a11y::menu_item(&resp, label, shortcut, on);
|
||||
resp.clicked()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn rtl_lit_row_places_art_opposite_label() {
|
||||
let ctx = egui::Context::default();
|
||||
ctx.all_styles_mut(|s| s.right_to_left = true);
|
||||
let mut art_rect = None;
|
||||
ctx.run_ui(Default::default(), |ui| {
|
||||
egui::Area::new(egui::Id::unique("menu-rtl-test")).fixed_pos(pos2(0.0, 0.0)).show(ui.ctx(), |ui| {
|
||||
ui.set_width(220.0);
|
||||
let _ = lit_row(
|
||||
ui,
|
||||
"קצוות עגולים",
|
||||
"",
|
||||
64.0,
|
||||
0.0,
|
||||
|_pt, r, _| {
|
||||
art_rect = Some(r);
|
||||
},
|
||||
false,
|
||||
);
|
||||
});
|
||||
})
|
||||
.textures_delta
|
||||
.clear();
|
||||
let art_r = art_rect.expect("art invoked");
|
||||
// Artwork paints relative to art_r.max.x in [art_r.max.x - 64.0, art_r.max.x],
|
||||
// so its right edge stays on the left side while the RTL label sits at r.max.x - MENU_PAD.
|
||||
assert!((art_r.max.x - (art_r.min.x + 64.0 + MENU_PAD)).abs() < 0.01, "art_r={art_r:?}");
|
||||
assert!(art_r.max.x < 100.0, "expected trailing left placement, got {art_r:?}");
|
||||
}
|
||||
}
|
||||
@@ -116,10 +116,10 @@ fn report(layers: usize) {
|
||||
let open: Vec<NodeId> = b.app.session.doc().unwrap().nodes().filter(|n| !n.children.is_empty()).map(|n| n.id).collect();
|
||||
b.app.ui.expanded.extend(open);
|
||||
rows.push(("first frame, every layer expanded", b.frame(vec![])));
|
||||
b.app.ui.layers_focus = true;
|
||||
let top = b.app.session.doc().ok().and_then(|d| d.node(page)?.children.last().copied());
|
||||
b.app.session.set_selection(top.into_iter().collect());
|
||||
b.frame(vec![]);
|
||||
b.frame(key(Key::F6, Modifiers::SHIFT));
|
||||
rows.push(("arrow key down the expanded layers", b.mean(30, |_| key(Key::ArrowDown, Modifiers::NONE))));
|
||||
b.app.ui.expanded.clear();
|
||||
b.frame(vec![]);
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
//! The pixel grid, drawn headless: from 400% its lines are one screen pixel wide and a grey that
|
||||
//! shows on a white frame and on the dark canvas alike, as in Figma.
|
||||
|
||||
use egui::{Color32, RawInput, Shape, ViewportId, ViewportInfo};
|
||||
use figcraft_engine::Session;
|
||||
use serde_json::json;
|
||||
|
||||
use crate::canvas::overlays::PIXEL_GRID;
|
||||
use crate::layers_drag_tests::Ui;
|
||||
use crate::live_tests::flat;
|
||||
|
||||
/// Each grid line drawn in a frame on a screen of `native` pixels per point (the last of a few,
|
||||
/// for a new scale to take effect): its width and the coordinate it runs along, its x if
|
||||
/// vertical and its y if horizontal.
|
||||
fn grid_lines(u: &mut Ui, native: f32) -> Vec<(f32, f32)> {
|
||||
let mut out = None;
|
||||
for _ in 0..4 {
|
||||
let mut raw = RawInput::default();
|
||||
raw.viewports.insert(ViewportId::ROOT, ViewportInfo { native_pixels_per_point: Some(native), ..Default::default() });
|
||||
out = Some(u.frame_raw(raw));
|
||||
}
|
||||
let shapes = flat(&out.map(|o| o.shapes).unwrap_or_default());
|
||||
shapes
|
||||
.iter()
|
||||
.filter_map(|s| match s {
|
||||
Shape::LineSegment { points: [a, b], stroke } if stroke.color == PIXEL_GRID => Some((stroke.width, if a.x == b.x { a.x } else { a.y })),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Whether every line in `lines` sits on the middle of a row or column of pixels of a screen of
|
||||
/// `native` pixels per point, so it covers that one pixel and no half of two.
|
||||
fn on_pixel_centres(lines: &[(f32, f32)], native: f32) -> bool {
|
||||
lines.iter().all(|(_, at)| ((at * native - 0.5) - (at * native - 0.5).round()).abs() < 1e-3)
|
||||
}
|
||||
|
||||
/// `c` drawn over a grey of `bg`, as the canvas blends it.
|
||||
fn over(c: Color32, bg: u8) -> f32 {
|
||||
let [r, _, _, a] = c.to_srgba_unmultiplied();
|
||||
let a = f32::from(a) / 255.0;
|
||||
f32::from(bg) * (1.0 - a) + f32::from(r) * a
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_pixel_grid_shows_on_white_and_on_dark_one_screen_pixel_wide() {
|
||||
let mut s = Session::new();
|
||||
s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 100, "height": 100})).unwrap();
|
||||
let mut u = Ui::new(s);
|
||||
let view = &mut u.app.session.ds_mut().unwrap().view;
|
||||
view.zoom = 8.0;
|
||||
// A view between whole points, so the page's pixels fall between the screen's.
|
||||
(view.cx, view.cy) = (50.03, 50.07);
|
||||
let lines = grid_lines(&mut u, 1.0);
|
||||
assert!(!lines.is_empty(), "the grid draws at 800%");
|
||||
assert!(lines.iter().all(|(w, _)| *w == 1.0), "one screen pixel: {lines:?}");
|
||||
assert!(on_pixel_centres(&lines, 1.0), "on the screen's pixels: {lines:?}");
|
||||
// Measured in Figma (2026-11-24): a grid line is 242 on white and 78 on a grey of 50.
|
||||
assert_eq!((over(PIXEL_GRID, 255).round(), over(PIXEL_GRID, 50).round()), (242.0, 78.0));
|
||||
// On a 2x screen the lines stay one of its pixels wide.
|
||||
let lines = grid_lines(&mut u, 2.0);
|
||||
assert!(!lines.is_empty() && lines.iter().all(|(w, _)| *w == 0.5), "{lines:?}");
|
||||
assert!(on_pixel_centres(&lines, 2.0), "on the 2x screen's pixels: {lines:?}");
|
||||
u.app.session.ds_mut().unwrap().view.zoom = 3.0;
|
||||
assert!(grid_lines(&mut u, 2.0).is_empty(), "no grid below 400%");
|
||||
}
|
||||
@@ -124,6 +124,11 @@ impl Popover {
|
||||
}
|
||||
}
|
||||
|
||||
/// The id of the header's drag handle: a drag there moves the panel, not a value in it.
|
||||
pub fn header_drag_id(&self) -> Id {
|
||||
self.id.with("drag")
|
||||
}
|
||||
|
||||
/// `width` points wide instead of [`WIDTH`].
|
||||
pub fn width(mut self, width: f32) -> Self {
|
||||
self.width = width.max(1.0);
|
||||
|
||||
@@ -102,3 +102,54 @@ fn right_panel_dropdown_menus_fit_the_panel() {
|
||||
assert!(menu.width() <= app.ui.right_width, "menu {menu:?} fits the {} px panel", app.ui.right_width);
|
||||
assert!(menu.max.x <= SCREEN.x && menu.min.x >= panel_left - 8.0, "menu {menu:?} inside the window, under the panel");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preferences_language_menu_stays_aligned_to_dropdown() {
|
||||
use egui::accesskit::Role;
|
||||
|
||||
let screen = Rect::from_min_size(Pos2::ZERO, vec2(1920.0, 1080.0));
|
||||
for mirrored in [false, true] {
|
||||
let mut app = FigApp::new(Session::new(), Box::new(NoServices));
|
||||
app.ui.preferences = true;
|
||||
let ctx = egui::Context::default();
|
||||
ctx.enable_accesskit();
|
||||
let mut t = 0.0;
|
||||
let mut frame = |app: &mut FigApp, events: Vec<Event>| {
|
||||
t += 1.0 / 60.0;
|
||||
let raw = RawInput { screen_rect: Some(screen), time: Some(t), events, ..Default::default() };
|
||||
let mut out = ctx.run_ui(raw, |ui| app.ui(ui));
|
||||
out.textures_delta.clear();
|
||||
out
|
||||
};
|
||||
for _ in 0..3 {
|
||||
frame(&mut app, vec![]);
|
||||
}
|
||||
// Set after viewport_setup's first-frame language init so it is not overwritten.
|
||||
app.ui.mirrored = mirrored;
|
||||
for _ in 0..2 {
|
||||
frame(&mut app, vec![]);
|
||||
}
|
||||
assert_eq!(ctx.global_style().right_to_left, mirrored);
|
||||
let out = frame(&mut app, vec![]);
|
||||
let nodes = out.platform_output.accesskit_update.expect("an AccessKit update").nodes;
|
||||
let combo =
|
||||
nodes.into_iter().map(|(_, n)| n).find(|n| n.role() == Role::ComboBox && n.value() == Some("System")).expect("the Language dropdown");
|
||||
let b = combo.bounds().expect("Language dropdown bounds");
|
||||
let dropdown = Rect::from_min_max(pos2(b.x0 as f32, b.y0 as f32), pos2(b.x1 as f32, b.y1 as f32));
|
||||
let at = dropdown.center();
|
||||
frame(&mut app, press(at, true));
|
||||
frame(&mut app, press(at, false));
|
||||
for _ in 0..3 {
|
||||
frame(&mut app, vec![]);
|
||||
}
|
||||
let shown = menus(&ctx);
|
||||
let [menu] = shown.as_slice() else { panic!("one Language menu open (mirrored={mirrored}): {shown:?}") };
|
||||
assert!(menu.height() <= 360.0, "Language menu should scroll instead of spanning screen (mirrored={mirrored}): {menu:?}");
|
||||
assert!(screen.contains_rect(*menu), "Language menu should fit inside screen (mirrored={mirrored}): {menu:?}");
|
||||
if mirrored {
|
||||
assert!((menu.max.x - dropdown.max.x).abs() <= 2.0, "RTL Language menu {menu:?} should align to dropdown right {dropdown:?}");
|
||||
} else {
|
||||
assert!((menu.min.x - dropdown.min.x).abs() <= 2.0, "LTR Language menu {menu:?} should align to dropdown left {dropdown:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -73,7 +73,12 @@ fn toast(app: &FigApp) -> &str {
|
||||
}
|
||||
|
||||
fn expected_picker() -> Vec<(String, String, Vec<String>)> {
|
||||
vec![("Save as".into(), "Prototype.figcraft".into(), vec!["figcraft".into(), "fig".into()])]
|
||||
picker_named("Prototype")
|
||||
}
|
||||
|
||||
/// The Save as picker suggesting `name` with the native extension.
|
||||
fn picker_named(name: &str) -> Vec<(String, String, Vec<String>)> {
|
||||
vec![("Save as".into(), format!("{name}.figcraft"), vec!["figcraft".into(), "fig".into()])]
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -124,7 +129,8 @@ fn native_paths_and_an_extensionless_default_save_native_files_and_show_the_writ
|
||||
let mut reopened = Session::empty();
|
||||
reopened.execute("file.open", &json!({"path": path})).unwrap();
|
||||
assert_eq!(reopened.doc().unwrap().nodes().count(), app.session.doc().unwrap().nodes().count());
|
||||
assert_eq!(reopened.doc().unwrap().name, "Prototype");
|
||||
let stem = std::path::Path::new(written).file_stem().unwrap().to_str().unwrap();
|
||||
assert_eq!(reopened.doc().unwrap().name, stem, "named after the file it was saved as");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -261,16 +267,19 @@ fn saving_legacy_fig_paths_keeps_the_success_toast_and_original_source_bytes() {
|
||||
let legacy_bytes = std::fs::read(&legacy).unwrap();
|
||||
app.save();
|
||||
app.poll_dialog(&egui::Context::default());
|
||||
assert_eq!(*picks.lock().unwrap(), expected_picker());
|
||||
assert_eq!(*picks.lock().unwrap(), picker_named("original"), "named after the file it was saved as first");
|
||||
assert_eq!(std::fs::read(&legacy).unwrap(), legacy_bytes);
|
||||
assert!(target.is_file());
|
||||
assert!(app.ui.last_error.is_none());
|
||||
assert_eq!(app.session.doc().unwrap(), &before);
|
||||
if destination == "corrected.figcraft" {
|
||||
let mut renamed = before.clone();
|
||||
renamed.name = "corrected".into();
|
||||
assert_eq!(app.session.doc().unwrap(), &renamed, "saved to another file: named after it");
|
||||
assert_eq!(toast(&app), "Saved corrected.figcraft");
|
||||
assert_eq!(app.session.ds().unwrap().path.as_deref(), target.to_str());
|
||||
assert!(!app.session.ds().unwrap().is_dirty());
|
||||
} else {
|
||||
assert_eq!(app.session.doc().unwrap(), &before, "an export leaves the document alone");
|
||||
assert_eq!(toast(&app), "Exported copy.fig");
|
||||
assert_eq!(app.session.ds().unwrap().path.as_deref(), Some(legacy_path.as_str()));
|
||||
assert!(app.session.ds().unwrap().is_dirty());
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
//! headless: arrows pan with nothing selected, the keyboard box selection key and Cmd/Ctrl+arrows
|
||||
//! drawing it out, list indentation while editing text, symbols another keyboard layout types with
|
||||
//! Shift, the presentation keys (Space and N forward, C comments, F full screen), Alt+R for the
|
||||
//! rotation origin, Enter placing a shape with its tool chosen and Cmd/Ctrl+= and - zooming the
|
||||
//! canvas, not the interface.
|
||||
//! rotation origin, Enter placing a shape with its tool chosen, Cmd/Ctrl+= and - zooming the
|
||||
//! canvas, not the interface, and Shift+Cmd/Ctrl+' saying whether it snaps to the pixel grid.
|
||||
|
||||
use egui::{Event, Key, Modifiers, ViewportCommand, ViewportId};
|
||||
use figcraft_doc::NodeId;
|
||||
@@ -299,3 +299,16 @@ fn cmd_alt_arrows_rotate_a_degree_and_fifteen_with_shift() {
|
||||
assert!((rot(&u) - rot_before).abs() < 1e-6, "no turn while editing points");
|
||||
u.app.run("vector.edit.end", json!({}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shift_cmd_quote_says_whether_snapping_to_the_pixel_grid_is_on() {
|
||||
let mut u = Ui::new(Session::new());
|
||||
let toast = |u: &Ui| u.app.ui.toast.as_ref().map(|t| t.0.clone()).unwrap_or_default();
|
||||
let snap = |u: &Ui| u.app.session.ds().unwrap().view.snap_pixel;
|
||||
press(&mut u, Key::Quote, cmd() | Modifiers::SHIFT);
|
||||
assert!(!snap(&u));
|
||||
assert_eq!(toast(&u), "Snap to pixel grid off");
|
||||
press(&mut u, Key::Quote, cmd() | Modifiers::SHIFT);
|
||||
assert!(snap(&u));
|
||||
assert_eq!(toast(&u), "Snap to pixel grid on");
|
||||
}
|
||||
@@ -483,10 +483,6 @@ fn key_event(app: &mut FigApp, key: Key, physical: Option<Key>, m: Modifiers, re
|
||||
}
|
||||
return true;
|
||||
}
|
||||
// Arrows move through the layers panel while it has the keyboard.
|
||||
if app.ui.layers_focus && !m.command && !m.alt && crate::layers::key_nav(app, key, m.shift) {
|
||||
return true;
|
||||
}
|
||||
// Arrow nudges, Alt held too (measuring stays on while the selection moves); with nothing
|
||||
// selected the arrows pan the view.
|
||||
let (dx, dy) = match key {
|
||||
@@ -783,6 +779,10 @@ fn text_keys(app: &mut FigApp, ctx: &Context, events: &[Event], ime_input: Optio
|
||||
let reject_ime = ime_input.is_some_and(|baseline| baseline.interrupted(app));
|
||||
// A key that ran a shortcut swallows the text it also produced (Alt+. types "≥" on macOS).
|
||||
let mut skip_text = false;
|
||||
let paste_in_batch = events.iter().any(|e| matches!(e, Event::Paste(_)));
|
||||
// The browser sends Shift/Alt+Cmd/Ctrl+V's keys along with its paste event: the chord on the
|
||||
// key, not the modifiers still held when the paste is handled, says to match the style.
|
||||
let match_style = events.iter().any(|e| matches!(e, Event::Key { key: Key::V, pressed: true, modifiers: m, .. } if match_style_chord(*m)));
|
||||
for ev in events {
|
||||
if reject_ime && matches!(ev, Event::Ime(_)) {
|
||||
continue;
|
||||
@@ -794,9 +794,19 @@ fn text_keys(app: &mut FigApp, ctx: &Context, events: &[Event], ime_input: Optio
|
||||
}
|
||||
}
|
||||
Event::Ime(ime) => ime_event(app, ctx, ime),
|
||||
Event::Paste(t) => insert_text(app, ctx, t),
|
||||
Event::Paste(t) => paste_text(app, ctx, t, match_style),
|
||||
Event::Copy => copy_or_cut(app, ctx, false),
|
||||
Event::Cut => copy_or_cut(app, ctx, true),
|
||||
// On the desktop the chord comes without a paste event: paste the clipboard's characters.
|
||||
Event::Key { key: Key::V, pressed: true, modifiers: m, .. } if match_style_chord(*m) => {
|
||||
if !paste_in_batch
|
||||
&& !app.control_synthetic
|
||||
&& let Some(t) = app.services.clipboard_get_text()
|
||||
{
|
||||
insert_text(app, ctx, &t);
|
||||
}
|
||||
skip_text = true;
|
||||
}
|
||||
Event::Key { key, physical_key, pressed: true, modifiers: m, .. } if text_key_event(app, ctx, *key, *physical_key, *m) => {
|
||||
skip_text = true;
|
||||
}
|
||||
@@ -820,6 +830,29 @@ fn insert_text(app: &mut FigApp, ctx: &Context, t: &str) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Shift or Alt with Cmd/Ctrl, the Paste and match style chord with V. Shift alone is another
|
||||
/// paste key (Shift+Insert), which keeps the copied formatting.
|
||||
fn match_style_chord(m: Modifiers) -> bool {
|
||||
m.command && (m.alt || m.shift)
|
||||
}
|
||||
|
||||
/// Paste `t` into the edit: with the formatting it was copied with when it's the characters
|
||||
/// FigCraft last copied and `match_style` is off, otherwise in the style at the caret.
|
||||
fn paste_text(app: &mut FigApp, ctx: &Context, t: &str, match_style: bool) {
|
||||
let pasted = t.replace("\r\n", "\n").replace('\r', "\n");
|
||||
let Some(copied) = app.ui.text_copy.clone().filter(|c| !match_style && c.text == pasted) else {
|
||||
insert_text(app, ctx, t);
|
||||
return;
|
||||
};
|
||||
let before = ime_stamp(app);
|
||||
if let Err(e) = figcraft_engine::textedit::insert_rich(&mut app.session, &copied) {
|
||||
app.toast(e.to_string());
|
||||
}
|
||||
if ime_stamp(app) != before {
|
||||
note_ime_application_change(app, ctx);
|
||||
}
|
||||
}
|
||||
|
||||
/// An IME commit, preedit or surrounding-text deletion for the edit.
|
||||
fn ime_event(app: &mut FigApp, ctx: &Context, ev: &egui::ImeEvent) {
|
||||
match ev {
|
||||
@@ -874,6 +907,7 @@ fn copy_or_cut(app: &mut FigApp, ctx: &Context, cut: bool) {
|
||||
&& let Some(text) = &selected
|
||||
{
|
||||
app.clipboard_set_text(text);
|
||||
app.ui.text_copy = figcraft_engine::textedit::selected_rich_text(&app.session);
|
||||
}
|
||||
if cut && selected.is_some() {
|
||||
let _ = figcraft_engine::textedit::key(&mut app.session, "Delete", false, false, false);
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
//! Enter and Escape on text, and the page a new file gets in each theme, driven through egui
|
||||
//! Enter, Escape and Tab on text, and the page a new file gets in each theme, driven through egui
|
||||
//! headless: Enter on a selected text layer edits it with all of its text selected (what a
|
||||
//! double-click into it does), typing replaces it, and Escape leaves editing with the layer still
|
||||
//! selected; File ▸ New in the dark theme makes a dark page.
|
||||
//! selected; Tab while editing goes on to the next text layer; File ▸ New in the dark theme makes
|
||||
//! a dark page.
|
||||
|
||||
use egui::{Event, Key, Modifiers};
|
||||
use figcraft_color::Color;
|
||||
@@ -12,7 +13,10 @@ use serde_json::json;
|
||||
use crate::layers_drag_tests::Ui;
|
||||
|
||||
fn press(u: &mut Ui, key: Key) {
|
||||
let modifiers = Modifiers::NONE;
|
||||
press_with(u, key, Modifiers::NONE);
|
||||
}
|
||||
|
||||
fn press_with(u: &mut Ui, key: Key, modifiers: Modifiers) {
|
||||
u.frame(vec![
|
||||
Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers },
|
||||
Event::Key { key, physical_key: None, pressed: false, repeat: false, modifiers },
|
||||
@@ -59,6 +63,48 @@ fn enter_edits_a_selected_text_with_all_of_it_selected_and_escape_keeps_the_laye
|
||||
assert!(u.app.session.selection().is_empty());
|
||||
}
|
||||
|
||||
/// The text layer inside instance `inst`.
|
||||
fn label_of(s: &Session, inst: NodeId) -> NodeId {
|
||||
let doc = s.doc().unwrap();
|
||||
doc.subtree(inst).into_iter().find(|i| doc.node(*i).is_some_and(|n| matches!(n.kind, NodeKind::Text(_)))).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tab_edits_the_label_in_the_next_row_of_a_form() {
|
||||
// A form: a vertical auto layout frame of instances of an option (a box and a label), each
|
||||
// label set on its instance.
|
||||
let mut s = Session::new();
|
||||
let id = |v: serde_json::Value| NodeId(v["id"].as_u64().unwrap());
|
||||
let option = id(s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 160, "height": 24, "name": "Option"})).unwrap());
|
||||
s.execute("node.set", &json!({"id": option, "props": {"layout": "horizontal", "gap": 8}})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 16, "height": 16, "parent": option})).unwrap();
|
||||
let main_label = id(s.execute("text.create", &json!({"text": "Label", "x": 0, "y": 0, "parent": option})).unwrap());
|
||||
let option = id(s.execute("component.create", &json!({"ids": [option]})).unwrap());
|
||||
let form = id(s.execute("frame.create", &json!({"x": 0, "y": 200, "width": 240, "height": 200, "name": "Form"})).unwrap());
|
||||
s.execute("node.set", &json!({"id": form, "props": {"layout": "vertical", "gap": 12}})).unwrap();
|
||||
let mut labels = Vec::new();
|
||||
for name in ["Instagram", "Architect", "Designer"] {
|
||||
let inst = id(s.execute("instance.create", &json!({"component": option, "parent": form})).unwrap());
|
||||
let label = label_of(&s, inst);
|
||||
s.execute("text.set", &json!({"id": label, "characters": name})).unwrap();
|
||||
labels.push(label);
|
||||
}
|
||||
s.execute("text.edit.begin", &json!({"id": labels[0], "caret": 9})).unwrap();
|
||||
let mut u = Ui::new(s);
|
||||
press(&mut u, Key::Tab);
|
||||
let te = u.app.session.ds().unwrap().text_edit.clone().expect("still editing");
|
||||
assert_eq!((te.id, te.anchor.min(te.caret), te.anchor.max(te.caret)), (labels[1], 0, 9), "Architect, all of it selected");
|
||||
u.frame(vec![Event::Text("Writer".into())]);
|
||||
assert_eq!(text(&u, labels[1]), "Writer", "typing replaces it");
|
||||
assert_eq!((text(&u, labels[0]), text(&u, main_label)), ("Instagram".into(), "Label".into()), "the others stay");
|
||||
press_with(&mut u, Key::Tab, Modifiers::SHIFT);
|
||||
assert_eq!(u.app.session.ds().unwrap().text_edit.as_ref().map(|te| te.id), Some(labels[0]), "Shift+Tab: back to Instagram");
|
||||
// An override: the main's label changing leaves it as typed.
|
||||
press(&mut u, Key::Escape);
|
||||
u.app.session.execute("text.set", &json!({"id": main_label, "characters": "Choice"})).unwrap();
|
||||
assert_eq!(text(&u, labels[1]), "Writer", "kept as the instance's own text");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copying_and_cutting_selected_text_use_clipboard_service() {
|
||||
use std::{cell::RefCell, rc::Rc};
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
//! Pasting into a text edit: characters FigCraft copied keep their formatting, while
|
||||
//! Shift/Alt+Cmd/Ctrl+V and text from other apps take the style at the caret.
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use egui::{Event, Key, Modifiers};
|
||||
use figcraft_doc::{NodeId, TextData};
|
||||
use figcraft_engine::{Session, textedit};
|
||||
use serde_json::json;
|
||||
|
||||
use crate::layers_drag_tests::Ui;
|
||||
|
||||
struct Clipboard(Rc<RefCell<String>>);
|
||||
|
||||
impl crate::Services for Clipboard {
|
||||
fn clipboard_set_text(&mut self, text: &str) {
|
||||
*self.0.borrow_mut() = text.to_string();
|
||||
}
|
||||
fn clipboard_get_text(&mut self) -> Option<String> {
|
||||
Some(self.0.borrow().clone())
|
||||
}
|
||||
}
|
||||
|
||||
fn text(u: &Ui, id: NodeId) -> TextData {
|
||||
u.app.session.doc().unwrap().node(id).unwrap().kind.text().unwrap().clone()
|
||||
}
|
||||
|
||||
fn layer(s: &mut Session, chars: &str, size: f64, y: f64) -> NodeId {
|
||||
NodeId(s.execute("text.create", &json!({"text": chars, "x": 0, "y": y, "props": {"fontSize": size}})).unwrap()["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
fn copy_the_bold_word() -> (Ui, NodeId, Rc<RefCell<String>>) {
|
||||
let mut s = Session::new();
|
||||
let source = layer(&mut s, "Bold plain", 24.0, 0.0);
|
||||
let target = layer(&mut s, "Target", 12.0, 100.0);
|
||||
textedit::begin(&mut s, source, Some(0), false).unwrap();
|
||||
textedit::set_caret(&mut s, 4, true).unwrap();
|
||||
s.execute("text.bold", &json!({})).unwrap();
|
||||
let mut u = Ui::new(s);
|
||||
let clipboard = Rc::new(RefCell::new(String::new()));
|
||||
u.app.services = Box::new(Clipboard(clipboard.clone()));
|
||||
u.frame(vec![Event::Copy]);
|
||||
textedit::end(&mut u.app.session).unwrap();
|
||||
textedit::begin(&mut u.app.session, target, Some(6), false).unwrap();
|
||||
(u, target, clipboard)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pasting_copied_text_brings_its_formatting() {
|
||||
let (mut u, target, clipboard) = copy_the_bold_word();
|
||||
assert_eq!(*clipboard.borrow(), "Bold");
|
||||
u.frame(vec![Event::Paste("Bold".into())]);
|
||||
let t = text(&u, target);
|
||||
assert_eq!(t.characters, "TargetBold");
|
||||
assert_eq!((t.style_at(6).font_style.as_str(), t.style_at(6).font_size), ("Bold", 24.0), "the copied characters keep their look");
|
||||
assert_eq!((t.style_at(0).font_style.as_str(), t.style_at(0).font_size), ("Regular", 12.0), "the text around them keeps its own");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn alt_cmd_v_pastes_the_characters_in_the_style_at_the_caret() {
|
||||
let (mut u, target, _) = copy_the_bold_word();
|
||||
let held = Modifiers { alt: true, command: true, mac_cmd: true, ..Modifiers::NONE };
|
||||
let v = Event::Key { key: Key::V, physical_key: Some(Key::V), pressed: true, repeat: false, modifiers: held };
|
||||
u.frame_with(vec![v], held);
|
||||
let t = text(&u, target);
|
||||
assert_eq!(t.characters, "TargetBold");
|
||||
assert_eq!((t.style_at(6).font_style.as_str(), t.style_at(6).font_size), ("Regular", 12.0), "the destination's look");
|
||||
assert!(t.runs.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_copied_elsewhere_pastes_in_the_style_at_the_caret() {
|
||||
let (mut u, target, _) = copy_the_bold_word();
|
||||
u.frame(vec![Event::Paste("From a browser".into())]);
|
||||
let t = text(&u, target);
|
||||
assert_eq!(t.characters, "TargetFrom a browser");
|
||||
assert!(t.runs.is_empty(), "nothing FigCraft copied: plain text");
|
||||
}
|
||||
|
||||
fn painted(s: &mut Session, id: NodeId, hex: &str) {
|
||||
let paint = figcraft_color::Paint::solid(figcraft_color::Color::from_hex(hex).unwrap());
|
||||
s.ds_mut().unwrap().doc_mut().get_mut(id).unwrap().fills = vec![paint];
|
||||
}
|
||||
|
||||
fn color_at(u: &Ui, id: NodeId, i: usize) -> Option<figcraft_color::Color> {
|
||||
let n = u.app.session.doc().unwrap().node(id).unwrap();
|
||||
let fills = n.kind.text().unwrap().style_at(i).fills.clone().unwrap_or_else(|| n.fills.clone());
|
||||
fills.first().and_then(figcraft_color::Paint::solid_color)
|
||||
}
|
||||
|
||||
fn red_source_and_black_target() -> (Ui, NodeId, NodeId) {
|
||||
let mut s = Session::new();
|
||||
let source = layer(&mut s, "Red", 24.0, 0.0);
|
||||
let target = layer(&mut s, "Target", 12.0, 100.0);
|
||||
painted(&mut s, source, "#FF0000");
|
||||
painted(&mut s, target, "#000000");
|
||||
let mut u = Ui::new(s);
|
||||
u.app.services = Box::new(Clipboard(Rc::new(RefCell::new(String::new()))));
|
||||
(u, source, target)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copied_characters_keep_the_colour_of_their_layer() {
|
||||
let (mut u, source, target) = red_source_and_black_target();
|
||||
textedit::begin(&mut u.app.session, source, Some(0), false).unwrap();
|
||||
textedit::set_caret(&mut u.app.session, 3, true).unwrap();
|
||||
u.frame(vec![Event::Copy]);
|
||||
textedit::end(&mut u.app.session).unwrap();
|
||||
textedit::begin(&mut u.app.session, target, Some(6), false).unwrap();
|
||||
u.frame(vec![Event::Paste("Red".into())]);
|
||||
assert_eq!(text(&u, target).characters, "TargetRed");
|
||||
assert_eq!(color_at(&u, target, 6), figcraft_color::Color::from_hex("#FF0000"), "the copied characters stay red");
|
||||
assert_eq!(color_at(&u, target, 0), figcraft_color::Color::from_hex("#000000"), "the target's own text stays black");
|
||||
assert_eq!(text(&u, target).style_at(6).font_size, 24.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_copied_text_layer_pastes_into_an_edit_with_its_look() {
|
||||
let (mut u, source, target) = red_source_and_black_target();
|
||||
u.app.session.execute("select.set", &json!({"ids": [source.0]})).unwrap();
|
||||
u.frame(vec![Event::Copy]);
|
||||
textedit::begin(&mut u.app.session, target, Some(6), false).unwrap();
|
||||
u.frame(vec![Event::Paste("Red".into())]);
|
||||
let t = text(&u, target);
|
||||
assert_eq!(t.characters, "TargetRed");
|
||||
assert_eq!(t.style_at(6).font_size, 24.0);
|
||||
assert_eq!(color_at(&u, target, 6), figcraft_color::Color::from_hex("#FF0000"));
|
||||
assert_eq!(t.style_at(0).font_size, 12.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shift_cmd_v_pastes_the_characters_in_the_style_at_the_caret() {
|
||||
let (mut u, target, _) = copy_the_bold_word();
|
||||
let held = Modifiers { shift: true, command: true, mac_cmd: true, ..Modifiers::NONE };
|
||||
let v = Event::Key { key: Key::V, physical_key: Some(Key::V), pressed: true, repeat: false, modifiers: held };
|
||||
u.frame_with(vec![v], held);
|
||||
let t = text(&u, target);
|
||||
assert_eq!(t.characters, "TargetBold");
|
||||
assert!(t.runs.is_empty(), "the destination's look");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shift_insert_is_an_ordinary_paste_and_keeps_the_formatting() {
|
||||
let (mut u, target, _) = copy_the_bold_word();
|
||||
u.frame_with(vec![Event::Paste("Bold".into())], Modifiers::SHIFT);
|
||||
let t = text(&u, target);
|
||||
assert_eq!(t.characters, "TargetBold");
|
||||
assert_eq!(t.style_at(6).font_style, "Bold");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_chord_matches_the_style_though_its_keys_are_up_by_the_paste() {
|
||||
let (mut u, target, _) = copy_the_bold_word();
|
||||
let chord = Modifiers { shift: true, command: true, mac_cmd: true, ..Modifiers::NONE };
|
||||
let v = Event::Key { key: Key::V, physical_key: Some(Key::V), pressed: true, repeat: false, modifiers: chord };
|
||||
u.frame_with(vec![v, Event::Paste("Bold".into())], Modifiers::NONE);
|
||||
let t = text(&u, target);
|
||||
assert_eq!(t.characters, "TargetBold");
|
||||
assert!(t.runs.is_empty(), "the destination's look");
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
//! Variables made and named with a group shown in the Local variables window: Create variable
|
||||
//! and Duplicate put the variable in that group, and renaming it in its row edits the part shown.
|
||||
use egui::{Event, Key, Modifiers, PointerButton, Pos2};
|
||||
use figcraft_engine::Session;
|
||||
use serde_json::json;
|
||||
|
||||
use crate::layers_drag_tests::Ui;
|
||||
use crate::live_tests::{flat, has_text, text_center, texts};
|
||||
|
||||
fn window_with_groups() -> Ui {
|
||||
let mut s = Session::new();
|
||||
s.execute("variable.createCollection", &json!({"name": "Theme"})).unwrap();
|
||||
for n in ["space/sm", "color/brand"] {
|
||||
s.execute("variable.create", &json!({"collection": "Theme", "name": n, "type": "number", "value": 1})).unwrap();
|
||||
}
|
||||
let mut u = Ui::new(s);
|
||||
u.app.ui.variables = Some(Default::default());
|
||||
settle(&mut u);
|
||||
u
|
||||
}
|
||||
|
||||
fn settle(u: &mut Ui) {
|
||||
for _ in 0..8 {
|
||||
u.frame(vec![]);
|
||||
}
|
||||
}
|
||||
|
||||
fn click(u: &mut Ui, p: Pos2, button: PointerButton) {
|
||||
for pressed in [true, false] {
|
||||
u.frame(vec![Event::PointerMoved(p), Event::PointerButton { pos: p, button, pressed, modifiers: Modifiers::NONE }]);
|
||||
}
|
||||
settle(u);
|
||||
}
|
||||
|
||||
fn leftmost(u: &mut Ui, s: &str) -> Pos2 {
|
||||
let shapes = flat(&u.frame_output(vec![]).shapes);
|
||||
let (_, at, size) =
|
||||
texts(&shapes).into_iter().filter(|(t, ..)| t == s).min_by(|a, b| a.1.x.total_cmp(&b.1.x)).unwrap_or_else(|| panic!("{s} drawn"));
|
||||
at + size / 2.0
|
||||
}
|
||||
|
||||
fn names(u: &Ui) -> Vec<String> {
|
||||
let mut v: Vec<String> = u.app.session.doc().unwrap().variables.variables.iter().map(|v| v.name.clone()).collect();
|
||||
v.sort();
|
||||
v
|
||||
}
|
||||
|
||||
fn shown(u: &mut Ui, s: &str) -> bool {
|
||||
has_text(&flat(&u.frame_output(vec![]).shapes), s)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_variable_created_with_a_group_shown_goes_into_that_group_and_keeps_it_when_named() {
|
||||
let mut u = window_with_groups();
|
||||
let group = leftmost(&mut u, "space");
|
||||
click(&mut u, group, PointerButton::Primary);
|
||||
assert!(!shown(&mut u, "brand"), "only the space group is shown");
|
||||
|
||||
let create = text_center(&flat(&u.frame_output(vec![]).shapes), "+ Create variable");
|
||||
click(&mut u, create, PointerButton::Primary);
|
||||
let number = text_center(&flat(&u.frame_output(vec![]).shapes), "Number");
|
||||
click(&mut u, number, PointerButton::Primary);
|
||||
assert_eq!(names(&u), ["color/brand", "space/Number", "space/sm"]);
|
||||
|
||||
u.frame(vec![Event::Text("lg".into())]);
|
||||
for pressed in [true, false] {
|
||||
u.frame(vec![Event::Key { key: Key::Enter, physical_key: None, pressed, repeat: false, modifiers: Modifiers::NONE }]);
|
||||
}
|
||||
settle(&mut u);
|
||||
assert_eq!(names(&u), ["color/brand", "space/lg", "space/sm"], "naming it in its row keeps the group");
|
||||
assert!(shown(&mut u, "lg"), "and it is in the table shown");
|
||||
assert!(u.app.ui.last_error.is_none(), "{:?}", u.app.ui.last_error);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_variable_duplicated_in_a_group_stays_in_it_and_in_view() {
|
||||
let mut u = window_with_groups();
|
||||
let group = leftmost(&mut u, "space");
|
||||
click(&mut u, group, PointerButton::Primary);
|
||||
let row = leftmost(&mut u, "sm");
|
||||
click(&mut u, row, PointerButton::Secondary);
|
||||
let duplicate = text_center(&flat(&u.frame_output(vec![]).shapes), "Duplicate");
|
||||
click(&mut u, duplicate, PointerButton::Primary);
|
||||
assert_eq!(names(&u), ["color/brand", "space/sm", "space/sm copy"]);
|
||||
assert!(shown(&mut u, "sm copy"));
|
||||
}
|
||||
|
||||
fn create_number(u: &mut Ui) {
|
||||
let create = text_center(&flat(&u.frame_output(vec![]).shapes), "+ Create variable");
|
||||
click(u, create, PointerButton::Primary);
|
||||
let number = text_center(&flat(&u.frame_output(vec![]).shapes), "Number");
|
||||
click(u, number, PointerButton::Primary);
|
||||
}
|
||||
|
||||
fn type_and_enter(u: &mut Ui, typed: &str) {
|
||||
u.frame(vec![Event::Text(typed.into())]);
|
||||
for pressed in [true, false] {
|
||||
u.frame(vec![Event::Key { key: Key::Enter, physical_key: None, pressed, repeat: false, modifiers: Modifiers::NONE }]);
|
||||
}
|
||||
settle(u);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_of_slashes_alone_leaves_the_variable_in_its_group() {
|
||||
for typed in ["/", " / / "] {
|
||||
let mut u = window_with_groups();
|
||||
let group = leftmost(&mut u, "space");
|
||||
click(&mut u, group, PointerButton::Primary);
|
||||
create_number(&mut u);
|
||||
type_and_enter(&mut u, typed);
|
||||
assert_eq!(names(&u), ["color/brand", "space/Number", "space/sm"], "{typed:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_collection_takes_its_first_variable_outside_the_group_shown_before() {
|
||||
let mut u = window_with_groups();
|
||||
let group = leftmost(&mut u, "space");
|
||||
click(&mut u, group, PointerButton::Primary);
|
||||
let heading = leftmost(&mut u, "Collections");
|
||||
let (_, at, _) = texts(&flat(&u.frame_output(vec![]).shapes)).into_iter().find(|(t, ..)| t == "Collections").unwrap();
|
||||
click(&mut u, Pos2::new(at.x - 16.0 + 200.0 - 20.0, heading.y), PointerButton::Primary);
|
||||
assert_eq!(u.app.session.doc().unwrap().variables.collections.len(), 2, "the + by Collections made one");
|
||||
type_and_enter(&mut u, "Sizes");
|
||||
create_number(&mut u);
|
||||
assert_eq!(names(&u), ["Number", "color/brand", "space/sm"]);
|
||||
}
|
||||
Loaded 100 of 116 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user