Merge pull request #2457 from storytold/carry/2282

M12: boards: code blocks (doc and engine): a board code block that hugs its lines, with a language (#2237)
This commit is contained in:
BFlat
2026-11-19 02:33:25 +07:00
committed by GitHub
20 changed files with 1081 additions and 17 deletions
+1 -1
View File
@@ -2,7 +2,7 @@
**Stage: alpha** · next: beta, ~26 points and ~162–292 h away (one Opus 5.5 agent; ~33–67 h wall-clock with 5 agents)
> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-18 · **Change:** minor (library analytics count insertions and detachments of styles and variables; web builds with craft-fonts embed Noto Sans Arabic by default so Persian and Arabic text draws without extra build flags (#1902); the browser build uses team libraries and plugin directories on a server; CLI post-parse errors escape terminal controls in paths and failure text; M6 `.fig` export writes text on a path (#2323), list spacing, hanging punctuation and lists, vertical trim (#2305), vector region paints (#2302), image adjustments (#2297) and a page's prototype background (#2326); M8 Tidy up keeps a row's or column's order and sizes and evens the gaps, rounds the gap, tidies overlapping rows and grids along their longer axis, and raises a negative gap so no layer reaches the one two before it, as measured in Figma (#2319); a polygon's or star's Count handle and a double-click on a layer's icon (zoom, range anchor) follow Figma; Tab while renaming moves only the rename and wraps from the last layer; Align is unavailable for a layer in an auto layout frame's flow; the Scale tool pivots on the opposite handle and starts its origin at the centre; Paste over selection puts the copies just above the selected layer; Crop from the image fill's menu crops with a drag (#2307); M10 code export writes every colour and gradient fill in paint order for CSS, SwiftUI, Compose and Flutter (#2271), CSS as one layered background; 24 pt icon buttons draw 16 pt glyphs (#2227, #2238); M5 marquee selection follows Figma's measured rules and Select layer lists locked layers with a padlock (#1560); M7 the Design panel shows the page's variable modes with nothing selected (#2215); M12 mind maps in a section or frame without a place centre on the view, stickies take a Small–Huge text-size menu, and M9 `.jam` shapes with text import as native board shapes (#1808); M4 a boolean group's corner radius rounds its result (#2222), Flatten bakes a point's corner radius into its path (#2195) and loops close through a joining segment (#1951); library links survive moving or cloning the project folder (#2132); renaming a variable group to a path with `/` nests it (#2353); SVG import, widget images, batches and grids take bounded work, and a host's server key is never sent over plain `ws://` to another machine (#1923); CI prefetches dependencies for Sonar coverage and runs Harden-Runner on every job; releases FigCraft v0.18.0 and v0.18.1 (Flatpak update fix); readiness estimates unchanged) · **Target:** Figma Design (desktop app 126.10.7)
> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-19 · **Change:** minor (code blocks, first step: a dark panel of monospace text as tall as its lines, in one of 16 languages (`board.codeBlock`, `board.setLanguage`, #2237); library analytics count insertions and detachments of styles and variables; web builds with craft-fonts embed Noto Sans Arabic by default so Persian and Arabic text draws without extra build flags (#1902); the browser build uses team libraries and plugin directories on a server; CLI post-parse errors escape terminal controls in paths and failure text; M6 `.fig` export writes text on a path (#2323), list spacing, hanging punctuation and lists, vertical trim (#2305), vector region paints (#2302), image adjustments (#2297) and a page's prototype background (#2326); M8 Tidy up keeps a row's or column's order and sizes and evens the gaps, rounds the gap, tidies overlapping rows and grids along their longer axis, and raises a negative gap so no layer reaches the one two before it, as measured in Figma (#2319); a polygon's or star's Count handle and a double-click on a layer's icon (zoom, range anchor) follow Figma; Tab while renaming moves only the rename and wraps from the last layer; Align is unavailable for a layer in an auto layout frame's flow; the Scale tool pivots on the opposite handle and starts its origin at the centre; Paste over selection puts the copies just above the selected layer; Crop from the image fill's menu crops with a drag (#2307); M10 code export writes every colour and gradient fill in paint order for CSS, SwiftUI, Compose and Flutter (#2271), CSS as one layered background; 24 pt icon buttons draw 16 pt glyphs (#2227, #2238); M5 marquee selection follows Figma's measured rules and Select layer lists locked layers with a padlock (#1560); M7 the Design panel shows the page's variable modes with nothing selected (#2215); M12 mind maps in a section or frame without a place centre on the view, stickies take a Small–Huge text-size menu, and M9 `.jam` shapes with text import as native board shapes (#1808); M4 a boolean group's corner radius rounds its result (#2222), Flatten bakes a point's corner radius into its path (#2195) and loops close through a joining segment (#1951); library links survive moving or cloning the project folder (#2132); renaming a variable group to a path with `/` nests it (#2353); SVG import, widget images, batches and grids take bounded work, and a host's server key is never sent over plain `ws://` to another machine (#1923); CI prefetches dependencies for Sonar coverage and runs Harden-Runner on every job; releases FigCraft v0.18.0 and v0.18.1 (Flatpak update fix); readiness estimates unchanged) · **Target:** Figma Design (desktop app 126.10.7)
FigCraft is a clean-room, open-source, pure-Rust reimplementation of the Figma design workflow,
native on macOS, Windows, Linux and FreeBSD and in the browser, fully drivable by agents through
+13 -2
View File
@@ -10,7 +10,7 @@ use figcraft_geom::kurbo::{Ellipse, RoundedRect};
use figcraft_geom::{BezPath, Point, Rect, Shape, Vec2};
use serde::{Deserialize, Serialize};
use crate::NodeId;
use crate::{CodeLanguage, NodeId};
/// What a file is for: designing screens, or a board to think together on.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
@@ -65,6 +65,12 @@ pub enum BoardItem {
/// A mind map's node: a frame hugging its text, with no outline. What it hangs from is the
/// branch (a connector with `branch`) arriving at it.
MindNode,
/// A code block: a dark panel holding one monospace text (its first text layer), as wide as
/// it was made and as tall as its lines. `language` picks the highlighting.
CodeBlock {
#[serde(default)]
language: CodeLanguage,
},
}
impl BoardItem {
@@ -79,12 +85,16 @@ impl BoardItem {
| BoardItem::Stamp { .. }
| BoardItem::Table
| BoardItem::MindNode
| BoardItem::CodeBlock { .. }
)
}
/// Objects whose first text layer is their text (a double-click or Enter edits it).
pub fn has_text(&self) -> bool {
matches!(self, BoardItem::Sticky { .. } | BoardItem::Shape { .. } | BoardItem::Label { .. } | BoardItem::MindNode)
matches!(
self,
BoardItem::Sticky { .. } | BoardItem::Shape { .. } | BoardItem::Label { .. } | BoardItem::MindNode | BoardItem::CodeBlock { .. }
)
}
/// Who made it (stickies and stamps; empty when unknown).
@@ -127,6 +137,7 @@ impl BoardItem {
BoardItem::Ink => "ink",
BoardItem::Table => "table",
BoardItem::MindNode => "mindNode",
BoardItem::CodeBlock { .. } => "codeBlock",
}
}
}
+130
View File
@@ -0,0 +1,130 @@
//! Code blocks (#2237): the languages a block is highlighted as, and the numbers of its look.
//! Pure data: the engine makes the block ([`crate::BoardItem::CodeBlock`]).
use figcraft_color::Color;
use serde::{Deserialize, Serialize};
/// The language a code block is highlighted as.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum CodeLanguage {
Bash,
Cpp,
Css,
Go,
Graphql,
Html,
Javascript,
Json,
Kotlin,
PlainText,
Python,
Ruby,
Rust,
Sql,
Swift,
#[default]
Typescript,
}
impl CodeLanguage {
/// In menu order: by name.
pub const ALL: [CodeLanguage; 16] = [
CodeLanguage::Bash,
CodeLanguage::Cpp,
CodeLanguage::Css,
CodeLanguage::Go,
CodeLanguage::Graphql,
CodeLanguage::Html,
CodeLanguage::Javascript,
CodeLanguage::Json,
CodeLanguage::Kotlin,
CodeLanguage::PlainText,
CodeLanguage::Python,
CodeLanguage::Ruby,
CodeLanguage::Rust,
CodeLanguage::Sql,
CodeLanguage::Swift,
CodeLanguage::Typescript,
];
/// The id used in commands and saved files ("cpp", "plainText", "typescript").
pub fn id(self) -> &'static str {
match self {
CodeLanguage::Bash => "bash",
CodeLanguage::Cpp => "cpp",
CodeLanguage::Css => "css",
CodeLanguage::Go => "go",
CodeLanguage::Graphql => "graphql",
CodeLanguage::Html => "html",
CodeLanguage::Javascript => "javascript",
CodeLanguage::Json => "json",
CodeLanguage::Kotlin => "kotlin",
CodeLanguage::PlainText => "plainText",
CodeLanguage::Python => "python",
CodeLanguage::Ruby => "ruby",
CodeLanguage::Rust => "rust",
CodeLanguage::Sql => "sql",
CodeLanguage::Swift => "swift",
CodeLanguage::Typescript => "typescript",
}
}
/// The name shown in the UI ("C++", "Plain text", "TypeScript").
pub fn label(self) -> &'static str {
match self {
CodeLanguage::Bash => "Bash",
CodeLanguage::Cpp => "C++",
CodeLanguage::Css => "CSS",
CodeLanguage::Go => "Go",
CodeLanguage::Graphql => "GraphQL",
CodeLanguage::Html => "HTML",
CodeLanguage::Javascript => "JavaScript",
CodeLanguage::Json => "JSON",
CodeLanguage::Kotlin => "Kotlin",
CodeLanguage::PlainText => "Plain text",
CodeLanguage::Python => "Python",
CodeLanguage::Ruby => "Ruby",
CodeLanguage::Rust => "Rust",
CodeLanguage::Sql => "SQL",
CodeLanguage::Swift => "Swift",
CodeLanguage::Typescript => "TypeScript",
}
}
/// By id or by name, in any case, trimmed ("cpp", "C++", "plain text").
pub fn from_id(s: &str) -> Option<CodeLanguage> {
let s = s.trim();
CodeLanguage::ALL.into_iter().find(|l| l.id().eq_ignore_ascii_case(s) || l.label().eq_ignore_ascii_case(s))
}
}
/// The font code is set in (always this family; the machine finds the nearest when it is absent).
pub const CODE_FONT: &str = "Liberation Mono";
pub const CODE_FONT_SIZE: f64 = 16.0;
/// A line of code: 150% of the size.
pub const CODE_LINE: f64 = 24.0;
/// Room around the code: top, right, bottom, left (the left holds the line numbers).
pub const CODE_PAD: [f64; 4] = [16.0, 16.0, 16.0, 64.0];
pub const CODE_MIN_LINES: usize = 4;
/// A block's least height: four lines.
pub const CODE_MIN_H: f64 = 128.0;
pub const CODE_WIDTH: f64 = 576.0;
pub const CODE_MIN_W: f64 = 210.0;
pub const CODE_MAX_W: f64 = 100_000.0;
/// The room between a block and the next one made beside it.
pub const CODE_GAP: f64 = 128.0;
pub const CODE_RADIUS: f64 = 10.0;
/// What Tab types in a block.
pub const CODE_TAB: &str = " ";
/// The most characters `board.codeBlock` takes.
pub const CODE_MAX_CHARS: usize = 100_000;
/// The panel: the board's ink.
pub const CODE_PANEL: Color = Color::from_rgb8_const(0x1E, 0x1E, 0x1E);
/// Plain code: the board's gray.
pub const CODE_TEXT: Color = Color::from_rgb8_const(0xE3, 0xE1, 0xDD);
/// A block's height holding `lines` visual lines (four at least): 32 + 24 a line.
pub fn code_height(lines: usize) -> f64 {
CODE_PAD[0] + CODE_PAD[2] + CODE_LINE * lines.clamp(CODE_MIN_LINES, 1_000_000) as f64
}
+58
View File
@@ -0,0 +1,58 @@
//! Code blocks (#2237): the languages, the saved item, the height rule and the colours.
use serde_json::json;
use crate::BoardItem;
use crate::board_code::{CODE_MIN_H, CODE_PAD, CODE_PANEL, CODE_TEXT, CodeLanguage, code_height};
#[test]
fn sixteen_languages_by_name_with_typescript_the_default() {
assert_eq!(CodeLanguage::ALL.len(), 16);
let ids: std::collections::BTreeSet<&str> = CodeLanguage::ALL.iter().map(|l| l.id()).collect();
assert_eq!(ids.len(), 16, "ids are unique");
let labels: Vec<String> = CodeLanguage::ALL.iter().map(|l| l.label().to_lowercase()).collect();
assert!(labels.windows(2).all(|w| w[0] < w[1]), "labels ascend: {labels:?}");
for l in CodeLanguage::ALL {
assert_eq!(CodeLanguage::from_id(l.id()), Some(l));
assert_eq!(CodeLanguage::from_id(l.label()), Some(l));
assert_eq!(serde_json::to_value(l).unwrap(), json!(l.id()));
}
assert_eq!(CodeLanguage::from_id("CPP"), Some(CodeLanguage::Cpp));
assert_eq!(CodeLanguage::from_id("c++"), Some(CodeLanguage::Cpp));
assert_eq!(CodeLanguage::from_id(" plain text "), Some(CodeLanguage::PlainText));
assert_eq!(CodeLanguage::from_id("markdown"), None);
assert_eq!(CodeLanguage::from_id(""), None);
assert_eq!(CodeLanguage::default(), CodeLanguage::Typescript);
}
#[test]
fn a_code_block_item_saves_its_language() {
let item = BoardItem::CodeBlock { language: CodeLanguage::Rust };
let v = json!({"type": "codeBlock", "language": "rust"});
assert_eq!(serde_json::to_value(&item).unwrap(), v);
assert_eq!(serde_json::from_value::<BoardItem>(v).unwrap(), item);
let plain: BoardItem = serde_json::from_value(json!({"type": "codeBlock"})).unwrap();
assert_eq!(plain, BoardItem::CodeBlock { language: CodeLanguage::Typescript });
assert!(serde_json::from_value::<BoardItem>(json!({"type": "codeBlock", "language": "klingon"})).is_err());
assert_eq!(item.kind_id(), "codeBlock");
assert!(item.is_atom());
assert!(item.has_text());
}
#[test]
fn the_height_is_32_and_24_a_line_from_four_lines_up() {
assert_eq!(code_height(0), 128.0);
assert_eq!(code_height(1), 128.0);
assert_eq!(code_height(4), 128.0);
assert_eq!(code_height(5), 152.0);
assert_eq!(code_height(9), 248.0);
assert!(code_height(usize::MAX).is_finite());
assert_eq!(CODE_MIN_H, code_height(0));
assert_eq!(CODE_PAD[0] + CODE_PAD[2], 32.0);
assert_eq!(CODE_PAD[1] + CODE_PAD[3], 80.0);
}
#[test]
fn plain_code_reads_on_the_panel() {
assert!(CODE_TEXT.contrast(CODE_PANEL) >= 4.5, "{}", CODE_TEXT.contrast(CODE_PANEL));
}
+4
View File
@@ -9,6 +9,7 @@
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
pub mod board;
mod board_code;
mod board_mindmap;
mod board_route;
pub mod colors;
@@ -28,6 +29,7 @@ pub mod vector_faces;
pub mod vector_regions;
pub use board::*;
pub use board_code::*;
pub use board_mindmap::{MIND_GAP_X, MIND_GAP_Y, MIND_MAX_DEPTH, MIND_MAX_NODES, MindBox, mind_layout};
pub use board_route::{END_GAP, MAX_RUNS, RouteEnd, attach_points, attached_sides, path_handles, reshaped, route_along, route_points};
pub use colors::*;
@@ -1321,6 +1323,8 @@ fn remap_action(a: &mut proto::Action, map: &BTreeMap<NodeId, NodeId>) {
#[cfg(test)]
mod blur_tests;
#[cfg(test)]
mod board_code_tests;
#[cfg(test)]
mod board_mindmap_tests;
#[cfg(test)]
mod board_route_tests;
+541
View File
@@ -0,0 +1,541 @@
//! Code blocks (#2237): `board.codeBlock` and `board.setLanguage`, the pass that keeps a block as
//! tall as its lines and its text plain code, and the text editor's three literal-typing lines.
use figcraft_color::{Color, Paint};
use figcraft_doc::{
BoardItem, CODE_FONT, CODE_MAX_CHARS, CodeLanguage, EffectKind, FileKind, LayoutMode, LineHeight, ListStyle, NodeId, NodeKind, Sizing,
TextAlignH, TextAutoResize, TextCase, TextData, TextDecoration,
};
use figcraft_geom::Rect;
use serde_json::{Value, json};
use crate::board::{is_code_text, text_of};
use crate::board_tests::{board, id, node};
use crate::collab_live_tests::Room;
use crate::tools::{PointerEvent, PointerKind};
use crate::{EngineError, Session};
fn bx(s: &Session, id: NodeId) -> Rect {
s.doc().unwrap().world_bounds(id).unwrap()
}
fn td(s: &Session, block: NodeId) -> TextData {
let t = text_of(s.doc().unwrap(), block).unwrap();
match node(s, t).kind {
NodeKind::Text(td) => td,
other => panic!("not text: {other:?}"),
}
}
/// `board.codeBlock` with `p`: the frame and its text.
fn block(s: &mut Session, p: Value) -> (NodeId, NodeId) {
let out = s.execute("board.codeBlock", &p).unwrap();
(id(&out, "id"), id(&out, "text"))
}
/// How many visual lines the text lays out in.
fn lines(s: &Session, text: NodeId) -> usize {
let n = node(s, text);
figcraft_text::layout_node(&n).map_or(0, |(l, _)| l.lines.len())
}
fn solid(hex: (u8, u8, u8)) -> Vec<Paint> {
vec![Paint::solid(Color::from_rgb8_const(hex.0, hex.1, hex.2))]
}
fn ten(n: usize) -> String {
vec!["x"; n].join("\n")
}
fn drag(s: &mut Session, from: (f64, f64), to: (f64, f64)) {
s.pointer(&PointerEvent::at(PointerKind::Down, from.0, from.1, 1.0)).unwrap();
s.pointer(&PointerEvent::at(PointerKind::Move, (from.0 + to.0) / 2.0, (from.1 + to.1) / 2.0, 1.0)).unwrap();
s.pointer(&PointerEvent::at(PointerKind::Move, to.0, to.1, 1.0)).unwrap();
s.pointer(&PointerEvent::at(PointerKind::Up, to.0, to.1, 1.0)).unwrap();
}
fn undo(s: &mut Session) {
s.execute("edit.undo", &json!({})).unwrap();
}
#[test]
fn a_code_block_is_a_dark_panel_576_by_128_holding_one_monospace_text() {
let mut s = board();
let before = s.doc().unwrap().ids().count();
let depth = s.undo_depth().0;
let out = s.execute("board.codeBlock", &json!({"x": 100, "y": 200})).unwrap();
assert_eq!(out["language"], json!("typescript"));
let (f, t) = (id(&out, "id"), id(&out, "text"));
let n = node(&s, f);
assert_eq!(n.board, Some(BoardItem::CodeBlock { language: CodeLanguage::Typescript }));
assert!(n.is_board_atom());
let r = bx(&s, f);
assert_eq!((r.x0, r.y0, r.x1, r.y1), (100.0, 200.0, 676.0, 328.0));
assert_eq!(n.fills, solid((0x1E, 0x1E, 0x1E)));
assert_eq!(n.corners.radii, [10.0; 4]);
assert_eq!(n.effects.iter().filter(|e| matches!(e.kind, EffectKind::DropShadow(_))).count(), 1);
let l = n.layout.clone().unwrap();
assert_eq!((l.mode, l.padding), (LayoutMode::Vertical, [16.0, 16.0, 16.0, 64.0]));
assert_eq!(n.child_layout.sizing_v, Sizing::Hug);
assert_eq!((n.child_layout.min_h, n.child_layout.min_w), (Some(128.0), Some(210.0)));
assert_eq!(n.children, vec![t]);
let tr = bx(&s, t);
assert_eq!((tr.x0, tr.y0, tr.width()), (164.0, 216.0, 496.0));
let d = td(&s, f);
assert_eq!(d.characters, "");
assert_eq!((d.style.font_family.as_str(), d.style.font_style.as_str(), d.style.font_size), (CODE_FONT, "Regular", 16.0));
assert_eq!(d.style.line_height, LineHeight::Percent(150.0));
assert_eq!((d.auto_resize, d.align_h), (TextAutoResize::Height, TextAlignH::Left));
assert_eq!(node(&s, t).fills, solid((0xE3, 0xE1, 0xDD)));
assert_eq!((d.features.get("liga"), d.features.get("calt")), (Some(&false), Some(&false)));
assert!(d.runs.is_empty());
assert_eq!(d.list, ListStyle::None);
assert_eq!(s.selection(), vec![f]);
assert_eq!(s.undo_depth().0, depth + 1);
undo(&mut s);
assert_eq!(s.doc().unwrap().ids().count(), before);
}
#[test]
fn a_block_without_a_place_is_centred_and_edit_asks_for_typing() {
let mut s = board();
// Centred on the view without a place.
let (vx, vy) = {
let v = &s.ds().unwrap().view;
(v.cx, v.cy)
};
let (f, _) = block(&mut s, json!({}));
let r = bx(&s, f);
assert_eq!((r.x0, r.y0), (vx - 288.0, vy - 64.0));
// Typing starts in it on request.
let (f, _) = block(&mut s, json!({"x": 0, "y": 500, "edit": true}));
assert!(s.ui_requests.iter().any(|q| q.kind == "board.editText" && q.data["id"] == json!(f)));
}
#[test]
fn the_height_is_its_lines_24_each_and_never_under_four() {
let mut s = board();
let heights = [("a", 128.0), ("a\nb\nc\nd", 128.0), ("a\nb\nc\nd\ne", 152.0)];
for (text, h) in heights {
let (f, _) = block(&mut s, json!({"x": 100, "y": 200, "text": text}));
let r = bx(&s, f);
assert_eq!((r.x0, r.y0, r.height()), (100.0, 200.0, h), "{text:?}");
}
let (f, t) = block(&mut s, json!({"x": 100, "y": 200, "text": ten(9)}));
assert_eq!(bx(&s, f).height(), 248.0);
assert_eq!(bx(&s, t).height(), 216.0);
s.execute("text.set", &json!({"id": t, "characters": "a\nb"})).unwrap();
let r = bx(&s, f);
assert_eq!((r.x0, r.y0, r.height()), (100.0, 200.0, 128.0));
}
#[test]
fn long_lines_wrap_and_each_visual_line_adds_24() {
let mut s = board();
let (f, t) = block(&mut s, json!({"x": 0, "y": 0, "text": "ab ".repeat(400)}));
let n = lines(&s, t);
assert!(n >= 3, "{n}");
assert_eq!(bx(&s, f).height(), 32.0 + 24.0 * n as f64);
assert_eq!(bx(&s, t).width(), 496.0);
if figcraft_text::has_family(CODE_FONT) {
let (f, _) = block(&mut s, json!({"x": 0, "y": 0, "width": 976, "text": "x".repeat(93)}));
assert_eq!(bx(&s, f).height(), 128.0);
let (f, t) = block(&mut s, json!({"x": 0, "y": 0, "width": 976, "text": "x".repeat(94)}));
assert_eq!(lines(&s, t), 2);
assert_eq!(bx(&s, f).height(), 128.0);
let (f, t) = block(&mut s, json!({"x": 0, "y": 0, "width": 976, "text": format!("{}\na\nb\nc", "x".repeat(94))}));
assert_eq!(lines(&s, t), 5);
assert_eq!(bx(&s, f).height(), 152.0);
}
}
#[test]
fn only_the_width_is_the_users() {
let mut s = board();
let (f, t) = block(&mut s, json!({"x": 100, "y": 200, "text": ten(9)}));
assert_eq!(bx(&s, f).height(), 248.0);
s.execute("node.set", &json!({"id": f, "props": {"height": 400}})).unwrap();
assert_eq!(bx(&s, f).height(), 248.0);
assert_eq!(node(&s, f).child_layout.sizing_v, Sizing::Hug);
s.execute("transform.resize", &json!({"ids": [f], "width": 300, "height": 500})).unwrap();
let r = bx(&s, f);
assert_eq!((r.width(), r.height(), bx(&s, t).width()), (300.0, 248.0, 220.0));
s.execute("node.set", &json!({"id": f, "props": {"width": 100}})).unwrap();
assert_eq!((bx(&s, f).width(), bx(&s, t).width()), (210.0, 130.0));
// A pointer drag of the bottom-right handle.
let mut s = board();
let (f, _) = block(&mut s, json!({"x": 100, "y": 200}));
let depth = s.undo_depth().0;
drag(&mut s, (676.0, 328.0), (876.0, 628.0));
let r = bx(&s, f);
assert_eq!((r.x0, r.y0, r.width(), r.height()), (100.0, 200.0, 776.0, 128.0));
assert_eq!(s.undo_depth().0, depth + 1);
undo(&mut s);
let r = bx(&s, f);
assert_eq!((r.width(), r.height()), (576.0, 128.0));
// A narrower block wraps into more lines and grows.
let mut s = board();
let (f, t) = block(&mut s, json!({"x": 0, "y": 0, "text": "ab ".repeat(400)}));
let was = lines(&s, t);
s.execute("node.set", &json!({"id": f, "props": {"width": 300}})).unwrap();
let now = lines(&s, t);
assert!(now > was, "{now} > {was}");
assert_eq!(bx(&s, f).height(), 32.0 + 24.0 * now as f64);
}
/// A block settled after `how` made it incoherent: still 5 lines tall, 576 wide, hugging, with
/// its layout, and a second pass changes nothing.
fn settled_after(how: impl Fn(&mut Session, NodeId)) {
let mut s = board();
let (f, t) = block(&mut s, json!({"x": 0, "y": 0, "text": ten(4)}));
how(&mut s, f);
s.execute("text.set", &json!({"id": t, "characters": ten(5)})).unwrap();
let n = node(&s, f);
assert!(n.layout.is_some(), "the layout is restored");
assert_eq!((n.child_layout.sizing_h, n.child_layout.sizing_v), (Sizing::Fixed, Sizing::Hug));
assert_eq!((bx(&s, f).width(), bx(&s, f).height()), (576.0, 152.0));
assert_eq!(node(&s, t).child_layout.sizing_h, Sizing::Fill);
let doc = s.doc().unwrap().clone();
let mut again = doc.clone();
again.mark_dirty(doc.ids().collect::<Vec<_>>());
crate::normalize(&mut again, &doc);
assert_eq!(again, doc, "a second pass changes nothing");
}
#[test]
fn the_pass_keeps_a_blocks_layout_and_width_sizing() {
settled_after(|s, f| {
s.execute("layout.remove", &json!({"ids": [f]})).unwrap();
});
settled_after(|s, f| {
s.execute("node.set", &json!({"id": f, "props": {"layout": null}})).unwrap();
});
settled_after(|s, f| {
s.execute("node.set", &json!({"id": f, "props": {"sizingH": "hug"}})).unwrap();
});
}
#[test]
fn a_block_in_a_section_without_a_place_is_centred_on_the_view_too() {
let mut s = board();
let (vx, vy) = {
let v = &s.ds().unwrap().view;
(v.cx, v.cy)
};
let sec = id(&s.execute("node.create", &json!({"type": "section", "x": 1000, "y": 500, "width": 4000, "height": 4000})).unwrap(), "id");
let (f, _) = block(&mut s, json!({"parent": sec}));
assert_eq!(node(&s, f).parent, Some(sec));
let r = bx(&s, f);
assert_eq!((r.x0, r.y0), (vx - 288.0, vy - 64.0), "on the page, where a block on the page would be");
}
#[test]
fn a_block_in_a_turned_frame_without_a_place_is_centred_on_the_view_and_a_given_place_is_the_frames() {
let mut s = board();
let (vx, vy) = {
let v = &s.ds().unwrap().view;
(v.cx, v.cy)
};
let fr = id(&s.execute("node.create", &json!({"type": "frame", "x": 300, "y": -200, "width": 3000, "height": 3000})).unwrap(), "id");
s.execute("node.set", &json!({"id": fr, "props": {"rotation": 30}})).unwrap();
// Left out: the block's middle (a four-line block) is on the view's centre, in the page.
let (f, _) = block(&mut s, json!({"parent": fr}));
let c = bx(&s, f).center();
assert!((c.x - vx).abs() < 1e-6 && (c.y - vy).abs() < 1e-6, "{c:?} vs ({vx}, {vy})");
// Given: `x`/`y` stay the frame's own coordinates.
let (g, _) = block(&mut s, json!({"parent": fr, "x": 10, "y": 20}));
let t = node(&s, g).transform.translation();
assert_eq!((t.x, t.y), (10.0, 20.0));
}
#[test]
fn a_default_position_is_within_a_billion_too() {
let mut s = board();
s.execute("view.set", &json!({"cx": 1e300})).unwrap();
match s.execute("board.codeBlock", &json!({})) {
Err(EngineError::BadParams { .. }) => {}
Err(other) => panic!("not a named refusal: {other:?}"),
Ok(out) => panic!("placed at {out}"),
}
}
#[test]
fn the_next_block_is_128_to_the_right_as_wide_and_in_the_same_language() {
let mut s = board();
let (a, _) = block(&mut s, json!({"x": 0, "y": 0, "width": 976, "language": "rust", "text": "fn main() {}"}));
let connectors = |s: &Session| s.doc().unwrap().nodes().filter(|n| matches!(n.board, Some(BoardItem::Connector(_)))).count();
let depth = s.undo_depth().0;
let out = s.execute("board.nextSticky", &json!({"id": a})).unwrap();
let b = id(&out, "id");
let r = bx(&s, b);
assert_eq!((r.x0, r.y0, r.width(), r.height()), (1104.0, 0.0, 976.0, 128.0));
assert_eq!(node(&s, b).board, Some(BoardItem::CodeBlock { language: CodeLanguage::Rust }));
assert_eq!(td(&s, b).characters, "");
assert_eq!(connectors(&s), 0);
assert_eq!(s.selection(), vec![b]);
assert_eq!(s.undo_depth().0, depth + 1);
undo(&mut s);
assert!(s.doc().unwrap().node(b).is_none());
// While typing in the source, with no id, and asking for the next one to be typed in.
let t = text_of(s.doc().unwrap(), a).unwrap();
s.execute("text.edit.begin", &json!({"id": t})).unwrap();
let out = s.execute("board.nextSticky", &json!({"edit": true})).unwrap();
let c = id(&out, "id");
assert_eq!(bx(&s, c).x0, 1104.0);
assert!(s.ds().unwrap().text_edit.is_none(), "the edit has ended");
assert!(s.ui_requests.iter().any(|q| q.kind == "board.editText" && q.data["id"] == json!(c)));
let out = s.execute("board.nextSticky", &json!({"id": a, "side": "below"})).unwrap();
let r = bx(&s, id(&out, "id"));
assert_eq!((r.x0, r.y0), (0.0, 256.0));
assert!(s.execute("board.nextSticky", &json!({"id": a, "side": "up"})).is_err());
}
#[test]
fn a_block_is_in_one_of_sixteen_languages() {
let mut s = board();
let (f, _) = block(&mut s, json!({"x": 0, "y": 0}));
let lang = |s: &Session| node(s, f).board;
s.execute("board.setLanguage", &json!({"id": f, "language": "python"})).unwrap();
assert_eq!(lang(&s), Some(BoardItem::CodeBlock { language: CodeLanguage::Python }));
for name in ["C++", "CPP"] {
s.execute("board.setLanguage", &json!({"id": f, "language": name})).unwrap();
assert_eq!(lang(&s), Some(BoardItem::CodeBlock { language: CodeLanguage::Cpp }));
}
for l in CodeLanguage::ALL {
s.execute("board.setLanguage", &json!({"id": f, "language": l.id()})).unwrap();
assert_eq!(lang(&s), Some(BoardItem::CodeBlock { language: l }));
}
s.execute("board.setLanguage", &json!({"id": f, "language": "go"})).unwrap();
let e = s.execute("board.setLanguage", &json!({"id": f, "language": "klingon"})).unwrap_err().to_string();
assert!(e.contains("typescript") && e.contains("plainText"), "{e}");
let sticky = id(&s.execute("board.sticky", &json!({"x": 900, "y": 0})).unwrap(), "id");
assert!(s.execute("board.setLanguage", &json!({"id": sticky, "language": "go"})).is_err());
s.execute("select.none", &json!({})).unwrap();
assert!(matches!(s.execute("board.setLanguage", &json!({"language": "go"})), Err(EngineError::Disabled(..))));
// While typing in it, the text is the selection and the edit goes on.
let t = text_of(s.doc().unwrap(), f).unwrap();
s.execute("text.edit.begin", &json!({"id": t})).unwrap();
s.execute("board.setLanguage", &json!({"language": "ruby"})).unwrap();
assert_eq!(lang(&s), Some(BoardItem::CodeBlock { language: CodeLanguage::Ruby }));
assert!(s.ds().unwrap().text_edit.is_some());
s.execute("text.edit.key", &json!({"key": "Escape"})).unwrap();
undo(&mut s);
assert_eq!(lang(&s), Some(BoardItem::CodeBlock { language: CodeLanguage::Go }));
// The creating command refuses what it cannot make.
assert!(s.execute("board.codeBlock", &json!({"language": "nope"})).is_err());
assert!(s.execute("board.codeBlock", &json!({"width": 5})).is_err());
assert!(s.execute("board.codeBlock", &json!({"text": "x".repeat(CODE_MAX_CHARS + 1)})).is_err());
}
fn insert(s: &mut Session, text: &str) {
s.execute("text.edit.insert", &json!({"text": text})).unwrap();
}
fn key(s: &mut Session, key: &str, shift: bool) {
s.execute("text.edit.key", &json!({"key": key, "shift": shift})).unwrap();
}
fn characters(s: &Session, t: NodeId) -> String {
match node(s, t).kind {
NodeKind::Text(td) => td.characters,
other => panic!("not text: {other:?}"),
}
}
#[test]
fn typing_in_a_block_is_literal() {
let mut s = board();
let (f, t) = block(&mut s, json!({"x": 0, "y": 0}));
assert!(is_code_text(s.doc().unwrap(), t));
s.execute("text.edit.begin", &json!({"id": t})).unwrap();
insert(&mut s, "-");
insert(&mut s, " ");
assert_eq!(characters(&s, t), "- ");
assert!(td(&s, f).paragraphs.iter().all(|p| p.list == ListStyle::None) && td(&s, f).list == ListStyle::None);
insert(&mut s, "\n1.");
insert(&mut s, " ");
assert_eq!(characters(&s, t), "- \n1. ");
assert!(td(&s, f).paragraphs.iter().all(|p| p.list == ListStyle::None));
// Tab types two spaces.
s.execute("text.set", &json!({"id": t, "characters": ""})).unwrap();
s.execute("text.edit.begin", &json!({"id": t, "caret": 0})).unwrap();
key(&mut s, "Tab", false);
assert_eq!(characters(&s, t), " ");
key(&mut s, "Tab", true);
assert_eq!(characters(&s, t), " ", "Shift+Tab does nothing");
// Enter keeps the line's indent, and nothing more after a brace.
insert(&mut s, "foo");
key(&mut s, "Enter", false);
assert_eq!(characters(&s, t), " foo\n ");
s.execute("text.set", &json!({"id": t, "characters": "foo"})).unwrap();
s.execute("text.edit.begin", &json!({"id": t, "caret": 3})).unwrap();
key(&mut s, "Enter", false);
assert_eq!(characters(&s, t), "foo\n");
s.execute("text.set", &json!({"id": t, "characters": "{"})).unwrap();
s.execute("text.edit.begin", &json!({"id": t, "caret": 1})).unwrap();
key(&mut s, "Enter", false);
assert_eq!(characters(&s, t), "{\n");
// Nothing is made smart.
s.execute("text.set", &json!({"id": t, "characters": ""})).unwrap();
s.execute("text.edit.begin", &json!({"id": t, "caret": 0})).unwrap();
let raw = "\"a\" -- 'b' ... -> != fi";
insert(&mut s, raw);
let got = characters(&s, t);
assert_eq!(got, raw);
assert!(!got.chars().any(|c| matches!(c, '\u{201C}' | '\u{2019}' | '\u{2014}' | '\u{2026}')));
// In a sticky the same keys still make a list.
let note = id(&s.execute("board.sticky", &json!({"x": 900, "y": 0})).unwrap(), "text");
s.execute("text.edit.begin", &json!({"id": note})).unwrap();
insert(&mut s, "-");
insert(&mut s, " ");
match node(&s, note).kind {
NodeKind::Text(d) => assert!(d.list == ListStyle::Bulleted || d.paragraphs.iter().any(|p| p.list == ListStyle::Bulleted)),
other => panic!("not text: {other:?}"),
}
}
#[test]
fn lists_links_and_styled_ranges_do_not_stick() {
let mut s = board();
let (f, t) = block(&mut s, json!({"x": 0, "y": 0, "text": "one\ntwo"}));
let plain = |s: &Session| {
let d = td(s, f);
assert_eq!(d.list, ListStyle::None);
assert!(d.paragraphs.iter().all(|p| p.list == ListStyle::None));
assert_eq!(d.style.link, None);
assert_eq!((d.style.decoration, d.style.case), (TextDecoration::None, TextCase::Original));
assert!(d.runs.is_empty());
assert_eq!(d.characters, "one\ntwo");
assert_eq!(d.auto_resize, TextAutoResize::Height);
};
for (cmd, p) in [
("text.bulletList", json!({"ids": [t]})),
("text.link", json!({"url": "https://example.com", "ids": [t]})),
("text.underline", json!({"ids": [t]})),
("text.caseUpper", json!({"ids": [t]})),
] {
// Done or refused by name, and the block is plain either way.
match s.execute(cmd, &p) {
Ok(_) | Err(EngineError::BadParams { .. } | EngineError::Disabled(..)) => {}
Err(other) => panic!("{cmd}: {other:?}"),
}
plain(&s);
}
s.execute("text.edit.begin", &json!({"id": t, "caret": 0})).unwrap();
for _ in 0..3 {
key(&mut s, "ArrowRight", true);
}
s.execute("text.bold", &json!({})).unwrap();
s.execute("text.edit.key", &json!({"key": "Escape"})).unwrap();
plain(&s);
assert_eq!(td(&s, f).style.font_style, "Regular");
s.execute("node.set", &json!({"id": t, "props": {"textAutoResize": "widthAndHeight"}})).unwrap();
plain(&s);
// A sticky's note keeps its link (the guard).
let note = id(&s.execute("board.sticky", &json!({"x": 900, "y": 0, "text": "hi"})).unwrap(), "text");
s.execute("text.link", &json!({"url": "https://example.com", "ids": [note]})).unwrap();
match node(&s, note).kind {
NodeKind::Text(d) => assert_eq!(d.style.link.as_deref(), Some("https://example.com")),
other => panic!("not text: {other:?}"),
}
}
#[test]
fn saved_files_live_sessions_and_a_second_pass() {
let mut s = board();
let (f, _) = block(&mut s, json!({"x": 100, "y": 200, "width": 400, "language": "rust", "text": "a\nb"}));
let doc = s.doc().unwrap();
let (back, _) = figcraft_format::from_json(&figcraft_format::to_json(doc).unwrap().to_string()).unwrap();
let n = back.node(f).unwrap();
assert_eq!(n.board, Some(BoardItem::CodeBlock { language: CodeLanguage::Rust }));
assert_eq!((n.width, n.height), (400.0, 128.0));
let mut s = board();
let (f, t) = block(&mut s, json!({"x": 0, "y": 0}));
let mut room = Room::new(s.doc().unwrap().clone(), 2, 7);
room.s(0).execute("text.set", &json!({"id": t, "characters": ten(6)})).unwrap();
room.s(1).execute("board.setLanguage", &json!({"id": f, "language": "go"})).unwrap();
room.settle();
room.check();
let server = room.server.document();
let n = server.node(f).unwrap();
assert_eq!(n.height, 176.0);
assert_eq!(n.board, Some(BoardItem::CodeBlock { language: CodeLanguage::Go }));
// A second pass over a settled document changes nothing.
let doc = s.doc().unwrap().clone();
let mut again = doc.clone();
again.mark_dirty(doc.ids().collect::<Vec<_>>());
crate::normalize(&mut again, &doc);
assert_eq!(again, doc);
// Not on design files.
let mut d = Session::new();
assert_eq!(d.doc().unwrap().kind, FileKind::Design);
assert!(matches!(d.execute("board.codeBlock", &json!({})), Err(EngineError::Disabled(..))));
assert!(matches!(d.execute("board.setLanguage", &json!({"language": "go"})), Err(EngineError::Disabled(..))));
}
#[test]
fn code_blocks_survive_junk_commands() {
let junk = [
json!({}),
json!(null),
json!({"language": 7, "id": "x", "ids": [1], "side": 3, "text": [1]}),
json!({"language": "nope", "id": 99_999, "side": "up", "width": 1e308, "x": "NaN"}),
];
let ids: Vec<&str> = crate::cmd::all_commands()
.iter()
.map(|c| c.id)
.filter(|i| {
i.starts_with("text.") && *i != "text.rescanFonts" || i.starts_with("layout.") || matches!(*i, "board.nextSticky" | "board.setLanguage")
})
.collect();
assert!(ids.len() > 20, "{ids:?}");
for editing in [false, true] {
for cmd in &ids {
for j in &junk {
let mut s = board();
let (f, t) = block(&mut s, json!({"x": 0, "y": 0, "text": "a\nb"}));
if editing {
s.execute("text.edit.begin", &json!({"id": t})).unwrap();
} else {
s.set_selection(vec![f]);
}
if let Err(EngineError::Internal { cmd, msg }) = s.execute(cmd, j) {
panic!("{cmd} panicked on {j} (editing {editing}): {msg}");
}
}
}
}
}
#[test]
fn a_structured_text_is_refused_and_no_block_is_made() {
for text in [json!({"a": 1}), json!([1]), json!(7), json!(true)] {
let mut s = board();
let before = s.doc().unwrap().ids().count();
let err = s.execute("board.codeBlock", &json!({"x": 0, "y": 0, "text": text}));
assert!(matches!(err, Err(EngineError::BadParams { .. })), "{text}: {err:?}");
assert_eq!(s.doc().unwrap().ids().count(), before, "{text}");
}
}
#[test]
fn the_pass_restores_padding_and_the_minimums() {
let mut s = board();
let (f, t) = block(&mut s, json!({"x": 0, "y": 0, "text": ten(6)}));
assert_eq!(bx(&s, f).height(), 176.0);
s.execute("node.set", &json!({"id": f, "props": {"padding": 0}})).unwrap();
s.execute("text.set", &json!({"id": t, "characters": ten(6)})).unwrap();
assert_eq!(node(&s, f).layout.unwrap().padding, [16.0, 16.0, 16.0, 64.0]);
assert_eq!(bx(&s, f).height(), 176.0);
let (f, t) = block(&mut s, json!({"x": 0, "y": 500}));
s.execute("node.set", &json!({"id": f, "props": {"minHeight": null}})).unwrap();
s.execute("text.set", &json!({"id": t, "characters": "a"})).unwrap();
assert_eq!(node(&s, f).child_layout.min_h, Some(128.0));
assert_eq!(bx(&s, f).height(), 128.0);
}
+3
View File
@@ -465,6 +465,7 @@ fn board_commands_survive_junk() {
json!({"end": "from", "target": {"x": 1e308, "y": -1e308}, "side": "inside", "style": "curved"}),
json!({"id": 99_999, "end": 7, "target": [1], "style": "wavy"}),
json!({"id": 99_999, "relation": 7, "children": "x", "text": [1], "x": "NaN", "y": 1e308}),
json!({"id": 99_999, "language": 7, "text": [1], "width": "wide", "x": "NaN", "y": 1e308, "side": 3}),
];
let ids: Vec<&str> = crate::cmd::all_commands()
.iter()
@@ -482,6 +483,7 @@ fn board_commands_survive_junk() {
let a = s.execute("board.sticky", &json!({"x": 0, "y": 0})).unwrap()["id"].clone();
let b = s.execute("board.shape", &json!({"x": 300, "y": 0})).unwrap()["id"].clone();
let _ = s.execute("board.connector", &json!({"from": a, "to": b, "label": "x"}));
let _ = s.execute("board.codeBlock", &json!({"x": 0, "y": 300, "text": "a\nb"}));
if let Err(EngineError::Internal { cmd, msg }) = s.execute(cmd, j) {
panic!("{cmd} panicked on {j}: {msg}");
}
@@ -497,6 +499,7 @@ fn board_commands_survive_junk() {
let a = s.execute("board.sticky", &json!({"x": 0, "y": 0})).unwrap()["id"].clone();
let b = s.execute("board.stamp", &json!({"x": 300, "y": 0})).unwrap()["id"].clone();
let _ = s.execute("board.connector", &json!({"from": a, "to": b}));
let _ = s.execute("board.codeBlock", &json!({"x": 0, "y": 300, "text": "a\nb"}));
if let Err(EngineError::Internal { cmd, msg }) = s.execute(spec.id, j) {
panic!("{cmd} panicked on {j}: {msg}");
}
+17 -1
View File
@@ -21,6 +21,7 @@ use crate::params::{boolean, color_of, get, id, id_of, num, num_or, opt_id, req_
use crate::tools::{Gesture, PointerEvent, ToolId};
use crate::{EngineError, Result, Session, bad, spec, textedit};
mod code;
mod connectors;
mod derived;
mod edit;
@@ -29,6 +30,7 @@ mod mindmap;
mod reshape;
mod tools;
pub use code::is_code_text;
pub(crate) use connectors::end_handle_at;
pub use connectors::{END_HANDLE_PX, selected_connector_ends};
use connectors::{connector_cmd, reattach};
@@ -144,7 +146,7 @@ pub fn specs() -> Vec<CommandSpec> {
spec!(
"board.nextSticky",
"Next sticky note",
"{id? (a sticky or shape; default the selected or edited one), side?: right|below|left|above (default right), edit? (start typing in it; default false)} → {id, text, connector?} a sticky of the same colour beside a sticky; after a shape, the next shape joined to it by a connector, as board.addConnected",
"{id? (a sticky, shape or code block; default the selected or edited one), side?: right|below|left|above (default right), edit? (start typing in it; default false)} → {id, text, connector?} a sticky of the same colour beside a sticky; after a shape, the next shape joined to it by a connector, as board.addConnected; after a code block, the next code block beside it (128 away), as wide and in the same language, not joined",
true,
next_sticky
),
@@ -197,6 +199,20 @@ pub fn specs() -> Vec<CommandSpec> {
true,
mindmap::mind_map_add
),
spec!(
"board.codeBlock",
"Code block",
"{x?, y? (its top-left in the parent; default a four-line block centred in the view), language? (bash|cpp|css|go|graphql|html|javascript|json|kotlin|plainText|python|ruby|rust|sql|swift|typescript; default typescript), text?, width? (210 to 100000; default 576), parent?, edit? (start typing in it; default false)} → {id, text, language} a dark panel holding monospace text: as wide as it is made, as tall as its lines (four at least)",
true,
code::code_block_cmd
),
spec!(
"board.setLanguage",
"Code language",
"{id? | ids? (code blocks; default the selected ones, or the one being typed in), language} → {ids}",
true,
code::set_language
),
spec!("board.label", "Connector label", "{id (a connector; default the selection), text (empty removes it)} → {id, label}", true, label_cmd),
spec!(
"board.stamp",
+260
View File
@@ -0,0 +1,260 @@
//! Code blocks (#2237): a frame hugging one monospace text ([`BoardItem::CodeBlock`]), as wide as
//! it was made and as tall as its lines. The commands only make the block; [`settle_code`] keeps
//! it that way in the normalize pass (the height is the lines', the text is plain code), so every
//! entry point (a drag, `node.set`, a styled paste, a live session's edit) ends the same.
use std::collections::BTreeSet;
use figcraft_color::Paint;
use figcraft_doc::{
AutoLayout, BoardItem, CODE_FONT, CODE_FONT_SIZE, CODE_GAP, CODE_MAX_CHARS, CODE_MAX_W, CODE_MIN_H, CODE_MIN_W, CODE_PAD, CODE_PANEL,
CODE_RADIUS, CODE_TEXT, CODE_WIDTH, CodeLanguage, Document, LayoutMode, LineHeight, ListStyle, NodeId, NodeKind, ParaList, Sizing, TextAlignH,
TextAutoResize, TextCase, TextData, TextDecoration,
};
use serde_json::{Value, json};
use super::items::{add, add_text, owner_of_text, soft_shadow, text_of};
use super::{Result, Session, bad, boolean, get, num, parent_of, req_string, req_targets, require, string, textedit};
/// How far from the page's middle a block may be put.
const CODE_MAX_COORD: f64 = 1.0e9;
/// Whether `text` is the text of a code block: what the text editor asks before it converts what
/// is typed (a list from `- `, and any smart punctuation or link to come).
pub fn is_code_text(doc: &Document, text: NodeId) -> bool {
owner_of_text(doc, text).and_then(|o| doc.node(o)).is_some_and(|n| matches!(n.board, Some(BoardItem::CodeBlock { .. })))
}
/// The auto layout every code block has: its text stacked inside the padding.
fn block_layout() -> AutoLayout {
AutoLayout { mode: LayoutMode::Vertical, gap: 0.0, padding: CODE_PAD, ..AutoLayout::default() }
}
/// A code block's frame and its text: `width` wide at `at` in `parent`, holding `text`.
fn make_code_block(doc: &mut Document, parent: NodeId, at: (f64, f64), width: f64, language: CodeLanguage, text: &str) -> Result<(NodeId, NodeId)> {
let frame = add(doc, parent, NodeKind::Frame, "Code block", at, (width, CODE_MIN_H), |n| {
n.fills = vec![Paint::solid(CODE_PANEL)];
n.corners.radii = [CODE_RADIUS; 4];
n.effects = vec![soft_shadow()];
n.clip = false;
n.layout = Some(block_layout());
n.child_layout.sizing_v = Sizing::Hug;
n.child_layout.min_h = Some(CODE_MIN_H);
n.child_layout.min_w = Some(CODE_MIN_W);
n.board = Some(BoardItem::CodeBlock { language });
})?;
let inner = width - CODE_PAD[1] - CODE_PAD[3];
let label = add_text(doc, frame, text, CODE_FONT_SIZE, CODE_TEXT, TextAlignH::Left, inner)?;
if let Some(NodeKind::Text(td)) = doc.node_mut(label).map(|n| &mut n.kind) {
td.style.font_family = CODE_FONT.into();
td.style.line_height = LineHeight::Percent(150.0);
td.features.insert("liga".into(), false);
td.features.insert("calt".into(), false);
}
Ok((frame, label))
}
/// A language from its id or name, or an error listing the ids.
fn language_of(cmd: &str, v: &str) -> Result<CodeLanguage> {
CodeLanguage::from_id(v).ok_or_else(|| {
let known: Vec<&str> = CodeLanguage::ALL.iter().map(|l| l.id()).collect();
bad(cmd, format!("unknown language `{v}` ({})", known.join("|")))
})
}
/// A coordinate from the params: given, it is a finite number within a billion of the origin.
fn coord(cmd: &str, p: &Value, key: &str, default: f64) -> Result<f64> {
let v = if get(p, key).is_none_or(Value::is_null) { Some(default) } else { num(p, key) };
v.filter(|v| v.is_finite() && v.abs() <= CODE_MAX_COORD).ok_or_else(|| bad(cmd, format!("`{key}` is a position within a billion of the origin")))
}
pub(super) fn code_block_cmd(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "board.codeBlock";
require(s, cmd)?;
let parent = parent_of(cmd, s, p)?;
let width = if get(p, "width").is_none_or(Value::is_null) {
CODE_WIDTH
} else {
num(p, "width")
.filter(|w| w.is_finite() && (CODE_MIN_W..=CODE_MAX_W).contains(w))
.ok_or_else(|| bad(cmd, format!("`width` is a size from {CODE_MIN_W} to {CODE_MAX_W}")))?
};
// The view's centre is on the page, and `x`/`y` are in the parent: a block in a section or
// frame takes the centre in that parent's coordinates (a parent that can't be inverted gives a
// non-finite centre, which `coord` refuses).
let (vx, vy) = {
let ds = s.ds()?;
let c = ds.doc.world_transform(parent).inverse() * figcraft_geom::Point::new(ds.view.cx, ds.view.cy);
(c.x, c.y)
};
let x = coord(cmd, p, "x", vx - width / 2.0)?;
let y = coord(cmd, p, "y", vy - CODE_MIN_H / 2.0)?;
let language = match string(p, "language") {
Some(v) => language_of(cmd, &v)?,
None if get(p, "language").is_none_or(Value::is_null) => CodeLanguage::default(),
None => return Err(bad(cmd, "`language` is a language id")),
};
let text = match get(p, "text") {
None | Some(Value::Null) => String::new(),
Some(Value::String(t)) => t.clone(),
Some(_) => return Err(bad(cmd, "`text` is a string")),
};
if text.chars().count() > CODE_MAX_CHARS {
return Err(bad(cmd, format!("`text` is at most {CODE_MAX_CHARS} characters")));
}
let (frame, label) = make_code_block(s.doc_mut()?, parent, (x, y), width, language, &text)?;
s.set_selection(vec![frame]);
if boolean(p, "edit") == Some(true) {
s.request_ui("board.editText", json!({"id": frame}));
}
Ok(json!({"id": frame, "text": label, "language": language.id()}))
}
pub(super) fn set_language(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "board.setLanguage";
require(s, cmd)?;
let language = language_of(cmd, &req_string(cmd, p, "language")?)?;
let targets = req_targets(cmd, s, p)?;
let doc = s.doc()?;
let blocks: BTreeSet<NodeId> = targets
.into_iter()
.map(|i| owner_of_text(doc, i).unwrap_or(i))
.filter(|i| doc.node(*i).is_some_and(|n| matches!(n.board, Some(BoardItem::CodeBlock { .. }))))
.collect();
if blocks.is_empty() {
return Err(bad(cmd, "select a code block"));
}
let doc = s.doc_mut()?;
for &b in &blocks {
if doc.node(b).is_some_and(|n| n.board != Some(BoardItem::CodeBlock { language })) {
doc.get_mut(b)?.board = Some(BoardItem::CodeBlock { language });
}
}
Ok(json!({"ids": blocks.into_iter().collect::<Vec<_>>()}))
}
/// `board.nextSticky` on code block `from`: the next one beside it, as wide and in the same
/// language, with no connector.
pub(super) fn next_block(s: &mut Session, from: NodeId, language: CodeLanguage, p: &Value) -> Result<Value> {
let cmd = "board.nextSticky";
let editing = s.ds()?.text_edit.is_some();
let doc = s.doc()?;
let n = doc.get(from)?;
let parent = n.parent.ok_or_else(|| bad(cmd, "that code block has no parent"))?;
let at = n.transform.translation();
let (w, h) = (n.width, n.height);
let (x, y) = match string(p, "side").as_deref().unwrap_or("right") {
"right" => (at.x + w + CODE_GAP, at.y),
"left" => (at.x - CODE_GAP - w, at.y),
"below" => (at.x, at.y + h + CODE_GAP),
"above" => (at.x, at.y - CODE_GAP - CODE_MIN_H),
other => return Err(bad(cmd, format!("`side` is right, below, left or above, not `{other}`"))),
};
if !(x.is_finite() && y.is_finite() && w.is_finite()) {
return Err(bad(cmd, "the next block can't be placed there"));
}
let width = w.clamp(CODE_MIN_W, CODE_MAX_W);
if editing {
textedit::end(s)?;
}
let (frame, label) = make_code_block(s.doc_mut()?, parent, (x, y), width, language, "")?;
s.set_selection(vec![frame]);
if boolean(p, "edit") == Some(true) {
s.request_ui("board.editText", json!({"id": frame}));
}
Ok(json!({"id": frame, "text": label, "language": language.id()}))
}
/// Whether `td` is already plain code: no list, indent, spacing, link, decoration, case change or
/// hand-made run, and a height that follows its lines.
fn is_plain(td: &TextData) -> bool {
td.auto_resize == TextAutoResize::Height
&& td.list == ListStyle::None
&& td.paragraphs == plain_paragraphs(&td.paragraphs)
&& td.paragraph_indent == 0.0
&& td.paragraph_spacing == 0.0
&& td.list_spacing == 0.0
&& td.style.link.is_none()
&& td.style.decoration == TextDecoration::None
&& td.style.decoration_look.is_none()
&& td.style.case == TextCase::Original
&& td.runs.is_empty()
}
/// `paragraphs` with no list, level or counting offset (the direction stays); empty when that
/// leaves every paragraph at its default.
fn plain_paragraphs(paragraphs: &[ParaList]) -> Vec<ParaList> {
let v: Vec<ParaList> = paragraphs.iter().map(|p| ParaList { direction: p.direction, ..ParaList::default() }).collect();
if v.iter().all(|p| *p == ParaList::default()) { Vec::new() } else { v }
}
fn make_plain(td: &mut TextData) {
td.auto_resize = TextAutoResize::Height;
td.list = ListStyle::None;
td.paragraphs = plain_paragraphs(&td.paragraphs);
td.paragraph_indent = 0.0;
td.paragraph_spacing = 0.0;
td.list_spacing = 0.0;
td.style.link = None;
td.style.decoration = TextDecoration::None;
td.style.decoration_look = None;
td.style.case = TextCase::Original;
td.runs.clear();
}
/// In the normalize pass, before text is measured and layout runs: every code block an edit
/// touched (or whose text it touched) is as tall as its lines again and holds plain code. Nothing
/// is written for a block already in that form, so a second pass changes nothing.
pub(crate) fn settle_code(doc: &mut Document, touched: &BTreeSet<NodeId>) {
let is_block = |doc: &Document, id: NodeId| doc.node(id).is_some_and(|n| matches!(n.board, Some(BoardItem::CodeBlock { .. })));
let mut blocks = BTreeSet::new();
for &id in touched {
if is_block(doc, id) {
blocks.insert(id);
} else if let Some(p) = doc.node(id).and_then(|n| n.parent).filter(|p| is_block(doc, *p)) {
blocks.insert(p);
}
}
for b in blocks {
// The frame's form is complete first: its layout and minimums (or it cannot hug) and a width that
// is not Hug (or its text cannot fill), else normalize puts them back every pass.
if let Some(n) = doc.node_mut(b) {
if n.layout.as_ref() != Some(&block_layout()) {
n.layout = Some(block_layout());
}
if n.child_layout.min_h != Some(CODE_MIN_H) {
n.child_layout.min_h = Some(CODE_MIN_H);
}
if n.child_layout.min_w != Some(CODE_MIN_W) {
n.child_layout.min_w = Some(CODE_MIN_W);
}
if n.child_layout.sizing_h == Sizing::Hug {
n.child_layout.sizing_h = Sizing::Fixed;
}
}
// A fixed height is not kept: the layout pass sizes the block to its lines again.
if doc.node(b).is_some_and(|n| n.child_layout.sizing_v != Sizing::Hug)
&& let Some(n) = doc.node_mut(b)
{
n.child_layout.sizing_v = Sizing::Hug;
}
let Some(t) = text_of(doc, b) else { continue };
let Some(node) = doc.node(t) else { continue };
let off = match &node.kind {
NodeKind::Text(td) => !is_plain(td),
_ => continue,
};
let fill_off = node.child_layout.sizing_h != Sizing::Fill;
if !(off || fill_off) {
continue;
}
if let Some(n) = doc.node_mut(t) {
if fill_off {
n.child_layout.sizing_h = Sizing::Fill;
}
if off && let NodeKind::Text(td) = &mut n.kind {
make_plain(td);
}
}
}
}
@@ -15,6 +15,7 @@ pub(crate) fn settle_text(doc: &mut Document, before: &Document, touched: &BTree
return;
}
crate::board_table::settle_resize(doc, before, touched);
super::code::settle_code(doc, touched);
for &id in touched {
let Some(n) = doc.node(id) else { continue };
if let Some(BoardItem::Shape { shape }) = n.board
+1 -1
View File
@@ -84,7 +84,7 @@ pub(super) fn set_color(s: &mut Session, p: &Value) -> Result<Value> {
n.strokes = vec![Paint::solid(line_shade(color))];
}
BoardItem::Connector(_) | BoardItem::Ink => doc.get_mut(id)?.strokes = vec![Paint::solid(line_shade(color))],
BoardItem::Label { .. } | BoardItem::Stamp { .. } | BoardItem::Table | BoardItem::MindNode => continue,
BoardItem::Label { .. } | BoardItem::Stamp { .. } | BoardItem::Table | BoardItem::MindNode | BoardItem::CodeBlock { .. } => continue,
}
changed.push(id);
}
+6 -3
View File
@@ -26,7 +26,7 @@ pub(super) fn add(
}
/// A soft shadow under stickies and stamps.
fn soft_shadow() -> Effect {
pub(super) fn soft_shadow() -> Effect {
Effect {
kind: EffectKind::DropShadow(Shadow { color: Color::new(0.0, 0.0, 0.0, 0.16), offset: (0.0, 2.0), radius: 6.0, ..Shadow::default() }),
visible: true,
@@ -142,14 +142,17 @@ pub(super) fn next_sticky(s: &mut Session, p: &Value) -> Result<Value> {
let from = id(p, "id")
.or_else(|| editing.and_then(|t| owner_of_text(doc, t)))
.or_else(|| s.selection().first().copied().map(|i| owner_of_text(doc, i).unwrap_or(i)))
.ok_or_else(|| EngineError::Disabled(cmd.into(), "select a sticky or a shape first".into()))?;
.ok_or_else(|| EngineError::Disabled(cmd.into(), "select a sticky, a shape or a code block first".into()))?;
let n = doc.get(from)?;
if let Some(BoardItem::CodeBlock { language }) = n.board {
return super::code::next_block(s, from, language, p);
}
if matches!(n.board, Some(BoardItem::Shape { .. })) {
// A shape gets the next one joined to it, as the "+" beside it makes (#1597).
return add_connected(s, p);
}
if !matches!(n.board, Some(BoardItem::Sticky { .. })) {
return Err(bad(cmd, "that isn't a sticky or a shape"));
return Err(bad(cmd, "that isn't a sticky, a shape or a code block"));
}
let color = n.fills.iter().find_map(Paint::solid_color).unwrap_or(s.tool.board.sticky);
let parent = n.parent.ok_or_else(|| bad(cmd, "that sticky has no parent"))?;
+19 -1
View File
@@ -87,6 +87,12 @@ fn text_of(s: &Session, id: NodeId) -> Result<TextData> {
}
}
/// Whether the text being edited is a code block's.
fn in_code(s: &Session) -> bool {
let Some(te) = s.ds().ok().and_then(|d| d.text_edit.as_ref()) else { return false };
s.doc().is_ok_and(|d| crate::board::is_code_text(d, te.id))
}
/// Start editing text node `id` with the caret at `caret` (None = select all).
pub fn begin(s: &mut Session, id: NodeId, caret: Option<usize>, created: bool) -> Result<()> {
let t = text_of(s, id)?;
@@ -282,13 +288,15 @@ fn insert_model(s: &mut Session, text: &str, ime_commit: bool) -> Result<ImeInse
// A commit the editor had to transform is an application edit, not a plain insertion.
let mut outcome = if normalized == text { ImeInsertion::Plain } else { ImeInsertion::Transformed };
let text = normalized;
// Code is typed as it is: no list from "- " (and no smart punctuation or link to come).
let code = in_code(s);
edit(s, |t, te| {
let (a, b) = range(te);
// "- ", "* ", "<number>. " or "1) " typed at the start of a plain paragraph starts a list
// (the creation characters of Create bulleted and numbered lists). As measured in Figma
// (2026-11-11), a typed "5. " starts the numbered list at 5 (there is no start-number
// field). "0. " and a bracket after a number other than 1 are not measured: plain text.
if text == " " && a == b && t.para_list(t.para_of(a)).list == ListStyle::None {
if !code && text == " " && a == b && t.para_list(t.para_of(a)).list == ListStyle::None {
let chars: Vec<char> = t.characters.chars().collect();
let start = line_start(&chars, a);
let typed: String = chars.get(start..a).unwrap_or(&[]).iter().collect();
@@ -463,6 +471,16 @@ pub fn key(s: &mut Session, key: &str, shift: bool, word: bool, line: bool) -> R
if matches!(key, "Tab" | "Backspace" | "Delete" | "Enter") && !word && !line && list_key(s, key, shift)? {
return Ok(());
}
// In a code block Tab types two spaces and Enter keeps the line's indent.
if matches!(key, "Tab" | "Enter") && !word && !line && in_code(s) {
if key == "Tab" {
return if shift { Ok(()) } else { insert(s, figcraft_doc::CODE_TAB) };
}
let (a, _) = range(&te);
let start = line_start(&chars, a);
let indent: String = chars.get(start..a).unwrap_or(&[]).iter().take(256).take_while(|c| matches!(c, ' ' | '\t')).collect();
return insert(s, &format!("\n{indent}"));
}
match key {
"Escape" => return end(s),
"Enter" => return insert(s, "\n"),
+1 -1
View File
@@ -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",
"{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",
true,
|s, p| {
let k = req_string("text.edit.key", p, "key")?;
+2
View File
@@ -208,6 +208,8 @@ mod batch_undo_snapshot_tests;
#[cfg(test)]
mod binding_lists_tests;
#[cfg(test)]
mod board_code_tests;
#[cfg(test)]
mod board_connected_tests;
#[cfg(test)]
mod board_connector_tests;
+1 -1
View File
@@ -153,7 +153,7 @@ fn has(app: &FigApp) -> Option<Has> {
}
Some(BoardItem::Label { .. } | BoardItem::MindNode) => h.text = true,
Some(BoardItem::Table) => h.table = true,
Some(BoardItem::Stamp { .. }) | None => {}
Some(BoardItem::Stamp { .. } | BoardItem::CodeBlock { .. }) | None => {}
}
}
h.only_lines = h.connector.is_some() && !others;
+4 -2
View File
@@ -1,6 +1,6 @@
# Boards parity
> **Last reviewed:** 2026-10-24 · **Last updated:** 2026-11-12 · **Change:** minor (a `.jam` file's shapes with text come in as native board shapes for the 23 kinds FigCraft draws, the other 7 as frames (#1808); a sticky has a text-size menu in the contextual bar, Small 16, Medium 24, Large 40, Extra large 64 and Huge 96, with Small the default (an earlier reading of 18 did not reproduce); `board.setStyle {fontSize}` sizes stickies and the sticky tool remembers the last size for new ones; the note grows taller at Huge and shrinks back, as measured in FigJam's web app, 2026-11-12; resizing a board table by height changes its rows, not blank space below them: a bottom or top edge grows the last row, a corner shares the change over every row, and a table keeps at least 40 per cell, measured in FigJam's web app, 2026-11-09 (#2172); a `.jam` file's stickies come in as native board stickies, with their colour, text and author kept and the size as saved (#1808); a sticky's text stays 18 and the note grows taller instead of the text shrinking, as measured in FigJam's web app (#2157); mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); a `.jam` elbowed connector saved with its path keeps it on import instead of being routed again (#1910); a "+" handle dragged carries the preview: the next shape is made where it is let go, or a connector joins the object it is let go on (#1919); a connector attached to a side starts 4 pt outside the border, so its stroke never lies on the fill (#1916); a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a connector end dropped along a side of a shape attaches to that side (#1708); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; a connector's bar sets its start and end points, dashes, weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); "+" handles beside a selected sticky or shape make the next one, joined by a connector (#1597); a FigJam `.jam` file opens as a board (#1342); board grid settings: dots, lines, graph paper or none, spacing, size and contrast; the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); templates and tables; facilitation: a shared timer and voting sessions; the dot grid, dragging a connector's end to re-attach it, curved connectors, elbows that go around what they join) · **Target:** the incumbent's whiteboard product (behaviour from its public help centre)
> **Last reviewed:** 2026-10-24 · **Last updated:** 2026-11-12 · **Change:** minor (code blocks, first step: a dark panel of monospace text as tall as its lines, in one of 16 languages (`board.codeBlock`, `board.setLanguage`, #2237); a `.jam` file's shapes with text come in as native board shapes for the 23 kinds FigCraft draws, the other 7 as frames (#1808); a sticky has a text-size menu in the contextual bar, Small 16, Medium 24, Large 40, Extra large 64 and Huge 96, with Small the default (an earlier reading of 18 did not reproduce); `board.setStyle {fontSize}` sizes stickies and the sticky tool remembers the last size for new ones; the note grows taller at Huge and shrinks back, as measured in FigJam's web app, 2026-11-12; resizing a board table by height changes its rows, not blank space below them: a bottom or top edge grows the last row, a corner shares the change over every row, and a table keeps at least 40 per cell, measured in FigJam's web app, 2026-11-09 (#2172); a `.jam` file's stickies come in as native board stickies, with their colour, text and author kept and the size as saved (#1808); a sticky's text stays 18 and the note grows taller instead of the text shrinking, as measured in FigJam's web app (#2157); mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); a `.jam` elbowed connector saved with its path keeps it on import instead of being routed again (#1910); a "+" handle dragged carries the preview: the next shape is made where it is let go, or a connector joins the object it is let go on (#1919); a connector attached to a side starts 4 pt outside the border, so its stroke never lies on the fill (#1916); a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a connector end dropped along a side of a shape attaches to that side (#1708); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; a connector's bar sets its start and end points, dashes, weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); "+" handles beside a selected sticky or shape make the next one, joined by a connector (#1597); a FigJam `.jam` file opens as a board (#1342); board grid settings: dots, lines, graph paper or none, spacing, size and contrast; the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); templates and tables; facilitation: a shared timer and voting sessions; the dot grid, dragging a connector's end to re-attach it, curved connectors, elbows that go around what they join) · **Target:** the incumbent's whiteboard product (behaviour from its public help centre)
**Breadth ~47%, ready ~29% (estimated, erring low).** A board is a FigCraft file of its own kind
(`file.newBoard`) with a dot grid on the page, sticky notes, shapes with text, connectors that
@@ -58,7 +58,8 @@ all end with the same geometry.
| Templates (retrospective, brainstorm, flow chart…) | partial | five built-in templates drawn up for FigCraft (retrospective, brainstorm, weekly planner, flow chart, kanban board), placed from the toolbar's templates picker (each with a picture of itself) or `board.template {name, x?, y?}` as ordinary sections, stickies, shapes, connectors and text in one undo step; `board.templates` lists them. No community templates, no saving your own |
| Tables | partial | `board.table {rows, columns, cells?, x?, y?}` (at most 50 × 20): an auto layout frame of rows of cells with text, a tinted header row and lines between rows and columns; a cell's row grows with its text; resizing a table by its bottom edge or its height grows the last row and a corner drag shares the change equally over every row and column (a side drag changes no row), the table keeps hugging its rows and a cell keeps at least 40 each way (measured in FigJam's web app, 2026-11-09: its floor is about 52, FigCraft's is 40, and its right edge grows only the last column); a double-click types in the cell under the pointer; add or remove a row or column from the bar over the selection or `board.tableEdit {id, action, index?}`; cells copied from a spreadsheet (tab-separated text, quoted cells kept whole) paste as a table, up to 50 × 20 with a note when there was more; undoable and synced in live sessions. No per-column widths yet (a width change splits equally), no column resizing by dragging, no cell colours, no Tab between cells; comma-separated text pastes as text |
| Mind maps | partial | from commands only so far (#2226): `board.mindMap {x?, y?, text?, children?}` places a first node (bold, no box) with three children on its right, joined by curved branches; `board.mindMapAdd {id?, relation?: child\|sibling}` adds a node. Nodes are text that grows wider as it is typed and taller with line breaks; a node's children stand in one column 88 units right of the widest node of its own column, 48 apart, centred on it, and the map lays itself out again in the normalize pass after every edit, undo and live-session change; moving the first node moves the map; a deleted node's children stay where they are without their branch. Branches are board connectors (`branch`: stroke 4, #757575, round caps), so their style, end points, weight and colour change like any connector's. No toolbar entry, shortcuts, "+" handles, dragging a node onto another, left side or `.jam` import yet |
| Washi tape, code blocks, image cropping on boards | missing | images can be placed as in design files |
| Code blocks | partial | from commands only so far (#2237): `board.codeBlock {x?, y?, language?, text?, width?}` places a dark panel holding monospace text (Liberation Mono 16 on a 24 line where it is embedded or installed), 576 wide; its height is its lines (32 + 24 a line, wrapped lines counted, never under four lines) and only its width can be changed (210 at least); `board.setLanguage {id?, language}` keeps one of 16 languages (TypeScript by default); `board.nextSticky` on a block makes the next one 128 to its right, as wide and in the same language. In a block Tab types two spaces, Enter keeps the line's indent, and lists, links and styled ranges don't apply. No toolbar entry, language menu, highlighting colours, line numbers or `.jam` import yet |
| Washi tape, image cropping on boards | missing | images can be placed as in design files |
| Audio and huddles | missing | |
| AI features (summaries, sorting stickies, generating boards) | missing | |
| Grid on the page | done | the canvas render draws it after the page colour and before the layers (`figcraft_render::Dots`), so objects cover it. Dots by default, or lines, graph paper (a strong line every 2–12 cells over fainter ones, like Japanese section paper) or none; spacing (4–512), mark size and contrast are settings kept with the preferences (`board.grid`; Preferences ▸ Board grid). Zoomed out it thins out (dots and lines by halves, graph paper down to its strong lines) until the marks are at least 14 points apart (10 for lines), the marks the next step drops fading out first; dots stay about a point and a half across on screen (1 to 3 points), scaled by the size setting. Dark marks on a light page, light ones on a dark page, from the theme's ink; written straight into the image, no allocation per mark, a crossing of two lines blended once; never in exports. FigCraft's own settings: the incumbent's board grid has none |
@@ -68,6 +69,7 @@ all end with the same geometry.
| Date | Change | Summary |
|---|---|---|
| 2026-11-11 | minor | M12, #2237 (step 1 of 4): code blocks in the document and engine. A code block is a board object of its own (`BoardItem::CodeBlock { language }`): a hugging frame holding one monospace text, 576 wide, 32 + 24 a visual line tall and never under four lines; only its width is kept from a resize. `board.codeBlock` places one, `board.setLanguage` picks one of 16 languages, and `board.nextSticky` makes the next block beside it. The normalize pass keeps a block's text plain code (`board::settle_code`) and the text editor types literally in it (two spaces for Tab, the line's indent after Enter, no list from `- `). The colours are FigCraft's own (the board's ink and tints); the sizes are from a FigJam measurement. Tests: `board_code_tests` in doc (four) and engine (thirteen). Numbers unchanged (no toolbar entry yet). |
| 2026-11-13 | patch | Rows that recent merges had duplicated or garbled are merged back into one row each (no behaviour change): Shapes with text, Connectors, Create the next shape already connected. |
| 2026-11-12 | minor | M12: a sticky's text-size menu. Measured in FigJam's web app, 2026-11-12: the menu lists Small 16, Medium 24, Large 40, Extra large 64 and Huge 96 (typing 40 shows Large), a fresh sticky is Small = 16 (read twice from the size field; the 18 of 2026-11-09 did not reproduce), the note stays square to Extra large and grows taller at Huge with the same width and shrinks back at Large, choosing a size with two stickies selected sets both, and the sticky tool remembers the last size. `STICKY_TEXT_SIZE` is 16, `STICKY_SIZES` holds the table, `board.setStyle {fontSize}` sizes stickies and sets the tool's size, `board.sticky` takes `fontSize`, and the contextual bar shows a size menu when only stickies carry text (shapes keep S/M/L/XL, unmeasured). Stacks are still missing. Tests: `a_new_sticky_is_small_16`, `the_sticky_sizes_are_figjams`, `set_style_font_size_sizes_every_selected_sticky`, `the_sticky_tool_remembers_the_last_size`, `a_huge_sticky_grows_taller_and_shrinks_back`, `a_selected_sticky_has_a_size_menu_instead_of_the_size_cells` |
| 2026-11-09 | minor | M12, #2172: a board table's height change goes into its rows. Measured in FigJam's web app, 2026-11-09 (a table has no lock-proportions control and never scales proportionally): a bottom-edge drag grows only the last row, a corner drag shares the change equally over every row and column, text keeps its size, and a table stops shrinking at about 52 per cell with a row never shorter than its wrapped text. FigCraft already split a width change equally (every cell fills); the bug was height: a bottom or corner resize turned the table from hugging to fixed height, so the rows stayed at 40 with blank space below them (or were clipped when shrunk) and typing no longer grew the table. `board_table::settle_resize`, called first in the normalize pass, finds a table left at a fixed height, puts the change into the rows' minimum height (the last row, or every row when both axes changed), raises a width that is too narrow to `columns x 40`, and returns the table to hugging, so every route (drag, `node.set`, `transform.resize`, MCP, live-session peers) gives the same result, in one undo step. FigCraft's floor is 40 (FigJam's is about 52) and there are no per-column widths yet: a side drag of the right edge still splits equally where FigJam grows only the last column. Numbers unchanged. Tests: `board_tables_tests` (the bottom, corner and side drags, the floor, typing after a resize and undo, live sessions, junk). |
+3 -2
View File
File diff suppressed because one or more lines are too long
+14 -1
View File
@@ -499,7 +499,7 @@ Returns `{fitted: [{id, fontSize, lines, fits, orphan}]}`. Use case: a carousel
A board is a file of its own kind for thinking together: `file.newBoard {name?}` opens one (its
page is light; `inspect_document` says `kind: "board"`). Board objects are ordinary layers with a
`board` entry `get_node` shows (`{type: sticky|shape|connector|label|stamp|ink|mindNode, …}`; a connector may say
`board` entry `get_node` shows (`{type: sticky|shape|connector|label|stamp|ink|mindNode|codeBlock, …}`; a connector may say
`branch: true`), so the usual
commands move, resize, recolour, copy, delete and undo them. On a design file the board commands
refuse; on a board `proto.*`, `dev.*`, `view.prototype` and `view.devMode` refuse. Each of these is
@@ -513,6 +513,8 @@ one undo step and returns the ids it made:
same colour beside the selected (or edited) one; with `edit: true` the app goes on typing in it
(`Shift+Cmd/Ctrl+Enter` in the app does both). On a shape it does what `board.addConnected` does:
the next shape, joined to it by a connector (`{id, text, connector}`).
On a code block it makes the next code block 128 units beside it (`side`, default right), as wide and
in the same language, not joined (`{id, text, language}`).
- `board.addConnected {id?, side?: right|below|left|above, edit?}` → `{id, text, connector}`: the
next sticky or shape of the same kind, size and colour on that side of the selected (or edited)
one, 80 units away, joined to it by a connector the way the Connector tool makes one; one undo
@@ -533,6 +535,17 @@ one undo step and returns the ids it made:
of the map that the given (or selected, or edited) one belongs to: a child below its other
children, or a sibling right after it (the first node has none); the map lays itself out again.
One undo step. With `edit: true` the app goes on typing in it.
- `board.codeBlock {x?, y?, language?, text?, width?, parent?, edit?}` → `{id, text, language}`: a code
block (`codeBlock` with its `language`): a dark panel holding monospace text (Liberation Mono 16 on a
24 line where it is embedded or installed). `language` is `bash cpp css go graphql html javascript json
kotlin plainText python ruby rust sql swift typescript` (default `typescript`); `width` is 210 to 100000
(default 576); `x`/`y` are its top-left corner, by default the view's centre less half the width and less 64 (half the
smallest height, 128), so a block of more lines reaches further down. Its height is its lines: 32 + 24 a visual line,
never under four lines, so only its width can be changed (a set or dragged height is not kept). In its
text Tab types two spaces, Enter keeps the line's indent, and lists, links and styled ranges do not stick.
One undo step.
- `board.setLanguage {id?, ids?, language}` → `{ids}`: the language of the given (or selected, or edited)
code blocks, by id or name (`cpp` or `C++`).
- `board.shape {shape, x, y, width?, height?, text?, color?, parent?}` → `{id, text}`: a shape with centred,
wrapping text: `rectangle roundedRectangle ellipse diamond triangle triangleDown parallelogramRight parallelogramLeft trapezoid pentagon hexagon octagon star plus arrowLeft arrowRight chevron speechBubble database document predefinedProcess manualInput internalStorage`.
- `board.connector {from, to, fromSide?, toSide?, fromAt?, toAt?, style?: straight|elbow|curved, startCap?, endCap?, label?}`
+2 -1
View File
File diff suppressed because one or more lines are too long