Merge pull request #2669 from storytold/fix/2237-code-highlight

M12: boards: code blocks colour keywords, strings, numbers and comments by their language (#2237, step 3)
This commit is contained in:
BFlat authored and GitHub committed 2026-11-28 09:26:48 +07:00
commit 771d48cd8b
5 files changed
+376 -16

No files matched your search

+207 -2
View File
@@ -1,5 +1,6 @@
//! 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`]).
//! Code blocks (#2237): the languages a block is highlighted as, the numbers of its look, and
//! which stretches of its code are keywords, strings, numbers and comments. Pure data: the engine
//! makes the block ([`crate::BoardItem::CodeBlock`]) and colours its text.
use figcraft_color::Color;
use serde::{Deserialize, Serialize};
@@ -116,3 +117,207 @@ pub const CODE_TEXT: Color = Color::from_rgb8_const(0xE3, 0xE1, 0xDD);
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
}
/// What a stretch of code is, for its colour.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CodeToken {
Keyword,
String,
Number,
Comment,
}
impl CodeToken {
/// Its colour on the panel (FigCraft's own, each at least 4.5:1 on [`CODE_PANEL`]).
pub fn color(self) -> Color {
match self {
CodeToken::Keyword => Color::from_rgb8_const(0x86, 0xB0, 0xFF),
CodeToken::String => Color::from_rgb8_const(0xA3, 0xD9, 0x8F),
CodeToken::Number => Color::from_rgb8_const(0xF5, 0xC5, 0x6E),
CodeToken::Comment => Color::from_rgb8_const(0x9C, 0x9C, 0x9C),
}
}
}
/// How a language writes keywords, comments and strings.
#[derive(Clone, Copy)]
struct Syntax {
/// Its keywords, apart by spaces.
keywords: &'static str,
/// Keywords in any case (SQL).
any_case: bool,
/// What starts a comment to the end of the line.
line: &'static [&'static str],
/// Stretches from an opening to a closing mark, over lines.
blocks: &'static [(&'static str, &'static str, CodeToken)],
/// What opens and closes a string on one line.
quotes: &'static [char],
/// Markup: the name after `<` or `</` is a keyword, and quotes are strings only inside a tag.
tags: bool,
}
const PLAIN: Syntax = Syntax { keywords: "", any_case: false, line: &[], blocks: &[], quotes: &[], tags: false };
const C_BLOCK: (&str, &str, CodeToken) = ("/*", "*/", CodeToken::Comment);
const TRIPLE: (&str, &str, CodeToken) = ("\"\"\"", "\"\"\"", CodeToken::String);
const BACKTICK: (&str, &str, CodeToken) = ("`", "`", CodeToken::String);
const BOTH_QUOTES: &[char] = &['"', '\''];
const JS: &str = "async await break case catch class const continue debugger default delete do else export extends false finally for from function if import in instanceof let new null of return static super switch this throw true try typeof undefined var void while yield";
const TS: &str = "abstract any as async await boolean break case catch class const continue debugger declare default delete do else enum export extends false finally for from function if implements import in instanceof interface keyof let namespace never new null number of private protected public readonly return static string super switch this throw true try type typeof undefined unknown var void while yield";
/// A language with `//` and `/* */` comments, and `blocks` beside them.
const fn c_like(keywords: &'static str, quotes: &'static [char], blocks: &'static [(&'static str, &'static str, CodeToken)]) -> Syntax {
Syntax { keywords, line: &["//"], blocks, quotes, ..PLAIN }
}
impl CodeLanguage {
fn syntax(self) -> Syntax {
match self {
CodeLanguage::PlainText => PLAIN,
CodeLanguage::Bash => Syntax {
keywords: "alias break case continue declare do done elif else esac exit export false fi for function if in local readonly return select shift source then true unset until while",
line: &["#"],
quotes: BOTH_QUOTES,
..PLAIN
},
CodeLanguage::Cpp => c_like(
"auto bool break case catch char class const constexpr continue default define delete do double else enum explicit extern false float for friend goto if include inline int long mutable namespace new noexcept nullptr operator private protected public return short signed sizeof static struct switch template this throw true try typedef typename union unsigned using virtual void volatile while",
BOTH_QUOTES,
&[C_BLOCK],
),
CodeLanguage::Css => Syntax { keywords: "import important keyframes media supports", blocks: &[C_BLOCK], quotes: BOTH_QUOTES, ..PLAIN },
CodeLanguage::Go => c_like(
"break case chan const continue default defer else fallthrough false for func go goto if import interface iota map nil package range return select struct switch true type var",
BOTH_QUOTES,
&[C_BLOCK, BACKTICK],
),
CodeLanguage::Graphql => Syntax {
keywords: "directive enum extend false fragment implements input interface mutation null on query scalar schema subscription true type union",
line: &["#"],
blocks: &[TRIPLE],
quotes: &['"'],
..PLAIN
},
CodeLanguage::Html => Syntax { blocks: &[("<!--", "-->", CodeToken::Comment)], quotes: BOTH_QUOTES, tags: true, ..PLAIN },
CodeLanguage::Javascript => c_like(JS, BOTH_QUOTES, &[C_BLOCK, BACKTICK]),
CodeLanguage::Typescript => c_like(TS, BOTH_QUOTES, &[C_BLOCK, BACKTICK]),
CodeLanguage::Json => Syntax { keywords: "false null true", quotes: &['"'], ..PLAIN },
CodeLanguage::Kotlin => c_like(
"as break by class companion continue data do else enum false for fun if import in init interface internal is null object open override package private protected public return sealed super suspend this throw true try typealias val var when while",
BOTH_QUOTES,
&[C_BLOCK, TRIPLE],
),
CodeLanguage::Python => Syntax {
keywords: "False None True and as assert async await break class continue def del elif else except finally for from global if import in is lambda nonlocal not or pass raise return self try while with yield",
line: &["#"],
blocks: &[TRIPLE, ("'''", "'''", CodeToken::String)],
quotes: BOTH_QUOTES,
..PLAIN
},
CodeLanguage::Ruby => Syntax {
keywords: "alias and begin break case class def defined do else elsif end ensure false for if in module next nil not or redo require rescue retry return self super then true undef unless until when while yield",
line: &["#"],
quotes: BOTH_QUOTES,
..PLAIN
},
// Only double quotes: a single one also starts a lifetime.
CodeLanguage::Rust => c_like(
"Self as async await break const continue crate dyn else enum extern false fn for if impl in let loop match mod move mut pub ref return self static struct super trait true type unsafe use where while",
&['"'],
&[C_BLOCK],
),
CodeLanguage::Sql => Syntax {
keywords: "all alter and as asc between by case count create default delete desc distinct drop else end exists foreign from full group having in index inner insert into is join key left like limit not null offset on or order outer primary references right select set table then union update values when where",
any_case: true,
line: &["--"],
blocks: &[C_BLOCK],
quotes: &['\''],
..PLAIN
},
CodeLanguage::Swift => c_like(
"Self as associatedtype break case catch class continue default defer do else enum extension fallthrough false for func guard if import in init inout internal is let nil operator private protocol public repeat rethrows return self static struct subscript super switch throw throws true try typealias var where while",
&['"'],
&[C_BLOCK, TRIPLE],
),
}
}
}
/// Where a Rust character literal opening at `i` ends (`'a'`, `'\n'`, `'\u{1F600}'`), or `None`
/// for a lifetime (`'a`), whose quote opens nothing.
fn rust_char(chars: &[char], i: usize) -> Option<usize> {
let close = if chars.get(i + 1) == Some(&'\\') { (i + 3..(i + 12).min(chars.len())).find(|&j| chars.get(j) == Some(&'\''))? } else { i + 2 };
(chars.get(close) == Some(&'\'') && !chars.get(i + 1..close)?.contains(&'\n')).then_some(close + 1)
}
/// The stretches of `text` that `language` colours, as char ranges (end exclusive), in order and
/// apart: keywords, strings (a quoted one ends with its line), numbers and comments. Plain text
/// colours nothing.
pub fn code_tokens(language: CodeLanguage, text: &str) -> Vec<(usize, usize, CodeToken)> {
if language == CodeLanguage::PlainText {
return Vec::new();
}
let syn = language.syntax();
let chars: Vec<char> = text.chars().collect();
let n = chars.len();
let at = |i: usize, mark: &str| mark.chars().enumerate().all(|(k, c)| chars.get(i + k) == Some(&c));
let word = |c: char| c.is_alphanumeric() || c == '_';
let mut out = Vec::new();
let (mut i, mut in_tag) = (0, false);
while let Some(&c) = chars.get(i) {
let prev = i.checked_sub(1).and_then(|p| chars.get(p)).copied();
let next = if let Some(&(open, close, token)) = syn.blocks.iter().find(|(open, ..)| at(i, open)) {
let from = i + open.chars().count();
// A string's closing mark escaped by a backslash doesn't close it.
let escaped = |j: usize| token == CodeToken::String && j.checked_sub(1).and_then(|p| chars.get(p)) == Some(&'\\');
let end = (from..n).find(|&j| at(j, close) && !escaped(j)).map_or(n, |j| j + close.chars().count());
out.push((i, end, token));
end
} else if syn.line.iter().any(|m| at(i, m))
&& (c != '#' || language != CodeLanguage::Bash || prev.is_none_or(|p| p.is_whitespace() || ";|&()".contains(p)))
{
// In Bash a `#` starts a comment only at the start of a word, after a space or an
// operator (`$#` and `a#b` are not).
let end = (i..n).find(|&j| chars.get(j) == Some(&'\n')).unwrap_or(n);
out.push((i, end, CodeToken::Comment));
end
} else if let Some(end) = (language == CodeLanguage::Rust && c == '\'').then(|| rust_char(&chars, i)).flatten() {
out.push((i, end, CodeToken::String));
end
} else if syn.quotes.contains(&c) && (!syn.tags || in_tag) {
let mut j = i + 1;
while let Some(&d) = chars.get(j).filter(|d| **d != c && **d != '\n') {
// An escape skips the next character, but never the end of the line.
j += if d == '\\' && chars.get(j + 1).is_some_and(|e| *e != '\n') { 2 } else { 1 };
}
let end = if chars.get(j) == Some(&c) { j + 1 } else { j.min(n) };
out.push((i, end, CodeToken::String));
end
} else if c.is_ascii_digit() && !prev.is_some_and(word) && !syn.tags {
let mut j = i + 1;
while chars.get(j).is_some_and(|d| word(*d) || (*d == '.' && chars.get(j + 1).is_some_and(char::is_ascii_digit))) {
j += 1;
}
out.push((i, j, CodeToken::Number));
j
} else if word(c) && !c.is_ascii_digit() {
let mut j = i + 1;
while chars.get(j).is_some_and(|d| word(*d)) {
j += 1;
}
let w: String = chars.get(i..j).unwrap_or(&[]).iter().collect();
let tag_name = syn.tags && (prev == Some('<') || (prev == Some('/') && i.checked_sub(2).and_then(|p| chars.get(p)) == Some(&'<')));
let keyword = syn.keywords.split_whitespace().any(|k| if syn.any_case { k.eq_ignore_ascii_case(&w) } else { k == w });
if tag_name || keyword {
out.push((i, j, CodeToken::Keyword));
}
j
} else {
if syn.tags && (c == '<' || c == '>') {
in_tag = c == '<';
}
i + 1
};
i = next;
}
out
}
+90 -1
View File
@@ -3,7 +3,7 @@
use serde_json::json;
use crate::BoardItem;
use crate::board_code::{CODE_MIN_H, CODE_PAD, CODE_PANEL, CODE_TEXT, CodeLanguage, code_height};
use crate::board_code::{CODE_MIN_H, CODE_PAD, CODE_PANEL, CODE_TEXT, CodeLanguage, CodeToken, code_height, code_tokens};
#[test]
fn sixteen_languages_by_name_with_typescript_the_default() {
@@ -56,3 +56,92 @@ fn the_height_is_32_and_24_a_line_from_four_lines_up() {
fn plain_code_reads_on_the_panel() {
assert!(CODE_TEXT.contrast(CODE_PANEL) >= 4.5, "{}", CODE_TEXT.contrast(CODE_PANEL));
}
/// The tokens of `text` in `language`, as the text they cover.
fn tokens(language: CodeLanguage, text: &str) -> Vec<(String, CodeToken)> {
code_tokens(language, text).into_iter().map(|(a, b, t)| (text.chars().skip(a).take(b - a).collect(), t)).collect()
}
fn want(v: &[(&str, CodeToken)]) -> Vec<(String, CodeToken)> {
v.iter().map(|(s, t)| ((*s).to_string(), *t)).collect()
}
#[test]
fn keywords_strings_numbers_and_comments_per_language() {
use CodeLanguage::*;
use CodeToken::*;
// A keyword inside a string or a comment is part of it.
assert_eq!(
tokens(
Rust,
"fn main() { let s = \"fn\"; // fn here
x = 4.2; }"
),
want(&[("fn", Keyword), ("let", Keyword), ("\"fn\"", String), ("// fn here", Comment), ("4.2", Number)])
);
assert_eq!(tokens(Python, "def f(): # note"), want(&[("def", Keyword), ("# note", Comment)]));
assert_eq!(tokens(Sql, "SELECT name FROM t -- all"), want(&[("SELECT", Keyword), ("FROM", Keyword), ("-- all", Comment)]));
// A quoted string ends with its line; a block comment runs over lines.
assert_eq!(
tokens(
Typescript,
"const a = 'open
let b /* x
y */"
),
want(&[
("const", Keyword),
("'open", String),
("let", Keyword),
(
"/* x
y */",
Comment
)
])
);
// Markup: tag names, quotes only inside a tag (an apostrophe in the text is none).
assert_eq!(
tokens(Html, "<a href=\"x\">don't</a> <!-- c -->"),
want(&[("a", Keyword), ("\"x\"", String), ("a", Keyword), ("<!-- c -->", Comment)])
);
// `#` starts a comment only at the start of a word.
assert_eq!(tokens(Bash, "echo $# a#b # c"), want(&[("# c", Comment)]));
assert!(tokens(PlainText, "fn \"x\" 1 // y").is_empty());
// Python's `#` needs no space before it; an escaped line end still ends a quoted string.
assert_eq!(tokens(Python, "x=1# return \"x\""), want(&[("1", Number), ("# return \"x\"", Comment)]));
assert_eq!(tokens(Json, "\"open\\\ntrue"), want(&[("\"open\\", String), ("true", Keyword)]));
// An escaped backtick doesn't end a template string; a `#` after a Bash operator starts a comment.
assert_eq!(
tokens(Javascript, "const s = `a\\`b`; const n = 1;"),
want(&[("const", Keyword), ("`a\\`b`", String), ("const", Keyword), ("1", Number)])
);
assert_eq!(tokens(Bash, "echo ok;# if true"), want(&[("# if true", Comment)]));
// Rust: a character literal is a string, and a lifetime's quote opens nothing.
assert_eq!(
tokens(Rust, "let q = '\"'; let n = '\\n'; fn f<'a>(x: &'a str) {}"),
want(&[("let", Keyword), ("'\"'", String), ("let", Keyword), ("'\\n'", String), ("fn", Keyword)])
);
// In every language the stretches are in order, apart and inside the text, even unclosed.
let text = "if (x) { y = \"a\\\"b\" + 'c' + `d` /* e */ // f
# g
-- h
<i j=\"k\"> 1.5 0x1F \"\"\" l";
let n = text.chars().count();
for l in CodeLanguage::ALL {
let v = code_tokens(l, text);
assert!(v.iter().all(|(a, b, _)| a < b && *b <= n), "{l:?}: {v:?}");
assert!(v.windows(2).all(|w| w[0].1 <= w[1].0), "{l:?}: {v:?}");
}
}
#[test]
fn highlight_colours_read_on_the_panel_and_differ() {
let all = [CodeToken::Keyword, CodeToken::String, CodeToken::Number, CodeToken::Comment];
for t in all {
assert!(t.color().contrast(CODE_PANEL) >= 4.5, "{t:?}: {}", t.color().contrast(CODE_PANEL));
assert_ne!(t.color(), CODE_TEXT, "{t:?}");
}
let distinct: std::collections::BTreeSet<String> = all.iter().map(|t| t.color().to_hex()).collect();
assert_eq!(distinct.len(), all.len());
}
+47 -1
View File
@@ -3,7 +3,7 @@
use figcraft_color::{Color, Paint};
use figcraft_doc::{
BoardItem, CODE_FONT, CODE_MAX_CHARS, CodeLanguage, EffectKind, FileKind, LayoutMode, LineHeight, ListStyle, NodeId, NodeKind, Sizing,
BoardItem, CODE_FONT, CODE_MAX_CHARS, CodeLanguage, CodeToken, EffectKind, FileKind, LayoutMode, LineHeight, ListStyle, NodeId, NodeKind, Sizing,
TextAlignH, TextAutoResize, TextCase, TextData, TextDecoration,
};
use figcraft_geom::Rect;
@@ -442,6 +442,52 @@ fn lists_links_and_styled_ranges_do_not_stick() {
}
}
#[test]
fn keywords_strings_numbers_and_comments_take_their_colours() {
// Step 3: the text is coloured as its language writes it, through its runs' fills, so the
// canvas and every export show it.
let mut s = board();
let (f, t) = block(
&mut s,
json!({"x": 0, "y": 0, "text": "const n = 1; // one
let s = \"two\";"}),
);
let fill_at = |s: &Session, word: &str| {
let d = td(s, f);
let i = d.characters.find(word).map(|b| d.characters[..b].chars().count()).unwrap_or_else(|| panic!("no {word:?}"));
d.style_at(i).fills.clone()
};
let colour = |t: CodeToken| Some(vec![Paint::solid(t.color())]);
for (word, token) in [
("const", CodeToken::Keyword),
("let", CodeToken::Keyword),
("1", CodeToken::Number),
("// one", CodeToken::Comment),
("\"two\"", CodeToken::String),
] {
assert_eq!(fill_at(&s, word), colour(token), "{word}");
}
assert_eq!(fill_at(&s, "n ="), None, "a name keeps the text's own colour");
assert!(td(&s, f).runs.iter().all(|r| r.style.font_family == CODE_FONT), "the runs keep the code font");
// A second pass over the coloured block 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);
// Plain text colours nothing; back in TypeScript, an edit is coloured again.
s.execute("board.setLanguage", &json!({"id": f, "language": "plainText"})).unwrap();
assert!(td(&s, f).runs.is_empty());
s.execute("board.setLanguage", &json!({"id": f, "language": "typescript"})).unwrap();
s.execute("text.set", &json!({"id": t, "characters": "return 2"})).unwrap();
assert_eq!((fill_at(&s, "return"), fill_at(&s, "2")), (colour(CodeToken::Keyword), colour(CodeToken::Number)));
// The same word is a keyword in one language and a name in another.
s.execute("board.setLanguage", &json!({"id": f, "language": "sql"})).unwrap();
assert_eq!(fill_at(&s, "return"), None);
}
#[test]
fn saved_files_live_sessions_and_a_second_pass() {
let mut s = board();
+29 -10
View File
@@ -8,8 +8,8 @@ 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,
CODE_RADIUS, CODE_TEXT, CODE_WIDTH, CodeLanguage, Document, LayoutMode, LineHeight, ListStyle, NodeId, NodeKind, ParaList, Sizing, StyleRun,
TextAlignH, TextAutoResize, TextCase, TextData, TextDecoration, TextStyle, code_tokens,
};
use serde_json::{Value, json};
@@ -165,9 +165,27 @@ pub(super) fn next_block(s: &mut Session, from: NodeId, language: CodeLanguage,
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 {
/// The runs that colour `td`'s keywords, strings, numbers and comments as `language` writes them:
/// its own style with the token's fill, touching runs of one colour merged.
fn highlight(td: &TextData, language: CodeLanguage) -> Vec<StyleRun> {
let mut runs: Vec<StyleRun> = Vec::new();
for (start, end, token) in code_tokens(language, &td.characters) {
let fills = Some(vec![Paint::solid(token.color())]);
// A run like the text's own style would be dropped as no run at all.
if fills == td.style.fills {
continue;
}
match runs.last_mut() {
Some(last) if last.end == start && last.style.fills == fills => last.end = end,
_ => runs.push(StyleRun { start, end, style: TextStyle { fills, ..td.style.clone() } }),
}
}
runs
}
/// Whether `td` is already plain code, coloured as `language`: no list, indent, spacing, link,
/// decoration, case change or hand-made run, and a height that follows its lines.
fn is_plain(td: &TextData, language: CodeLanguage) -> bool {
td.auto_resize == TextAutoResize::Height
&& td.list == ListStyle::None
&& td.paragraphs == plain_paragraphs(&td.paragraphs)
@@ -178,7 +196,7 @@ fn is_plain(td: &TextData) -> bool {
&& td.style.decoration == TextDecoration::None
&& td.style.decoration_look.is_none()
&& td.style.case == TextCase::Original
&& td.runs.is_empty()
&& td.runs == highlight(td, language)
}
/// `paragraphs` with no list, level or counting offset (the direction stays); empty when that
@@ -188,7 +206,7 @@ fn plain_paragraphs(paragraphs: &[ParaList]) -> Vec<ParaList> {
if v.iter().all(|p| *p == ParaList::default()) { Vec::new() } else { v }
}
fn make_plain(td: &mut TextData) {
fn make_plain(td: &mut TextData, language: CodeLanguage) {
td.auto_resize = TextAutoResize::Height;
td.list = ListStyle::None;
td.paragraphs = plain_paragraphs(&td.paragraphs);
@@ -199,7 +217,7 @@ fn make_plain(td: &mut TextData) {
td.style.decoration = TextDecoration::None;
td.style.decoration_look = None;
td.style.case = TextCase::Original;
td.runs.clear();
td.runs = highlight(td, language);
}
/// In the normalize pass, before text is measured and layout runs: every code block an edit
@@ -238,10 +256,11 @@ pub(crate) fn settle_code(doc: &mut Document, touched: &BTreeSet<NodeId>) {
{
n.child_layout.sizing_v = Sizing::Hug;
}
let Some(BoardItem::CodeBlock { language }) = doc.node(b).and_then(|n| n.board.clone()) else { continue };
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),
NodeKind::Text(td) => !is_plain(td, language),
_ => continue,
};
let fill_off = node.child_layout.sizing_h != Sizing::Fill;
@@ -253,7 +272,7 @@ pub(crate) fn settle_code(doc: &mut Document, touched: &BTreeSet<NodeId>) {
n.child_layout.sizing_h = Sizing::Fill;
}
if off && let NodeKind::Text(td) = &mut n.kind {
make_plain(td);
make_plain(td, language);
}
}
}
+3 -2
View File
@@ -1,6 +1,6 @@
# Boards parity
> **Last reviewed:** 2026-10-24 · **Last updated:** 2026-11-27 · **Change:** minor (the ink colour and stroke weight of the Marker, Highlighter and Pencil are chosen before drawing, in a bar above the toolbar (#2395); mind maps from the toolbar and the keyboard: Shapes ▸ Mind map places one with a click, Cmd/Ctrl+Enter adds a child and Shift+Cmd/Ctrl+Enter a sibling, Tab goes to the next sibling (#2226); 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)
> **Last reviewed:** 2026-10-24 · **Last updated:** 2026-11-28 · **Change:** minor (code blocks colour keywords, strings, numbers and comments by their language (#2237); the ink colour and stroke weight of the Marker, Highlighter and Pencil are chosen before drawing, in a bar above the toolbar (#2395); mind maps from the toolbar and the keyboard: Shapes ▸ Mind map places one with a click, Cmd/Ctrl+Enter adds a child and Shift+Cmd/Ctrl+Enter a sibling, Tab goes to the next sibling (#2226); 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 ~48%, ready ~30% (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,7 @@ 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 | Shapes ▸ Mind map in the toolbar, then a click: a first node (bold, no box) whose text starts at the click, with three children on its right joined by curved branches, and typing starts in the first node (#2226). Cmd/Ctrl+Enter on a node, selected or being typed in, adds a child below its other children; Shift+Cmd/Ctrl+Enter adds a sibling right after it (the first node has none); both go on typing in the new node. Tab and Shift+Tab select the next and previous sibling; Enter types in the selected node. The bar over a node sets its text colour and size; over a branch its colour, start and end points, dashes and weight. From commands: `board.mindMap {x?, y?, text?, children?}`, `board.mindMapAdd {id?, relation?: child\|sibling}`, `tool.mindMap`. 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). No "+" handles, outline around the map, dragging a node onto another, left side or `.jam` import yet |
| 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 |
| 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. The code is coloured as its language writes it: keywords, strings, numbers and comments each in a colour of FigCraft's own (each at least 4.5:1 on the panel), kept on the text's runs by the normalize pass, so the canvas and PNG, SVG and PDF exports show the same, and a language change or an edit colours it again (`board::code_tokens`, a small tokenizer per language; a quoted string ends with its line, plain text stays uncoloured). No toolbar entry, language menu, 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 | |
@@ -69,6 +69,7 @@ all end with the same geometry.
| Date | Change | Summary |
|---|---|---|
| 2026-11-28 | minor | M12, #2237 (step 3 of 4): a code block's text was one colour whatever its language. The normalize pass now colours it as its language writes it: keywords, strings, numbers and comments, from a small tokenizer per language in the document crate (`code_tokens`: each language's keywords, line and block comments, quotes, and for HTML the tag names, with quotes counted only inside a tag). The colours are FigCraft's own, each at least 4.5:1 on the panel, and they live on the text's runs, so the canvas, PNG, SVG and PDF exports and saved files show the same; a language change, an edit, an undo or a live session's change colours it again, and a second pass changes nothing. Plain text stays uncoloured. Tests: `board_code_tests::keywords_strings_numbers_and_comments_per_language` and `highlight_colours_read_on_the_panel_and_differ` (doc), `board_code_tests::keywords_strings_numbers_and_comments_take_their_colours` (engine). Numbers unchanged (no toolbar entry yet). |
| 2026-11-27 | minor | M12, #2395: the Marker, Highlighter and Pencil had no way to choose the ink before drawing; only a stroke already drawn could be recoloured. While one of them is the tool, a bar above the bottom toolbar shows its ink: eight colours (the Pencil also its automatic black, or white on a dark page or frame), any colour through the colour picker, and the stroke weight. Each tool keeps its own for the session and new strokes, and their preview, take it. The engine command `tool.ink {tool?, color?, weight?}` sets and reads it, and `board.ink` takes a `weight`. Tests: `new_strokes_take_the_ink_chosen_before_drawing`. |
| 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-10 | minor | M12, #2226 (step 2 of 4): mind maps in the UI. The Shapes flyout ends in a mind map tool (`tool.mindMap`): a click places a map with the first node's text starting there and types in it. Cmd/Ctrl+Enter adds a child of the selected or edited node (`board.mindMapAdd`), Shift+Cmd/Ctrl+Enter its next sibling (`board.nextSticky` on a node), both typing on; Tab and Shift+Tab walk a node's siblings in the map's order (`select.next`, `select.previous`). The bar over the selection colours a node's text (`board.setColor`) and shows a branch the connector's controls without the line types. Tests: `board_mindmap_tests` (four more), `board_ui_tests` (five more). Breadth ~47% → ~48%, ready ~29% → ~30%. |