Merge branch 'main' into patch-6

This commit is contained in:
Mex authored and GitHub committed 2026-11-18 21:12:24 +01:00
commit ceea6da487
195 files changed
+9422 -1055

No files matched your search

+29
View File
@@ -0,0 +1,29 @@
# This file is machine-generated by `gh actions-lock`.
# Do not edit by hand; run `gh actions-lock` to update.
# Docs: https://gh.io/actions-lockfile
version: 'v0.0.3'
workflows:
'.github/workflows/ci.yml': []
'.github/workflows/freebsd.yml': []
'.github/workflows/house-rules.yml': []
'.github/workflows/lockfile.yml':
- 'actions/checkout@v7.0.1'
- 'step-security/harden-runner@v2.22.4'
'.github/workflows/nix.yml': []
'.github/workflows/packaging-lint.yml':
- 'actions/checkout@v7.0.1'
- 'step-security/harden-runner@v2.22.4'
'.github/workflows/release.yml': []
'.github/workflows/sonarcloud.yml': []
'.github/workflows/windows-arm64.yml': []
dependencies:
'actions/checkout@v7.0.1':
ref: 'v7.0.1'
commit: 'sha1-3d3c42e5aac5ba805825da76410c181273ba90b1'
owner_id: 44036562
repo_id: 197814629
'step-security/harden-runner@v2.22.4':
ref: 'v2.22.4'
commit: 'sha1-1d88384fd173af6ecb012dfd0264a306b711241a'
owner_id: 88700172
repo_id: 422287306
+34
View File
@@ -0,0 +1,34 @@
name: Lockfile
# Fails when .github/workflows/actions.lock is out of sync with the workflows, or when a locked pin
# no longer verifies upstream, so a moved tag cannot slip a different commit into a run.
# Docs: https://gh.io/actions-lockfile
on:
pull_request:
push:
branches: [main]
workflow_dispatch:
permissions:
contents: read
env:
GH_TOKEN: ${{ github.token }}
jobs:
lockfile:
name: Lockfile is in sync
runs-on: ubuntu-24.04
timeout-minutes: 10
steps:
- name: Harden runner
uses: step-security/harden-runner@v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@v7.0.1
with:
persist-credentials: false
- name: Install gh-actions-lock
run: gh extension install github/gh-actions-lock --pin v0.4.1
- name: Verify the lockfile
run: gh actions-lock --verify
+2 -2
View File
@@ -30,10 +30,10 @@ jobs:
runs-on: windows-latest
steps:
- name: Harden runner
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
uses: step-security/harden-runner@v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: actions/checkout@v7.0.1
with:
persist-credentials: false
- name: Install the pinned packaging toolchain
+5 -1
View File
@@ -59,7 +59,7 @@ inspection. It runs natively on macOS, Windows, Linux and FreeBSD, and in the br
Siblings: `../vectorcraft` (Illustrator-class), `../photocraft` (Photoshop-class), `../designcraft`
(InDesign-class) and the other Crafting Apps; same conventions.
Repos don't share code.
Share reusable code through craft-libs; do not depend on sibling application crates.
## Start every session here
1. Read [`ROADMAP.md`](ROADMAP.md) (stage, headline numbers, estimates) and
@@ -182,3 +182,7 @@ commit. Grade by behaviour against the incumbent, not by whether a menu item exi
- Workflows in `.github/workflows/` call the shared workflows in [`storytold/craft-common-actions`](https://github.com/storytold/craft-common-actions) at `@main`, with their inputs and secrets. No other jobs: if no shared workflow does what's needed, it doesn't go here.
- Don't add or change CI in a feature or fix PR. If the existing workflows can't build or test a change, link an existing craft-common-actions issue or PR, or open a new issue, or a PR only for a small fix that is safe for every app and does not increase CI time.
- Some workflow files here still run their own jobs. Don't add to them. Moving a job into craft-common-actions is its own task, never part of another PR, and the job stays here until a shared workflow runs it.
## Shared Craft libraries
Before adding or changing reusable file-format, codec, protocol or UI code, check [craft-libs](https://github.com/storytold/craft-libs) and existing contributor work; reuse its public APIs or extend the appropriate shared library instead of adding an app-local duplicate, keeping app-specific policy and model mapping local and preserving compatibility, security limits and regression coverage.
Generated
+59 -3
View File
@@ -1016,7 +1016,7 @@ name = "craft-fig"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d13ac58a15c45d618f25910772502e38c4ce1d4c#d13ac58a15c45d618f25910772502e38c4ce1d4c"
dependencies = [
"craft-figma-rest",
"craft-figma-rest 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d13ac58a15c45d618f25910772502e38c4ce1d4c)",
"craft-kiwi",
"craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d13ac58a15c45d618f25910772502e38c4ce1d4c)",
"flate2",
@@ -1048,6 +1048,16 @@ dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-figma-rest"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ff142b3ad58aa7306676749428f4f2f9b277b5dd#ff142b3ad58aa7306676749428f4f2f9b277b5dd"
dependencies = [
"serde",
"serde_json",
"thiserror 2.0.21",
]
[[package]]
name = "craft-font-catalog"
version = "0.1.0"
@@ -1131,6 +1141,17 @@ dependencies = [
"objc2-app-kit 0.3.2",
]
[[package]]
name = "craft-penpot"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=064afccce82b01cbf85da5e265bcf897553bea2a#064afccce82b01cbf85da5e265bcf897553bea2a"
dependencies = [
"craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=064afccce82b01cbf85da5e265bcf897553bea2a)",
"serde",
"serde_json",
"thiserror 2.0.21",
]
[[package]]
name = "craft-quit"
version = "0.1.0"
@@ -1153,6 +1174,18 @@ dependencies = [
"toml_edit",
]
[[package]]
name = "craft-sketch"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ff142b3ad58aa7306676749428f4f2f9b277b5dd#ff142b3ad58aa7306676749428f4f2f9b277b5dd"
dependencies = [
"craft-figma-rest 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ff142b3ad58aa7306676749428f4f2f9b277b5dd)",
"craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ff142b3ad58aa7306676749428f4f2f9b277b5dd)",
"kurbo",
"serde_json",
"thiserror 2.0.21",
]
[[package]]
name = "craft-ui"
version = "0.1.0"
@@ -1203,7 +1236,7 @@ dependencies = [
[[package]]
name = "craft-vectordrawable"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d13ac58a15c45d618f25910772502e38c4ce1d4c#d13ac58a15c45d618f25910772502e38c4ce1d4c"
source = "git+https://github.com/storytold/craft-libs?rev=5cd16f2b9ac2a84c4c0794e609914e2bbf848bd7#5cd16f2b9ac2a84c4c0794e609914e2bbf848bd7"
dependencies = [
"kurbo",
]
@@ -1245,6 +1278,16 @@ dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-zip"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=064afccce82b01cbf85da5e265bcf897553bea2a#064afccce82b01cbf85da5e265bcf897553bea2a"
dependencies = [
"flate2",
"thiserror 2.0.21",
"zip 9.1.1",
]
[[package]]
name = "craft-zip"
version = "0.1.0"
@@ -1265,6 +1308,16 @@ dependencies = [
"zip 9.1.1",
]
[[package]]
name = "craft-zip"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ff142b3ad58aa7306676749428f4f2f9b277b5dd#ff142b3ad58aa7306676749428f4f2f9b277b5dd"
dependencies = [
"flate2",
"thiserror 2.0.21",
"zip 9.1.1",
]
[[package]]
name = "crc32fast"
version = "1.5.3"
@@ -2016,7 +2069,9 @@ version = "0.18.1"
dependencies = [
"craft-fig",
"craft-figcraft-format",
"craft-figma-rest",
"craft-figma-rest 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d13ac58a15c45d618f25910772502e38c4ce1d4c)",
"craft-penpot",
"craft-sketch",
"figcraft-doc",
"figcraft-layout",
"figcraft-pathops",
@@ -2170,6 +2225,7 @@ dependencies = [
"craft-font-catalog",
"figcraft-doc",
"figcraft-geom",
"flate2",
"harfrust 0.13.3",
"icu_segmenter",
"log",
+5 -1
View File
@@ -14,7 +14,7 @@ repository = "https://github.com/storytold/figcraft"
[workspace.dependencies]
craft-xml = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "d13ac58a15c45d618f25910772502e38c4ce1d4c" }
craft-vectordrawable = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "d13ac58a15c45d618f25910772502e38c4ce1d4c" }
craft-vectordrawable = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5cd16f2b9ac2a84c4c0794e609914e2bbf848bd7" }
# internal
figcraft-geom = { path = "crates/geom" }
figcraft-color = { path = "crates/color" }
@@ -58,9 +58,13 @@ craft-menu = { git = "https://github.com/storytold/craft-libs", rev = "e11f9d9ae
# Where the settings live: the suite's folder rules, portable mode included (craft-libs).
craft-settings = { git = "https://github.com/storytold/craft-libs", rev = "e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545" }
# Penpot export container only; JSON values cross this boundary, not shared model types.
craft-penpot = { git = "https://github.com/storytold/craft-libs", rev = "064afccce82b01cbf85da5e265bcf897553bea2a" }
# The design-file formats (craft-libs): the .fig container and its kiwi encoding, the mapping of
# a .fig message onto the REST file JSON, and that JSON's shared helpers. These crates share
# types, so they stay on one rev; they share none with the crates above.
craft-sketch = { git = "https://github.com/storytold/craft-libs", rev = "ff142b3ad58aa7306676749428f4f2f9b277b5dd" }
craft-fig = { git = "https://github.com/storytold/craft-libs", rev = "d13ac58a15c45d618f25910772502e38c4ce1d4c" }
craft-figcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "976eb51c59edb0a37f24105850f52d921c8518ee" }
craft-figma-rest = { git = "https://github.com/storytold/craft-libs", rev = "d13ac58a15c45d618f25910772502e38c4ce1d4c" }
+8 -2
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-15 · **Change:** minor (CLI help and docs name the first non-divider page as the default for export and render; 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 (CLI help and docs name the first non-divider page as the default for export and render; 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
@@ -105,7 +105,7 @@ native speakers' reviews of the nine language drafts need people.
| Traditional Chinese (Taiwan) | zh-Hant | 2,647 / 2,647 entries (100%, counted 2026-11-03) | draft (needs native review) |
| Spanish | es, es-419 | 100% (es-419: an overlay of 101 entries) | draft (needs native review) |
| Hindi | hi | 0% | none |
| Arabic | ar | 2,508 / 2,508 entries (100%, counted 2026-10-28) | draft; the window mirrors (panels swap sides); native review and mirrored panel rows pending |
| Arabic | ar | 2,508 / 2,508 entries (100%, counted 2026-10-28) | draft; web builds with craft-fonts offer Arabic by default; the window mirrors (panels swap sides); native review and mirrored panel rows pending |
| French | fr | 95% | draft (needs native review) |
| Portuguese (Brazil) | pt-BR | 95% | draft (needs native review) |
| Indonesian | id | 99% | draft (needs native review) |
@@ -134,6 +134,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md).
## Progress log
- **2026-11-07** · M10, #1902: web builds with craft-fonts embed Noto Sans Arabic Regular by default, so Persian and Arabic text has a fallback without `FIGCRAFT_EMBED_SCRIPTS=Arab`; required web builds reject catalogs without that face. Web faces are compressed losslessly at build time and restored once at runtime to keep the default catalog within the WASM size budget. A decode failure logs the unavailable face once; a compiler regression checks generated catalog initialization. Additional scripts remain opt-in. Exact Iran Sans appearance still needs the installed font through supported browsers' local font access. Numbers unchanged.
- **2026-11-05** · M2, #1823: Suggest auto layout is its own command. `layout.suggest` used to run `layout.add` and made one row of everything. It now splits a frame's layers into rows or columns by the gaps between them, wraps each band of several layers in a hugging frame without fill and repeats inside it, so the design gets as many auto layout frames as it needs and keeps its placement where the gaps are even (the frame keeps its size). Uneven gaps, bands that start at different offsets across the flow (lined up at the smallest) and layers that overlap along both axes are reported as `warnings`, and instances and layers inside them are refused. `layout.add` is unchanged. Tests in `layout_suggest_tests.rs`. Numbers unchanged.
- **2026-11-05** · M3, #2002: the Local variables window selects several variables with a click, Shift+click (range) and Cmd/Ctrl+click (toggle), cleared by Escape or a click on the empty space; delete, move to a group and scope act on the selected local variables as one undo step (`command.batch`); inherited variables can be selected but are left out, since they change in their own collection, and the bulk menu needs two or more local variables selected (otherwise the row shows its own menu). Rename and value edits stay single-row.
- **2026-11-05** · M10, #2014: the desktop UI takes a system face for Ethiopic, Devanagari, Gurmukhi, Gujarati, Tamil, Telugu, Kannada and Malayalam, Sinhala, Lao, Myanmar, Khmer, Armenian and Georgian as it did for Hebrew and Arabic (`bidi::script_fallbacks`: one sample letter per script, the system's families for each; Bengali and Thai keep `crate::cjk`'s choice), so a layer name or a String variable's Amharic value draws in the panels instead of boxes. Test: `bidi::tests::other_scripts_take_an_installed_system_face`.
@@ -365,9 +366,14 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md).
| Date | Change | Summary |
|---|---|---|
| 2026-11-18 | minor | M3, gap 10: library analytics count insertions and detachments of styles and variables. Applying one, or copying or duplicating content that uses it, inserts it; the Detach button detaches it; an instance counts as its component alone. Show usage and `library.usage` give them per style and variable over the chosen period. Modes aren't counted. Numbers unchanged. Tests: `library_asset_counts_tests`, `library_assets_tests`. |
| 2026-11-18 | minor | M9, gap 6: the browser build uses team libraries and plugin directories on a server, through its WebSocket requests: adding a library by its link, its styles and components, publishing to it, Show usage and the reports a file sends; browsing a directory and installing from it, for the page only. Scripts through `window.figcraft` still can't, as commands there don't wait for the server. Numbers unchanged. Tests: `exchange_tests`. |
| 2026-11-17 | minor | M6: Android Vector Drawable XML serialization uses the shared writer; application projection and colour policy remain local. Byte-parity tests cover full documents and generated deep wrappers; no new format capability or incumbent certification. |
| 2026-11-15 | patch | CLI usage and operation failures escape terminal controls in paths and error text, using the same printable-text rule as info and script diagnostics; exit codes and ordinary quotes and paths stay unchanged. |
| 2026-11-15 | patch | CLI export and render help and docs name the existing first non-divider page default, including the all-divider fallback and explicit page selection. Behavior unchanged. |
| 2026-11-10 | minor | M4, #2222: a boolean group takes a corner radius that rounds every sharp corner of its result. Numbers unchanged |
| 2026-11-10 | minor | M12, #2226 (step 1 of 4): mind maps in the document and engine. `board.mindMap` places a first node with three children on curved branches and `board.mindMapAdd` adds a child or a sibling; the normalize pass lays a touched map out again from its first node (88 between columns, 48 between siblings, stacks centred on their parents). No toolbar entry yet; numbers unchanged. |
| 2026-11-07 | patch | M10, #1902: web builds with craft-fonts embed Noto Sans Arabic Regular by default, so Persian and Arabic text has a fallback without `FIGCRAFT_EMBED_SCRIPTS=Arab`; required web builds reject catalogs without that face. Web faces are compressed losslessly at build time and restored once at runtime to keep the default catalog within the WASM size budget. A decode failure logs the unavailable face once; a compiler regression checks generated catalog initialization. Additional scripts remain opt-in. Exact Iran Sans appearance still needs the installed font through supported browsers' local font access. Numbers unchanged. |
| 2026-11-03 | minor | Traditional Chinese (Taiwan) (`zh-Hant`, 繁體中文(台灣)) draft catalog: every UI string (1,975), command label (641) and menu wording (31), translated clean-room from the English source; `zh-TW`, `zh-HK`, `zh-MO` and `zh-Hant` read it while an explicit Hans stays Simplified; the desktop UI prefers an installed Noto Sans CJK TC, then Microsoft JhengHei, PingFang TC and Heiti TC; no font is bundled; native review pending. Numbers unchanged |
| 2026-11-06 | patch | M1, #2028: Edit ▸ Set default properties gives new rectangles, ellipses, polygons and stars drawn with the tools (and, set from a text layer, new text) the selected layer's properties; it only copied them for Paste properties. Tests: `default_props_tests` (3). Numbers unchanged |
| 2026-11-06 | patch | M5, #2027: `proto.settings` refuses an unknown device name with the list of devices (it saved any string, and the presenter showed no device), takes known names in any case, and answers the page's prototype settings, so `proto.settings {}` reads them back over MCP. Test: `proto_present_tests::unknown_devices_are_refused_and_settings_read_back`. Numbers unchanged |
+16 -1
View File
@@ -316,7 +316,10 @@ fn whole_number(s: &str) -> Result<usize, ValueError> {
/// `mcp --attach`: `host:port` as given, or a bare port on 127.0.0.1.
fn attach(s: &str) -> Result<String, ValueError> {
if s.contains(':') {
if let Some((host, port)) = s.rsplit_once(':') {
if host.is_empty() || port.parse::<u16>().is_err() {
return Err(ValueError::Attach);
}
return Ok(s.to_owned());
}
let port: u16 = s.parse().map_err(|_| ValueError::Attach)?;
@@ -461,6 +464,12 @@ mod tests {
assert_eq!(a.attach.as_deref(), Some("127.0.0.1:7979"));
let Command::Mcp(a) = ok(&["mcp", "--attach=localhost:7979"]) else { panic!("mcp") };
assert_eq!(a.attach.as_deref(), Some("localhost:7979"));
for address in ["127.0.0.1:7979", "[::1]:7979", "[fe80::1%3]:7979", "localhost:0"] {
let Command::Mcp(a) = ok(&["mcp", "--attach", address]) else { panic!("mcp") };
assert_eq!(a.attach.as_deref(), Some(address));
}
let Command::Mcp(a) = ok(&["mcp", "--attach", "0"]) else { panic!("mcp") };
assert_eq!(a.attach.as_deref(), Some("127.0.0.1:0"));
let Command::Mcp(a) = ok(&["mcp", "--attach", "7979", "--timeout", "300"]) else { panic!("mcp") };
assert_eq!(a.timeout, Some(300));
let Command::Mcp(a) = ok(&["mcp", "--automation-read-root", "in", "--automation-write-root", "out"]) else { panic!("mcp") };
@@ -514,6 +523,11 @@ mod tests {
(&["perf", "--layers", "10,x"], ValueValidation),
(&["perf", "--layers", "10", "--layers", "20"], ArgumentConflict),
(&["mcp", "--attach", "notaport"], ValueValidation),
(&["mcp", "--attach", ":7979"], ValueValidation),
(&["mcp", "--attach", "localhost:"], ValueValidation),
(&["mcp", "--attach", "localhost:notaport"], ValueValidation),
(&["mcp", "--attach", "localhost:65536"], ValueValidation),
(&["mcp", "--attach", "[::1]"], ValueValidation),
(&["mcp", "--attach", "7979", "--timeout", "0"], ValueValidation),
(&["mcp", "--attach", "7979", "--timeout", "601"], ValueValidation),
(&["mcp", "--timeout", "300"], MissingRequiredArgument),
@@ -543,6 +557,7 @@ mod tests {
&["export", "x.figcraft", "-o", "out", "--help"],
&["export", "-o", "--help"],
&["mcp", "--attach", "notaport", "--help"],
&["mcp", "--attach", "localhost:notaport", "--help"],
&["mcp", "--bogus", "-h"],
&["--no-system-fonts", "plugin", "publish", "--bogus", "--help"],
] {
+19 -2
View File
@@ -12,7 +12,7 @@ use crate::{CliError, CliResult};
/// A document's or plugin's text as a terminal should show it: control characters escaped, and
/// everything else (quotes, backslashes in paths) left as it is.
fn plain(text: &str) -> String {
pub(crate) fn plain(text: &str) -> String {
text.chars().map(|c| if c.is_control() { c.escape_default().to_string() } else { c.to_string() }).collect()
}
@@ -242,7 +242,10 @@ pub fn info(path: &str, as_json: bool) -> CliResult<ExitCode> {
fn sanitize(name: &str) -> String {
let s = figcraft_engine::cmd::file::safe_file_name(name);
let s = s.trim_matches(|c: char| c == '.' || c.is_whitespace());
if s.is_empty() { "layer".into() } else { s.char_indices().take(100).take_while(|(i, c)| i + c.len_utf8() <= 200).map(|(_, c)| c).collect() }
let cap = |s: &str| s.char_indices().take(100).take_while(|(i, c)| i + c.len_utf8() <= 200).map(|(_, c)| c).collect::<String>();
// Truncation can expose a device name; its escape must still fit the limits.
let s = figcraft_engine::file_access::escape_device_names(&cap(s));
if s.is_empty() { "layer".into() } else { cap(&s) }
}
/// What `export` exports and how.
@@ -543,6 +546,10 @@ mod tests {
assert_eq!(sanitize("Home / Hero"), "Home _ Hero");
assert_eq!(sanitize("../.."), "_");
assert_eq!(sanitize(""), "layer");
assert_eq!(sanitize("CON"), "_CON");
assert_eq!(sanitize(" .nul.txt. "), "_nul.txt");
assert_eq!(sanitize("COM1"), "_COM1");
assert_eq!(sanitize("HomeCON"), "HomeCON");
// The same characters the app's export keeps (#1154): only what file systems refuse goes.
assert_eq!(sanitize("Homepage - desktop (live + verbeteringen)"), "Homepage - desktop (live + verbeteringen)");
assert_eq!(sanitize("Q&A, 50% #1 [v2] {x} ~é"), "Q&A, 50% #1 [v2] {x} ~é");
@@ -553,6 +560,16 @@ mod tests {
assert_eq!(sanitize(&"\u{1F600}".repeat(100)), "\u{1F600}".repeat(50), "at most 200 bytes, whole characters");
}
#[test]
fn sanitizes_names_that_become_devices_at_the_character_limit() {
assert_eq!(sanitize(&format!("CON{}X", " ".repeat(97))), format!("_CON{}", " ".repeat(96)));
}
#[test]
fn sanitizes_names_that_become_devices_at_the_byte_limit() {
assert_eq!(sanitize(&format!("NUL{} X", "\u{2003}".repeat(65))), format!("_NUL{} ", "\u{2003}".repeat(65)));
}
#[test]
fn default_page_skips_leading_divider() {
let mut doc = Document::new("divider");
+3 -2
View File
@@ -38,14 +38,15 @@ fn main() -> ExitCode {
return ExitCode::from(u8::try_from(e.exit_code()).unwrap_or(2));
}
};
// Paths and imported/plugin errors may carry terminal controls; keep diagnostics printable.
match run(cli) {
Ok(code) => code,
Err(CliError::Usage(msg)) => {
eprintln!("error: {msg}\n\nFor more information, try '--help'.");
eprintln!("error: {}\n\nFor more information, try '--help'.", files::plain(&msg));
ExitCode::from(2)
}
Err(CliError::Failed(msg)) => {
eprintln!("error: {msg}");
eprintln!("error: {}", files::plain(&msg));
ExitCode::from(1)
}
}
+16
View File
@@ -106,6 +106,22 @@ fn bad_arguments_exit_2_without_panicking() {
assert_eq!(out.status.code(), Some(1));
}
#[test]
fn post_parse_errors_escape_terminal_controls() {
let missing = format!("__figcraft_missing_diagnostic_{}_\u{1b}[31m\n.figcraft", std::process::id());
let failed = ["info", missing.as_str()];
let usage = ["connect", "publish", "invalid-\u{1b}[31m\n.txt"];
for (args, expected) in [(&failed[..], 1), (&usage[..], 2)] {
let out = bin().arg("--no-system-fonts").args(args).output().unwrap();
let error = String::from_utf8_lossy(&out.stderr);
assert_eq!(out.status.code(), Some(expected), "{args:?}: {error:?}");
assert!(error.starts_with("error: "), "{args:?}: {error:?}");
assert!(!error.contains('\u{1b}'), "{args:?}: {error:?}");
assert!(error.contains(r"\u{1b}[31m\n"), "{args:?}: {error:?}");
assert!(out.stdout.is_empty(), "{args:?}");
}
}
/// `--help` / `-h` after a subcommand prints that subcommand's help on stdout and exits 0, as it
/// does first (#1155), whatever else is on the line; nothing runs.
#[test]
+1
View File
@@ -28,6 +28,7 @@ pub const LINKS: &str = "links.json";
pub const LIBRARY: &str = "library.bin";
pub const USAGE: &str = "usage.json";
pub const ACTIONS: &str = "actions.json";
pub const ASSET_ACTIONS: &str = "asset-actions.json";
const SNAP_MAGIC: &[u8; 4] = b"FCSN";
const LOG_MAGIC: &[u8; 4] = b"FCLG";
@@ -5,12 +5,15 @@
use std::time::{Duration, Instant};
use figcraft_collab::message::{Access, AssetUsage, ClientMsg, LibraryReply, LibraryReq, MAX_ASSET_USAGE, OpenLibrary, PROTOCOL, ServerMsg};
use figcraft_collab::message::{
Access, AssetActions, AssetUsage, ClientMsg, LibraryReply, LibraryReq, MAX_ASSET_USAGE, OpenLibrary, PROTOCOL, ServerMsg, Usage,
};
use figcraft_collab_net::Invite;
use figcraft_doc::NodeId;
use figcraft_engine::Session;
use serde_json::{Value, json};
use crate::store::{MAX_USERS, Store};
use crate::test_util::{Raw, TempDir, config, publish, session};
fn ex(s: &mut Session, cmd: &str, p: Value) -> Value {
@@ -79,7 +82,7 @@ fn styles_and_variables_are_counted_per_layer_and_file() {
// Bo takes the style off one layer and the variable off its only one.
ex(&mut b, "style.detach", json!({"ids": [two], "which": "fill"}));
ex(&mut b, "variable.bind", json!({"ids": [three], "field": "fill"}));
let u = usage_when(&mut a, &mut b, |u| u["styles"][0]["layers"] == 1 && u["variables"].as_array().is_some_and(Vec::is_empty));
let u = usage_when(&mut a, &mut b, |u| u["styles"][0]["layers"] == 1 && u["variables"][0]["layers"] == 0);
assert_eq!(u["styles"].as_array().unwrap().len(), 1, "{u}");
server.stop();
}
@@ -143,3 +146,76 @@ fn answer(raw: &mut Raw) -> LibraryReply {
other => panic!("not a library answer: {other:?}"),
}
}
#[test]
fn inserts_and_detaches_count_per_style_and_variable_in_the_period() {
let dir = TempDir::new("library-asset-actions");
let cfg = config(dir.path());
let mut server = crate::start(&cfg).unwrap();
let addr = server.addr();
let mut a = session("Ada");
let r = rect(&mut a, 0);
ex(&mut a, "style.create", json!({"type": "paint", "name": "Brand", "from": r.0}));
let collection = ex(&mut a, "variable.createCollection", json!({"name": "Tokens"}));
ex(&mut a, "variable.create", json!({"name": "Accent", "type": "color", "collection": collection["id"], "value": "#0D99FF"}));
let p = publish(&mut a, dir.path(), addr);
ex(&mut a, "library.publishToServer", json!({}));
let mut b = session("Bo");
let lid = ex(&mut b, "library.add", json!({"path": p.view}))["id"].as_str().unwrap().to_string();
let (one, two) = (rect(&mut b, 0), rect(&mut b, 100));
ex(&mut b, "library.applyStyle", json!({"library": lid, "style": "Brand", "ids": [one.0, two.0]}));
ex(&mut b, "style.detach", json!({"ids": [two.0], "which": "fill"}));
ex(&mut b, "library.bindVariable", json!({"library": lid, "variable": "Accent", "ids": [two.0], "field": "fill"}));
let u = usage_when(&mut a, &mut b, |u| {
u["assetActionsKnown"] == true
&& u["styles"][0]["insertions"] == 2
&& u["styles"][0]["detachments"] == 1
&& u["variables"][0]["insertions"] == 1
});
assert_eq!(u["assetActionsKnown"], true, "{u}");
assert_eq!(u["styles"][0]["detachments"], 1, "{u}");
assert_eq!(u["variables"][0]["detachments"], 0, "{u}");
assert_eq!(u["insertions"], 0, "components count on their own: {u}");
// An undo and a redo count once, and a style no layer uses any more stays listed.
ex(&mut b, "edit.undo", json!({}));
ex(&mut b, "edit.redo", json!({}));
ex(&mut b, "style.detach", json!({"ids": [one.0], "which": "fill"}));
let u = usage_when(&mut a, &mut b, |u| u["styles"][0]["detachments"] == 2 && u["styles"][0]["layers"] == 0);
assert_eq!((u["styles"][0]["insertions"].clone(), u["styles"][0]["layers"].clone()), (json!(2), json!(0)), "{u}");
assert_eq!(u["variables"][0]["insertions"], 1, "{u}");
server.stop();
}
#[test]
fn evicting_capped_usage_rows_keeps_asset_peaks_so_a_repeat_report_is_not_counted_twice() {
let dir = TempDir::new("library-asset-peaks-evict");
let cfg = config(dir.path());
let mut server = crate::start(&cfg).unwrap();
let addr = server.addr();
let mut a = session("Ada");
let r = rect(&mut a, 0);
ex(&mut a, "style.create", json!({"type": "paint", "name": "Brand", "from": r.0}));
let p = publish(&mut a, dir.path(), addr);
ex(&mut a, "library.publishToServer", json!({}));
let file = Invite::parse(&p.edit).unwrap().file;
server.stop();
drop(server);
let mut store = Store::open(dir.path(), cfg.store()).unwrap();
for i in 0..MAX_USERS {
store.report_usage(&file, Usage { file: format!("Old{i}"), components: Vec::new() }).unwrap();
}
let actions = AssetActions { file: "Kept".into(), inserted: vec![("Brand".into(), 2)], detached: Vec::new() };
store.report_asset_actions(&file, actions.clone()).unwrap();
// One more usage-only file would evict "Kept" if asset activity did not count for retention.
store.report_usage(&file, Usage { file: "Extra".into(), components: Vec::new() }).unwrap();
store.report_asset_actions(&file, actions).unwrap();
let weeks = store.library_asset_actions(&file).unwrap();
let brand: Vec<_> = weeks.iter().filter(|w| w.component == "Brand").collect();
assert_eq!(brand.len(), 1, "{weeks:?}");
assert_eq!(brand[0].insertions, 2, "lost peaks would grow the same totals again: {weeks:?}");
assert_eq!(brand[0].detachments, 0, "{weeks:?}");
}
+12 -5
View File
@@ -40,8 +40,8 @@ use std::path::{Path, PathBuf};
use std::time::{Instant, SystemTime, UNIX_EPOCH};
use figcraft_collab::message::{
Access, Admin, AdminReply, AssetUsage, ClientMsg, Detached, FileDetached, FileInfo, FileRow, FileUsage, HostInfo, LibraryReply, LibraryReq,
LinkInfo, MAX_OWNED, NewLink, OwnedFile, PluginReply, PluginReq, ReportInfo, Usage, WeekActions,
Access, Admin, AdminReply, AssetActions, AssetUsage, ClientMsg, Detached, FileDetached, FileInfo, FileRow, FileUsage, HostInfo, LibraryReply,
LibraryReq, LinkInfo, MAX_OWNED, NewLink, OwnedFile, PluginReply, PluginReq, ReportInfo, Usage, WeekActions,
};
use figcraft_collab::{Change, NodeId, Replica, Server, same_secret};
use figcraft_collab_net::hub::{Admission, Backend, Closing, Handled, OpenFile, ip_blocks, ip_key};
@@ -52,7 +52,7 @@ use sha2::{Digest, Sha256};
use crate::abuse::{Abuse, AbuseConfig, Action};
use crate::codes::{self, Sealed};
use crate::directory::{Directory, DirectoryConfig};
use crate::disk::{self, ACTIONS, LIBRARY, LINKS, LOG, LOG_HEADER, META, SNAPSHOT, USAGE};
use crate::disk::{self, ACTIONS, ASSET_ACTIONS, LIBRARY, LINKS, LOG, LOG_HEADER, META, SNAPSHOT, USAGE};
mod backend;
mod files;
@@ -103,7 +103,7 @@ pub const NO_PUBLIC_LIBRARY: &str = "on this public server only files published
/// Most files whose usage of one library is kept (the least recently changed go first), and most
/// components one file's report keeps.
const MAX_USERS: usize = 200;
pub(crate) const MAX_USERS: usize = 200;
const MAX_REPORTED: usize = 1_000;
/// Largest `usage.json` (and `actions.json`) read.
const MAX_USAGE_FILE: u64 = 16 << 20;
@@ -298,6 +298,8 @@ struct UsageCache {
list: Vec<UsageEntry>,
/// Insertions and detachments week by week, over every file (kept in `actions.json`).
weeks: Vec<WeekActions>,
/// The same for styles and variables (kept in `asset-actions.json`).
asset_weeks: Vec<WeekActions<String>>,
dirty: bool,
written: u64,
}
@@ -321,6 +323,11 @@ struct UsageEntry {
styles: Vec<(String, u32)>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
variables: Vec<(String, u32)>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
asset_peaks: Vec<(String, u32, u32)>,
/// When this file last reported style or variable insertions or detachments (seconds since 1970, UTC).
#[serde(default, skip_serializing_if = "is_zero")]
asset_updated: u64,
}
fn is_zero(n: &u64) -> bool {
@@ -560,7 +567,7 @@ impl Store {
/// A file folder's description and links, after checking its snapshot and log. Leftover
/// temporary files (writes cut short) are removed.
fn check(&self, path: &Path) -> Result<Entry, String> {
for name in [SNAPSHOT, LOG, META, LINKS, USAGE, ACTIONS] {
for name in [SNAPSHOT, LOG, META, LINKS, USAGE, ACTIONS, ASSET_ACTIONS] {
let tmp = disk::temp_of(&path.join(name));
if tmp.exists() {
let _ = fs::remove_file(&tmp);
@@ -278,6 +278,8 @@ impl Backend for Store {
LibraryReq::Actions => self.library_actions(file).map_or_else(failed, LibraryReply::Actions),
LibraryReq::ReportAssets(a) => self.report_assets(file, a).map_or_else(failed, |()| LibraryReply::Noted),
LibraryReq::Assets => self.library_assets(file).map_or_else(failed, LibraryReply::Assets),
LibraryReq::ReportAssetActions(a) => self.report_asset_actions(file, a).map_or_else(failed, |()| LibraryReply::Noted),
LibraryReq::AssetActions => self.library_asset_actions(file).map_or_else(failed, LibraryReply::AssetActions),
}
}
+92 -33
View File
@@ -1,9 +1,9 @@
use figcraft_collab::message::MAX_ASSET_USAGE;
use super::{
ACTIONS, Action, AssetUsage, BUSY_DOWNLOADS, Cursor, Detached, FILES, FileDetached, FileUsage, IpAddr, LIBRARY, LibraryMeta, LibraryReply,
MAX_FIRST_LIBRARY_VERSION, MAX_REPORTED, MAX_USAGE_FILE, MAX_USERS, MAX_WEEK_ROWS, MAX_WEEKS, META, NO_PUBLIC_LIBRARY, NodeId, Path, PathBuf,
Store, USAGE, USAGE_WRITE_EVERY, Usage, UsageCache, UsageEntry, WeekActions, clean_name, disk, fs, now, write_json,
ACTIONS, ASSET_ACTIONS, Action, AssetActions, AssetUsage, BUSY_DOWNLOADS, Cursor, Detached, FILES, FileDetached, FileUsage, IpAddr, LIBRARY,
LibraryMeta, LibraryReply, MAX_FIRST_LIBRARY_VERSION, MAX_REPORTED, MAX_USAGE_FILE, MAX_USERS, MAX_WEEK_ROWS, MAX_WEEKS, META, NO_PUBLIC_LIBRARY,
NodeId, Path, PathBuf, Store, USAGE, USAGE_WRITE_EVERY, Usage, UsageCache, UsageEntry, WeekActions, clean_name, disk, fs, now, write_json,
};
/// Which of a file's totals a report brings.
@@ -46,49 +46,55 @@ fn read_kept<T: serde::de::DeserializeOwned>(path: &Path) -> Vec<T> {
disk::read_capped(path, MAX_USAGE_FILE).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default()
}
/// Raise the highest `kind` totals in `peaks` to `counts`, each from what `last` says was reported
/// before them; what grew past them, by how much.
fn grow<K: PartialEq + Clone>(peaks: &mut Vec<(K, u32, u32)>, counts: &[(K, u32)], kind: Count, last: impl Fn(&K) -> u32) -> Vec<(K, u32)> {
let mut grown = Vec::new();
for (c, n) in counts {
let at = match peaks.iter().position(|p| p.0 == *c) {
Some(at) => at,
None if peaks.len() < MAX_REPORTED => {
peaks.push((c.clone(), 0, 0));
peaks.len() - 1
}
None => continue,
};
let Some(p) = peaks.get_mut(at) else { continue };
let peak = if kind == Count::Inserted { &mut p.1 } else { &mut p.2 };
let base = (*peak).max(last(c));
if *n > base {
grown.push((c.clone(), *n - base));
}
*peak = base.max(*n);
}
grown
}
impl UsageEntry {
/// Raise this file's highest `kind` totals to `counts`; what grew past them, by how much.
/// A detach total reported before peaks were kept starts from that report.
fn grow_peaks(&mut self, counts: &[(NodeId, u32)], kind: Count) -> Vec<(NodeId, u32)> {
let mut grown = Vec::new();
for &(c, n) in counts {
let last = if kind == Count::Detached { self.detached.iter().find(|d| d.0 == c).map_or(0, |d| d.1) } else { 0 };
let at = match self.peaks.iter().position(|p| p.0 == c) {
Some(at) => at,
None if self.peaks.len() < MAX_REPORTED => {
self.peaks.push((c, 0, 0));
self.peaks.len() - 1
}
None => continue,
};
let Some(p) = self.peaks.get_mut(at) else { continue };
let peak = if kind == Count::Inserted { &mut p.1 } else { &mut p.2 };
let base = (*peak).max(last);
if n > base {
grown.push((c, n - base));
}
*peak = base.max(n);
}
grown
let detached = &self.detached;
grow(&mut self.peaks, counts, kind, |c| if kind == Count::Detached { detached.iter().find(|d| d.0 == *c).map_or(0, |d| d.1) } else { 0 })
}
}
/// Add `grown` to this week's `kind` counts in `weeks`, dropping weeks older than [`MAX_WEEKS`]
/// and, past [`MAX_WEEK_ROWS`], the oldest rows.
fn add_to_week(weeks: &mut Vec<WeekActions>, grown: &[(NodeId, u32)], kind: Count, t: u64) {
fn add_to_week<K: PartialEq + Clone>(weeks: &mut Vec<WeekActions<K>>, grown: &[(K, u32)], kind: Count, t: u64) {
let week = week_of(t);
weeks.retain(|w| w.week.saturating_add(MAX_WEEKS * WEEK) > week);
for &(component, n) in grown {
let at = match weeks.iter().position(|w| w.week == week && w.component == component) {
for (component, n) in grown {
let at = match weeks.iter().position(|w| w.week == week && w.component == *component) {
Some(at) => at,
None => {
weeks.push(WeekActions { week, component, insertions: 0, detachments: 0 });
weeks.push(WeekActions { week, component: component.clone(), insertions: 0, detachments: 0 });
weeks.len() - 1
}
};
if let Some(w) = weeks.get_mut(at) {
let slot = if kind == Count::Inserted { &mut w.insertions } else { &mut w.detachments };
*slot = slot.saturating_add(n);
*slot = slot.saturating_add(*n);
}
}
if weeks.len() > MAX_WEEK_ROWS {
@@ -184,8 +190,9 @@ impl Store {
}
if !self.usage.contains_key(file) {
let path = self.dir(file).join(USAGE);
let (list, weeks) = (read_kept(&path), read_kept(&self.dir(file).join(ACTIONS)));
self.usage.insert(file.to_string(), UsageCache { list, weeks, dirty: false, written: now() });
let dir = self.dir(file);
let (list, weeks, asset_weeks) = (read_kept(&path), read_kept(&dir.join(ACTIONS)), read_kept(&dir.join(ASSET_ACTIONS)));
self.usage.insert(file.to_string(), UsageCache { list, weeks, asset_weeks, dirty: false, written: now() });
}
Ok(self.usage.get_mut(file))
}
@@ -234,6 +241,37 @@ impl Store {
})
}
/// A file's library's styles' and variables' insertions and detachments week by week, over
/// the last [`MAX_WEEKS`] weeks (none when it has no library).
pub fn library_asset_actions(&mut self, file: &str) -> Result<Vec<WeekActions<String>>, String> {
let since = week_of(now()).saturating_sub((MAX_WEEKS - 1) * WEEK);
let weeks = self.usage_of(file)?.map(|u| u.asset_weeks.as_slice()).unwrap_or_default();
Ok(weeks.iter().filter(|w| w.week >= since).cloned().collect())
}
/// Note how many times one file has inserted and detached a file's library's styles and
/// variables: what its totals grew past their highest counts in this week.
pub fn report_asset_actions(&mut self, file: &str, actions: AssetActions) -> Result<(), String> {
for (counts, kind) in [(actions.inserted, Count::Inserted), (actions.detached, Count::Detached)] {
let mut grown = Vec::new();
self.report(file, &actions.file, known_assets(counts), |e, counts| {
grown = grow(&mut e.asset_peaks, &counts, kind, |_| 0);
if grown.is_empty() {
return false;
}
// Heard from for retention: evicting the row would drop asset_peaks, the
// baseline grow uses so a later identical report is not counted twice.
e.asset_updated = now();
true
})?;
if let (false, Some(u)) = (grown.is_empty(), self.usage.get_mut(file)) {
add_to_week(&mut u.asset_weeks, &grown, kind, now());
u.dirty = true;
}
}
Ok(())
}
/// Keep how many layers of one file use a file's library's styles and variables (as
/// [`Self::report_usage`] keeps its usage, beside it).
pub fn report_assets(&mut self, file: &str, assets: AssetUsage) -> Result<(), String> {
@@ -297,7 +335,7 @@ impl Store {
let at = match u.list.iter().position(|e| e.usage.file == name) {
Some(at) => at,
None => {
u.list.push(UsageEntry { usage: Usage { file: name, components: Vec::new() }, ..UsageEntry::default() });
u.list.push(UsageEntry { usage: Usage { file: name.clone(), components: Vec::new() }, ..UsageEntry::default() });
u.list.len() - 1
}
};
@@ -306,7 +344,13 @@ impl Store {
return Ok(());
}
if u.list.len() > MAX_USERS {
u.list.sort_by_key(|e| std::cmp::Reverse(e.updated.max(e.detached_updated)));
// The file just heard from stays, even when several share a timestamp (now() is
// seconds). Asset-action reports use asset_updated so their peaks are not dropped
// in favour of a usage-only row from the same second.
u.list.sort_by_key(|e| {
let recent = e.usage.file == name;
std::cmp::Reverse((e.updated.max(e.detached_updated).max(e.asset_updated), recent))
});
u.list.truncate(MAX_USERS);
}
u.dirty = true;
@@ -325,7 +369,8 @@ impl Store {
if let Err(e) = write_json(&root.join(file).join(USAGE), &u.list) {
log::warn!("file {file}: library usage couldn't be kept: {e}");
}
if let Err(e) = write_json(&root.join(file).join(ACTIONS), &u.weeks) {
let actions = write_json(&root.join(file).join(ACTIONS), &u.weeks);
if let Err(e) = actions.and_then(|()| write_json(&root.join(file).join(ASSET_ACTIONS), &u.asset_weeks)) {
log::warn!("file {file}: library analytics couldn't be kept: {e}");
}
(u.dirty, u.written) = (false, t);
@@ -345,3 +390,17 @@ fn library_file(dir: &Path, version: u64) -> PathBuf {
let path = dir.join(library_name(version));
if path.exists() { path } else { dir.join(LIBRARY) }
}
#[cfg(test)]
mod grow_tests {
use super::*;
#[test]
fn a_new_key_is_dropped_once_peaks_are_full() {
let mut peaks: Vec<(u32, u32, u32)> = (0..MAX_REPORTED as u32).map(|i| (i, 1, 0)).collect();
let grown = grow(&mut peaks, &[(MAX_REPORTED as u32, 3)], Count::Inserted, |_| 0);
assert!(grown.is_empty(), "a key past the cap must not start a peak or count as growth");
assert_eq!(peaks.len(), MAX_REPORTED);
assert!(peaks.iter().all(|p| p.0 < MAX_REPORTED as u32));
}
}
+7
View File
@@ -118,3 +118,10 @@ real_name = "Ashok Ram"
[people.GiovanniBot]
sync_github_name = true
[people.gmrmad1]
real_name = "Madhav Agarwal"
[people.Aathish-D]
real_name = "Aathish Duraiswamy"
sync_github_name = true
+6
View File
@@ -152,6 +152,12 @@ impl<S: Socket> Driver<S> {
None => self.done = true,
}
}
exchange::Next::Tell(events, then) => {
for e in events {
self.inbox.push(e);
}
self.follow(*then, now);
}
}
}
+93 -12
View File
@@ -7,11 +7,17 @@
//! Publishing ([`publish`]) uploads the document, makes the links and codes others join with when
//! it shares, then joins the new file with its edit link; [`background`] sends the hosting and
//! sharing requests the engine sends in the background (asking a server about its hosting,
//! starting and stopping a share).
//! starting and stopping a share) and those about team libraries and plugin directories;
//! [`libraries`] the checks of a file's team libraries.
use std::collections::VecDeque;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use figcraft_collab::message::{self, Admin, AdminReply, ClientMsg, HostInfo, Manage, OpenHosting, PROTOCOL, ServerMsg};
use figcraft_collab::message::{
self, Admin, AdminReply, ClientMsg, HostInfo, LibraryReply, LibraryReq, Manage, OpenHosting, OpenLibrary, OpenPlugins, PROTOCOL, PluginReply,
PluginReq, ServerMsg,
};
use figcraft_engine::live::{Event, NetReply, NetRequest, Shared, Status};
use crate::invite::{Endpoint, Invite};
@@ -21,7 +27,7 @@ use crate::requests::{self, Publish, REFUSED};
pub(crate) struct Exchange {
pub(crate) server: Endpoint,
open: ClientMsg,
requests: VecDeque<Admin>,
requests: VecDeque<ClientMsg>,
answers: Answers,
/// The server let the connection in (its first answer came).
ready: bool,
@@ -35,6 +41,9 @@ pub(crate) struct Exchange {
pub(crate) struct Answers {
pub(crate) hosting: Option<HostInfo>,
pub(crate) replies: Vec<AdminReply>,
/// The answer on a library or plugin directory connection.
pub(crate) library: Option<LibraryReply>,
pub(crate) plugins: Option<PluginReply>,
}
/// What follows an exchange's answers (or why it failed).
@@ -46,6 +55,8 @@ pub(crate) enum Next {
Ask(Box<Exchange>, Then),
/// Done: tell the UI these, then join the file this invite names (`None`: nothing to join).
Done(Vec<Event>, Option<Invite>),
/// Tell the UI these now, then go on with what follows.
Tell(Vec<Event>, Box<Next>),
}
impl Exchange {
@@ -61,7 +72,23 @@ impl Exchange {
owner: owner.to_string(),
}),
};
Self { server, open, requests: requests.into(), answers: Answers::default(), ready: false, asked: false }
Self::opened(server, open, requests.into_iter().map(ClientMsg::Admin).collect())
}
/// Ask the library of the file behind `invite` one thing.
pub(crate) fn library(invite: Invite, req: LibraryReq) -> Self {
let open = OpenLibrary { protocol: PROTOCOL, file: invite.file, token: invite.token, client_version: message::client_version() };
Self::opened(invite.server, ClientMsg::OpenLibrary(open), VecDeque::from([ClientMsg::Library(req)]))
}
/// Ask the plugin directory of `server` one thing, with its `key` (empty: only browsing).
pub(crate) fn plugins(server: Endpoint, key: String, req: PluginReq) -> Self {
let open = OpenPlugins { protocol: PROTOCOL, key, client_version: message::client_version() };
Self::opened(server, ClientMsg::OpenPlugins(open), VecDeque::from([ClientMsg::Plugins(req)]))
}
fn opened(server: Endpoint, open: ClientMsg, requests: VecDeque<ClientMsg>) -> Self {
Self { server, open, requests, answers: Answers::default(), ready: false, asked: false }
}
/// The connection's first message.
@@ -81,7 +108,11 @@ impl Exchange {
/// Why the exchange failed with `e`, as the app says it: a server older than open hosting
/// can't read the opening.
pub(crate) fn failed(&self, e: String) -> String {
if self.ready || !matches!(self.open, ClientMsg::OpenHosting(_)) { e } else { requests::hosting_error(&self.server, e) }
match self.open {
ClientMsg::OpenHosting(_) if !self.ready => requests::hosting_error(&self.server, e),
ClientMsg::OpenPlugins(_) if !self.ready => requests::directory_error(&self.server, e),
_ => e,
}
}
/// Take in one message from the server: the next request to send, if one is due; an error
@@ -99,13 +130,22 @@ impl Exchange {
self.ready = true;
self.answers.hosting = Some(*info);
}
ServerMsg::Library(r) if self.asked => self.answers.library = Some(*r),
ServerMsg::Library(r) if !self.ready => match *r {
LibraryReply::Ready { .. } => self.ready = true,
other => return Err(format!("the server answered {other:?} instead of opening the library")),
},
ServerMsg::Plugins(r) if self.asked => self.answers.plugins = Some(*r),
ServerMsg::Plugins(r) if !self.ready => match *r {
PluginReply::Ready { .. } => self.ready = true,
other => return Err(format!("the server answered {other:?} instead of opening its plugin directory")),
},
_ => return Err("the server sent something other than an answer".into()),
}
self.asked = false;
Ok(self.requests.pop_front().map(|r| {
self.asked = true;
ClientMsg::Admin(r)
}))
let next = self.requests.pop_front();
self.asked = next.is_some();
Ok(next)
}
}
@@ -204,9 +244,35 @@ fn codes(s: Sharing, links: requests::Links, then: LinksThen) -> Next {
)
}
/// The answer to a library request, from what its exchange got.
fn library_reply(answers: Result<Answers, String>) -> Result<LibraryReply, String> {
answers.and_then(|a| a.library.ok_or_else(|| "the server didn't answer".to_string()))
}
/// Ask about the team libraries `jobs` `(link, request)`, in order, each on a connection of its
/// own. A fetch's answer goes to the UI as it comes, before the next connection, as the desktop's
/// does, so a slow or silent server further on holds no library back; the others' answers are left
/// out (a report's says nothing, and an older server refuses it). `fetching` goes down at the end.
pub(crate) fn libraries(mut jobs: VecDeque<(String, LibraryReq)>, fetching: Arc<AtomicBool>) -> Next {
let Some((link, req)) = jobs.pop_front() else {
fetching.store(false, Ordering::SeqCst);
return Next::Done(Vec::new(), None);
};
let fetch = matches!(req, LibraryReq::Fetch { .. });
let invite = Invite::parse(&link);
let then = move |reply: Result<LibraryReply, String>| {
let rest = libraries(jobs, fetching);
if fetch { Next::Tell(vec![Event::Library { link, reply }], Box::new(rest)) } else { rest }
};
match invite {
Err(e) => then(Err(e)),
Ok(invite) => Next::Ask(Box::new(Exchange::library(invite, req)), Box::new(move |answers| then(library_reply(answers)))),
}
}
/// Background request `req` (answered as [`Event::Net`] with `job`), for the requests the
/// browser sends: about a server's hosting, and changing who else gets into a file. `None` for
/// the others.
/// browser sends: about a server's hosting, changing who else gets into a file, its team libraries
/// and its plugin directory. `None` for the others.
pub(crate) fn background(job: u64, req: NetRequest) -> Option<Next> {
let answer = move |reply: NetReply| Next::Done(vec![Event::Net { job, reply: Box::new(reply) }], None);
Some(match req {
@@ -231,6 +297,21 @@ pub(crate) fn background(job: u64, req: NetRequest) -> Option<Next> {
share_links(Sharing { server, key, file, owner, revoke, create }, Box::new(move |r| answer(NetReply::Share(r))))
}
},
NetRequest::Plugins { .. } | NetRequest::Library { .. } | NetRequest::Upload(_) => return None,
NetRequest::Library { link, req } => match Invite::parse(&link) {
Err(e) => answer(NetReply::Library(Err(e))),
Ok(invite) => Next::Ask(Box::new(Exchange::library(invite, req)), Box::new(move |a| answer(NetReply::Library(library_reply(a))))),
},
NetRequest::Plugins { server, req } => match Endpoint::parse(&server) {
Err(e) => answer(NetReply::Plugins(Err(e))),
Ok((server, query)) => {
let key = query.into_iter().find(|(k, _)| k == "key").map(|(_, v)| v).unwrap_or_default();
let ex = Exchange::plugins(server, key.trim().to_string(), req);
Next::Ask(
Box::new(ex),
Box::new(move |a| answer(NetReply::Plugins(a.and_then(|a| a.plugins.ok_or_else(|| "the server didn't answer".to_string()))))),
)
}
},
NetRequest::Upload(_) => return None,
})
}
+112 -3
View File
@@ -4,9 +4,13 @@
//! background requests the browser can send.
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};
use figcraft_collab::message::{self, Access, Admin, AdminReply, ClientMsg, FileInfo, HostInfo, LinkInfo, NewLink, Presence, ServerMsg};
use figcraft_collab::message::{
self, Access, Admin, AdminReply, ClientMsg, Detached, FileInfo, HostInfo, LibraryReply, LibraryReq, LinkInfo, NewLink, PluginReply, PluginReq,
Presence, ServerMsg,
};
use figcraft_doc::{Document, NodeId};
use figcraft_engine::live::{Event, NetReply, NetRequest, Shared, Status};
@@ -344,6 +348,111 @@ fn background_requests_ask_about_hosting_and_sharing() {
let Some(Next::Done(events, None)) = exchange::background(1, bad) else { panic!("not answered at once") };
assert!(matches!(events.as_slice(), [Event::Net { reply, .. }] if matches!(**reply, NetReply::Hosting(Err(_)) | NetReply::Share(Err(_)))));
}
let plugins = NetRequest::Plugins { server: SERVER.into(), req: figcraft_collab::message::PluginReq::List { query: String::new() } };
assert!(exchange::background(1, plugins).is_none());
}
fn library(r: LibraryReply) -> ServerMsg {
ServerMsg::Library(Box::new(r))
}
fn directory(r: PluginReply) -> ServerMsg {
ServerMsg::Plugins(Box::new(r))
}
fn link() -> String {
format!("figcraft://join?host=127.0.0.1:47910&file={FILE}&token={TOKEN}")
}
/// The browser opens a team library, asks, and takes the answer; failures come back as answers.
#[test]
fn background_requests_ask_a_team_library() {
let ready = library(LibraryReply::Ready { access: Access::View });
let req = |req| NetRequest::Library { link: link(), req };
let (reply, sent) = background(req(LibraryReq::Usage), &[ready.clone(), library(LibraryReply::Usage(Vec::new()))]);
assert!(matches!(reply, NetReply::Library(Ok(LibraryReply::Usage(u))) if u.is_empty()));
assert!(matches!(sent.as_slice(), [ClientMsg::OpenLibrary(o), ClientMsg::Library(LibraryReq::Usage)] if o.file == FILE && o.token == TOKEN));
// A refusal, and a link that isn't one.
let (reply, _) = background(req(LibraryReq::Usage), &[ServerMsg::Refused { reason: "that link was revoked".into() }]);
assert!(matches!(reply, NetReply::Library(Err(e)) if e.contains("revoked")));
let bad = NetRequest::Library { link: "nope".into(), req: LibraryReq::Usage };
let Some(Next::Done(events, None)) = exchange::background(1, bad) else { panic!("not answered at once") };
assert!(matches!(events.as_slice(), [Event::Net { reply, .. }] if matches!(**reply, NetReply::Library(Err(_)))));
// Anything but the opening's answer first is no answer.
let (reply, _) = background(req(LibraryReq::Usage), &[library(LibraryReply::Empty)]);
assert!(matches!(reply, NetReply::Library(Err(e)) if e.contains("instead of opening the library")));
}
/// The browser asks a plugin directory, with the address's key when it has one.
#[test]
fn background_requests_ask_a_plugin_directory() {
let ready = directory(PluginReply::Ready { publisher: true });
let req = PluginReq::List { query: String::new() };
let ask = NetRequest::Plugins { server: format!("{SERVER}?key=k3y"), req: req.clone() };
let (reply, sent) = background(ask, &[ready, directory(PluginReply::List(Vec::new()))]);
assert!(matches!(reply, NetReply::Plugins(Ok(PluginReply::List(entries))) if entries.is_empty()));
assert!(matches!(sent.as_slice(), [ClientMsg::OpenPlugins(o), ClientMsg::Plugins(_)] if o.key == "k3y"));
// A server from before directories can't read the opening.
let older = NetRequest::Plugins { server: SERVER.into(), req };
let (reply, _) = background(older, &[ServerMsg::Refused { reason: "that couldn't be read".into() }]);
assert!(matches!(reply, NetReply::Plugins(Err(e)) if e.contains("has no plugin directory")));
let bad = NetRequest::Plugins { server: "nope".into(), req: PluginReq::List { query: String::new() } };
assert!(matches!(exchange::background(1, bad), Some(Next::Done(..))));
}
/// A file's check of its team libraries runs its requests in order, each on a connection of its
/// own; only fetches come back, whatever a report's answer, and a bad link doesn't stop the rest.
#[test]
fn a_library_check_runs_in_order_and_answers_only_its_fetches() {
let fetch = LibraryReq::Fetch { have: None, usage: None };
let jobs = vec![
("nope".to_string(), fetch.clone()),
(link(), fetch),
(link(), LibraryReq::ReportDetached(Detached::default())),
(link(), LibraryReq::ReportInserted(Detached::default())),
];
let fetching = Arc::new(AtomicBool::new(true));
let t0 = Instant::now();
let (mut d, inbox) = run(exchange::libraries(jobs.into(), fetching.clone()), t0);
let ready = library(LibraryReply::Ready { access: Access::View });
d.opened(t0);
say(&mut d, &ready, t0);
say(&mut d, &library(LibraryReply::Empty), t0);
d.opened(t0);
say(&mut d, &ready, t0);
// An older server refuses the report: the check goes on.
say(&mut d, &library(LibraryReply::Failed { reason: "no".into() }), t0);
d.opened(t0);
say(&mut d, &ServerMsg::Refused { reason: "couldn't be read".into() }, t0);
assert!(!fetching.load(Ordering::SeqCst), "the next check may start");
let events = inbox.drain();
let replies: Vec<_> = events.iter().filter_map(|e| if let Event::Library { reply, .. } = e { Some(reply) } else { None }).collect();
assert_eq!(replies.len(), 2, "{events:#?}");
assert!(replies[0].is_err());
assert!(matches!(replies[1], Ok(LibraryReply::Empty)));
}
/// A fetch's answer reaches the UI as it comes, not at the end of the check: a report after it
/// whose server never answers holds the first library back no longer than its own connection.
#[test]
fn a_library_check_hands_each_fetch_over_as_it_comes() {
let fetch = LibraryReq::Fetch { have: None, usage: None };
let jobs = vec![(link(), fetch.clone()), (link(), LibraryReq::ReportDetached(Detached::default())), (link(), fetch)];
let fetching = Arc::new(AtomicBool::new(true));
let t0 = Instant::now();
let (mut d, inbox) = run(exchange::libraries(jobs.into(), fetching.clone()), t0);
let fetched = |events: &[Event]| events.iter().filter(|e| matches!(e, Event::Library { .. })).count();
let ready = library(LibraryReply::Ready { access: Access::View });
d.opened(t0);
say(&mut d, &ready, t0);
say(&mut d, &library(LibraryReply::Empty), t0);
assert_eq!(fetched(&inbox.drain()), 1, "the first library is in while the report's server is asked");
// The report's connection never opens: the check gives up on it and goes on, saying nothing.
let t1 = t0 + Duration::from_secs(5);
d.tick(t1);
assert_eq!(fetched(&inbox.drain()), 0);
assert!(fetching.load(Ordering::SeqCst), "the check is still running");
d.opened(t1);
say(&mut d, &ready, t1);
say(&mut d, &library(LibraryReply::Empty), t1);
assert_eq!(fetched(&inbox.drain()), 1);
assert!(!fetching.load(Ordering::SeqCst) && d.done());
}
+3 -2
View File
@@ -8,8 +8,9 @@
//! engine's `collab.*` commands drive it and the UI reads the engine's live state. Network
//! threads wake the UI through a [`Waker`] only when something arrives; nothing polls.
//!
//! The browser build's [`NetLink`] joins sessions and publishes files to servers through the
//! browser's WebSocket API (`web-sys`); hosting a session needs the desktop app. Its connection
//! The browser build's [`NetLink`] joins sessions, publishes files to servers and asks them about
//! team libraries and plugin directories through the browser's WebSocket API (`web-sys`); hosting
//! a session needs the desktop app. Its connection
//! logic (`driver.rs`, `exchange.rs`) is target-independent and tested natively.
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
+4 -1
View File
@@ -277,7 +277,10 @@ impl LiveLink for NetLink {
let spawned = std::thread::Builder::new().name("library-fetch".into()).spawn(move || {
for (link, req) in jobs {
// A report's answer says nothing about the library (and an older server refuses it).
let report = matches!(req, LibraryReq::ReportDetached(_) | LibraryReq::ReportInserted(_) | LibraryReq::ReportAssets(_));
let report = matches!(
req,
LibraryReq::ReportDetached(_) | LibraryReq::ReportInserted(_) | LibraryReq::ReportAssets(_) | LibraryReq::ReportAssetActions(_)
);
let reply = manage::library(&link, req, &limits, CONNECT);
if !report {
inbox.push(Event::Library { link, reply });
+2 -3
View File
@@ -17,7 +17,7 @@ use crate::invite::{Endpoint, Invite, Lookup};
use crate::join::ask;
use crate::net::{Duplex, NetLimits, config, open};
pub(crate) use crate::requests::REFUSED;
use crate::requests::{code_requests, comment_request, hosting_error, link_requests, made_comment, made_links, shared};
use crate::requests::{code_requests, comment_request, directory_error, hosting_error, link_requests, made_comment, made_links, shared};
type Ws = WebSocket<Duplex>;
@@ -165,8 +165,7 @@ pub fn plugins(server: &Endpoint, key: &str, req: PluginReq, limits: &NetLimits,
match reply(&mut ws, limits, pick) {
Ok(PluginReply::Ready { .. }) => {}
// An older server can't read the request at all.
Err(e) if e.contains("couldn't be read") => return Err(format!("{} has no plugin directory (update the server)", server.display())),
Err(e) => return Err(e),
Err(e) => return Err(directory_error(server, e)),
Ok(other) => return Err(format!("the server answered {other:?} instead of opening its plugin directory")),
}
send(&mut ws, &ClientMsg::Plugins(req))?;
+6
View File
@@ -43,6 +43,12 @@ pub(crate) fn key_over_tls(server: &Endpoint, key: Option<&str>) -> Result<(), S
/// Why asking `server` about its hosting failed with `e`: a server older than open hosting can't
/// read the question.
/// Why opening `server`'s plugin directory failed with `e`: a server from before directories can't
/// read the opening.
pub(crate) fn directory_error(server: &Endpoint, e: String) -> String {
if e.contains("couldn't be read") { format!("{} has no plugin directory (update the server)", server.display()) } else { e }
}
pub(crate) fn hosting_error(server: &Endpoint, e: String) -> String {
if e.contains("couldn't be read") {
format!("{} takes files only with its key (it is older than this app): add ?key=… to the address", server.display())
+23 -8
View File
@@ -17,8 +17,10 @@
use std::cell::{Cell, RefCell};
use std::collections::BTreeMap;
use std::rc::Rc;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use figcraft_collab::message::{ClientMsg, Presence};
use figcraft_collab::message::{ClientMsg, LibraryReq, Presence};
use figcraft_engine::live::{Event, HostOptions, LiveLink, NO_SESSION, NetRequest, PublishOptions, SessionId, SessionInfo};
use wasm_bindgen::JsCast as _;
use wasm_bindgen::closure::Closure;
@@ -163,19 +165,29 @@ fn socket() -> (u64, BrowserSocket) {
(id, BrowserSocket { id, ws: None })
}
/// The browser's [`LiveLink`]: joins sessions and publishes files to servers; hosting a session
/// needs the desktop app.
/// The browser's [`LiveLink`]: joins sessions, publishes files to servers and asks them about team
/// libraries and plugin directories; hosting a session needs the desktop app.
pub struct NetLink {
/// Each session's number in the thread-local table.
sessions: Sessions<u64>,
/// Answers to requests sent in the background (outlives sessions).
background: Inbox,
/// A check of the team libraries is out.
fetching: Arc<AtomicBool>,
}
impl NetLink {
/// `wake` is called whenever something arrives for the UI (egui's `request_repaint`).
pub fn new(wake: Waker) -> Self {
Self { background: Inbox::new(wake.clone()), sessions: Sessions::new(wake) }
Self { background: Inbox::new(wake.clone()), sessions: Sessions::new(wake), fetching: Arc::default() }
}
/// Run `next` on a connection of its own, its answers for the background.
fn ask(&self, next: exchange::Next) {
let (id, sock) = socket();
// The exchanges name their own servers.
let cfg = GuestConfig::new(Invite::new("", "", ""), String::new());
run(id, Driver::asking(sock, cfg, next, self.background.clone(), Instant::now()));
}
/// Session `session` runs on connection `id` now (the one it had ends).
@@ -229,13 +241,16 @@ impl LiveLink for NetLink {
fn background(&mut self, job: u64, req: NetRequest) -> bool {
let Some(next) = exchange::background(job, req) else { return false };
let (id, sock) = socket();
// The exchanges name their own servers.
let cfg = GuestConfig::new(Invite::new("", "", ""), String::new());
run(id, Driver::asking(sock, cfg, next, self.background.clone(), Instant::now()));
self.ask(next);
true
}
fn library_background(&mut self, jobs: Vec<(String, LibraryReq)>) {
if !jobs.is_empty() && !self.fetching.swap(true, Ordering::SeqCst) {
self.ask(exchange::libraries(jobs.into(), self.fetching.clone()));
}
}
fn leave(&mut self, session: SessionId) {
if let Some(id) = self.sessions.remove(session) {
with_driver(id, |d, now| d.leave(now));
+18 -2
View File
@@ -629,6 +629,15 @@ pub struct AssetUsage {
pub variables: Vec<(String, u32)>,
}
/// How many times one file has inserted and detached a library's styles and variables, as its app
/// reports them: its name and its totals of each (by their ids in the library).
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct AssetActions {
pub file: String,
pub inserted: Vec<(String, u32)>,
pub detached: Vec<(String, u32)>,
}
/// A file's last usage report, with when it came (seconds since 1970, UTC).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct FileUsage {
@@ -655,9 +664,9 @@ pub struct FileDetached {
/// 1970 UTC, a Monday at 00:00), over every file that reported it: instances inserted (placed,
/// pasted or duplicated) and detached, counted when the server first heard of them.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct WeekActions {
pub struct WeekActions<K = NodeId> {
pub week: u64,
pub component: NodeId,
pub component: K,
pub insertions: u32,
pub detachments: u32,
}
@@ -692,6 +701,12 @@ pub enum LibraryReq {
ReportAssets(AssetUsage),
/// The style and variable reports of the files that use the library.
Assets,
/// How many times the asking file has inserted and detached the library's styles and variables
/// (answered with [`LibraryReply::Noted`]).
ReportAssetActions(AssetActions),
/// The library's styles' and variables' insertions and detachments week by week (answered with
/// [`LibraryReply::AssetActions`]).
AssetActions,
}
/// The answer to a [`LibraryReq`] (the first one on a connection answers [`OpenLibrary`]).
@@ -727,6 +742,7 @@ pub enum LibraryReply {
Detached(Vec<FileDetached>),
Actions(Vec<WeekActions>),
Assets(Vec<AssetUsage>),
AssetActions(Vec<WeekActions<String>>),
}
/// Opens a connection to a server's plugin directory (instead of [`Hello`]). Anyone who can reach
+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));
}
+6
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;
@@ -1355,6 +1359,8 @@ mod proto_overlay_anchor_tests;
#[cfg(test)]
mod tests;
#[cfg(test)]
mod vector_radius_tests;
#[cfg(test)]
mod vector_regions_tests;
#[cfg(test)]
mod width_sides_tests;
+31
View File
@@ -217,6 +217,10 @@ pub struct Libraries {
/// or duplicated; reported like [`Self::detached`]), at most [`MAX_DETACH_COUNTS`] components.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub inserted: Vec<DetachCount>,
/// How often this document has inserted and detached each library style and variable
/// (reported like [`Self::detached`]), at most [`MAX_DETACH_COUNTS`] of them.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub asset_counts: Vec<AssetCount>,
}
/// Most library components a document counts detaches for.
@@ -233,6 +237,17 @@ pub struct DetachCount {
pub count: u32,
}
/// Inserts and detaches of one library style or variable in a document.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct AssetCount {
/// The library's id.
pub library: String,
/// Its id in the library.
pub key: String,
pub inserted: u32,
pub detached: u32,
}
/// Count one more instance of component `key` of library `library` in `list` (a component not
/// counted yet is left out once [`MAX_DETACH_COUNTS`] are).
fn count(list: &mut Vec<DetachCount>, library: &str, key: NodeId) {
@@ -256,6 +271,21 @@ impl Libraries {
count(&mut self.inserted, library, key);
}
/// Count `n` more inserts (or, with `detach`, detaches) of style or variable `key` of library
/// `library` (one not counted yet is left out once [`MAX_DETACH_COUNTS`] are).
pub fn count_asset(&mut self, library: &str, key: &str, detach: bool, n: u32) {
let at = self.asset_counts.iter().position(|c| c.library == library && c.key == key);
let at = at.or_else(|| {
let room = self.asset_counts.len() < MAX_DETACH_COUNTS;
room.then(|| self.asset_counts.push(AssetCount { library: library.to_string(), key: key.to_string(), inserted: 0, detached: 0 }))?;
Some(self.asset_counts.len() - 1)
});
if let Some(c) = at.and_then(|at| self.asset_counts.get_mut(at)) {
let total = if detach { &mut c.detached } else { &mut c.inserted };
*total = total.saturating_add(n);
}
}
/// Whether nothing is enabled, kept or counted.
pub fn is_empty(&self) -> bool {
self.enabled.is_empty()
@@ -266,6 +296,7 @@ impl Libraries {
&& self.variables.is_empty()
&& self.detached.is_empty()
&& self.inserted.is_empty()
&& self.asset_counts.is_empty()
}
/// Serde helper: leave the field out of files that use no libraries.
+49 -11
View File
@@ -145,6 +145,25 @@ struct Corner {
cut2: f64,
}
/// Where point `v` turns between its two segments, for rounding it: `r` its radius, `s1`/`s2` the
/// segments (`a1`/`a2` whether `v` is their `a` end), `c1`/`c2` them as curves running away from
/// `v`, `u1`/`u2` the directions they leave in, `angle` between those, and `l1`/`l2` their lengths.
struct Turn {
v: usize,
r: f64,
s1: usize,
a1: bool,
s2: usize,
a2: bool,
c1: CubicBez,
c2: CubicBez,
u1: Vec2,
u2: Vec2,
angle: f64,
l1: f64,
l2: f64,
}
/// One curve of a rounded point: its handles at its start (`ta`) and its end (`tb`), relative to
/// those ends, and the point it ends at.
struct CornerCurve {
@@ -391,10 +410,11 @@ impl VectorNetwork {
}
/// The network with its rounded points drawn in: each sharp point with a corner radius becomes
/// an arc between its two segments (the radius shrinks so the arc fits in half of each
/// segment, like a polygon's corners). A curved segment is cut where the arc meets it and keeps
/// the rest of its curve, the arc leaving along its direction there. `None` when no point is
/// rounded.
/// an arc between its two segments. The radius shrinks so the arc fits: a segment whose other
/// end is rounded too is shared, half for each end, as a polygon's sides are, and one whose
/// other end stays sharp can be used whole (as in Figma, #2334). A curved segment is cut where
/// the arc meets it and keeps the rest of its curve, the arc leaving along its direction there.
/// `None` when no point is rounded.
pub fn rounded(&self) -> Option<VectorNetwork> {
self.rounded_smoothed(0.0)
}
@@ -424,7 +444,9 @@ impl VectorNetwork {
*x = true;
}
}
let corners: Vec<Corner> = (0..self.vertices.len()).filter_map(|v| self.corner(v, incident.get(v)?, smoothing, &on_loop)).collect();
let turns: Vec<Option<Turn>> = (0..self.vertices.len()).map(|v| self.turn(v, incident.get(v)?)).collect();
let rounds: Vec<bool> = turns.iter().map(Option::is_some).collect();
let corners: Vec<Corner> = turns.iter().flatten().filter_map(|t| self.corner(t, smoothing, &on_loop, &rounds)).collect();
let mut out = self.clone();
for v in &mut out.vertices {
v.radius = 0.0;
@@ -558,10 +580,9 @@ impl VectorNetwork {
joining.next().is_none().then_some(first)
}
/// How point `v` (its `incident` segments) is rounded, if it is: not where the two segments
/// run on smoothly or fold back. With `smoothing`, a point between two straight segments that
/// are both `on_loop` gets a smoothed corner.
fn corner(&self, v: usize, incident: &[(usize, bool)], smoothing: f64, on_loop: &[bool]) -> Option<Corner> {
/// How point `v` (its `incident` segments) turns, if it is rounded: it has a radius and two
/// segments that neither run on smoothly nor fold back there.
fn turn(&self, v: usize, incident: &[(usize, bool)]) -> Option<Turn> {
let r = self.vertices.get(v)?.radius;
let [(s1, a1), (s2, a2)] = *incident else { return None };
if !(r > 0.0 && r.is_finite()) || s1 == s2 {
@@ -577,6 +598,23 @@ impl VectorNetwork {
if !(l1 > 1e-9 && l2 > 1e-9) {
return None;
}
Some(Turn { v, r, s1, a1, s2, a2, c1, c2, u1, u2, angle, l1, l2 })
}
/// How far along segment `s` (`l` long) from its `a` end (`at_a`) or its `b` end the corner
/// there may reach: all of it when the other end stays sharp, half when that end is rounded
/// too (`rounds`, by point) and takes the other half.
fn room(&self, s: usize, at_a: bool, l: f64, rounds: &[bool]) -> f64 {
let far = self.segments.get(s).map(|x| if at_a { x.b } else { x.a });
if far.and_then(|f| rounds.get(f)).copied().unwrap_or(false) { l / 2.0 } else { l }
}
/// The corner of a rounded point (`p`, see [`Self::turn`]); it reaches along each segment as
/// far as [`Self::room`] allows (`rounds`: which points are rounded). With `smoothing`, a point
/// between two straight segments that are both `on_loop` gets a smoothed corner.
fn corner(&self, p: &Turn, smoothing: f64, on_loop: &[bool], rounds: &[bool]) -> Option<Corner> {
let &Turn { v, r, s1, a1, s2, a2, c1, c2, u1, u2, angle, l1, l2 } = p;
let reach = self.room(s1, a1, l1, rounds).min(self.room(s2, a2, l2, rounds));
let own = |at_a: bool, t: f64| if at_a { t } else { 1.0 - t };
let closed = |s: usize| on_loop.get(s).copied().unwrap_or(false);
if smoothing > 0.0
@@ -584,7 +622,7 @@ impl VectorNetwork {
&& is_line(&c2)
&& closed(s1)
&& closed(s2)
&& let Some(curves) = figcraft_geom::smoothed_corner(c1.p0, u1, u2, l1.min(l2) / 2.0, r, smoothing)
&& let Some(curves) = figcraft_geom::smoothed_corner(c1.p0, u1, u2, reach, r, smoothing)
&& let (Some(first), Some(last)) = (curves.first(), curves.last())
{
let (a, b) = (first.p0, last.p3);
@@ -595,7 +633,7 @@ impl VectorNetwork {
let (cut1, cut2) = ((a - c1.p0).hypot() / l1, (b - c2.p0).hypot() / l2);
return Some(Corner { v, s1, s1_at_a: a1, s2, s2_at_a: a2, a, chain, cut1: own(a1, cut1), cut2: own(a2, cut2) });
}
let t = (r / (angle / 2.0).tan()).min(l1.min(l2) / 2.0);
let t = (r / (angle / 2.0).tan()).min(reach);
let ((a, d1, k1), (b, d2, k2)) = (trim(&c1, t, l1), trim(&c2, t, l2));
// A cubic arc: handles of 4/3·tan(φ/4)·ρ along each end's direction, φ the turn between
// them and ρ the radius of the circle through both ends (the corner radius between lines).
+118
View File
@@ -0,0 +1,118 @@
//! How far a rounded point's arc may reach along its segments (#2334): the whole segment when the
//! segment's other end stays sharp, half of it when that end is rounded too. Figma draws a single
//! rounded point of a 100 × 100 square with radius 100 as an arc from one neighbour to the other.
use figcraft_geom::kurbo::{CubicBez, ParamCurve, PathSeg};
use figcraft_geom::{BezPath, Point};
use crate::vector::VectorNetwork;
/// A 100 × 100 square's points: top left, top right, bottom right, bottom left.
const SQUARE: [Point; 4] = [Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(100.0, 100.0), Point::new(0.0, 100.0)];
/// A network through `pts` (closed or open) whose points have radii `radii`.
fn network(pts: &[Point], closed: bool, radii: &[f64]) -> VectorNetwork {
let mut n = VectorNetwork::from_points(pts, closed);
for (v, r) in n.vertices.iter_mut().zip(radii) {
v.radius = *r;
}
n
}
/// The cubic curves of `path` (the rounded points' arcs; every other segment is straight).
fn curves(path: &BezPath) -> Vec<CubicBez> {
path.segments()
.filter_map(|s| match s {
PathSeg::Cubic(c) => Some(c),
_ => None,
})
.collect()
}
/// Whether `a` and `b` are the same point to within rounding.
fn near(a: Point, b: Point) -> bool {
(a - b).hypot() < 1e-9
}
/// Checks that `path` draws, for each `(corner, prev, next, t)` of `want`, a circular arc
/// between the points `t` from `corner` toward `prev` and toward `next` (a right angle, so the
/// circle's radius is `t`), and no other curve.
fn assert_arcs(path: &BezPath, want: &[(Point, Point, Point, f64)], why: &str) {
let got = curves(path);
assert_eq!(got.len(), want.len(), "{why}: {got:?}");
for &(corner, prev, next, t) in want {
let toward = |p: Point| corner + (p - corner) / (p - corner).hypot() * t;
let (a, b) = (toward(prev), toward(next));
let center = a + (b - corner);
let mid = center + (corner - center) / (corner - center).hypot() * t;
// Two arcs can share both ends (opposite corners of a square), so the middle picks one.
let ends = |c: &&CubicBez| (near(c.p0, a) && near(c.p3, b)) || (near(c.p0, b) && near(c.p3, a));
let passing: Vec<Point> = got.iter().filter(ends).map(|c| c.eval(0.5)).collect();
assert!(
passing.iter().any(|&m| near(m, mid)),
"{why}: no arc at {corner:?} from {a:?} to {b:?} through {mid:?}; arcs between them pass {passing:?}"
);
}
}
#[test]
fn a_rounded_points_arc_reaches_as_far_as_its_segments_other_ends_allow() {
let [tl, tr, br, bl] = SQUARE;
// (radii of [top left, top right, bottom right, bottom left], each arc as (point, its
// neighbours, how far it reaches along both), derivation)
#[allow(clippy::type_complexity)]
let rows: Vec<([f64; 4], Vec<(Point, Point, Point, f64)>, &str)> = vec![
([0.0, 0.0, 100.0, 0.0], vec![(br, tr, bl, 100.0)], "the issue's square: the arc runs from one sharp neighbour to the other"),
([0.0, 0.0, 500.0, 0.0], vec![(br, tr, bl, 100.0)], "a larger radius stops at the sharp neighbours"),
([0.0, 0.0, 75.0, 0.0], vec![(br, tr, bl, 75.0)], "a radius past half the segments is drawn whole"),
([0.0, 0.0, 40.0, 0.0], vec![(br, tr, bl, 40.0)], "a radius that fits half the segments is unchanged"),
(
[0.0, 10.0, 100.0, 0.0],
vec![(tr, tl, br, 10.0), (br, tr, bl, 50.0)],
"the segment to the rounded top right is shared, half each, and the shorter room wins",
),
(
[100.0, 0.0, 100.0, 0.0],
vec![(tl, bl, tr, 100.0), (br, tr, bl, 100.0)],
"opposite points share no segment: each reaches its sharp neighbours (a lens)",
),
(
[100.0; 4],
vec![(tl, bl, tr, 50.0), (tr, tl, br, 50.0), (br, tr, bl, 50.0), (bl, br, tl, 50.0)],
"every point rounded: a circle, as before",
),
];
for (radii, want, why) in rows {
let net = network(&SQUARE, true, &radii);
assert_arcs(&net.fill_path(), &want, why);
assert_arcs(&net.stroke_path(), &want, why);
// The stored radii stay as they were set.
assert_eq!(net.vertices.iter().map(|p| p.radius).collect::<Vec<_>>(), radii.to_vec(), "{why}");
}
}
#[test]
fn an_open_paths_ends_leave_its_rounded_point_the_whole_segments() {
let pts = [Point::new(0.0, 0.0), Point::new(0.0, 100.0), Point::new(100.0, 100.0)];
// (radii, derivation): the ends don't turn, so a radius on them rounds nothing and takes no
// room from the middle point.
let rows: Vec<([f64; 3], &str)> =
vec![([0.0, 100.0, 0.0], "sharp ends"), ([100.0, 100.0, 100.0], "ends with a radius of their own stay sharp and leave the room to it")];
for (radii, why) in rows {
let net = network(&pts, false, &radii);
assert_arcs(&net.stroke_path(), &[(pts[1], pts[0], pts[2], 100.0)], why);
}
}
#[test]
fn a_smoothed_corner_takes_the_room_of_a_sharp_neighbour_before_losing_smoothing() {
// Radius 40 with smoothing 0.6 eases in from 1.6 × 40 = 64 along each side. Half of a 100
// side (50) would cut smoothing down; the whole side next to sharp points leaves all of it.
let net = network(&SQUARE, true, &[0.0, 0.0, 40.0, 0.0]);
let path = net.rounded_smoothed(0.6).unwrap().fill_path();
let ends: Vec<Point> = curves(&path).iter().flat_map(|c| [c.p0, c.p3]).collect();
for p in [Point::new(100.0, 36.0), Point::new(36.0, 100.0)] {
assert!(ends.iter().any(|e| (*e - p).hypot() < 1e-6), "the smoothed corner starts at {p:?}: {ends:?}");
}
assert!(ends.iter().all(|e| e.x >= 36.0 - 1e-6 && e.y >= 36.0 - 1e-6), "and reaches no further: {ends:?}");
}
+121
View File
@@ -72,6 +72,127 @@ fn fill_on_a_child_turns_the_hugging_parent_fixed() {
assert_eq!(sizing(&s, f), (Sizing::Hug, Sizing::Hug));
}
fn name_of(s: &Session, node: NodeId) -> String {
s.doc().unwrap().node(node).unwrap().name.clone()
}
/// Measured in Figma web (2026-11-08): across the flow a Fill child
/// leaves its hugging parent hugging and takes the line's cross size; the parent turns Fixed (with
/// a notice) only when no non-Fill child is left on that axis.
#[test]
fn fill_across_a_hugging_parent_keeps_it_hugging_and_takes_the_line() {
let mut s = Session::new();
let f = al_frame(&mut s, json!({"sizingH": "hug", "sizingV": "hug"}));
let a = rect(&mut s, f, 4.0, 20.0, "#FF0000");
let b = rect(&mut s, f, 50.0, 40.0, "#0000FF");
assert_eq!(size(&s, f), (54.0, 40.0));
s.message = None;
set(&mut s, a, json!({"sizingV": "fill"}));
assert_eq!(sizing(&s, f), (Sizing::Hug, Sizing::Hug), "a non-Fill sibling is left: the parent keeps hugging");
assert_eq!(sizing(&s, a), (Sizing::Fixed, Sizing::Fill));
assert_eq!((size(&s, a), size(&s, f)), ((4.0, 40.0), (54.0, 40.0)));
assert_eq!(s.message, None, "no notice");
// The sibling grows: the bar and the parent follow.
set(&mut s, b, json!({"height": 60}));
assert_eq!((size(&s, a), size(&s, f)), ((4.0, 60.0), (54.0, 60.0)));
// The last non-Fill child fills too: the parent turns Fixed at its current height, with a notice.
set(&mut s, b, json!({"sizingV": "fill"}));
assert_eq!(sizing(&s, f), (Sizing::Hug, Sizing::Fixed));
assert_eq!(s.message, Some(format!("Height set to Fixed for {}", name_of(&s, f))));
assert_eq!((size(&s, a), size(&s, b), size(&s, f)), ((4.0, 60.0), (50.0, 60.0), (54.0, 60.0)));
set(&mut s, f, json!({"height": 80}));
assert_eq!((size(&s, a), size(&s, b)), ((4.0, 80.0), (50.0, 80.0)));
// One undo step puts the sizing back.
s.undo().unwrap();
s.undo().unwrap();
assert_eq!(sizing(&s, f), (Sizing::Hug, Sizing::Hug));
assert_eq!(sizing(&s, b), (Sizing::Fixed, Sizing::Fixed));
}
#[test]
fn fill_along_a_hugging_parent_notes_that_the_width_is_fixed() {
let mut s = Session::new();
let f = al_frame(&mut s, json!({"sizingH": "hug", "sizingV": "hug"}));
let a = rect(&mut s, f, 50.0, 20.0, "#FF0000");
rect(&mut s, f, 30.0, 40.0, "#0000FF");
s.message = None;
set(&mut s, a, json!({"sizingH": "fill"}));
assert_eq!(sizing(&s, f), (Sizing::Fixed, Sizing::Hug));
assert_eq!(s.message, Some(format!("Width set to Fixed for {}", name_of(&s, f))));
// A Fill that changes nothing about the parent has no notice.
s.message = None;
set(&mut s, a, json!({"sizingV": "fill"}));
assert_eq!(s.message, None);
}
#[test]
fn hugging_a_row_notes_the_child_that_filled_its_width_turned_fixed() {
let mut s = Session::new();
let f = al_frame(&mut s, json!({"sizingH": "fixed", "sizingV": "fixed"}));
let a = rect(&mut s, f, 50.0, 20.0, "#FF0000");
rect(&mut s, f, 30.0, 40.0, "#0000FF");
set(&mut s, a, json!({"sizingH": "fill"}));
assert_eq!(sizing(&s, a).0, Sizing::Fill);
s.message = None;
set(&mut s, f, json!({"sizingH": "hug"}));
assert_eq!(sizing(&s, a).0, Sizing::Fixed);
assert_eq!(s.message, Some(format!("Width set to Fixed for {}", name_of(&s, a))));
}
#[test]
fn hugging_a_row_keeps_and_does_not_note_the_child_that_fills_across_it() {
let mut s = Session::new();
let f = al_frame(&mut s, json!({"sizingH": "fixed", "sizingV": "fixed"}));
let a = rect(&mut s, f, 50.0, 20.0, "#FF0000");
rect(&mut s, f, 30.0, 40.0, "#0000FF");
set(&mut s, a, json!({"sizingV": "fill"}));
s.message = None;
set(&mut s, f, json!({"sizingV": "hug"}));
assert_eq!(sizing(&s, a).1, Sizing::Fill);
assert_eq!(s.message, None);
}
#[test]
fn a_fill_childs_min_counts_toward_the_hugging_size() {
let mut s = Session::new();
let f = al_frame(&mut s, json!({"sizingH": "hug", "sizingV": "hug"}));
let a = rect(&mut s, f, 4.0, 20.0, "#FF0000");
let b = rect(&mut s, f, 50.0, 40.0, "#0000FF");
set(&mut s, a, json!({"sizingV": "fill"}));
set(&mut s, a, json!({"minHeight": 50}));
assert_eq!(sizing(&s, f), (Sizing::Hug, Sizing::Hug));
assert_eq!((size(&s, a), size(&s, b), size(&s, f)), ((4.0, 50.0), (50.0, 40.0), (54.0, 50.0)));
}
#[test]
fn a_parent_set_back_to_hug_keeps_the_child_that_fills_across_it() {
let mut s = Session::new();
let f = al_frame(&mut s, json!({"sizingH": "hug", "sizingV": "fixed", "height": 100}));
let a = rect(&mut s, f, 4.0, 20.0, "#FF0000");
rect(&mut s, f, 50.0, 40.0, "#0000FF");
set(&mut s, a, json!({"sizingV": "fill"}));
assert_eq!(size(&s, a), (4.0, 100.0));
set(&mut s, f, json!({"sizingV": "hug"}));
assert_eq!(sizing(&s, a), (Sizing::Fixed, Sizing::Fill), "a non-Fill sibling is left on that axis");
assert_eq!((size(&s, a), size(&s, f)), ((4.0, 40.0), (54.0, 40.0)));
}
#[test]
fn fill_across_a_wrapping_row_that_hugs_that_axis_is_not_offered() {
let mut s = Session::new();
let f = al_frame(&mut s, json!({"wrap": true, "sizingH": "fixed", "sizingV": "hug", "width": 120}));
let a = rect(&mut s, f, 40.0, 20.0, "#FF0000");
let r = s.execute("node.set", &json!({"id": a, "props": {"sizingV": "fill"}}));
assert!(r.is_err(), "Fill height in a wrapping row that hugs its height");
assert_eq!(sizing(&s, a), (Sizing::Fixed, Sizing::Fixed));
assert_eq!(sizing(&s, f), (Sizing::Fixed, Sizing::Hug));
// Along the flow a wrapping row still takes Fill width, and with a fixed height Fill height.
set(&mut s, a, json!({"sizingH": "fill"}));
set(&mut s, f, json!({"sizingV": "fixed"}));
set(&mut s, a, json!({"sizingV": "fill"}));
assert_eq!(sizing(&s, a), (Sizing::Fill, Sizing::Fill));
}
#[test]
fn a_child_resized_to_the_full_available_space_becomes_fill() {
// Documented: "Child objects of an auto layout frame will also be set to Fill container if
+23 -1
View File
@@ -336,6 +336,28 @@ fn index_old_layers(doc: &Document, inst: NodeId, spare: BTreeMap<NodeId, std::s
(old, by_source, by_src)
}
/// The `ChildLayout` of an instance's rebuilt root. Its placement is its own (absolute position,
/// grid cell, min and max). `sizing_h` / `sizing_v` serve two roles: how a frame sizes its own
/// content (Hug, Fixed), which follows the main unless the instance overrides its size (measured in
/// Figma: a plain instance turns Fixed when its main does and back to Hug with it; a typed width
/// stays), and Fill in an auto layout parent, which is the instance's own and is kept.
fn instance_child_layout(doc: &Document, root: &Node, comp: &Node) -> figcraft_doc::ChildLayout {
let mut cl = root.child_layout.clone();
// One "size" override covers both axes, as in Figma ("Reset size"): it keeps both.
if root.overrides.contains("size") || root.overrides.contains("resizing") {
return cl;
}
let in_flow = root.parent.and_then(|p| doc.node(p)).is_some_and(|p| p.layout.is_some());
let take = |own: &mut figcraft_doc::Sizing, main: figcraft_doc::Sizing| {
if !(in_flow && *own == figcraft_doc::Sizing::Fill) && main != figcraft_doc::Sizing::Fill {
*own = main;
}
};
take(&mut cl.sizing_h, comp.child_layout.sizing_h);
take(&mut cl.sizing_v, comp.child_layout.sizing_v);
cl
}
/// The rebuilt root of instance `inst` of `comp`.
fn fresh_root(doc: &Document, root: &mut Node, comp: &Node, inst: NodeId, component: NodeId, map: &BTreeMap<NodeId, NodeId>) -> Node {
// Root: follows the main except its own placement, name, size and overrides.
@@ -351,7 +373,7 @@ fn fresh_root(doc: &Document, root: &mut Node, comp: &Node, inst: NodeId, compon
let nested_copy = inside_instance(doc, inst);
fresh.source = if nested_copy { root.source } else { Some(component) };
fresh.constraints = root.constraints;
fresh.child_layout = root.child_layout.clone();
fresh.child_layout = instance_child_layout(doc, root, comp);
fresh.interactions = root.interactions.clone();
fresh.exports = root.exports.clone();
fresh.prop_refs = root.prop_refs.clone();
+65 -5
View File
@@ -83,14 +83,66 @@ pub fn asset_root(doc: &Document, id: NodeId) -> Option<NodeId> {
chain.into_iter().rfind(|c| doc.node(*c).is_some_and(is_asset))
}
/// The styles and variables layer `n` links to, each once.
fn asset_links(n: &Node) -> BTreeSet<&str> {
style_links(n).map(String::as_str).chain(n.bound.values().map(String::as_str)).collect()
}
/// The library and the id there of a local copy of a library style or variable.
fn asset_record<'a>(doc: &'a Document, local: &str) -> Option<&'a ImportedRecord> {
doc.libraries.styles.iter().chain(&doc.libraries.variables).find(|r| r.local == local)
}
/// How many layers link to each local copy of a library style or variable. An instance and the
/// layers in it don't count: an instance counts as its component alone, as in [`count_inserted`].
fn library_links(doc: &Document) -> BTreeMap<String, u32> {
let mut links = BTreeMap::new();
if doc.libraries.styles.is_empty() && doc.libraries.variables.is_empty() {
return links;
}
let mut stack = doc.pages.clone();
while let Some(id) = stack.pop() {
let Some(n) = doc.node(id) else { continue };
if matches!(n.kind, NodeKind::Instance { .. }) {
continue;
}
stack.extend(n.children.iter().copied());
for local in asset_links(n).into_iter().filter(|l| asset_record(doc, l).is_some()) {
*links.entry(local.to_string()).or_default() += 1;
}
}
links
}
/// Run `edit`, a user's applying (or, with `detach`, detaching) of styles or variables, and count
/// the layers it links to library copies (or unlinks from them) for the libraries' analytics. A
/// style replaced by another isn't a detach: only what the action names counts.
pub(crate) fn counting_links<T>(s: &mut crate::Session, detach: bool, edit: impl FnOnce(&mut crate::Session) -> Result<T>) -> Result<T> {
let before = library_links(s.doc()?);
let out = edit(s)?;
let after = library_links(s.doc()?);
let (from, to) = if detach { (&after, &before) } else { (&before, &after) };
let grown: Vec<_> = to.iter().map(|(l, n)| (l, n.saturating_sub(from.get(l).copied().unwrap_or(0)))).filter(|g| g.1 > 0).collect();
for (local, n) in grown {
let doc = s.doc_mut()?;
if let Some(r) = asset_record(doc, local).cloned() {
doc.libraries_mut().count_asset(&r.library, &r.key, detach, n);
}
}
Ok(out)
}
/// Count the instances of library components among `roots` (new layers: placed, pasted or
/// duplicated) and in what they hold as inserted, for the libraries' analytics. An instance inside
/// another instance is part of it and isn't counted on its own.
/// duplicated) and in what they hold as inserted, and the library styles and variables of the
/// rest, for the libraries' analytics. An instance inside another instance is part of it and isn't
/// counted on its own, and what an instance uses is counted as the instance alone.
pub(crate) fn count_inserted(doc: &mut Document, roots: &[NodeId]) {
if doc.libraries.components.is_empty() {
let l = &doc.libraries;
if l.components.is_empty() && l.styles.is_empty() && l.variables.is_empty() {
return;
}
let mut found = Vec::new();
let mut assets = Vec::new();
let mut stack = roots.to_vec();
while let Some(id) = stack.pop() {
let Some(n) = doc.node(id) else { continue };
@@ -99,12 +151,18 @@ pub(crate) fn count_inserted(doc: &mut Document, roots: &[NodeId]) {
let root = asset_root(doc, component);
found.extend(doc.libraries.components.iter().find(|r| Some(r.root) == root).map(|r| (r.library.clone(), r.key)));
}
_ => stack.extend(n.children.iter().copied()),
_ => {
stack.extend(n.children.iter().copied());
assets.extend(asset_links(n).into_iter().filter_map(|l| asset_record(doc, l)).cloned());
}
}
}
for (library, key) in found {
doc.libraries_mut().count_insert(&library, key);
}
for r in assets {
doc.libraries_mut().count_asset(&r.library, &r.key, false, 1);
}
}
/// Components the layers of `root` use: mains of instances, instance swap defaults and values.
@@ -1158,10 +1216,12 @@ pub fn prune(doc: &mut Document, library: &str) -> Result<()> {
doc.styles.retain(|s| !unused.contains(&s.id));
doc.libraries_mut().styles.retain(|r| !unused.contains(&r.local));
}
// Variables layers bind or set, local variables alias or extend (with what those alias).
// Variables layers bind or set, styles bind, local variables alias or extend (with what those
// alias).
let seeds = doc
.nodes()
.flat_map(|n| n.bound.values().map(String::as_str).chain(action_variables(n)))
.chain(doc.styles.iter().flat_map(|s| s.bound.values().map(String::as_str)))
.chain(doc.variables.variables.iter().filter_map(|v| v.extends.as_deref()))
.map(str::to_string)
.chain(
+40 -2
View File
@@ -15,7 +15,7 @@ use std::collections::{BTreeMap, BTreeSet};
use std::io::Cursor;
use std::sync::Arc;
use figcraft_collab::message::{AssetUsage, Detached, LibraryReply, LibraryReq, MAX_ASSET_USAGE, Usage};
use figcraft_collab::message::{AssetActions, AssetUsage, Detached, LibraryReply, LibraryReq, MAX_ASSET_USAGE, Usage};
use figcraft_doc::{DetachCount, Document, ImportedRecord, NodeId, NodeKind, PublishedLibrary};
use crate::live::{NetReply, NetRequest};
@@ -123,6 +123,43 @@ pub fn asset_usage(doc: &Document, library: &str) -> Option<AssetUsage> {
Some(AssetUsage { file: doc.name.clone(), styles: most_used(styles), variables: most_used(variables) })
}
/// How many times `doc` has inserted and detached `library`'s styles and variables, its totals;
/// `None` when it has done neither. Every count the document keeps is included (up to
/// [`figcraft_doc::MAX_DETACH_COUNTS`]); the wire message is capped at [`MAX_ASSET_USAGE`], so
/// [`asset_action_reports`] splits them into batches an older server still accepts.
pub fn asset_actions(doc: &Document, library: &str) -> Option<AssetActions> {
let counts: Vec<_> = doc.libraries.asset_counts.iter().filter(|c| c.library == library).collect();
let totals = |n: fn(&figcraft_doc::AssetCount) -> u32| counts.iter().filter(|c| n(c) > 0).map(|c| (c.key.clone(), n(c))).collect();
(!counts.is_empty()).then(|| AssetActions { file: doc.name.clone(), inserted: totals(|c| c.inserted), detached: totals(|c| c.detached) })
}
/// Reports for the server, each with at most [`MAX_ASSET_USAGE`] inserted and detached counts.
pub fn asset_action_reports(doc: &Document, library: &str) -> Vec<AssetActions> {
let Some(full) = asset_actions(doc, library) else { return Vec::new() };
chunk_asset_actions(full)
}
fn chunk_asset_actions(actions: AssetActions) -> Vec<AssetActions> {
let AssetActions { file, inserted, detached } = actions;
if inserted.is_empty() && detached.is_empty() {
return Vec::new();
}
let mut out = Vec::new();
let mut i = 0;
let mut d = 0;
loop {
let ins: Vec<_> = inserted.get(i..).unwrap_or(&[]).iter().take(MAX_ASSET_USAGE).cloned().collect();
let det: Vec<_> = detached.get(d..).unwrap_or(&[]).iter().take(MAX_ASSET_USAGE).cloned().collect();
if ins.is_empty() && det.is_empty() {
break;
}
i += ins.len();
d += det.len();
out.push(AssetActions { file: file.clone(), inserted: ins, detached: det });
}
out
}
/// `counts`, the most used first, at most [`MAX_ASSET_USAGE`].
fn most_used(counts: BTreeMap<&str, u32>) -> Vec<(String, u32)> {
let mut list: Vec<(String, u32)> = counts.into_iter().map(|(k, n)| (k.to_string(), n)).collect();
@@ -271,8 +308,9 @@ impl Session {
inserted(doc, &l.id).map(LibraryReq::ReportInserted),
asset_usage(doc, &l.id).map(LibraryReq::ReportAssets),
];
let asset_reports = asset_action_reports(doc, &l.id).into_iter().map(LibraryReq::ReportAssetActions);
let fetch = LibraryReq::Fetch { have, usage: Some(usage(doc, &l.id)) };
std::iter::once(fetch).chain(reports.into_iter().flatten()).map(|req| (l.path.clone(), req))
std::iter::once(fetch).chain(reports.into_iter().flatten()).chain(asset_reports).map(|req| (l.path.clone(), req))
})
.collect();
// Confined to automation roots, nothing reaches a server (#1095).
+60 -2
View File
@@ -127,6 +127,10 @@ const MAX_LINKS: u8 = 40;
/// on the share of one of `roots` goes on to the usual check. A path that can't be made absolute
/// is refused as well, rather than left to what comes next.
fn refused_unresolved(path: &Path, roots: &[PathBuf]) -> Option<Unresolved> {
// Win32 lookups trim a trailing period or space from a name, but not always from one in the middle of a path: refused as given.
if has_trimmed_name(path) {
return Some(Unresolved::Linked);
}
// Made absolute without looking at the disk (on Windows `GetFullPathNameW`, which also turns a
// bare device name such as `NUL` into `\\.\NUL`, as opening it would). Like opening, it takes
// `..` by name, so `link\..\x` is `x` and never goes through the link.
@@ -180,6 +184,10 @@ fn nothing_there(e: &std::io::Error) -> bool {
/// the way is opened in turn while the path is resolved, and the device behind a name such as
/// `LPT1` can be a printer on another computer.
fn refused_spelling(p: &str, roots: &[PathBuf]) -> Option<Refused> {
// A native NT name (`\Device\Mup\server\share`) has no prefix for `std` or `craft_docpath`, yet the system follows it to wherever it names.
if is_native_name(Path::new(p)) {
return Some(Refused::Device);
}
match craft_docpath::resolve(p, None) {
// With a root passed as the document path (what a link would be relative to), a path on
// that root's share is allowed.
@@ -199,7 +207,11 @@ fn is_volume(p: &str) -> bool {
let (Some(""), Some(""), Some("?" | "."), Some(volume)) = (names.next(), names.next(), names.next(), names.next()) else {
return false;
};
volume.get(..7).is_some_and(|v| v.eq_ignore_ascii_case("Volume{")) && volume.ends_with('}')
let bytes = volume.as_bytes();
bytes.len() == 44
&& volume.get(..7).is_some_and(|v| v.eq_ignore_ascii_case("Volume{"))
&& volume.ends_with('}')
&& bytes[7..43].iter().enumerate().all(|(i, b)| if matches!(i, 8 | 13 | 18 | 23) { *b == b'-' } else { b.is_ascii_hexdigit() })
}
/// Whether a link on the way to `abs` (an absolute path) leads to a path [`refused_spelling`]
@@ -224,6 +236,11 @@ fn link_refused(abs: &Path, roots: &[PathBuf], links: u8, look: &dyn Fn(&Path) -
Entry::Link(target) => target,
};
let (Some(links), Some(target)) = (links.checked_sub(1), target) else { return true };
// Judged as written too: joined onto the link's folder, a rooted target such as `\Device\Mup\x` would keep that folder's drive,
// and Win32 trims a trailing period or space that the kernel follows as it is.
if refused_spelling(&target.to_string_lossy(), roots).is_some() || is_rooted_without_drive(&target) || has_trimmed_name(&target) {
return true;
}
// A relative target is relative to the link's folder; an absolute one replaces it.
let next = lexical(&at.parent().unwrap_or(&at).join(target).join(rest.as_path()));
return refused_spelling(&next.to_string_lossy(), roots).is_some() || link_refused(&next, roots, links, look);
@@ -231,6 +248,26 @@ fn link_refused(abs: &Path, roots: &[PathBuf], links: u8, look: &dyn Fn(&Path) -
false
}
/// Whether `path` is a native NT name (`\Device\…`, `\DosDevices\…`, `\GLOBAL??\…`, `\??\…`, `\Sessions\…`, `\GLOBALROOT\…`), which a link
/// may hold: no prefix for `std`, yet the system follows it to wherever it names.
fn is_native_name(path: &Path) -> bool {
let bytes = path.as_os_str().as_encoded_bytes();
[&br"\Device\"[..], &br"\DosDevices\"[..], &br"\GLOBAL??\"[..], &br"\??\"[..], &br"\Sessions\"[..], &br"\GLOBALROOT\"[..]].iter().any(|p| {
bytes.get(..p.len() - 1).is_some_and(|b| b.eq_ignore_ascii_case(&p[..p.len() - 1])) && matches!(bytes.get(p.len() - 1), None | Some(b'\\'))
})
}
/// Whether a link's target starts with one separator and no drive (`\RPC Control\x`, `\BaseNamedObjects\x`, `\work`): `std` sees no
/// prefix in it, yet the system reads it in its own object namespace or on the link's drive, and may follow it to wherever it names.
fn is_rooted_without_drive(path: &Path) -> bool {
matches!(path.as_os_str().as_encoded_bytes(), [b'\\', rest @ ..] if rest.first() != Some(&b'\\'))
}
/// Whether any plain name in `path` ends in a period or a space, which Win32 path handling trims before it looks the name up.
fn has_trimmed_name(path: &Path) -> bool {
path.components().any(|c| matches!(c, Component::Normal(n) if n.as_encoded_bytes().last().is_some_and(|b| matches!(b, b'.' | b' '))))
}
/// `p` with its `.` and `..` taken by name, as Windows takes them.
fn lexical(p: &Path) -> PathBuf {
let mut out = PathBuf::new();
@@ -273,9 +310,24 @@ pub(crate) fn within_app_folder(path: &Path, folder: &Path) -> bool {
matches!((std::fs::canonicalize(path), std::fs::canonicalize(folder)), (Ok(p), Ok(f)) if p.starts_with(&f))
}
/// Whether `a` and `b` are the same file. Comparing opens both, so while roots confine this thread a
/// path that resolving would not be allowed to open (on another computer, or a device: see
/// [`refused_unresolved`]) is never opened. Whether it is the same file can't then be told, and the
/// callers guard against overwriting a file through another name for it, so it counts as the same:
/// the guard keeps asking (a path like that can't be written anyway). A local path outside the
/// roots is compared.
pub fn same_file(a: impl AsRef<Path>, b: impl AsRef<Path>) -> bool {
let (a, b) = (a.as_ref(), b.as_ref());
a == b || same_file::is_same_file(a, b).unwrap_or(false)
if a == b {
return true;
}
if let Some(scope) = current() {
let roots = [scope.read.as_slice(), scope.write.as_slice()].concat();
if cfg!(windows) && [a, b].into_iter().any(|p| refused_unresolved(p, &roots).is_some()) {
return true;
}
}
same_file::is_same_file(a, b).unwrap_or(false)
}
/// `p` without Windows' `\\?\` prefix, for messages.
@@ -345,6 +397,12 @@ fn device_name(n: &str) -> bool {
&& stem.chars().last().is_some_and(|c| c.is_ascii_digit() || matches!(c, '¹' | '²' | '³')))
}
/// Prefix Windows device-name components of a generated export path with `_`.
/// Apply after character filtering and suffix construction, so a safe suffix stays unchanged.
pub fn escape_device_names(path: &str) -> String {
path.split('/').map(|name| if device_name(name) { format!("_{name}") } else { name.to_string() }).collect::<Vec<_>>().join("/")
}
thread_local! {
static ROOTS: RefCell<Option<Arc<Roots>>> = const { RefCell::new(None) };
}
@@ -9,6 +9,27 @@ use serde_json::json;
use super::{Access, Roots, allow, confined, current};
use crate::Session;
#[test]
fn generated_export_paths_escape_device_components_and_preserve_other_names() {
for (path, expected) in [
("CON", "_CON"),
("CoN.txt", "_CoN.txt"),
("nul.txt", "_nul.txt"),
("PRN/icon", "_PRN/icon"),
("folder/COM1", "folder/_COM1"),
("LPT9.png", "_LPT9.png"),
("COM¹", "_COM¹"),
("LPT²/icon", "_LPT²/icon"),
("CONIN$", "_CONIN$"),
("HomeCON", "HomeCON"),
("COM10", "COM10"),
("CON@2x", "CON@2x"),
("folder/.NUL", "folder/.NUL"),
] {
assert_eq!(super::escape_device_names(path), expected, "{path}");
}
}
/// A fresh folder for one test: `<tmp>/figcraft-roots-<name>-<pid>`, holding `root/`, `root2/`
/// (a sibling whose name starts like the root's) and `outside/`.
struct Fixture(PathBuf);
@@ -229,6 +250,8 @@ fn spellings_of_other_computers_and_devices_are_refused() {
r"C:\work\LPT³\x.png",
r"C:\work\conout$",
r"C:\work\aux:stream",
// A volume name that is not a GUID could be an alias of anything.
r"\\?\Volume{remote}\x.png",
// After a name `craft_docpath` refuses for another reason.
r"C:\work\a:b\prn.png",
];
@@ -402,6 +425,34 @@ fn a_parent_after_a_link_is_taken_by_name() {
assert_eq!(std::fs::read(&through).unwrap(), b"in", "Windows opens the file in the root");
}
/// Comparing two files opens both, so a path the roots don't allow is not compared: it is not the
/// same file as one inside, even when it is another name for it (a hard link outside the roots).
#[test]
fn same_file_does_not_open_a_path_outside_the_roots() {
let f = Fixture::new("same-file");
let inside = f.p("root/in.txt");
let outside = f.p("outside/linked.txt");
if std::fs::hard_link(&inside, &outside).is_err() {
eprintln!("skipped: hard links can't be made here");
return;
}
assert!(super::same_file(&inside, &outside), "unconfined, another name for a file is the same file");
let roots = Arc::new(f.rw());
confined(Some(&roots), || {
assert!(super::same_file(&inside, &outside), "a local path outside the roots is compared, and a hard link to a file inside is that file");
if cfg!(windows) {
assert!(
super::same_file(&inside, r"\\192.0.2.1\share\x"),
"a path on another computer is never opened, and counts as the same so that the guard keeps asking"
);
}
assert!(super::same_file(&inside, &inside), "a path is the same file as itself");
let other = f.p("root/sub/other.txt");
std::fs::write(&other, b"other").unwrap();
assert!(!super::same_file(&inside, &other), "two files inside are compared, and differ");
});
}
/// A path on another computer and a device path are refused before anything is opened: resolving
/// them made Windows contact the server, which may send it the signed-in user's credentials
/// (#1094). Each is refused with a message that only the check before resolving gives: had the
@@ -468,6 +519,59 @@ fn links_to_other_computers_are_refused_before_they_are_followed() {
assert!(r.check(Path::new(&f.p("root/alias/x.png")), Access::Write).is_ok());
}
/// A native NT name is told with or without the separator after its first name: a link to `\Device` alone, with the
/// rest of the path after it, reaches `\Device\Mup\...`.
#[test]
fn native_names_are_told_with_or_without_the_closing_separator() {
for p in
[r"\Device", r"\Device\Mup\203.0.113.5\s", r"\device\mup", r"\DosDevices", r"\GLOBAL??", r"\??", r"\??\UNC\x\y", r"\Sessions", r"\GLOBALROOT"]
{
assert!(super::is_native_name(Path::new(p)), "{p}");
}
for p in [r"\Devices", r"\Devicex\y", r"Device", r"\work\Device", r"\\server\share", r"\"] {
assert!(!super::is_native_name(Path::new(p)), "{p}");
}
}
/// A link target that starts with one separator and no drive names a root the system reads in its own object namespace or on the
/// link's drive, whichever directory it names.
#[test]
fn rooted_link_targets_without_a_drive_are_refused() {
for p in [r"\Device\Mup\203.0.113.5\s", r"\RPC Control\remote", r"\BaseNamedObjects\x", r"\??\UNC\x\y", r"\work", r"\"] {
assert!(super::is_rooted_without_drive(Path::new(p)), "{p}");
}
for p in [r"Device", r"work\x", r"C:\x", r"\\server\share", r"\\?\C:\x", ""] {
assert!(!super::is_rooted_without_drive(Path::new(p)), "{p}");
}
}
/// A link whose text is a native NT name (`\Device\Mup\server\share`) or ends in a period, and a path with a name that ends in a
/// space, are refused as written: joined onto the link's folder the first would keep that folder's drive, and Windows trims the
/// others where it looks a name up but not where the kernel follows a link.
#[test]
#[cfg(windows)]
fn native_names_and_names_windows_trims_are_refused_as_written() {
let f = Fixture::new("native-trimmed");
let r = f.rw();
if !symlink_dir(Path::new(r"\Device\Mup\192.0.2.1\share"), &f.0.join("root/native"))
|| !symlink_dir(Path::new("remote."), &f.0.join("root/trimmed"))
{
eprintln!("skipped: this system doesn't let tests make symbolic links");
return;
}
let standard = |p: &str| format!("automation path rejected: {p} is outside the folders that may be");
// However the system stores the native name, the link is refused.
let native = f.p("root/native/x.png");
assert!(r.check(Path::new(&native), Access::Read).is_err(), "{native}");
let p = f.p("root/trimmed/x.png");
let e = r.check(Path::new(&p), Access::Read).expect_err(&p);
assert!(e.starts_with(&standard(&p)), "{p}: {e}");
let p = f.p("root/remote /x.png");
let e = r.check(Path::new(&p), Access::Write).expect_err(&p);
assert!(e.starts_with(&standard(&p)), "{p}: {e}");
assert_eq!(super::refused_spelling(r"\??\UNC\192.0.2.1\share\x", &[]), Some(craft_docpath::Refused::Device));
}
#[test]
fn a_scope_confines_the_thread_and_ends_with_it() {
let f = Fixture::new("scope");
+39 -1
View File
@@ -1,6 +1,6 @@
//! Document inspection as JSON, so agents can verify their work without screenshots.
use figcraft_doc::{Document, Node, NodeId, NodeKind, StrokeJoin, TextData, TextDecoration};
use figcraft_doc::{Document, Node, NodeId, NodeKind, StrokeCap, StrokeJoin, TextAlignV, TextCase, TextData, TextDecoration};
use serde_json::{Value, json};
use crate::Session;
@@ -34,7 +34,10 @@ pub const NODE_KEYS: &[&str] = &[
"devResources",
"devStatus",
"effects",
"endCap",
"exports",
"exposedInstance",
"features",
"fills",
"flows",
"fontFamily",
@@ -76,13 +79,17 @@ pub const NODE_KEYS: &[&str] = &[
"opacity",
"operandOperation",
"overrides",
"paragraphIndent",
"paragraphSpacing",
"pluginData",
"pointCount",
"propertyReferences",
"rotation",
"sectionContentsHidden",
"segments",
"sizing",
"slot",
"startCap",
"strokeAlign",
"strokeJoin",
"strokeSides",
@@ -91,7 +98,9 @@ pub const NODE_KEYS: &[&str] = &[
"styledRuns",
"styles",
"textAlign",
"textAlignVertical",
"textAutoResize",
"textCase",
"textDecoration",
"textDecorationColor",
"textDecorationOffset",
@@ -102,6 +111,7 @@ pub const NODE_KEYS: &[&str] = &[
"textPath",
"textStyleRanges",
"type",
"variableModes",
"vertices",
"visible",
"width",
@@ -263,6 +273,11 @@ fn paint_props(n: &Node, o: &mut serde_json::Map<String, Value>, options: &Inspe
if !n.stroke.dashes.is_empty() {
insert_prop(o, options, "dashes", || json!(n.stroke.dashes));
}
for (k, cap) in [("startCap", n.stroke.cap_start), ("endCap", n.stroke.cap_end)] {
if cap != StrokeCap::None {
insert_prop(o, options, k, || json!(cap));
}
}
if let Some(cap) = n.stroke.dash_cap {
insert_prop(o, options, "dashCap", || json!(cap));
}
@@ -383,6 +398,15 @@ fn dev_props(doc: &Document, n: &Node, o: &mut serde_json::Map<String, Value>, o
if !n.bound.is_empty() {
insert_prop(o, options, "boundVariables", || json!(n.bound));
}
if !n.var_modes.is_empty() {
insert_prop(o, options, "variableModes", || json!(n.var_modes));
}
if !n.prop_refs.is_empty() {
insert_prop(o, options, "propertyReferences", || json!(n.prop_refs));
}
if n.exposed {
insert_prop(o, options, "exposedInstance", || json!(true));
}
if !n.overrides.is_empty() {
insert_prop(o, options, "overrides", || json!(n.overrides));
}
@@ -417,7 +441,21 @@ fn text_props(t: &TextData, o: &mut serde_json::Map<String, Value>, options: &In
insert_prop(o, options, "lineHeight", || json!(t.style.line_height.label()));
insert_prop(o, options, "letterSpacing", || json!(t.style.letter_spacing.label()));
insert_prop(o, options, "textAlign", || json!(t.align_h));
if t.align_v != TextAlignV::default() {
insert_prop(o, options, "textAlignVertical", || json!(t.align_v));
}
insert_prop(o, options, "textAutoResize", || json!(t.auto_resize));
if t.style.case != TextCase::default() {
insert_prop(o, options, "textCase", || json!(t.style.case));
}
for (k, v) in [("paragraphSpacing", t.paragraph_spacing), ("paragraphIndent", t.paragraph_indent)] {
if v != 0.0 {
insert_prop(o, options, k, || json!(v));
}
}
if !t.features.is_empty() {
insert_prop(o, options, "features", || json!(t.features));
}
if t.max_lines > 0 {
insert_prop(o, options, "maxLines", || json!(t.max_lines));
}
+57
View File
@@ -652,3 +652,60 @@ fn a_continue_batch_reports_runtime_errors_and_runs_later_steps() {
assert_eq!(results[6]["ok"], true);
assert_eq!(s.doc().unwrap().node(s.page().unwrap()).unwrap().name, "Done");
}
#[test]
fn a_refused_step_names_its_step_and_keeps_its_kind() {
let mut s = Session::new();
let comp = id(&s.execute("node.create", &json!({"type": "component", "name": "Button", "width": 100, "height": 40})).unwrap());
let inst = id(&s.execute("instance.create", &json!({"component": comp})).unwrap());
let before = s.doc().unwrap().clone();
let undo = s.undo_depth();
let result = s.execute(
"command.batch",
&json!({"commands": [
{"command": "node.create", "params": {"type": "rectangle", "parent": inst, "width": 10, "height": 10}}
]}),
);
match result {
Err(EngineError::Disabled(cmd, msg)) => {
assert_eq!(cmd, "node.create");
assert!(msg.starts_with("step 0: "), "{msg}");
assert!(msg.contains("can't be added"), "{msg}");
}
other => panic!("expected Disabled, got {other:?}"),
}
assert_eq!(s.doc().unwrap(), &before, "the batch rolled back");
assert_eq!(s.undo_depth(), undo, "no undo step for the refused batch");
// Outside a batch the same refusal keeps its kind and says no step.
match s.execute("node.create", &json!({"type": "rectangle", "parent": inst, "width": 10, "height": 10})) {
Err(EngineError::Disabled(_, msg)) => assert!(!msg.contains("step "), "{msg}"),
other => panic!("expected Disabled, got {other:?}"),
}
}
#[test]
fn an_internal_step_says_which_step_without_changing_kind() {
use crate::derived;
let mut s = Session::new();
let r = id(&s.execute("node.create", &json!({"type": "rectangle", "width": 10, "height": 10})).unwrap());
let before = s.doc().unwrap().clone();
derived::PANIC.with(|p| p.set(true));
let result = s.execute(
"command.batch",
&json!({"commands": [
{"command": "node.set", "params": {"ids": [r], "props": {"name": "Renamed"}}}
]}),
);
derived::PANIC.with(|p| p.set(false));
match result {
Err(EngineError::Internal { cmd, msg }) => {
assert_eq!(cmd, "node.set");
assert!(msg.starts_with("step 0: "), "{msg}");
}
other => panic!("expected Internal, got {other:?}"),
}
assert_eq!(s.doc().unwrap(), &before, "the panicking step is rolled back");
// Kinds without a message are left as they are.
assert!(matches!(EngineError::NoNode(figcraft_doc::NodeId(7)).at_step(2), EngineError::NoNode(_)));
assert!(matches!(EngineError::Waiting.at_step(2), EngineError::Waiting));
}
+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"),
+5 -2
View File
@@ -431,6 +431,9 @@ pub(crate) enum Gesture {
additive: bool,
base: Vec<NodeId>,
within: Option<NodeId>,
/// A click stepping out of a selected descendant picks its frame. Wait for a real drag
/// before replacing that selection with the marquee's contents.
pending_click: bool,
},
Move {
start: Point,
@@ -441,8 +444,8 @@ pub(crate) enum Gesture {
/// A Shift-press on this selected layer: it leaves the selection on release, unless the
/// press became a drag.
deselect: Option<NodeId>,
/// A press on one layer of a multi-selection that keeps the selection to drag it all: a
/// release without a drag selects just this layer.
/// A press on one layer of a multi-selection, or on a layer inside a selected one, that
/// keeps the selection to drag it all: a release without a drag selects just this layer.
keep: Option<NodeId>,
},
Resize {
+42 -14
View File
@@ -77,8 +77,8 @@ impl Session {
}
// A frame's name label picks the frame itself. The background of a top-level frame with
// layers in it is like the canvas (a press starts a marquee inside it) unless the frame is
// selected; an empty frame (or a widget, or a board object such as a sticky) is picked and
// dragged.
// selected; stepping out from a selected descendant is handled by the marquee below.
// An empty frame (or a widget, or a board object such as a sticky) is picked and dragged.
let board_background = |leaf: NodeId| {
!sel.contains(&leaf)
&& doc.node(leaf).is_some_and(|n| {
@@ -86,17 +86,20 @@ impl Session {
})
};
let label = label_at(&doc, page, &self.tool.labels, ev.p());
let target = label.or_else(|| {
self.hit(&doc, page, ev.p(), ev.tol() * 2.0)
.filter(|leaf| ev.cmd || !board_background(*leaf))
.map(|leaf| select_target(&doc, leaf, &sel, ev.cmd))
});
let hit = label.or_else(|| self.hit(&doc, page, ev.p(), ev.tol() * 2.0));
let target = label.or_else(|| hit.filter(|leaf| ev.cmd || !board_background(*leaf)).map(|leaf| select_target(&doc, leaf, &sel, ev.cmd)));
// A press inside the selection's box that reaches nothing above it (an unfilled shape's
// inside, the frame or canvas behind it, or a layer stacked below the selected layer the
// press is in) drags the selection. In a gap between selected layers, what's there is hit.
let in_own_box = |s: NodeId| selection_box(&doc, &[s]).is_some_and(|q| in_quad(&q, ev.p()));
// A press on a layer inside a selected one (a child of a selected frame) drags the
// selection too, and a click selects that layer; Cmd/Ctrl keeps the deep pick.
let in_selected = |t: NodeId| sel.iter().any(|s| *s != t && doc.is_ancestor(*s, t));
let behind_sel = |t: Option<NodeId>| {
t.is_none_or(|t| sel.iter().any(|s| *s != t && (doc.is_ancestor(t, *s) || (in_own_box(*s) && paints_below(&doc, t, *s)))))
t.is_none_or(|t| {
(!ev.cmd && in_selected(t))
|| sel.iter().any(|s| *s != t && (doc.is_ancestor(t, *s) || (in_own_box(*s) && paints_below(&doc, t, *s))))
})
};
// What the press hit (a label or a painted layer): a click that doesn't become a drag
// selects just it. A press that reaches nothing above the selection uses the selection as
@@ -119,8 +122,12 @@ impl Session {
let without_target = || sel.iter().copied().filter(|x| *x != target).collect::<Vec<_>>();
// A release without a drag narrows the selection to the layer the press hit. A
// selected frame's name label sits outside the selection bounds, so it counts too.
let keep = clicked
.filter(|c| (label.is_some() || in_sel_box) && !ev.cmd && (sel.contains(c) || sel.iter().any(|s| doc.is_ancestor(*s, *c))));
// A layer inside a selected one counts as well: the press drags the selection, and
// a click selects that layer.
let keep = clicked.filter(|c| {
!ev.cmd
&& (((label.is_some() || in_sel_box) && (sel.contains(c) || sel.iter().any(|s| doc.is_ancestor(*s, *c)))) || in_selected(*c))
});
let new_sel = if keep.is_some() {
sel.clone()
} else if ev.shift && deselect.is_none() {
@@ -138,7 +145,7 @@ impl Session {
if !edits {
if deselect.is_some() {
self.set_selection(without_target());
} else if let Some(k) = keep.filter(|_| sel.len() > 1) {
} else if let Some(k) = keep.filter(|k| sel.as_slice() != [*k]) {
self.set_selection(vec![k]);
}
return Ok(());
@@ -172,10 +179,22 @@ impl Session {
}
None => {
let within = self.marquee_within(ev.p())?;
if !ev.shift {
// Clicking the background of the frame containing the current selection steps
// out to that frame. Keep the marquee gesture (without a Move interaction), so
// dragging here still selects its contents and cannot leave a stale snapshot.
let parent = hit.filter(|f| !ev.shift && !ev.cmd && within == Some(*f) && sel.iter().any(|s| doc.is_ancestor(*f, *s)));
if let Some(f) = parent {
self.set_selection(vec![f]);
} else if !ev.shift {
self.set_selection(vec![]);
}
self.tool.gesture = Gesture::Marquee { start: ev.p(), additive: ev.shift, base: if ev.shift { sel } else { vec![] }, within };
self.tool.gesture = Gesture::Marquee {
start: ev.p(),
additive: ev.shift,
base: if ev.shift { sel } else { vec![] },
within,
pending_click: parent.is_some(),
};
}
}
Ok(())
@@ -196,9 +215,18 @@ impl Session {
it.label = if ev.alt { "Duplicate" } else { "Move" }.into();
}
}
if let Gesture::Marquee { start, pending_click, .. } = &mut g
&& *pending_click
{
if within_slop(ev, *start) {
self.tool.gesture = g;
return Ok(());
}
*pending_click = false;
}
let res = match &g {
Gesture::None => return self.hover(ev),
Gesture::Marquee { start, additive, base, within } => {
Gesture::Marquee { start, additive, base, within, .. } => {
let r = Rect::from_points(*start, ev.p());
self.tool.overlay.marquee = Some([r.x0, r.y0, r.x1, r.y1]);
// Cmd/Ctrl: the nested layers it touches.
+3 -2
View File
@@ -176,10 +176,11 @@ impl Session {
let sel = self.selection().into_iter().filter(|x| *x != d).collect();
self.set_selection(sel);
} else if let Some(k) = keep {
// A click (not a drag) on one layer of a multi-selection selects just it.
// A click (not a drag) on one layer of a multi-selection, or on a layer
// inside a selected one, selects just it.
let doc = self.doc()?.clone();
let sel = self.selection();
if sel.len() > 1 && (sel.contains(&k) || sel.iter().any(|s| doc.is_ancestor(*s, k))) {
if sel.as_slice() != [k] && (sel.contains(&k) || sel.iter().any(|s| doc.is_ancestor(*s, k))) {
self.set_selection(vec![k]);
}
}
+2
View File
@@ -7,6 +7,8 @@
//! the transform box around several points (in one layer or several) in [`transform`], point snapping in `point_snap.rs` and
//! hovering, hatching and selecting filled regions in [`regions`].
#[cfg(test)]
mod align_tests;
pub mod ops;
pub(crate) mod point_snap;
mod pointer;
@@ -0,0 +1,261 @@
//! Align and distribute the selected points in vector edit mode.
use serde_json::json;
use super::tests::{ex, net, pt, ve};
use super::*;
/// The measured path: points at (330, 480), (480, 430), (560, 560), (380, 620), in edit mode.
fn path(s: &mut Session) -> NodeId {
let r = ex(s, "vector.create", json!({"points": [[330, 480], [480, 430], [560, 560], [380, 620]], "closed": false}));
let id = crate::params::id_of(&r["id"]).unwrap();
ex(s, "vector.edit.begin", json!({"id": id}));
id
}
fn page(s: &Session, id: NodeId) -> Vec<Point> {
let w = s.doc().unwrap().world_transform(id);
net(s, id).vertices.iter().map(|v| w * v.point()).collect()
}
fn page_of(s: &Session, id: NodeId, p: Point) -> Point {
s.doc().unwrap().world_transform(id) * p
}
fn select(s: &mut Session, v: &[usize]) {
ex(s, "vector.edit.select", json!({"vertices": v}));
}
fn near(a: Point, b: Point) -> bool {
(a - b).hypot() < 1e-6
}
#[test]
fn each_alignment_moves_the_points_along_one_axis_to_their_box() {
// Points 0 and 1: box x 330..480, y 430..480.
let cases = [
("align.left", [pt(330.0, 480.0), pt(330.0, 430.0)]),
("align.hcenter", [pt(405.0, 480.0), pt(405.0, 430.0)]),
("align.right", [pt(480.0, 480.0), pt(480.0, 430.0)]),
("align.top", [pt(330.0, 430.0), pt(480.0, 430.0)]),
("align.vcenter", [pt(330.0, 455.0), pt(480.0, 455.0)]),
("align.bottom", [pt(330.0, 480.0), pt(480.0, 480.0)]),
];
for (cmd, want) in cases {
let mut s = Session::new();
let id = path(&mut s);
let before = page(&s, id);
select(&mut s, &[0, 1]);
ex(&mut s, cmd, json!({}));
let after = page(&s, id);
assert!(near(after[0], want[0]) && near(after[1], want[1]), "{cmd}: {after:?}");
assert!(near(after[2], before[2]) && near(after[3], before[3]), "{cmd} left the others");
}
}
#[test]
fn one_point_does_not_move() {
let mut s = Session::new();
let id = path(&mut s);
let before = page(&s, id);
select(&mut s, &[1]);
for c in ["align.left", "align.bottom", "distribute.horizontal"] {
ex(&mut s, c, json!({}));
}
assert_eq!(page(&s, id), before);
}
#[test]
fn two_points_do_not_distribute() {
let mut s = Session::new();
let id = path(&mut s);
let before = page(&s, id);
select(&mut s, &[0, 1]);
for c in ["distribute.horizontal", "distribute.vertical"] {
ex(&mut s, c, json!({}));
}
assert_eq!(page(&s, id), before);
}
/// A vector inside a frame at (100, 100), its left (150) well inside the frame.
fn framed(s: &mut Session) -> (NodeId, NodeId) {
let f = crate::params::id_of(&ex(s, "frame.create", json!({"x": 100, "y": 100, "width": 400, "height": 400}))["id"]).unwrap();
let r = ex(s, "vector.create", json!({"points": [[50, 100], [150, 50], [200, 200]], "closed": false, "parent": f}));
(f, crate::params::id_of(&r["id"]).unwrap())
}
const ALIGNS: [&str; 6] = ["align.left", "align.hcenter", "align.right", "align.top", "align.vcenter", "align.bottom"];
#[test]
fn no_points_selected_moves_nothing_and_not_the_layer() {
let mut s = Session::new();
let (frame, v) = framed(&mut s);
ex(&mut s, "vector.edit.begin", json!({"id": v}));
ex(&mut s, "vector.edit.select", json!({"vertices": []}));
assert_eq!(transform::edit_point_count(s.doc().unwrap(), &ve(&s)), 0);
let (points, bounds, local) = (page(&s, v), s.doc().unwrap().world_bounds(v), net(&s, v).vertices);
assert!(bounds.unwrap().x0 > s.doc().unwrap().world_bounds(frame).unwrap().x0 + 10.0, "starts well inside the frame");
for c in ALIGNS.into_iter().chain(["distribute.horizontal", "distribute.vertical"]) {
ex(&mut s, c, json!({}));
assert_eq!(page(&s, v), points, "{c}");
assert_eq!(s.doc().unwrap().world_bounds(v), bounds, "{c} moved the layer");
assert_eq!(net(&s, v).vertices, local, "{c}");
}
}
#[test]
fn points_of_several_layers_align_and_one_undo_restores_all() {
let mut s = Session::new();
let mut line = |p: serde_json::Value| crate::params::id_of(&ex(&mut s, "vector.create", json!({"points": p, "closed": false}))["id"]).unwrap();
let (a, b) = (line(json!([[0, 100], [100, 150]])), line(json!([[300, 40], [400, 90]])));
ex(&mut s, "vector.edit.begin", json!({"ids": [a, b]}));
ex(&mut s, "vector.edit.select", json!({"id": a, "vertices": [0]}));
ex(&mut s, "vector.edit.select", json!({"id": b, "vertices": [1], "add": true}));
let (pa, pb) = (page(&s, a), page(&s, b));
ex(&mut s, "align.top", json!({}));
let (na, nb) = (page(&s, a), page(&s, b));
let top = pa[0].y.min(pb[1].y);
assert!(near(na[0], pt(pa[0].x, top)) && near(nb[1], pt(pb[1].x, top)), "{na:?} {nb:?}");
assert!(near(na[1], pa[1]) && near(nb[0], pb[0]), "unselected points stay");
s.undo().unwrap();
let (ua, ub) = (page(&s, a), page(&s, b));
assert!(pa.iter().zip(&ua).chain(pb.iter().zip(&ub)).all(|(x, y)| near(*x, *y)), "{ua:?} {ub:?}");
}
#[test]
fn a_rotated_layer_aligns_in_the_boxs_own_frame() {
let mut s = Session::new();
let id = path(&mut s);
ex(&mut s, "node.set", json!({"id": id, "props": {"rotation": 30}}));
select(&mut s, &[0, 1]);
let b = transform::point_box(s.doc().unwrap(), &ve(&s)).unwrap();
let inv = b.frame.inverse();
let before: Vec<Point> = page(&s, id).iter().map(|p| inv * *p).collect();
assert!((before[0].x - before[1].x).abs() > 1.0, "the points differ in box x");
ex(&mut s, "align.left", json!({}));
let after: Vec<Point> = page(&s, id).iter().map(|p| inv * *p).collect();
for i in 0..2 {
assert!(after[i].x.abs() < 1e-6, "box x is the box's left: {after:?}");
assert!((after[i].y - before[i].y).abs() < 1e-6, "box y unchanged: {after:?}");
}
}
#[test]
fn id_in_edit_mode_moves_the_layer_not_the_points() {
let mut s = Session::new();
let (frame, v) = framed(&mut s);
ex(&mut s, "vector.edit.begin", json!({"id": v}));
select(&mut s, &[0, 1]);
let local = net(&s, v).vertices;
ex(&mut s, "align.left", json!({"id": v}));
let d = s.doc().unwrap();
assert!((d.world_bounds(v).unwrap().x0 - d.world_bounds(frame).unwrap().x0).abs() < 1e-6, "layer at the frame's left");
assert_eq!(net(&s, v).vertices, local, "points were not aligned to each other");
}
#[test]
fn ids_distribute_layers_and_leave_the_edited_layers_points() {
let mut s = Session::new();
let mut rect = |x: f64| crate::params::id_of(&ex(&mut s, "shape.rectangle", json!({"x": x, "y": 0, "width": 50, "height": 50}))["id"]).unwrap();
let (r1, r2, r3) = (rect(0.0), rect(60.0), rect(400.0));
ex(&mut s, "vector.edit.begin", json!({"id": r2}));
select(&mut s, &[0, 1]);
let local = net(&s, r2).vertices;
ex(&mut s, "distribute.horizontal", json!({"ids": [r1, r2, r3]}));
let x0 = s.doc().unwrap().world_bounds(r2).unwrap().x0;
assert!((x0 - 200.0).abs() < 1e-6, "middle layer centred between the outer two: {x0}");
assert_eq!(net(&s, r2).vertices, local);
}
#[test]
fn distribute_spaces_the_points_evenly_between_the_outermost() {
let mut s = Session::new();
let id = path(&mut s);
select(&mut s, &[0, 1, 2, 3]);
ex(&mut s, "distribute.horizontal", json!({}));
let p = page(&s, id);
let want_x = [330.0, 483.0 + 1.0 / 3.0, 560.0, 380.0 + 80.0 / 3.0];
for (q, x) in p.iter().zip(want_x) {
assert!((q.x - x).abs() < 1e-6, "{p:?}");
}
let want_y = [480.0, 430.0, 560.0, 620.0];
assert!(p.iter().zip(want_y).all(|(q, y)| (q.y - y).abs() < 1e-6), "y unchanged: {p:?}");
ex(&mut s, "distribute.vertical", json!({}));
let p = page(&s, id);
// y sorted 430, 480, 560, 620 spread over 430..620.
let step = 190.0 / 3.0;
let want_y = [430.0 + step, 430.0, 430.0 + 2.0 * step, 620.0];
assert!(p.iter().zip(want_y).all(|(q, y)| (q.y - y).abs() < 1e-6), "{p:?}");
}
#[test]
fn a_curved_points_handles_move_with_it() {
let mut s = Session::new();
let r = ex(&mut s, "vector.create", json!({"path": "M 0 0 C 0 50 50 100 100 100 L 200 0", "x": 0, "y": 0}));
let id = crate::params::id_of(&r["id"]).unwrap();
ex(&mut s, "vector.edit.begin", json!({"id": id}));
let before = net(&s, id);
let page_before = page(&s, id);
let handle = |s: &Session, n: &VectorNetwork, v: usize, t: (f64, f64)| page_of(s, id, n.vertices[v].point() + Vec2::new(t.0, t.1));
let (h1_before, h0_before) = (handle(&s, &before, 1, before.segments[0].tb), handle(&s, &before, 0, before.segments[0].ta));
select(&mut s, &[0, 1]);
ex(&mut s, "align.left", json!({}));
let after = net(&s, id);
let moved: Vec<usize> = (0..2).filter(|i| !near(page(&s, id)[*i], page_before[*i])).collect();
assert!(!moved.is_empty(), "something moved");
let p = page(&s, id);
assert!(near(p[0], pt(0.0, 0.0)) && near(p[1], pt(0.0, 100.0)), "{p:?}");
assert!(near(p[2], page_before[2]), "vertex 2 stays");
// Handles: vertex 1's incoming one (vertex + segment 0's `tb`) moves with it by (-100, 0).
let a0 = &after.segments[0];
assert!(near(h1_before, pt(50.0, 100.0)) && near(handle(&s, &after, 1, a0.tb), pt(-50.0, 100.0)), "vertex 1's handle moved by (-100, 0)");
assert!(near(h0_before, handle(&s, &after, 0, a0.ta)), "vertex 0's handle stays");
assert_eq!(before.segments.len(), after.segments.len());
for (a, b) in before.segments.iter().zip(&after.segments) {
assert_eq!((a.ta, a.tb), (b.ta, b.tb), "handle offsets travel with their vertex");
}
}
#[test]
fn one_undo_restores_the_points() {
let mut s = Session::new();
let id = path(&mut s);
let before = page(&s, id);
select(&mut s, &[0, 1, 2, 3]);
ex(&mut s, "align.right", json!({}));
assert_ne!(page(&s, id), before);
s.undo().unwrap();
let after = page(&s, id);
assert!(before.iter().zip(&after).all(|(a, b)| near(*a, *b)), "{after:?}");
}
#[test]
fn ids_in_edit_mode_still_align_layers() {
let mut s = Session::new();
let mut square = |x: f64| crate::params::id_of(&ex(&mut s, "shape.rectangle", json!({"x": x, "y": 0, "width": 50, "height": 50}))["id"]).unwrap();
let (a, b) = (square(0.0), square(200.0));
ex(&mut s, "vector.edit.begin", json!({"id": a}));
select(&mut s, &[0, 1]);
let local = net(&s, a).vertices;
ex(&mut s, "align.left", json!({"ids": [a, b]}));
let x = |id| s.doc().unwrap().world_bounds(id).unwrap().x0;
assert!((x(a) - x(b)).abs() < 1e-6, "layers aligned");
assert_eq!(net(&s, a).vertices, local, "the selected points kept their local positions");
}
#[test]
fn a_segment_selected_in_another_edited_layer_counts_both_its_ends() {
// `a`'s segment (two ends) and `b`'s first point: three points, so the panel offers
// Distribute and the command spaces all three.
let mut s = Session::new();
let mut line = |p: serde_json::Value| crate::params::id_of(&ex(&mut s, "vector.create", json!({"points": p, "closed": false}))["id"]).unwrap();
let (a, b) = (line(json!([[0, 0], [100, 50]])), line(json!([[300, 200], [400, 260]])));
ex(&mut s, "vector.edit.begin", json!({"ids": [a, b]}));
ex(&mut s, "vector.edit.select", json!({"id": a, "segments": [0]}));
ex(&mut s, "vector.edit.select", json!({"id": b, "vertices": [0], "add": true}));
assert_eq!(transform::edit_point_count(s.doc().unwrap(), &ve(&s)), 3);
ex(&mut s, "distribute.horizontal", json!({}));
let xs: Vec<f64> = page(&s, a).iter().chain(page(&s, b).first()).map(|p| p.x).collect();
assert!(xs.iter().zip([0.0, 150.0, 300.0]).all(|(x, w)| (x - w).abs() < 1e-6), "{xs:?}");
}
@@ -172,6 +172,126 @@ pub fn transform_in_edit_mode(s: &mut Session, p: &Value, f: impl FnOnce(&PointB
Some(s.doc_mut().and_then(|doc| transform_points(doc, ve.id, &b.points, m)).map(|()| json!({"ok": true})))
}
/// Which edge or centre line of the selected points' box each point goes to.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PointAlign {
Left,
HCenter,
Right,
Top,
VCenter,
Bottom,
}
/// Every selected point of `b` in every layer as (layer, vertex, page position).
fn page_points(doc: &Document, b: &PointBox, id: NodeId) -> Vec<(NodeId, usize, Point)> {
let layers = std::iter::once((id, &b.points)).chain(b.others.iter().map(|(o, v)| (*o, v)));
layers
.flat_map(|(l, verts)| {
let w = doc.world_transform(l);
let net = network(doc, l);
verts.iter().filter_map(move |v| net.and_then(|n| n.vertices.get(*v)).map(|vx| (l, *v, w * vx.point()))).collect::<Vec<_>>()
})
.collect()
}
/// The box to align or distribute in: all edited layers' points when several are selected.
fn edit_box(doc: &Document, ve: &VectorEdit) -> Option<PointBox> {
let b = if ve.others_selected() { layers_box(doc, ve) } else { point_box(doc, ve) };
b.filter(|b| b.point_count() > 0)
}
/// How many points align and distribute act on: the selected points and selected segments' ends
/// of every edited layer.
pub fn edit_point_count(doc: &Document, ve: &VectorEdit) -> usize {
edit_box(doc, ve).map_or(0, |b| b.point_count())
}
/// Move each point by its own page delta, one vertex at a time (handles go with their vertex).
fn move_each(doc: &mut Document, moves: &[(NodeId, usize, Point)]) -> Result<()> {
for (l, v, d) in moves {
if d.x.is_finite() && d.y.is_finite() && (d.x != 0.0 || d.y != 0.0) {
transform_points(doc, *l, &[*v], Affine::translate((d.x, d.y)))?;
}
}
Ok(())
}
/// The page delta of moving by `(dx, dy)` along the box's axes.
fn along(frame: Affine, dx: f64, dy: f64) -> Point {
let [a, b, c, d, _, _] = frame.as_coeffs();
Point::new(a * dx + c * dy, b * dx + d * dy)
}
/// Align the selected points to their box's edge or centre line (`None` when edit mode is off or
/// the command names layers; with no points selected in edit mode nothing moves, and the edited
/// layer is not aligned to its parent). Each point moves along one axis of the box only; fewer than
/// two points stay put.
pub fn align_points_in_edit_mode(s: &mut Session, p: &Value, how: PointAlign) -> Option<Result<Value>> {
if get(p, "ids").is_some() || get(p, "id").is_some() {
return None;
}
let ve = editing(s).ok()?;
let Some(b) = edit_box(s.doc().ok()?, &ve) else {
return Some(Ok(json!({"ok": true})));
};
let pts = page_points(s.doc().ok()?, &b, ve.id);
let inv = b.frame.inverse();
let moves: Vec<(NodeId, usize, Point)> = if b.point_count() < 2 {
vec![]
} else {
pts.iter()
.map(|(l, v, pg)| {
let q = inv * *pg;
let (dx, dy) = match how {
PointAlign::Left => (-q.x, 0.0),
PointAlign::HCenter => (b.width / 2.0 - q.x, 0.0),
PointAlign::Right => (b.width - q.x, 0.0),
PointAlign::Top => (0.0, -q.y),
PointAlign::VCenter => (0.0, b.height / 2.0 - q.y),
PointAlign::Bottom => (0.0, b.height - q.y),
};
(*l, *v, along(b.frame, dx, dy))
})
.collect()
};
Some(s.doc_mut().and_then(|doc| move_each(doc, &moves)).map(|()| json!({"ok": true})))
}
/// Space the selected points evenly along the box's x (or y) axis between the outermost two, in
/// order along it (`None` when edit mode is off or the command names layers; with no points
/// selected in edit mode nothing moves). Fewer than three points stay put.
pub fn distribute_points_in_edit_mode(s: &mut Session, p: &Value, horizontal: bool) -> Option<Result<Value>> {
if get(p, "ids").is_some() || get(p, "id").is_some() {
return None;
}
let ve = editing(s).ok()?;
let Some(b) = edit_box(s.doc().ok()?, &ve) else {
return Some(Ok(json!({"ok": true})));
};
let pts = page_points(s.doc().ok()?, &b, ve.id);
let inv = b.frame.inverse();
let mut items: Vec<(NodeId, usize, Point)> = pts.iter().map(|(l, v, pg)| (*l, *v, inv * *pg)).collect();
let axis = |q: &Point| if horizontal { q.x } else { q.y };
items.sort_by(|a, c| axis(&a.2).total_cmp(&axis(&c.2)));
let n = items.len();
let moves: Vec<(NodeId, usize, Point)> = if n < 3 {
vec![]
} else {
let (lo, hi) = (0.0, if horizontal { b.width } else { b.height });
items
.iter()
.enumerate()
.map(|(k, (l, v, q))| {
let target = lo + (hi - lo) * k as f64 / (n - 1) as f64;
let d = target - axis(q);
(*l, *v, if horizontal { along(b.frame, d, 0.0) } else { along(b.frame, 0.0, d) })
})
.collect()
};
Some(s.doc_mut().and_then(|doc| move_each(doc, &moves)).map(|()| json!({"ok": true})))
}
/// The selected points' box, or an error naming `cmd`.
fn selected_box(s: &Session, cmd: &str) -> Result<(VectorEdit, PointBox)> {
let ve = editing(s)?;
@@ -315,9 +315,23 @@ fn edit_mode_transform_commands_survive_junk() {
json!({"width": -1e308, "height": "x", "center": "maybe", "angle": 1e308, "cx": "NaN", "matrix": [1, 2, 3, "a", 5, 6]}),
json!({"matrix": [0, 0, 0, 0, 0, 0], "vertices": [1e12, -1], "width": 1e308, "height": 0}),
];
for c in
["object.flipH", "object.flipV", "object.rotate180", "object.rotateLeft", "object.rotateRight", "vector.edit.resize", "vector.edit.rotate"]
{
for c in [
"object.flipH",
"object.flipV",
"object.rotate180",
"object.rotateLeft",
"object.rotateRight",
"vector.edit.resize",
"vector.edit.rotate",
"align.left",
"align.hcenter",
"align.right",
"align.top",
"align.vcenter",
"align.bottom",
"distribute.horizontal",
"distribute.vertical",
] {
for j in &junk {
let mut s = Session::new();
let id = rect(&mut s);
+71 -8
View File
@@ -11,14 +11,62 @@ use crate::{Result, Session, bad, spec};
pub fn specs() -> Vec<CommandSpec> {
vec![
spec!("align.left", "Align left", "{ids?}", true, |s, p| align(s, p, Al::Left)),
spec!("align.hcenter", "Align horizontal centers", "{ids?}", true, |s, p| align(s, p, Al::HCenter)),
spec!("align.right", "Align right", "{ids?}", true, |s, p| align(s, p, Al::Right)),
spec!("align.top", "Align top", "{ids?}", true, |s, p| align(s, p, Al::Top)),
spec!("align.vcenter", "Align vertical centers", "{ids?}", true, |s, p| align(s, p, Al::VCenter)),
spec!("align.bottom", "Align bottom", "{ids?}", true, |s, p| align(s, p, Al::Bottom)),
spec!("distribute.horizontal", "Distribute horizontal spacing", "{ids?, spacing?}", true, |s, p| distribute(s, p, true)),
spec!("distribute.vertical", "Distribute vertical spacing", "{ids?, spacing?}", true, |s, p| distribute(s, p, false)),
spec!(
"align.left",
"Align left",
"{ids?} (in vector edit mode without ids: the selected points, and nothing moves with none selected)",
true,
|s, p| align(s, p, Al::Left)
),
spec!(
"align.hcenter",
"Align horizontal centers",
"{ids?} (in vector edit mode without ids: the selected points, and nothing moves with none selected)",
true,
|s, p| align(s, p, Al::HCenter)
),
spec!(
"align.right",
"Align right",
"{ids?} (in vector edit mode without ids: the selected points, and nothing moves with none selected)",
true,
|s, p| align(s, p, Al::Right)
),
spec!(
"align.top",
"Align top",
"{ids?} (in vector edit mode without ids: the selected points, and nothing moves with none selected)",
true,
|s, p| align(s, p, Al::Top)
),
spec!(
"align.vcenter",
"Align vertical centers",
"{ids?} (in vector edit mode without ids: the selected points, and nothing moves with none selected)",
true,
|s, p| align(s, p, Al::VCenter)
),
spec!(
"align.bottom",
"Align bottom",
"{ids?} (in vector edit mode without ids: the selected points, and nothing moves with none selected)",
true,
|s, p| align(s, p, Al::Bottom)
),
spec!(
"distribute.horizontal",
"Distribute horizontal spacing",
"{ids?, spacing?} (in vector edit mode without ids: the selected points, and nothing moves with none selected)",
true,
|s, p| distribute(s, p, true)
),
spec!(
"distribute.vertical",
"Distribute vertical spacing",
"{ids?, spacing?} (in vector edit mode without ids: the selected points, and nothing moves with none selected)",
true,
|s, p| distribute(s, p, false)
),
spec!(
"arrange.spacing",
"Spacing",
@@ -192,6 +240,18 @@ fn align_target(doc: &Document, roots: &[NodeId]) -> Option<Rect> {
}
fn align(s: &mut Session, p: &Value, a: Al) -> Result<Value> {
use crate::vectoredit::transform::PointAlign;
let how = match a {
Al::Left => PointAlign::Left,
Al::HCenter => PointAlign::HCenter,
Al::Right => PointAlign::Right,
Al::Top => PointAlign::Top,
Al::VCenter => PointAlign::VCenter,
Al::Bottom => PointAlign::Bottom,
};
if let Some(r) = crate::vectoredit::transform::align_points_in_edit_mode(s, p, how) {
return r;
}
let ids = req_targets("align", s, p)?;
let doc = s.doc_mut()?;
let ids = roots(doc, &ids);
@@ -212,6 +272,9 @@ fn align(s: &mut Session, p: &Value, a: Al) -> Result<Value> {
}
fn distribute(s: &mut Session, p: &Value, horizontal: bool) -> Result<Value> {
if let Some(r) = crate::vectoredit::transform::distribute_points_in_edit_mode(s, p, horizontal) {
return r;
}
let ids = req_targets("distribute", s, p)?;
let doc = s.doc_mut()?;
let ids = roots(doc, &ids);
+40 -7
View File
@@ -312,9 +312,12 @@ fn own(cmd: &str, m: &Message, who: &str, what: &str) -> crate::Result<()> {
}
/// A node to pin to: a node id on `page`, `true` for the innermost frame under the point, else none.
fn anchor_at(doc: &Document, page: NodeId, x: f64, y: f64, v: Option<&Value>) -> Option<NodeId> {
fn anchor_at(doc: &Document, page: NodeId, x: f64, y: f64, v: Option<&Value>, within: Option<NodeId>) -> Option<NodeId> {
match v {
Some(Value::Bool(true)) => frame_at(doc, page, x, y),
Some(Value::Bool(true)) => match within.filter(|w| *w != page && doc.page_of(*w) == Some(page) && contains(doc, *w, x, y)) {
Some(w) => frame_in(doc, w, x, y, Some(w)),
None => frame_at(doc, page, x, y),
},
Some(v) => id_of(v).filter(|a| *a != page && doc.page_of(*a) == Some(page)),
None => None,
}
@@ -670,7 +673,7 @@ pub fn specs() -> Vec<CommandSpec> {
spec!(
"comment.add",
"Add comment",
"{x, y, text, page?, author?, anchor? (node id to pin to; true = innermost frame under the point)}",
"{x, y, text, page?, author?, anchor? (node id to pin to; true = innermost frame under the point), within? (with anchor true: search only inside this frame on the page, which is the anchor when no child holds the point)}",
true,
|s, p| {
let x = req_num("comment.add", p, "x")?;
@@ -682,7 +685,7 @@ pub fn specs() -> Vec<CommandSpec> {
if !doc.pages.contains(&page) {
return Err(bad("comment.add", format!("{page} is not a page")));
}
let anchor = anchor_at(doc, page, x, y, get(p, "anchor"));
let anchor = anchor_at(doc, page, x, y, get(p, "anchor"), id(p, "within"));
let (lx, ly) = local(doc, anchor, x, y);
let mut c = Comment {
id: s.doc_mut()?.new_comment_id(),
@@ -772,7 +775,7 @@ pub fn specs() -> Vec<CommandSpec> {
let (x, y) = (req_num("comment.move", p, "x")?, req_num("comment.move", p, "y")?);
let doc = s.doc()?;
let page = doc.comment(id).map(|c| c.page).ok_or_else(|| bad("comment.move", "no comment"))?;
let anchor = anchor_at(doc, page, x, y, Some(get(p, "anchor").unwrap_or(&Value::Bool(true))));
let anchor = anchor_at(doc, page, x, y, Some(get(p, "anchor").unwrap_or(&Value::Bool(true))), None);
let (lx, ly) = local(doc, anchor, x, y);
if let Some(c) = s.doc_mut()?.comment_mut(id) {
(c.x, c.y, c.anchor) = (lx, ly, anchor);
@@ -974,9 +977,20 @@ pub fn specs() -> Vec<CommandSpec> {
/// Innermost frame (or component/instance/section) under a page point, for anchoring.
fn frame_at(doc: &Document, page: NodeId, x: f64, y: f64) -> Option<NodeId> {
frame_in(doc, page, x, y, None)
}
/// Whether the page point lies inside node `n`'s box.
fn contains(doc: &Document, n: NodeId, x: f64, y: f64) -> bool {
let Some(node) = doc.node(n) else { return false };
let l = doc.world_transform(n).inverse() * geom::Point::new(x, y);
l.x >= 0.0 && l.y >= 0.0 && l.x <= node.width && l.y <= node.height
}
/// The innermost frame-like or section under the point, searching from `root` (with `found` as the fallback).
fn frame_in(doc: &Document, root: NodeId, x: f64, y: f64, mut found: Option<NodeId>) -> Option<NodeId> {
let pt = geom::Point::new(x, y);
let mut found = None;
let mut stack = vec![page];
let mut stack = vec![root];
while let Some(parent) = stack.pop() {
let Some(n) = doc.node(parent) else { continue };
for c in n.children.iter().rev() {
@@ -1012,6 +1026,25 @@ mod tests {
assert_eq!(super::parse_link("figcraft://comment/5/"), Some(5));
}
#[test]
fn comment_add_within_anchors_to_the_presented_frame() {
let mut s = Session::new();
let mk = |s: &mut Session, params: serde_json::Value| crate::params::id_of(&s.execute("node.create", &params).unwrap()["id"]).unwrap();
let a = mk(&mut s, json!({"type": "frame", "x": 0, "y": 0, "width": 200, "height": 200}));
let b = mk(&mut s, json!({"type": "frame", "x": 100, "y": 0, "width": 200, "height": 200}));
let anchor = |s: &mut Session, params: serde_json::Value| {
let c = s.execute("comment.add", &params).unwrap();
let id = c["id"].as_u64().unwrap();
s.doc().unwrap().comment(id).unwrap().anchor
};
assert_eq!(anchor(&mut s, json!({"x": 150, "y": 50, "text": "t", "anchor": true})), Some(b));
assert_eq!(anchor(&mut s, json!({"x": 150, "y": 50, "text": "t", "anchor": true, "within": a})), Some(a));
let c = mk(&mut s, json!({"type": "frame", "x": 120, "y": 20, "width": 50, "height": 50, "parent": a}));
assert_eq!(anchor(&mut s, json!({"x": 130, "y": 30, "text": "t", "anchor": true, "within": a})), Some(c));
// A point outside `within` ignores it.
assert_eq!(anchor(&mut s, json!({"x": 250, "y": 50, "text": "t", "anchor": true, "within": a})), Some(b));
}
#[test]
fn comment_thread_lifecycle_and_anchoring() {
let mut s = Session::new();
+44 -14
View File
@@ -218,6 +218,49 @@ fn set_prop_defs(doc: &mut Document, c: NodeId, rename: Option<(&str, &str)>, f:
Ok(())
}
/// Give each of components `comps` that lacks it property `name` (`def`), and their existing
/// instances its default.
fn give_prop(doc: &mut Document, comps: &[NodeId], name: &str, def: &PropDef) -> Result<()> {
for c in comps {
if prop_defs(doc, *c).contains_key(name) {
continue;
}
set_prop_defs(doc, *c, None, |m| {
m.insert(name.to_string(), def.clone());
})?;
if !takes_value(def) {
continue;
}
for inst in instances_of(doc, *c) {
if let NodeKind::Instance { props, .. } = &mut doc.get_mut(inst)?.kind {
props.entry(name.to_string()).or_insert_with(|| prop_default_value(def));
}
}
}
Ok(())
}
/// Give every one of components `comps` (the variants of a set) the properties any of them has:
/// a set's properties belong to all its variants, as `component.addProperty` gives them, so one
/// made on a component before it was combined stays on an instance switched to another variant.
/// A variant that has a property of that name keeps its own.
pub(super) fn share_props(doc: &mut Document, comps: &[NodeId]) -> Result<()> {
let mut all: Vec<(String, PropDef)> = Vec::new();
for c in comps {
if let Some(NodeKind::Component { props, prop_order, .. }) = doc.node(*c).map(|n| &n.kind) {
for (k, d) in ordered_props(props, prop_order) {
if !all.iter().any(|(n, _)| n == k) {
all.push((k.clone(), d.clone()));
}
}
}
}
for (name, def) in &all {
give_prop(doc, comps, name, def)?;
}
Ok(())
}
fn valid_prop_name(cmd: &str, name: &str) -> Result<String> {
let name = name.trim();
if name.is_empty() || name.contains([',', '=']) || name.chars().count() > 200 {
@@ -295,20 +338,7 @@ pub(super) fn add_prop_for(cmd: &str, s: &mut Session, p: &Value) -> Result<Valu
}
_ => return Err(bad(cmd, "type: boolean|text|instanceSwap|variant|slot")),
};
for c in &comps {
set_prop_defs(doc, *c, None, |m| {
m.insert(name.clone(), def.clone());
})?;
// Existing instances get the default.
if !takes_value(&def) {
continue;
}
for inst in instances_of(doc, *c) {
if let NodeKind::Instance { props, .. } = &mut doc.get_mut(inst)?.kind {
props.entry(name.clone()).or_insert_with(|| prop_default_value(&def));
}
}
}
give_prop(doc, &comps, &name, &def)?;
if let Some(l) = layer {
bind(cmd, doc, l, Some(&name), None)?;
}
+3 -1
View File
@@ -68,7 +68,8 @@ pub fn can_add_variant(doc: &Document, id: NodeId) -> bool {
}
/// Wrap `ids` (z-sorted main components) in a new component set, naming them "Property 1=Default",
/// "Property 1=VariantN" unless already in prop=value form. Returns the set.
/// "Property 1=VariantN" unless already in prop=value form, each with the component properties
/// any of them has. Returns the set.
fn make_variant_set(cmd: &str, doc: &mut Document, ids: &[NodeId]) -> Result<NodeId> {
let set = wrap_in_set(cmd, doc, ids)?;
for (k, i) in ids.iter().enumerate() {
@@ -77,6 +78,7 @@ fn make_variant_set(cmd: &str, doc: &mut Document, ids: &[NodeId]) -> Result<Nod
node.name = format!("Property 1={}", if k == 0 { "Default".to_string() } else { format!("Variant{}", k + 1) });
}
}
super::props::share_props(doc, ids)?;
Ok(set)
}
+2
View File
@@ -20,6 +20,8 @@ mod select;
mod vector_clipboard;
pub use vector_clipboard::clipboard_svg;
#[cfg(test)]
mod nudge_rotated_parent_tests;
#[cfg(test)]
mod vector_clipboard_tests;
pub(crate) use clipboard::apply_copied_props;
+36 -8
View File
@@ -295,6 +295,9 @@ pub(super) fn paste(s: &mut Session, p: &Value) -> Result<Value> {
})
.filter(|i| !copy_local || !s.clipboard.copied_components.iter().any(|root| doc.is_ancestor(*root, *i)))
});
// One layer selected that isn't a frame target: the copy joins its parent, just above it (#2355).
let sibling_of = if target.is_none() && id(p, "parent").is_none() { sibling_anchor(s, &sel, copy_local) } else { None };
let target = target.or_else(|| sibling_of.and_then(|i| doc.node(i).and_then(|n| n.parent)));
let parent = target.unwrap_or(page);
let at = match (num(p, "x"), num(p, "y")) {
(Some(x), Some(y)) => Some((x, y)),
@@ -321,10 +324,42 @@ pub(super) fn paste(s: &mut Session, p: &Value) -> Result<Value> {
}
};
let ids = paste_into(s, parent, at)?;
if let Some(sel) = sibling_of {
let above = s.doc()?.index_in_parent(sel).map(|ix| ix + 1);
move_above(s, &ids, parent, above)?;
}
s.set_selection(ids.clone());
Ok(json!({"ids": ids}))
}
/// The one selected layer a plain paste goes next to: not a page-level layer, not inside an instance
/// (its children are fixed), not a board atom, a component set (a variant's parent) or inside a copied
/// component. Else the page, as before.
fn sibling_anchor(s: &Session, sel: &[NodeId], copy_local: bool) -> Option<NodeId> {
let [only] = sel else { return None };
let doc = s.doc().ok()?;
let parent = doc.node(*only)?.parent?;
let pn = doc.node(parent)?;
let ok = !pn.is_page()
&& pn.kind.is_frame_like()
&& !pn.is_board_atom()
&& !crate::components::inside_instance(doc, *only)
&& !matches!(pn.kind, NodeKind::Instance { .. } | NodeKind::ComponentSet { .. })
&& (!copy_local || !s.clipboard.copied_components.iter().any(|root| doc.is_ancestor(*root, parent)));
ok.then_some(*only)
}
/// Move the pasted copies that landed in `parent` to `above` and after, in the copied order.
fn move_above(s: &mut Session, ids: &[NodeId], parent: NodeId, above: Option<usize>) -> Result<()> {
let Some(above) = above else { return Ok(()) };
let doc = s.doc_mut()?;
for (k, i) in ids.iter().filter(|i| doc.node(**i).is_some_and(|n| n.parent == Some(parent))).copied().collect::<Vec<_>>().into_iter().enumerate()
{
doc.reorder(i, above + k)?;
}
Ok(())
}
pub(super) fn paste_over(s: &mut Session, _p: &Value) -> Result<Value> {
let sel = s.selection();
let page = s.page()?;
@@ -337,14 +372,7 @@ pub(super) fn paste_over(s: &mut Session, _p: &Value) -> Result<Value> {
None => (page, None, None),
};
let ids = paste_into(s, parent, at)?;
if let Some(above) = above {
let doc = s.doc_mut()?;
for (k, i) in
ids.iter().filter(|i| doc.node(**i).is_some_and(|n| n.parent == Some(parent))).copied().collect::<Vec<_>>().into_iter().enumerate()
{
doc.reorder(i, above + k)?;
}
}
move_above(s, &ids, parent, above)?;
s.set_selection(ids.clone());
Ok(json!({"ids": ids}))
}
@@ -0,0 +1,92 @@
//! The arrow keys move a layer along the canvas axes whatever its parent's rotation (#2372).
use serde_json::{Value, json};
use crate::Session;
use crate::params::id_of;
use figcraft_doc::NodeId;
fn frame(s: &mut Session, parent: Option<NodeId>, w: f64, h: f64, rotation: f64) -> NodeId {
let mut p = json!({"x": 10, "y": 20, "width": w, "height": h});
if let (Some(par), Some(o)) = (parent, p.as_object_mut()) {
o.insert("parent".into(), json!(par));
}
let r = s.execute("frame.create", &p).unwrap();
let id = id_of(&r["id"]).unwrap();
if rotation != 0.0 {
s.execute("node.set", &json!({"id": id, "props": {"rotation": rotation}})).unwrap();
}
id
}
fn world(s: &Session, id: NodeId) -> (f64, f64) {
let c = s.doc().unwrap().world_transform(id).as_coeffs();
(c[4], c[5])
}
fn nudge(s: &mut Session, id: NodeId, params: Value) {
let mut p = params;
if let Some(o) = p.as_object_mut() {
o.insert("ids".into(), json!([id]));
}
s.execute("transform.nudge", &p).unwrap();
}
fn moved_by(s: &mut Session, id: NodeId, params: Value) -> (f64, f64) {
let before = world(s, id);
nudge(s, id, params);
let after = world(s, id);
(after.0 - before.0, after.1 - before.1)
}
fn near(got: (f64, f64), want: (f64, f64)) {
assert!((got.0 - want.0).abs() < 1e-6 && (got.1 - want.1).abs() < 1e-6, "moved by {got:?}, wanted {want:?}");
}
fn in_rotated(rotation: f64) -> (Session, NodeId) {
let mut s = Session::new();
let outer = frame(&mut s, None, 400.0, 300.0, rotation);
let child = frame(&mut s, Some(outer), 100.0, 80.0, 0.0);
(s, child)
}
#[test]
fn down_moves_a_child_of_a_frame_rotated_90_down_the_canvas() {
let (mut s, child) = in_rotated(90.0);
let k = s.prefs.nudge_small;
near(moved_by(&mut s, child, json!({"dx": 0, "dy": 1})), (0.0, k));
}
#[test]
fn right_moves_it_right_on_the_canvas() {
let (mut s, child) = in_rotated(90.0);
let k = s.prefs.nudge_small;
near(moved_by(&mut s, child, json!({"dx": 1, "dy": 0})), (k, 0.0));
}
#[test]
fn a_big_nudge_in_a_rotated_parent_follows_the_canvas_too() {
let (mut s, child) = in_rotated(90.0);
let k = s.prefs.nudge_big;
near(moved_by(&mut s, child, json!({"dx": 1, "dy": 0, "big": true})), (k, 0.0));
}
#[test]
fn a_child_of_an_unrotated_frame_moves_as_before() {
let (mut s, child) = in_rotated(0.0);
let k = s.prefs.nudge_small;
let local_before = s.doc().unwrap().node(child).unwrap().transform.as_coeffs();
near(moved_by(&mut s, child, json!({"dx": 1, "dy": 0})), (k, 0.0));
let local_after = s.doc().unwrap().node(child).unwrap().transform.as_coeffs();
assert!((local_after[4] - local_before[4] - k).abs() < 1e-6 && (local_after[5] - local_before[5]).abs() < 1e-6);
}
#[test]
fn a_layer_two_rotated_frames_deep_moves_along_the_canvas() {
let mut s = Session::new();
let outer = frame(&mut s, None, 500.0, 400.0, 45.0);
let inner = frame(&mut s, Some(outer), 300.0, 200.0, 30.0);
let child = frame(&mut s, Some(inner), 100.0, 80.0, 0.0);
let k = s.prefs.nudge_small;
near(moved_by(&mut s, child, json!({"dx": 0, "dy": 1})), (0.0, k));
}
+17
View File
@@ -163,6 +163,9 @@ pub(super) fn set(s: &mut Session, p: &Value) -> Result<Value> {
names.join(", ")
));
}
let mut hugging = crate::cmd::props::hugging_parents(&s.ds()?.doc, &ids, &props);
let filling = crate::cmd::props::filling_children(&s.ds()?.doc, &ids, &props);
let targets = ids.clone();
let doc = s.doc_mut()?;
let before = crate::cmd::styles::bound_before(doc, &ids);
let mut ids = ids;
@@ -182,6 +185,20 @@ pub(super) fn set(s: &mut Session, p: &Value) -> Result<Value> {
}
}
}
// A child that filled a hugging parent along its flow turned the parent Fixed: say so.
// A frame set to Hug turns the children that filled it along its flow Fixed. That is the
// coherence pass `normalize` runs once the command returns; run it here for those frames
// (idempotent) so the notice sees the demotion.
if !filling.is_empty() {
let doc = s.doc_mut()?;
for f in &targets {
figcraft_layout::coherent_sizing(doc, *f);
}
hugging.extend(filling);
}
if let Some(notice) = crate::cmd::props::fixed_notice(&s.ds()?.doc, &hugging) {
s.message = Some(notice);
}
if warnings.is_empty() { ok() } else { Ok(json!({"ok": true, "warnings": warnings})) }
}
+12 -1
View File
@@ -184,8 +184,19 @@ pub(super) fn nudge(s: &mut Session, p: &Value) -> Result<Value> {
// Children in an auto layout flow move one place instead (see `al_keys`).
for i in &ids {
if crate::al_keys::flowing_parent(doc, *i).is_none() && (dx, dy) != (0.0, 0.0) {
// The step is along the canvas axes; the layer's transform is in its parent's space.
let (lx, ly) = match doc.node(*i).and_then(|n| n.parent) {
Some(par) => {
let inv = doc.world_transform(par).inverse();
let o = inv * figcraft_geom::Point::new(0.0, 0.0);
let q = inv * figcraft_geom::Point::new(dx, dy);
let (lx, ly) = (q.x - o.x, q.y - o.y);
if lx.is_finite() && ly.is_finite() { (lx, ly) } else { (dx, dy) }
}
None => (dx, dy),
};
let n = doc.get_mut(*i)?;
n.transform = Affine::translate((dx, dy)) * n.transform;
n.transform = Affine::translate((lx, ly)) * n.transform;
changed = true;
}
}
+29 -1
View File
@@ -295,7 +295,7 @@ pub fn jobs_for(items: impl IntoIterator<Item = (NodeId, Vec<ExportSetting>)>, d
if out.len() >= MAX_EXPORT_FILES {
return out;
}
let stem = format!("{base}{}", safe_file_name(&e.file_suffix()));
let stem = crate::file_access::escape_device_names(&format!("{base}{}", safe_file_name(&e.file_suffix())));
let ext = e.format.ext();
let file =
(1..).map(|k| if k == 1 { format!("{stem}.{ext}") } else { format!("{stem} {k}.{ext}") }).find(|f| used.insert(f.to_lowercase()));
@@ -439,3 +439,31 @@ pub(super) fn export_frames_pdf(s: &mut Session, p: &Value) -> Result<Value> {
None => Ok(json!({"format": "pdf", "pages": pages, "data": base64::engine::general_purpose::STANDARD.encode(&bytes)})),
}
}
#[cfg(test)]
mod filename_tests {
use super::*;
#[test]
fn export_jobs_escape_device_names_after_suffixes_and_before_numbering() {
let mut doc = Document::new("Export names");
let page = doc.first_page().unwrap();
let cases = [
("C", "ON", "_CON.png"),
("_con", "", "_con 2.png"),
("CON/icon", "", "_CON/icon.png"),
("Home", "CON", "HomeCON.png"),
("COM", "1", "_COM1.png"),
("COM1", "@2x", "COM1@2x.png"),
];
let items: Vec<_> = cases
.iter()
.map(|(name, suffix, _)| {
let id = doc.create(page, NodeKind::Frame, name, 0.0, 0.0, 10.0, 10.0).unwrap();
(id, vec![ExportSetting { suffix: (*suffix).into(), ..Default::default() }])
})
.collect();
let files: Vec<_> = jobs_for(items, &doc).into_iter().map(|job| job.file).collect();
assert_eq!(files, cases.map(|(_, _, expected)| expected));
}
}
+39 -5
View File
@@ -436,6 +436,8 @@ fn usage_cmd(s: &mut Session, p: &Value) -> Result<Value> {
Err(EngineError::Waiting) => return Err(EngineError::Waiting),
_ => None,
};
let asset_weeks = asset_week_rows(s, &link, since)?;
let asset_actions = asset_period(asset_weeks.as_deref().unwrap_or_default());
let m = &lib.manifest;
// Component → (instances, files using it, instances detached).
let mut per: std::collections::BTreeMap<NodeId, (u64, u64, u64)> = std::collections::BTreeMap::new();
@@ -481,30 +483,62 @@ fn usage_cmd(s: &mut Session, p: &Value) -> Result<Value> {
"files": rows,
"components": components,
"assetsKnown": assets.is_some(),
"styles": asset_rows(assets.iter().flatten().map(|a| &a.styles), |id| {
"assetActionsKnown": asset_weeks.is_some(),
"styles": asset_rows(assets.iter().flatten().map(|a| &a.styles), &asset_actions, |id| {
m.style(id).map(|x| json!({"name": x.name, "type": x.kind}))
}),
"variables": asset_rows(assets.iter().flatten().map(|a| &a.variables), |id| {
"variables": asset_rows(assets.iter().flatten().map(|a| &a.variables), &asset_actions, |id| {
let v = m.variable(id)?;
Some(json!({"name": v.name, "collection": m.collection(&v.collection).map(|c| c.name.clone())}))
}),
}))
}
/// The style or variable reports' totals, the most used first: each one's `id`, `layers` and
/// `files`, with what `describe` says of it (nothing for one no longer published).
fn asset_rows<'a>(reports: impl Iterator<Item = &'a Vec<(String, u32)>>, describe: impl Fn(&str) -> Option<Value>) -> Vec<Value> {
/// The styles' and variables' weeks overlapping a period from `since`; `None` from a server from
/// before them.
fn asset_week_rows(s: &mut Session, link: &str, since: u64) -> Result<Option<Vec<WeekActions<String>>>> {
match s.library_request(link, LibraryReq::AssetActions) {
Ok(LibraryReply::AssetActions(w)) => Ok(Some(w.into_iter().filter(|w| w.week.saturating_add(7 * 86_400) > since).collect())),
Err(EngineError::Waiting) => Err(EngineError::Waiting),
_ => Ok(None),
}
}
/// Each style's or variable's insertions and detachments in `weeks`.
fn asset_period(weeks: &[WeekActions<String>]) -> std::collections::BTreeMap<&str, (u64, u64)> {
let mut per = std::collections::BTreeMap::<&str, (u64, u64)>::new();
for w in weeks {
let e = per.entry(&w.component).or_default();
e.0 += u64::from(w.insertions);
e.1 += u64::from(w.detachments);
}
per
}
/// The style or variable reports' totals, the most used first: each one's `id`, `layers`, `files`,
/// `insertions` and `detachments` in the period, with what `describe` says of it (nothing for one
/// no longer published). One only inserted or detached is listed too, when it's of this kind.
fn asset_rows<'a>(
reports: impl Iterator<Item = &'a Vec<(String, u32)>>,
actions: &std::collections::BTreeMap<&str, (u64, u64)>,
describe: impl Fn(&str) -> Option<Value>,
) -> Vec<Value> {
let mut per = std::collections::BTreeMap::<&str, (u64, u64)>::new();
for (id, n) in reports.flatten() {
let e = per.entry(id).or_default();
e.0 += u64::from(*n);
e.1 += 1;
}
for id in actions.keys().filter(|id| describe(id).is_some()) {
per.entry(id).or_default();
}
let mut rows: Vec<_> = per.into_iter().collect();
rows.sort_by_key(|r| std::cmp::Reverse(r.1.0));
let row = |(id, (layers, files)): (&str, (u64, u64))| {
let mut r = describe(id).unwrap_or_else(|| json!({}));
let (insertions, detachments) = actions.get(id).copied().unwrap_or_default();
(r["id"], r["layers"], r["files"]) = (json!(id), json!(layers), json!(files));
(r["insertions"], r["detachments"]) = (json!(insertions), json!(detachments));
r
};
rows.into_iter().map(row).collect()
+2 -4
View File
@@ -53,9 +53,8 @@ pub fn specs() -> Vec<CommandSpec> {
return Ok(json!({"id": id, "divider": true}));
}
let ds = s.ds_mut()?;
ds.page = id;
ds.open_page(id);
ds.selection.clear();
ds.zoom_to_fit();
Ok(json!({"id": id}))
}),
spec!("page.select", "Go to page", "{id | index}", false, |s, p| {
@@ -74,10 +73,9 @@ pub fn specs() -> Vec<CommandSpec> {
return Err(bad("page.select", "a divider isn't a page to open"));
}
let ds = s.ds_mut()?;
ds.page = id;
ds.open_page(id);
ds.selection.clear();
ds.text_edit = None;
ds.zoom_to_fit();
ok()
}),
spec!("page.rename", "Rename page", "{id?, name} (an empty page named with a leading hyphen becomes a divider)", true, |s, p| {
+91 -12
View File
@@ -1234,14 +1234,16 @@ pub fn apply(cmd: &str, doc: &mut Document, id: NodeId, props: &Map<String, Valu
if !unknown.is_empty() {
return Err(bad(cmd, format!("unknown properties: {} (known: {KEYS})", unknown.join(", "))));
}
// Inside an instance, record which property groups were overridden (an instance's own
// resizing, export settings and interactions are its own, not overrides).
// Inside an instance, record which property groups were overridden (an instance's own export
// settings and interactions are its own, not overrides). Its resizing is recorded like any
// layer's: the sync takes the main's Hug / Fixed unless it is overridden, and Reset instance
// clears it. Inferred: Figma was measured only with a typed width (kept); a resizing chosen
// from the dropdown is taken as an override the same way, as every property set on an
// instance in Figma is one.
let own_root = matches!(doc.get(id)?.kind, NodeKind::Instance { .. }) && !crate::components::inside_instance(doc, id);
let n = doc.get_mut(id)?;
if n.source.is_some() {
for g in
props.keys().map(|k| override_group(k)).filter(|g| *g != "other" && !(own_root && matches!(*g, "resizing" | "exports" | "interactions")))
{
for g in props.keys().map(|k| override_group(k)).filter(|g| *g != "other" && !(own_root && matches!(*g, "exports" | "interactions"))) {
n.overrides.insert(g.to_string());
}
}
@@ -1485,16 +1487,39 @@ fn set_sizing(cmd: &str, doc: &mut Document, id: NodeId, s: Sizing, horizontal:
}
_ => {}
}
// A child can't fill an axis its parent hugs: the parent becomes fixed at its current size.
// (The other way round, a parent that starts to hug fixes the children that filled it: see
// `figcraft_layout::coherent_sizing`, applied after every edit.)
// A child can't fill the axis its parent hugs along the flow: the parent becomes fixed at its
// current size. Across the flow the parent keeps hugging and the child takes the line's size
// (the largest sibling that doesn't fill); the parent becomes fixed only when no such sibling
// is left. (The other way round, a parent that starts to hug fixes the children that filled it
// along the flow: see `figcraft_layout::coherent_sizing`, applied after every edit.)
if s == Sizing::Fill
&& let Some(p) = parent
{
let cl = &mut doc.get_mut(p)?.child_layout;
let ps = if horizontal { &mut cl.sizing_h } else { &mut cl.sizing_v };
if *ps == Sizing::Hug {
*ps = Sizing::Fixed;
let pn = doc.get(p)?;
if figcraft_layout::wrapping_row_hugs_across(pn, horizontal) {
return Err(bad(cmd, "Fill container across a wrapping row is not offered"));
}
let along = match pn.layout.as_ref().map(|al| al.mode) {
Some(LayoutMode::Horizontal) => horizontal,
Some(LayoutMode::Vertical) => !horizontal,
_ => true,
};
let others_fill = figcraft_layout::flow_children(doc, p)
.into_iter()
.filter(|c| *c != id)
.all(|c| doc.node(c).is_some_and(|c| (if horizontal { c.child_layout.sizing_h } else { c.child_layout.sizing_v }) == Sizing::Fill));
if along || others_fill {
let cl = &mut doc.get_mut(p)?.child_layout;
let ps = if horizontal { &mut cl.sizing_h } else { &mut cl.sizing_v };
if *ps == Sizing::Hug {
*ps = Sizing::Fixed;
// An instance's own root, or a layer inside one, turned Fixed by this edit: that
// is its resizing now, an override, or the next rebuild from the main would take
// the main's Hug back and the child would stop filling.
if doc.get(p)?.source.is_some() {
doc.get_mut(p)?.overrides.insert("resizing".to_string());
}
}
}
}
// Start from the sizing the layer has in effect (an auto-width text hugs both axes), so the
@@ -1517,6 +1542,60 @@ fn set_sizing(cmd: &str, doc: &mut Document, id: NodeId, s: Sizing, horizontal:
Ok(())
}
/// The hugging parents that `props` setting Fill on `ids` may turn Fixed, as (parent, horizontal):
/// taken before the edit, for [`fixed_notice`].
pub(crate) fn hugging_parents(doc: &Document, ids: &[NodeId], props: &Map<String, Value>) -> Vec<(NodeId, bool)> {
let mut out = Vec::new();
for (horizontal, keys) in [(true, ["sizingH", "layoutSizingHorizontal"]), (false, ["sizingV", "layoutSizingVertical"])] {
if !keys.iter().any(|k| props.get(*k).and_then(sizing) == Some(Sizing::Fill)) {
continue;
}
for p in ids.iter().filter_map(|i| doc.node(*i)).filter_map(|n| n.parent) {
let hugs = doc
.node(p)
.is_some_and(|p| p.layout.is_some() && (if horizontal { p.child_layout.sizing_h } else { p.child_layout.sizing_v }) == Sizing::Hug);
if hugs && !out.contains(&(p, horizontal)) {
out.push((p, horizontal));
}
}
}
out
}
/// The children, as (child, horizontal), that fill an axis of a frame in `ids` which `props` sets
/// to Hug: taken before the edit, for [`fixed_notice`] (the coherence pass turns them Fixed).
pub(crate) fn filling_children(doc: &Document, ids: &[NodeId], props: &Map<String, Value>) -> Vec<(NodeId, bool)> {
let mut out = Vec::new();
for (horizontal, keys) in [(true, ["sizingH", "layoutSizingHorizontal"]), (false, ["sizingV", "layoutSizingVertical"])] {
if !keys.iter().any(|k| props.get(*k).and_then(sizing) == Some(Sizing::Hug)) {
continue;
}
for f in ids.iter().filter_map(|i| doc.node(*i)).filter(|n| n.layout.is_some() && n.kind.is_frame_like()) {
for c in f.children.iter().filter_map(|c| doc.node(*c)) {
let fills = (if horizontal { c.child_layout.sizing_h } else { c.child_layout.sizing_v }) == Sizing::Fill;
if fills && !out.contains(&(c.id, horizontal)) {
out.push((c.id, horizontal));
}
}
}
}
out
}
/// The notice for the layers of [`hugging_parents`] or [`filling_children`] that the edit turned
/// Fixed ("Height set to Fixed for Frame 1"), `None` when every one kept its sizing.
pub(crate) fn fixed_notice(doc: &Document, before: &[(NodeId, bool)]) -> Option<String> {
let notes: Vec<String> = before
.iter()
.filter_map(|(p, horizontal)| {
let p = doc.node(*p)?;
let now = if *horizontal { p.child_layout.sizing_h } else { p.child_layout.sizing_v };
(now == Sizing::Fixed).then(|| format!("{} set to Fixed for {}", if *horizontal { "Width" } else { "Height" }, p.name))
})
.collect();
(!notes.is_empty()).then(|| notes.join("; "))
}
/// Resize a node's box from its top-left, applying constraints / group scaling to children.
/// The page transforms of `id`'s children, to put back with [`restore_worlds`] once a container
/// whose contents stay where they are on the page (a section; a frame resized with Cmd/Ctrl held)
+12
View File
@@ -302,6 +302,10 @@ fn paragraph_style_of(n: &Node, range: Option<(usize, usize)>) -> Option<Paragra
}
fn detach(s: &mut Session, p: &Value) -> Result<Value> {
crate::library::counting_links(s, true, |s| detach_style(s, p))
}
fn detach_style(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "style.detach";
let which = req_string(cmd, p, "which")?;
if which == "text" {
@@ -458,6 +462,10 @@ pub fn apply_style_ref(doc: &mut Document, id: NodeId, field: &str, sid: Option<
}
pub(crate) fn apply(s: &mut Session, p: &Value) -> Result<Value> {
crate::library::counting_links(s, false, |s| apply_style(s, p))
}
fn apply_style(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "style.apply";
let st = req_string(cmd, p, "style")?;
let style = s.doc()?.style(&st).cloned().ok_or_else(|| bad(cmd, format!("no style `{st}`")))?;
@@ -846,6 +854,10 @@ pub fn sync_list_styles(doc: &mut Document, before: &Document, ids: &[NodeId]) {
/// `variable.bind`: bind (or with no variable, unbind) `field` of the targets.
pub fn bind(s: &mut Session, p: &Value) -> Result<Value> {
crate::library::counting_links(s, string(p, "variable").is_none(), |s| bind_field(s, p))
}
fn bind_field(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "variable.bind";
let field = req_string(cmd, p, "field")?;
let var = string(p, "variable");
+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")?;
+1 -2
View File
@@ -187,9 +187,8 @@ fn page_step(s: &mut Session, dir: i64) -> Result<Value> {
}
};
let ds = s.ds_mut()?;
ds.page = pg;
ds.open_page(pg);
ds.selection.clear();
ds.zoom_to_fit();
Ok(json!({"page": pg}))
}
@@ -1002,6 +1002,180 @@ fn deleting_a_layer_inside_an_instance_hides_it_instead() {
assert!(s.doc().unwrap().node(k.inst).is_none());
}
/// Issue 2090 item 2: after a main's child is set to fill, the instance's copy must match the main's
/// child (sizing, size) and the copy's parent must match the main's parent sizing. Relative, not
/// absolute, so it holds whatever the cross-axis rule is.
fn fill_matches_main(horizontal: bool, axis: &str) {
let hug_axis = if horizontal { "sizingV" } else { "sizingH" };
fill_matches_main_hugging(horizontal, axis, hug_axis);
}
/// As `fill_matches_main`, with the axis the main root hugs given explicitly.
fn fill_matches_main_hugging(horizontal: bool, axis: &str, hug_axis: &str) {
let mut s = Session::new();
let mode = if horizontal { "horizontal" } else { "vertical" };
let comp = idv(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 200, "height": 60, "name": "Note"})));
let bar = idv(&ex(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 3, "height": 20, "parent": comp, "props": {"name": "Bar"}})));
ex(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 40, "parent": comp, "props": {"name": "Body"}}));
ex(&mut s, "node.set", json!({"id": comp, "props": {"layout": mode, "gap": 12, "padding": 10, hug_axis: "hug"}}));
let comp = idv(&ex(&mut s, "component.create", json!({"ids": [comp]})));
let inst = idv(&ex(&mut s, "instance.create", json!({"component": comp, "x": 400, "y": 0})));
let bar = if node(&s, bar).parent.is_some() { bar } else { kids(&s, comp)[0] };
ex(&mut s, "node.set", json!({"id": bar, "props": {axis: "fill"}}));
let ibar = copy_of(&s, inst, bar);
let (m, c) = (node(&s, bar), node(&s, ibar));
let (mp, cp) = (node(&s, comp), node(&s, inst));
eprintln!(
"{axis}: main bar {}x{} sizing {:?}/{:?}; copy {}x{} sizing {:?}/{:?}; main parent {}x{} {:?}/{:?}; inst {}x{} {:?}/{:?}",
m.width,
m.height,
m.child_layout.sizing_h,
m.child_layout.sizing_v,
c.width,
c.height,
c.child_layout.sizing_h,
c.child_layout.sizing_v,
mp.width,
mp.height,
mp.child_layout.sizing_h,
mp.child_layout.sizing_v,
cp.width,
cp.height,
cp.child_layout.sizing_h,
cp.child_layout.sizing_v
);
assert_eq!((c.child_layout.sizing_h, c.child_layout.sizing_v), (m.child_layout.sizing_h, m.child_layout.sizing_v), "copy sizing");
assert_eq!((c.width, c.height), (m.width, m.height), "copy size matches main child");
assert_eq!(
(cp.child_layout.sizing_h, cp.child_layout.sizing_v),
(mp.child_layout.sizing_h, mp.child_layout.sizing_v),
"parent sizing matches main parent"
);
}
#[test]
fn instance_follows_main_child_fill_on_the_cross_axis() {
fill_matches_main(true, "sizingV");
}
#[test]
fn instance_follows_main_child_fill_on_the_main_axis() {
fill_matches_main(true, "sizingH");
}
#[test]
fn instance_follows_main_child_fill_along_a_hugging_main_axis() {
fill_matches_main_hugging(true, "sizingH", "sizingH");
}
/// A horizontal auto layout main hugging its width, with a "Bar" and a "Body" child, and an instance.
fn hugging_note(s: &mut Session) -> (NodeId, NodeId, NodeId) {
let comp = idv(&ex(s, "frame.create", json!({"x": 0, "y": 0, "width": 200, "height": 60, "name": "Note"})));
let bar = idv(&ex(s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 3, "height": 20, "parent": comp, "props": {"name": "Bar"}})));
ex(s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 40, "parent": comp, "props": {"name": "Body"}}));
ex(s, "node.set", json!({"id": comp, "props": {"layout": "horizontal", "gap": 12, "padding": 10, "sizingH": "hug"}}));
let comp = idv(&ex(s, "component.create", json!({"ids": [comp]})));
let inst = idv(&ex(s, "instance.create", json!({"component": comp, "x": 400, "y": 0})));
let bar = if node(s, bar).parent.is_some() { bar } else { kids(s, comp)[0] };
(comp, inst, bar)
}
fn sizing_h(s: &Session, id: NodeId) -> Sizing {
node(s, id).child_layout.sizing_h
}
/// Measured in Figma: the main's root turning Fixed (set directly) reaches a plain instance, and
/// the main going back to Hug brings it back.
#[test]
fn a_plain_instances_resizing_follows_the_mains_root_both_ways() {
let mut s = Session::new();
let (comp, inst, _) = hugging_note(&mut s);
assert_eq!(sizing_h(&s, inst), Sizing::Hug);
ex(&mut s, "node.set", json!({"id": comp, "props": {"sizingH": "fixed"}}));
assert_eq!(sizing_h(&s, comp), Sizing::Fixed);
assert_eq!(sizing_h(&s, inst), Sizing::Fixed, "the instance turns Fixed with its main");
ex(&mut s, "node.set", json!({"id": comp, "props": {"sizingH": "hug"}}));
assert_eq!(sizing_h(&s, inst), Sizing::Hug, "and back to Hug with it");
}
/// Measured in Figma: a child set to Fill along the hugging axis turns the main Fixed; the plain
/// instance follows it, and follows it back to Hug.
#[test]
fn a_plain_instance_goes_fixed_and_back_to_hug_with_its_main() {
let mut s = Session::new();
let (comp, inst, bar) = hugging_note(&mut s);
ex(&mut s, "node.set", json!({"id": bar, "props": {"sizingH": "fill"}}));
assert_eq!(sizing_h(&s, comp), Sizing::Fixed);
assert_eq!(sizing_h(&s, inst), Sizing::Fixed);
ex(&mut s, "node.set", json!({"id": comp, "props": {"sizingH": "hug"}}));
assert_eq!(sizing_h(&s, inst), Sizing::Hug);
}
/// Measured in Figma: an instance whose width was typed keeps that Fixed width through both
/// changes, while its height kept hugging its content. Figma keeps one size override for both
/// axes, as FigCraft does: with the width typed, a change to a fixed main's height does not reach
/// the instance, and the only size reset is "Reset size" (measured 2026-11-09).
#[test]
fn an_instance_with_a_typed_width_keeps_it_when_the_main_turns_fixed_and_back() {
let mut s = Session::new();
let (comp, inst, bar) = hugging_note(&mut s);
ex(&mut s, "node.set", json!({"id": inst, "props": {"width": 200}}));
assert_eq!(sizing_h(&s, inst), Sizing::Fixed);
assert_eq!(node(&s, inst).width, 200.0);
ex(&mut s, "node.set", json!({"id": bar, "props": {"sizingH": "fill"}}));
assert_eq!(sizing_h(&s, inst), Sizing::Fixed);
assert_eq!(node(&s, inst).width, 200.0, "the typed width stays");
ex(&mut s, "node.set", json!({"id": comp, "props": {"sizingH": "hug"}}));
assert_eq!(sizing_h(&s, inst), Sizing::Fixed, "still Fixed after the main hugs again");
assert_eq!(node(&s, inst).width, 200.0);
}
/// An instance placed in an auto layout frame and set to Fill there keeps Fill when its main changes.
#[test]
fn an_instance_filling_its_auto_layout_parent_keeps_fill_when_the_main_changes() {
let mut s = Session::new();
let (comp, inst, bar) = hugging_note(&mut s);
let row = idv(&ex(&mut s, "frame.create", json!({"x": 0, "y": 200, "width": 500, "height": 100, "name": "Row"})));
ex(&mut s, "node.set", json!({"id": row, "props": {"layout": "horizontal"}}));
ex(&mut s, "node.reparent", json!({"ids": [inst], "parent": row}));
ex(&mut s, "node.set", json!({"id": inst, "props": {"sizingH": "fill"}}));
assert_eq!(sizing_h(&s, inst), Sizing::Fill);
ex(&mut s, "node.set", json!({"id": bar, "props": {"sizingH": "fill"}}));
assert_eq!(sizing_h(&s, comp), Sizing::Fixed);
assert_eq!(sizing_h(&s, inst), Sizing::Fill, "its own Fill in the row is kept");
ex(&mut s, "node.set", json!({"id": comp, "props": {"sizingH": "hug"}}));
assert_eq!(sizing_h(&s, inst), Sizing::Fill);
}
/// Inferred (Figma was measured only with a typed width): a Fixed set directly on an instance's
/// root, with no width typed, is an override the sync keeps when the main's root turns Hug, Fixed
/// and Hug again.
#[test]
fn an_instance_root_set_to_fixed_keeps_it_through_the_mains_resizing_changes() {
let mut s = Session::new();
let (comp, inst, _) = hugging_note(&mut s);
ex(&mut s, "node.set", json!({"id": inst, "props": {"sizingH": "fixed"}}));
assert_eq!(sizing_h(&s, inst), Sizing::Fixed);
assert!(node(&s, inst).overrides.contains("resizing"), "{:?}", node(&s, inst).overrides);
ex(&mut s, "node.set", json!({"id": comp, "props": {"sizingH": "fixed"}}));
assert_eq!(sizing_h(&s, inst), Sizing::Fixed);
ex(&mut s, "node.set", json!({"id": comp, "props": {"sizingH": "hug"}}));
assert_eq!(sizing_h(&s, comp), Sizing::Hug);
assert_eq!(sizing_h(&s, inst), Sizing::Fixed, "its own Fixed stays after the main hugs again");
}
/// Resetting that instance brings its resizing back to the main's.
#[test]
fn resetting_an_instance_brings_its_own_resizing_back_to_the_mains() {
let mut s = Session::new();
let (_, inst, _) = hugging_note(&mut s);
ex(&mut s, "node.set", json!({"id": inst, "props": {"sizingH": "fixed"}}));
assert_eq!(sizing_h(&s, inst), Sizing::Fixed);
ex(&mut s, "component.resetInstance", json!({"ids": [inst]}));
assert!(!node(&s, inst).overrides.contains("resizing"));
assert_eq!(sizing_h(&s, inst), Sizing::Hug, "the main hugs");
}
/// Create multiple components (#2088): each selected layer becomes its own component in place,
/// keeping its name and position; all stay selected and one undo reverts them all.
#[test]
+11 -1
View File
@@ -162,6 +162,7 @@ pub(crate) fn css_decls(doc: &Document, n: &Node, t: &mut Tokens, hug: (bool, bo
}
if matches!(n.kind, NodeKind::Text(_)) {
// Text: a solid is the ink (`color`), one per fill, so the last (top) one wins.
let top = n.fills.iter().rposition(|p| p.visible);
for (i, p) in n.fills.iter().enumerate().filter(|(_, p)| p.visible) {
match &p.kind {
PaintKind::Solid { color } => {
@@ -169,7 +170,16 @@ pub(crate) fn css_decls(doc: &Document, n: &Node, t: &mut Tokens, hug: (bool, bo
// A variable binds the first paint's colour.
put("color", if i == 0 { tok(doc, n, &["fill"], c, t) } else { c });
}
PaintKind::Gradient(g) => put("background", css_gradient(g, n.width, n.height, p.opacity)),
PaintKind::Gradient(g) => {
put("background", css_gradient(g, n.width, n.height, p.opacity));
// A gradient on top fills the glyphs: clip the background to the text and clear the ink.
// Under a later paint it must not hide that paint's colour, so it stays a plain background.
if Some(i) == top {
put("-webkit-background-clip", "text".into());
put("background-clip", "text".into());
put("color", "transparent".into());
}
}
PaintKind::Image(_) => put("background", "url(image.png) center / cover".into()),
PaintKind::Pattern(_) => put("background", "url(pattern.png) repeat".into()),
}
+3
View File
@@ -293,6 +293,9 @@ fn decl(key: &str, value: &str) -> Vec<(String, String)> {
// An image shorthand (`url(…) center / cover`) is a whole `background`, not a bg colour.
("background", v) if v.starts_with("url(") => one(format!("[background:{}]", arb(v).trim_matches(['[', ']']))),
("background", v) => one(util("bg", "color", v, "color:")),
("-webkit-background-clip", "text") => Vec::new(),
("background-clip", "text") => kw("bg-clip-text"),
("color", "transparent") => kw("text-transparent"),
("color", v) => one(util("text", "color", v, "color:")),
("border", v) => border("", v),
("border-top", v) => border("t", v),
+22 -1
View File
@@ -1,5 +1,7 @@
use super::view_state::ViewState;
use super::{Arc, BTreeSet, Deserialize, Document, NodeId, Serialize, cmd, components, file_access, guides, library, rotation_origin, vectoredit};
use super::{
Arc, BTreeMap, BTreeSet, Deserialize, Document, NodeId, Serialize, cmd, components, file_access, guides, library, rotation_origin, vectoredit,
};
/// One undo step.
#[derive(Clone, Debug)]
@@ -114,6 +116,9 @@ pub struct DocState {
/// The file on disk as this tab last read or wrote it: a save refuses to replace what another
/// app (figcraft-cli, say) wrote to it since (#1330).
pub(crate) on_disk: Option<library::Stamp>,
/// Where each page's view was left in this session (its centre and zoom; see
/// [`Self::open_page`]; not saved).
page_views: BTreeMap<NodeId, (f64, f64, f64)>,
}
/// A version shown on the canvas in place of the document: read-only until it's restored or the
@@ -178,6 +183,7 @@ impl DocState {
last_duplicate: None,
images_left_in_file: None,
on_disk: None,
page_views: BTreeMap::new(),
};
st.zoom_to_fit();
st
@@ -311,6 +317,21 @@ impl DocState {
}
/// Fit the current page's content (or centre on the origin when empty).
/// Show `page` at the view it was left at in this session, or one that fits its content the
/// first time; the page shown till now keeps its view for when it comes back. The page shown
/// already keeps its view.
pub fn open_page(&mut self, page: NodeId) {
if page == self.page {
return;
}
self.page_views.insert(self.page, (self.view.cx, self.view.cy, self.view.zoom));
self.page = page;
match self.page_views.get(&page) {
Some(&(cx, cy, zoom)) => (self.view.cx, self.view.cy, self.view.zoom) = (cx, cy, zoom),
None => self.zoom_to_fit(),
}
}
pub fn zoom_to_fit(&mut self) {
match self.doc.page_content_bounds(self.page) {
Some(b) => self.view.fit(b, 1.0),
+2
View File
@@ -43,6 +43,8 @@ impl EngineError {
match self {
EngineError::BadParams { cmd, msg } => EngineError::BadParams { cmd, msg: format!("step {step}: {msg}") },
EngineError::Other(msg) => EngineError::Other(format!("step {step}: {msg}")),
EngineError::Disabled(cmd, msg) => EngineError::Disabled(cmd, format!("step {step}: {msg}")),
EngineError::Internal { cmd, msg } => EngineError::Internal { cmd, msg: format!("step {step}: {msg}") },
e => e,
}
}
@@ -355,3 +355,35 @@ fn rem_conversion_keeps_the_original_pixels() {
assert_eq!(f("padding: 3px;", 16.0), "padding: 0.1875rem;");
assert_eq!(f("gap: 0.5px;", 16.0), "gap: 0.03125rem;");
}
#[test]
fn text_gradient_fill_clips_to_the_glyphs() {
let mut s = Session::new();
let fills = json!([{"type": "linearGradient", "stops": ["#D98200", "#FF6B4A"]}]);
let t = id(&ex(&mut s, "node.create", json!({"type": "text", "text": "Gradient", "props": {"fontSize": 48, "fills": fills}})));
let c = css(&mut s, t);
assert!(c.contains("background: linear-gradient("), "{c}");
assert!(c.contains("-webkit-background-clip: text;"), "{c}");
assert!(c.contains("\nbackground-clip: text;"), "{c}");
assert!(c.contains("color: transparent;"), "{c}");
let tw = code(&mut s, t, json!({"language": "tailwind"}));
assert!(tw.contains("bg-clip-text") && tw.contains("text-transparent"), "{tw}");
// A box keeps its gradient as a plain background.
let r = rect(&mut s, 0.0, 0.0, 50.0, 50.0, None);
let set = s.execute("node.set", &json!({"id": r, "props": {"fills": fills}}));
assert!(set.is_ok(), "{set:?}");
let box_css = css(&mut s, r);
assert!(box_css.contains("background: linear-gradient("), "{box_css}");
assert!(!box_css.contains("background-clip"), "{box_css}");
}
#[test]
fn text_gradient_under_a_solid_fill_keeps_the_solid_ink() {
let mut s = Session::new();
let fills = json!([{"type": "linearGradient", "stops": ["#D98200", "#FF6B4A"]}, {"type": "solid", "color": "#112233"}]);
let t = id(&ex(&mut s, "node.create", json!({"type": "text", "text": "Gradient", "props": {"fontSize": 48, "fills": fills}})));
let c = css(&mut s, t);
assert!(!c.contains("color: transparent;"), "{c}");
assert!(!c.contains("background-clip"), "{c}");
assert!(c.contains("color: #112233;"), "{c}");
}
+56
View File
@@ -505,3 +505,59 @@ fn node_get_uses_options_but_keeps_its_existing_depth_and_selection() {
assert_eq!(s.selection(), selection);
assert_eq!(s.undo_depth(), history);
}
/// Text and stroke settings a layer stores are reported, under the names `node.set` takes, so a
/// value read can be written back unchanged.
#[test]
fn stored_text_and_stroke_settings_are_read_back_as_set() {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
let text = s.execute("node.create", &json!({"type": "text", "text": "Hi", "width": 120})).unwrap()["id"].clone();
let line =
s.execute("node.create", &json!({"type": "line", "width": 80, "props": {"strokes": ["#000000"], "strokeWeight": 2}})).unwrap()["id"].clone();
let set = json!({
"textAlignVertical": "middle", "textCase": "upper", "paragraphSpacing": 8.0, "paragraphIndent": 12.0, "features": {"liga": false},
});
s.execute("node.set", &json!({"ids": [text.clone()], "props": set})).unwrap();
s.execute("node.set", &json!({"ids": [line.clone()], "props": {"startCap": "round", "endCap": "triangleArrow"}})).unwrap();
let got = s.execute("node.get", &json!({"id": text})).unwrap();
for (key, value) in set.as_object().unwrap() {
assert_eq!(&got[key], value, "{key}: {got}");
// Written back as read, it changes nothing.
s.execute("node.set", &json!({"ids": [text.clone()], "props": {key.as_str(): got[key].clone()}})).unwrap();
assert_eq!(s.execute("node.get", &json!({"id": text})).unwrap()[key], *value, "{key}");
}
let got = s.execute("node.get", &json!({"id": line})).unwrap();
assert_eq!((got["startCap"].as_str(), got["endCap"].as_str()), (Some("round"), Some("triangleArrow")), "{got}");
// Defaults stay out, as they do for other keys.
let plain = s.execute("node.create", &json!({"type": "text", "text": "x"})).unwrap()["id"].clone();
let got = s.execute("node.get", &json!({"id": plain})).unwrap();
for key in ["textAlignVertical", "textCase", "paragraphSpacing", "paragraphIndent", "features", "startCap", "endCap", "variableModes"] {
assert!(got.get(key).is_none(), "{key} at its default: {got}");
}
}
/// A frame's variable modes, a layer's component property bindings and an exposed nested instance
/// are reported.
#[test]
fn modes_property_bindings_and_exposed_instances_are_read() {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
let c = s.execute("variable.createCollection", &json!({"name": "Theme", "modes": ["Light", "Dark"]})).unwrap();
let frame = s.execute("node.create", &json!({"type": "frame", "width": 100, "height": 100})).unwrap()["id"].clone();
s.execute("variable.setMode", &json!({"ids": [frame.clone()], "collection": c["id"], "mode": "Dark"})).unwrap();
let modes = s.execute("node.get", &json!({"id": frame})).unwrap()["variableModes"].clone();
assert_eq!(modes.as_object().map(|m| m.len()), Some(1), "{modes}");
let card = s.execute("node.create", &json!({"type": "frame", "name": "Card", "width": 100, "height": 50})).unwrap()["id"].clone();
let title = s.execute("node.create", &json!({"type": "text", "parent": card.clone(), "text": "Title"})).unwrap()["id"].clone();
let main = s.execute("component.create", &json!({"ids": [card]})).unwrap()["id"].clone();
s.execute("component.addProperty", &json!({"id": main.clone(), "name": "Label", "type": "text", "layer": title.clone()})).unwrap();
let refs = s.execute("node.get", &json!({"id": title})).unwrap()["propertyReferences"].clone();
assert!(refs.as_object().is_some_and(|r| r.values().any(|v| v.as_str().is_some_and(|p| p.starts_with("Label")))), "{refs}");
let tag = s.execute("node.create", &json!({"type": "frame", "name": "Tag", "x": 300, "width": 40, "height": 20})).unwrap()["id"].clone();
let tag_main = s.execute("component.create", &json!({"ids": [tag]})).unwrap()["id"].clone();
let nested = s.execute("instance.create", &json!({"component": tag_main})).unwrap()["id"].clone();
s.execute("node.reparent", &json!({"ids": [nested.clone()], "parent": main})).unwrap();
s.execute("component.exposeInstance", &json!({"id": nested.clone()})).unwrap();
assert_eq!(s.execute("node.get", &json!({"id": nested})).unwrap()["exposedInstance"], true);
}
+31 -1
View File
@@ -77,6 +77,34 @@ fn a_layer_in_an_instance_fills_and_keeps_it_through_main_edits() {
healthy(&s);
}
/// A child set to Fill along a hugging instance root turns the root Fixed: that is the root's own
/// resizing now, recorded as an override, so a later rebuild from the main (an edit of the main's
/// resizing or structure) keeps it Fixed and the child keeps filling.
#[test]
fn a_child_filling_a_hugging_instance_root_keeps_the_root_fixed_through_a_rebuild() {
let mut s = Session::new();
let f = idv(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 120, "height": 40, "name": "Row"})));
ex(&mut s, "node.set", json!({"id": f, "props": {"layout": "horizontal", "padding": 0, "gap": 0, "sizingH": "hug", "sizingV": "hug"}}));
let atom = idv(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 50, "height": 20, "parent": f, "name": "Atom"})));
ex(&mut s, "node.set", json!({"id": atom, "props": {"layout": "horizontal", "padding": 0, "gap": 0, "sizingH": "hug", "sizingV": "hug"}}));
ex(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 20, "parent": atom, "props": {"name": "Dot"}}));
let c = idv(&ex(&mut s, "component.create", json!({"ids": [f]})));
let i = idv(&ex(&mut s, "instance.create", json!({"component": c, "x": 0, "y": 100})));
let ia = copy_of(&s, i, atom);
assert_eq!((sizing_h(&s, i), sizing_h(&s, ia), node(&s, i).width), (Sizing::Hug, Sizing::Hug, 50.0));
ex(&mut s, "node.set", json!({"id": ia, "props": {"sizingH": "fill"}}));
assert_eq!((sizing_h(&s, i), sizing_h(&s, ia)), (Sizing::Fixed, Sizing::Fill), "the root turned Fixed, the child fills");
// The main's resizing changes, and its structure: both rebuild the instance.
ex(&mut s, "node.set", json!({"id": c, "props": {"minWidth": 60}}));
ex(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 5, "height": 5, "parent": c}));
assert_eq!((sizing_h(&s, i), sizing_h(&s, ia)), (Sizing::Fixed, Sizing::Fill), "the root stays Fixed through the rebuild");
assert!(node(&s, i).overrides.contains("resizing"), "{:?}", node(&s, i).overrides);
// Reset instance gives the main's Hug back.
ex(&mut s, "component.resetInstance", json!({"ids": [i]}));
assert_eq!(sizing_h(&s, i), Sizing::Hug);
healthy(&s);
}
#[test]
fn size_and_resizing_overrides_undo_reset_and_detach() {
let mut s = Session::new();
@@ -123,8 +151,10 @@ fn layers_in_instances_resize_but_keep_their_place() {
for props in [json!({"x": 50}), json!({"rotation": 15}), json!({"constraints": {"horizontal": "right"}})] {
assert!(s.execute("node.set", &json!({"id": it, "props": props})).is_err(), "{props} is refused");
}
// The instance's own resizing is its own, not an override.
// The instance's own resizing is recorded as an override (inferred), which Reset instance clears.
ex(&mut s, "node.set", json!({"id": i, "props": {"minWidth": 100}}));
assert!(node(&s, i).overrides.contains("resizing"));
ex(&mut s, "component.resetInstance", json!({"ids": [i]}));
assert!(!node(&s, i).overrides.contains("resizing"));
healthy(&s);
}
+10
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;
@@ -404,6 +406,8 @@ mod keymap_tests;
#[cfg(test)]
mod layout_suggest_tests;
#[cfg(test)]
mod library_asset_counts_tests;
#[cfg(test)]
mod library_beacon_tests;
#[cfg(test)]
mod library_path_tests;
@@ -474,6 +478,8 @@ mod panels_behaviour_tests;
#[cfg(test)]
mod paste_missing_image_tests;
#[cfg(test)]
mod paste_sibling_tests;
#[cfg(test)]
mod path_read_caps_tests;
#[cfg(test)]
mod pdf_print_tests;
@@ -634,6 +640,8 @@ mod variables_import_shapes_tests;
#[cfg(test)]
mod variables_io_tests;
#[cfg(test)]
mod variant_shared_props_tests;
#[cfg(test)]
mod variants_discovery_tests;
#[cfg(test)]
mod vector_behaviour_tests;
@@ -668,6 +676,8 @@ mod widget_shapes_tests;
#[cfg(test)]
mod widgets_tests;
#[cfg(test)]
mod page_view_tests;
#[cfg(test)]
mod selection_reorder_tests;
#[cfg(test)]
@@ -0,0 +1,183 @@
//! What a file counts as inserting and detaching a library's styles and variables, as the help
//! center's library analytics page says: applying one, or copying or duplicating content that uses
//! it, inserts it; the Detach button detaches it. Content that is an instance counts as the
//! instance alone, and local styles and variables count nothing. An undo takes its count back.
use serde_json::{Value, json};
use crate::Session;
use crate::components::tests::{ex, idv};
use crate::library_server::{asset_action_reports, asset_actions};
use figcraft_collab::message::MAX_ASSET_USAGE;
use figcraft_doc::{AssetCount, Document, NodeId, NodeKind, PublishedLibrary};
/// A file with a published library holding a paint style, a colour variable and a Card, and a
/// second file that uses it: the second session, the library's id and its keys.
fn user() -> (Session, String, Value) {
let mut a = Session::new();
let r = idv(&ex(&mut a, "shape.rectangle", json!({"x": 0, "y": 0, "width": 40, "height": 40})));
let style = ex(&mut a, "style.create", json!({"type": "paint", "name": "Brand", "from": r.0}));
let coll = ex(&mut a, "variable.createCollection", json!({"name": "Tokens"}));
ex(&mut a, "variable.create", json!({"name": "Accent", "type": "color", "collection": coll["id"], "value": "#0D99FF"}));
let card = idv(&ex(&mut a, "frame.create", json!({"x": 0, "y": 100, "width": 100, "height": 40, "name": "Card"})));
ex(&mut a, "style.apply", json!({"ids": [card.0], "style": style["id"]}));
ex(&mut a, "component.create", json!({"ids": [card.0]}));
ex(&mut a, "library.publish", json!({}));
let lib: PublishedLibrary = a.doc().unwrap().published.as_deref().unwrap().clone();
let path = std::env::temp_dir().join(format!("figcraft-asset-counts-{}-{:?}.figcraft", std::process::id(), std::thread::current().id()));
ex(&mut a, "file.save", json!({"path": path.to_string_lossy()}));
let mut b = Session::new();
let id = ex(&mut b, "library.add", json!({"path": path.to_string_lossy()}))["id"].as_str().unwrap().to_string();
assert_eq!(lib.manifest.id, id);
(b, id, json!({"style": "Brand", "variable": "Accent"}))
}
fn rect(s: &mut Session, x: i32) -> NodeId {
idv(&ex(s, "shape.rectangle", json!({"x": x, "y": 0, "width": 40, "height": 40})))
}
/// (inserted, detached) of the style and of the variable, as `doc` keeps them.
fn counts(s: &Session) -> ((u32, u32), (u32, u32)) {
let of = |key: &str| {
s.doc().unwrap().libraries.asset_counts.iter().find(|c: &&AssetCount| c.key.starts_with(key)).map_or((0, 0), |c| (c.inserted, c.detached))
};
(of("S:"), of("VariableID:"))
}
#[test]
fn applying_counts_once_per_layer_that_takes_it() {
let (mut s, lib, _) = user();
let (one, two) = (rect(&mut s, 0), rect(&mut s, 100));
ex(&mut s, "library.applyStyle", json!({"library": lib, "style": "Brand", "ids": [one.0, two.0]}));
assert_eq!(counts(&s).0, (2, 0));
ex(&mut s, "library.applyStyle", json!({"library": lib, "style": "Brand", "ids": [one.0]}));
assert_eq!(counts(&s).0, (2, 0), "a layer that has it already adds nothing");
let three = rect(&mut s, 200);
ex(&mut s, "library.bindVariable", json!({"library": lib, "variable": "Accent", "ids": [three.0], "field": "fill"}));
assert_eq!(counts(&s).1, (1, 0));
}
#[test]
fn duplicating_and_pasting_content_counts_what_it_uses() {
let (mut s, lib, _) = user();
let one = rect(&mut s, 0);
ex(&mut s, "library.applyStyle", json!({"library": lib, "style": "Brand", "ids": [one.0]}));
ex(&mut s, "select.set", json!({"ids": [one.0]}));
ex(&mut s, "edit.duplicate", json!({}));
assert_eq!(counts(&s).0, (2, 0), "the copy inserts it too");
ex(&mut s, "select.set", json!({"ids": [one.0]}));
ex(&mut s, "edit.copy", json!({}));
ex(&mut s, "edit.paste", json!({}));
assert_eq!(counts(&s).0, (3, 0));
}
#[test]
fn an_instance_counts_as_its_component_alone() {
let (mut s, lib, _) = user();
let i = idv(&ex(&mut s, "library.place", json!({"library": lib, "component": "Card", "x": 0, "y": 0})));
assert_eq!(counts(&s).0, (0, 0), "placing it");
ex(&mut s, "select.set", json!({"ids": [i.0]}));
ex(&mut s, "edit.duplicate", json!({}));
assert_eq!(counts(&s).0, (0, 0), "duplicating it");
assert_eq!(s.doc().unwrap().libraries.inserted[0].count, 2);
}
/// Applying and detaching a library style or variable on an instance, on a layer in it, or on a
/// layer of an instance nested in it counts nothing either: what an instance uses counts as it.
#[test]
fn applying_and_detaching_inside_an_instance_counts_nothing() {
let (mut s, lib, _) = user();
let placed = idv(&ex(&mut s, "library.place", json!({"library": lib, "component": "Card", "x": 0, "y": 0})));
// A Button holding a rectangle and an Icon instance (the Icon holds a dot), and a Button instance.
let icon = idv(&ex(&mut s, "frame.create", json!({"x": 0, "y": 200, "width": 24, "height": 24, "name": "Icon"})));
ex(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 8, "height": 8, "parent": icon.0}));
let icon = idv(&ex(&mut s, "component.create", json!({"ids": [icon.0]})));
let button = idv(&ex(&mut s, "frame.create", json!({"x": 100, "y": 200, "width": 80, "height": 40, "name": "Button"})));
ex(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 80, "height": 40, "parent": button.0}));
ex(&mut s, "instance.create", json!({"component": icon.0, "parent": button.0, "x": 4, "y": 4}));
let button = idv(&ex(&mut s, "component.create", json!({"ids": [button.0]})));
let i = idv(&ex(&mut s, "instance.create", json!({"component": button.0, "x": 300, "y": 200})));
let (layer, nested, deep) = {
let d = s.doc().unwrap();
let kids = |id: NodeId| d.node(id).unwrap().children.clone();
let nested = kids(i).into_iter().find(|k| matches!(d.node(*k).unwrap().kind, NodeKind::Instance { .. })).unwrap();
let layer = kids(i).into_iter().find(|k| *k != nested).unwrap();
(layer, nested, kids(nested)[0])
};
let targets = [placed.0, i.0, layer.0, nested.0, deep.0];
ex(&mut s, "library.applyStyle", json!({"library": lib, "style": "Brand", "ids": targets}));
ex(&mut s, "library.bindVariable", json!({"library": lib, "variable": "Accent", "ids": targets, "field": "stroke"}));
let d = s.doc().unwrap();
assert!(d.node(deep).unwrap().styles.fill.is_some() && !d.node(deep).unwrap().bound.is_empty(), "the nested layer took both");
ex(&mut s, "style.detach", json!({"ids": targets, "which": "fill"}));
ex(&mut s, "variable.bind", json!({"ids": targets, "field": "stroke"}));
assert_eq!(counts(&s), ((0, 0), (0, 0)));
// The same on a plain layer counts.
let plain = rect(&mut s, 600);
ex(&mut s, "library.applyStyle", json!({"library": lib, "style": "Brand", "ids": [plain.0]}));
ex(&mut s, "library.bindVariable", json!({"library": lib, "variable": "Accent", "ids": [plain.0], "field": "stroke"}));
ex(&mut s, "style.detach", json!({"ids": [plain.0], "which": "fill"}));
ex(&mut s, "variable.bind", json!({"ids": [plain.0], "field": "stroke"}));
assert_eq!(counts(&s), ((1, 1), (1, 1)));
}
#[test]
fn only_the_detach_buttons_detach() {
let (mut s, lib, _) = user();
let (one, two) = (rect(&mut s, 0), rect(&mut s, 100));
ex(&mut s, "library.applyStyle", json!({"library": lib, "style": "Brand", "ids": [one.0, two.0]}));
ex(&mut s, "library.bindVariable", json!({"library": lib, "variable": "Accent", "ids": [two.0], "field": "stroke"}));
ex(&mut s, "style.detach", json!({"ids": [one.0, two.0], "which": "fill"}));
assert_eq!(counts(&s).0, (2, 2));
ex(&mut s, "variable.bind", json!({"ids": [two.0], "field": "stroke"}));
assert_eq!(counts(&s).1, (1, 1));
// Another style in its place isn't a detach of the first.
let local = ex(&mut s, "style.create", json!({"type": "paint", "name": "Mine", "from": one.0}));
ex(&mut s, "library.applyStyle", json!({"library": lib, "style": "Brand", "ids": [one.0]}));
ex(&mut s, "style.apply", json!({"ids": [one.0], "style": local["id"]}));
assert_eq!(counts(&s).0, (3, 2));
}
#[test]
fn local_styles_count_nothing_and_undo_takes_a_count_back() {
let (mut s, lib, _) = user();
let one = rect(&mut s, 0);
let local = ex(&mut s, "style.create", json!({"type": "paint", "name": "Mine", "from": one.0}));
ex(&mut s, "style.apply", json!({"ids": [one.0], "style": local["id"]}));
ex(&mut s, "style.detach", json!({"ids": [one.0], "which": "fill"}));
assert!(s.doc().unwrap().libraries.asset_counts.is_empty());
assert!(asset_actions(s.doc().unwrap(), &lib).is_none());
ex(&mut s, "library.applyStyle", json!({"library": lib, "style": "Brand", "ids": [one.0]}));
let report = asset_actions(s.doc().unwrap(), &lib).unwrap();
assert_eq!((report.inserted.len(), report.detached.len()), (1, 0));
ex(&mut s, "edit.undo", json!({}));
assert_eq!(counts(&s).0, (0, 0));
}
#[test]
fn asset_action_reports_cover_every_count_past_the_message_cap() {
let mut doc = Document::new("File");
let n = MAX_ASSET_USAGE + 1;
let libraries = std::sync::Arc::make_mut(&mut doc.libraries);
for i in 0..n {
let key = format!("s{i}");
libraries.count_asset("Lib", &key, false, 1);
libraries.count_asset("Lib", &key, true, 2);
}
// Another library's counts do not belong in these reports.
libraries.count_asset("Other", "x", false, 9);
libraries.count_asset("Other", "x", true, 9);
let full = asset_actions(&doc, "Lib").unwrap();
assert_eq!(full.inserted.len(), n, "the document's counts are not truncated");
assert_eq!(full.detached.len(), n);
let reports = asset_action_reports(&doc, "Lib");
assert!(reports.len() >= 2, "one message cannot carry {n} counts");
assert!(reports.iter().all(|r| r.file == "File" && r.inserted.len() <= MAX_ASSET_USAGE && r.detached.len() <= MAX_ASSET_USAGE));
let inserted: Vec<_> = reports.iter().flat_map(|r| r.inserted.iter().cloned()).collect();
let detached: Vec<_> = reports.iter().flat_map(|r| r.detached.iter().cloned()).collect();
assert_eq!(inserted, full.inserted);
assert_eq!(detached, full.detached);
assert!(asset_action_reports(&doc, "Missing").is_empty());
}
@@ -550,3 +550,55 @@ fn stored_variable_ids_keep_library_alias_dependencies() {
assert!(copy.values.values().all(|v| *v == VariableValue::Alias(map.variables[target].clone())));
assert!(dest.variables.collections.iter().any(|c| c.name == "Base"));
}
/// A library with collection `coll` (Main/Alt), a colour variable `var` and a paint style `var`
/// bound to it, published to `path`; returns (the library session, its id).
fn styled_library(path: &str, coll: &str, var: &str, main: &str, alt: &str) -> (Session, String) {
let mut lib = Session::new();
ex(&mut lib, "variable.createCollection", json!({"name": coll, "modes": ["Main", "Alt"]}));
let v = ex(&mut lib, "variable.create", json!({"collection": coll, "name": var, "type": "color", "values": {"Main": main, "Alt": alt}}))["id"]
.clone();
let style = ex(&mut lib, "style.create", json!({"type": "paint", "name": var, "value": main}))["id"].clone();
ex(&mut lib, "style.bind", json!({"style": style, "field": "fill", "variable": v}));
let lid = publish_to(&mut lib, path);
(lib, lid)
}
#[test]
fn accepting_updates_keeps_variables_only_library_styles_use() {
let d = dir("accept-style-vars");
let (pa, pb) = (path_str(&d.join("a.figcraft")), path_str(&d.join("b.figcraft")));
let (mut a, la) = styled_library(&pa, "TokensA", "accent", "#1565c0", "#2e7d32");
let (_b, lb) = styled_library(&pb, "TokensB", "primary", "#7b1fa2", "#00838f");
let mut s = Session::new();
let frame = idv(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 200, "height": 200})));
let ra = idv(&ex(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20, "parent": frame})));
let rb = idv(&ex(&mut s, "shape.rectangle", json!({"x": 50, "y": 10, "width": 20, "height": 20, "parent": frame})));
ex(&mut s, "library.add", json!({"path": pa}));
ex(&mut s, "library.add", json!({"path": pb}));
ex(&mut s, "library.applyStyle", json!({"library": la, "style": "accent", "id": ra}));
ex(&mut s, "library.applyStyle", json!({"library": lb, "style": "primary", "id": rb}));
ex(&mut s, "library.setVariableMode", json!({"library": la, "collection": "TokensA", "mode": "Alt", "ids": [frame]}));
ex(&mut s, "library.setVariableMode", json!({"library": lb, "collection": "TokensB", "mode": "Alt", "ids": [frame]}));
assert_eq!(fill(&s, ra), "2E7D32");
assert_eq!(fill(&s, rb), "00838F");
healthy(&s);
ex(&mut a, "variable.set", json!({"variable": "accent", "mode": "Alt", "value": "#ef6c00"}));
republish(&mut a);
let r = ex(&mut s, "library.acceptUpdates", json!({}));
assert_eq!(r["variables"], 1, "{r}");
let doc = s.doc().unwrap();
for name in ["accent", "primary"] {
let v = doc.variables.variables.iter().find(|v| v.name == name && is_remote_variable(doc, &v.id));
assert!(v.is_some(), "library variable copy `{name}` was deleted");
let id = &v.unwrap().id;
assert!(doc.libraries.variables.iter().any(|r| &r.local == id), "record of `{name}` was deleted");
}
assert_eq!(fill(&s, ra), "EF6C00");
assert_eq!(fill(&s, rb), "00838F");
healthy(&s);
let _ = std::fs::remove_dir_all(&d);
}
+35
View File
@@ -0,0 +1,35 @@
//! Each page keeps its view in a session: going back to a page shows it where it was left, not
//! fitted again (a new page is still fitted); going to the page shown changes nothing.
use serde_json::{Value, json};
use crate::Session;
fn view(s: &mut Session) -> (f64, f64, f64) {
let v: Value = s.execute("view.get", &json!({})).unwrap();
(v["cx"].as_f64().unwrap(), v["cy"].as_f64().unwrap(), v["zoom"].as_f64().unwrap())
}
#[test]
fn going_back_to_a_page_shows_it_where_it_was_left() {
let mut s = Session::new();
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 400, "height": 300})).unwrap();
let first = s.page().unwrap();
s.execute("view.set", &json!({"zoom": 2.5, "cx": 1000, "cy": 500})).unwrap();
let second = crate::params::id_of(&s.execute("page.add", &json!({})).unwrap()["id"]).unwrap();
assert_ne!(view(&mut s), (1000.0, 500.0, 2.5), "a new page is fitted, not shown at the last page's view");
s.execute("shape.ellipse", &json!({"x": 5000, "y": 5000, "width": 100, "height": 100})).unwrap();
s.execute("view.set", &json!({"zoom": 0.5, "cx": -200, "cy": 40})).unwrap();
s.execute("page.select", &json!({"id": first})).unwrap();
assert_eq!(view(&mut s), (1000.0, 500.0, 2.5), "the first page as it was left");
s.execute("view.nextPage", &json!({})).unwrap();
assert_eq!(s.page().unwrap(), second);
assert_eq!(view(&mut s), (-200.0, 40.0, 0.5), "the second page as it was left");
// The page shown: nothing moves.
s.execute("view.set", &json!({"zoom": 3.0, "cx": 7, "cy": 8})).unwrap();
s.execute("page.select", &json!({"id": second})).unwrap();
assert_eq!(view(&mut s), (7.0, 8.0, 3.0));
s.execute("view.prevPage", &json!({})).unwrap();
assert_eq!(view(&mut s), (1000.0, 500.0, 2.5));
}
+122
View File
@@ -0,0 +1,122 @@
//! Cmd/Ctrl+V with one layer inside a frame selected pastes next to it, in its parent (#2355).
use serde_json::{Value, json};
use crate::Session;
use crate::params::id_of;
use figcraft_doc::NodeId;
fn id(v: &Value) -> NodeId {
id_of(&v["id"]).unwrap()
}
fn sess() -> Session {
Session::new()
}
fn rect(s: &mut Session, parent: Option<NodeId>, x: f64, y: f64) -> NodeId {
let mut p = json!({"x": x, "y": y, "width": 40, "height": 20});
if let Some(parent) = parent {
p["parent"] = json!(parent);
}
id(&s.execute("shape.rectangle", &p).unwrap())
}
fn kids(s: &Session, parent: NodeId) -> Vec<NodeId> {
s.doc().unwrap().node(parent).unwrap().children.clone()
}
fn parent_of(s: &Session, n: NodeId) -> Option<NodeId> {
s.doc().unwrap().node(n).unwrap().parent
}
fn paste(s: &mut Session) -> Vec<NodeId> {
s.execute("edit.paste", &json!({})).unwrap()["ids"].as_array().unwrap().iter().filter_map(id_of).collect()
}
#[test]
fn paste_with_a_layer_in_an_auto_layout_frame_selected_goes_right_after_it() {
let mut s = sess();
let a = rect(&mut s, None, 0.0, 0.0);
let b = rect(&mut s, None, 0.0, 30.0);
let r = s.execute("layout.add", &json!({"ids": [a, b], "direction": "vertical"})).unwrap();
let frame = id_of(&r["ids"][0]).unwrap();
s.execute("node.set", &json!({"id": frame, "props": {"gap": 10}})).unwrap();
let h0 = s.doc().unwrap().node(frame).unwrap().height;
assert_eq!(h0, 50.0);
assert_eq!(kids(&s, frame), vec![a, b]);
s.set_selection(vec![b]);
s.execute("edit.copy", &json!({})).unwrap();
let pasted = paste(&mut s);
assert_eq!(pasted.len(), 1);
assert_eq!(parent_of(&s, pasted[0]), Some(frame), "the copy joins the selected layer's frame");
assert_eq!(kids(&s, frame), vec![a, b, pasted[0]], "right after the selected layer in the flow");
assert_eq!(s.doc().unwrap().node(frame).unwrap().height, h0 + 20.0 + 10.0, "the frame grew by the copy's height plus the gap");
assert_eq!(s.selection(), pasted);
}
#[test]
fn paste_with_a_layer_in_a_plain_frame_selected_stays_in_the_frame_in_place() {
let mut s = sess();
let frame = id(&s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 200, "height": 200})).unwrap());
let a = rect(&mut s, Some(frame), 10.0, 10.0);
let b = rect(&mut s, Some(frame), 100.0, 100.0);
s.set_selection(vec![a]);
s.execute("edit.copy", &json!({})).unwrap();
let pasted = paste(&mut s);
assert_eq!(pasted.len(), 1);
assert_eq!(parent_of(&s, pasted[0]), Some(frame));
assert_eq!(kids(&s, frame), vec![a, pasted[0], b], "just above the selected layer");
let wb = s.doc().unwrap().world_bounds(pasted[0]).unwrap();
assert_eq!((wb.x0, wb.y0), (10.0, 10.0), "at the selected layer's position");
assert_eq!(s.selection(), pasted);
}
#[test]
fn paste_with_a_top_level_layer_selected_is_unchanged() {
let mut s = sess();
let a = rect(&mut s, None, 10.0, 10.0);
let page = parent_of(&s, a).unwrap();
let before = kids(&s, page);
s.set_selection(vec![a]);
s.execute("edit.copy", &json!({})).unwrap();
let pasted = paste(&mut s);
assert_eq!(parent_of(&s, pasted[0]), Some(page));
let mut want = before;
want.push(pasted[0]);
assert_eq!(kids(&s, page), want, "on the page, on top, as before");
}
#[test]
fn paste_with_two_layers_selected_is_unchanged() {
let mut s = sess();
let frame = id(&s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 200, "height": 200})).unwrap());
let a = rect(&mut s, Some(frame), 10.0, 10.0);
let b = rect(&mut s, Some(frame), 100.0, 100.0);
let page = parent_of(&s, frame).unwrap();
s.set_selection(vec![a, b]);
s.execute("edit.copy", &json!({})).unwrap();
let pasted = paste(&mut s);
assert_eq!(pasted.len(), 2);
assert!(pasted.iter().all(|p| parent_of(&s, *p) == Some(page)), "on the page, as before");
assert_eq!(kids(&s, frame), vec![a, b]);
}
#[test]
fn paste_with_a_layer_inside_an_instance_selected_is_unchanged() {
let mut s = sess();
let f = id(&s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 100, "height": 50, "name": "Button"})).unwrap());
s.execute("text.create", &json!({"text": "OK", "x": 10, "y": 10, "parent": f})).unwrap();
let c = id(&s.execute("component.create", &json!({"ids": [f]})).unwrap());
let inst = id(&s.execute("instance.create", &json!({"component": c, "x": 200, "y": 0})).unwrap());
let page = parent_of(&s, inst).unwrap();
let inner = kids(&s, inst)[0];
let inner_kids = kids(&s, inst);
let other = rect(&mut s, None, 500.0, 500.0);
s.set_selection(vec![other]);
s.execute("edit.copy", &json!({})).unwrap();
s.set_selection(vec![inner]);
let pasted = paste(&mut s);
assert_eq!(parent_of(&s, pasted[0]), Some(page), "an instance's children are fixed: the copy goes to the page");
assert_eq!(kids(&s, inst), inner_kids);
}
@@ -108,6 +108,42 @@ fn sorted(mut v: Vec<NodeId>) -> Vec<NodeId> {
v
}
#[test]
fn clicking_a_device_background_after_its_nested_button_selects_the_device() {
let mut s = Session::new();
let device = id(&ex(&mut s, "frame.create", json!({"x": 132, "y": -148, "width": 440, "height": 956})));
let button = id(&ex(&mut s, "frame.create", json!({"parent": device, "x": 155, "y": 30, "width": 130, "height": 34})));
rect(&mut s, 10.0, 5.0, Some(button));
ex(&mut s, "layout.add", json!({"ids": [button], "direction": "horizontal"}));
ex(&mut s, "select.set", json!({"ids": [button]}));
let before = s.doc().unwrap().clone();
let history = s.undo_depth();
s.pointer(&ev(PointerKind::Down, 352.0, 330.0, NONE)).unwrap();
assert_eq!(s.selection(), vec![device], "the parent is selected on press");
// Small pointer jitter must not turn the click into a zero-sized marquee.
s.pointer(&ev(PointerKind::Move, 353.0, 330.0, NONE)).unwrap();
s.pointer(&ev(PointerKind::Up, 353.0, 330.0, NONE)).unwrap();
s.pointer(&ev(PointerKind::Hover, 353.0, 330.0, NONE)).unwrap();
assert_eq!(s.selection(), vec![device], "the parent stays selected after release and hover");
assert_eq!(*s.doc().unwrap(), before);
assert_eq!(s.undo_depth(), history, "selection adds no edit history");
}
#[test]
fn dragging_a_device_background_after_its_child_still_marquees_and_closes_cleanly() {
let mut s = Session::new();
let k = scene(&mut s);
ex(&mut s, "select.set", json!({"ids": [k.d]}));
drag(&mut s, (390.0, 290.0), (190.0, 10.0), NONE);
assert_eq!(s.selection(), vec![k.n], "a background drag selects the nested frame");
assert!(s.ds().unwrap().interaction.is_none(), "a marquee leaves no move snapshot behind");
ex(&mut s, "node.set", json!({"id": k.n, "props": {"opacity": 0.5}}));
click(&mut s, 30.0, 130.0, NONE);
assert_eq!(s.doc().unwrap().node(k.n).unwrap().opacity, 0.5, "the next click keeps the edit");
ex(&mut s, "edit.undo", json!({}));
assert_eq!(s.doc().unwrap().node(k.n).unwrap().opacity, 1.0, "the edit retains its undo step");
}
#[test]
fn clicking_selects_by_the_documented_rules() {
let mut s = Session::new();
@@ -130,6 +166,9 @@ fn clicking_selects_by_the_documented_rules() {
((520.0, 120.0), NONE, vec![], vec![k.r2], "a locked layer can't be selected on the canvas: the click goes to what is under it"),
((520.0, 220.0), NONE, vec![k.r], vec![], "a hidden layer can't be selected on the canvas (empty canvas deselects)"),
((390.0, 290.0), NONE, vec![k.r], vec![], "the background of a top-level frame with layers is like the canvas: a click deselects"),
((390.0, 290.0), NONE, vec![k.c], vec![k.f], "clicking the containing frame's background steps out from its child"),
((390.0, 290.0), NONE, vec![k.d], vec![k.f], "stepping out works from a deeper descendant too"),
((390.0, 290.0), NONE, vec![], vec![], "without a selected descendant the background remains canvas-like"),
((390.0, 290.0), NONE, vec![k.f], vec![k.f], "a selected top-level frame stays selected when its background is clicked"),
((390.0, 290.0), CMD, vec![], vec![k.f], "silent: Cmd/Ctrl-click on a frame's background selects the frame (the deepest layer there)"),
((640.0, 40.0), NONE, vec![], vec![k.empty], "an empty top-level frame is selected by a click on it"),
@@ -523,3 +562,71 @@ fn shift_click_takes_a_layer_out_where_nothing_can_move() {
s.pointer(&ev(PointerKind::Up, 520.0, 20.0, SHIFT)).unwrap();
assert_eq!(s.selection(), vec![k.empty], "Shift-click still takes the layer out");
}
/// A top-level 300 x 300 frame with a filled 100 x 100 rectangle at (50, 50) and a nested 100 x 100
/// frame at (180, 180) holding a 40 x 40 rectangle at (200, 200).
fn frame_with_child(s: &mut Session) -> (NodeId, NodeId, NodeId, NodeId) {
let f = id(&ex(s, "frame.create", json!({"x": 0, "y": 0, "width": 300, "height": 300})));
let c = id(&ex(s, "shape.rectangle", json!({"x": 50, "y": 50, "width": 100, "height": 100, "parent": f})));
let n = id(&ex(s, "frame.create", json!({"x": 180, "y": 180, "width": 100, "height": 100, "parent": f})));
let gc = id(&ex(s, "shape.rectangle", json!({"x": 200, "y": 200, "width": 40, "height": 40, "parent": n})));
(f, c, n, gc)
}
#[test]
fn a_drag_from_a_child_of_a_selected_frame_moves_the_frame() {
let mut s = Session::new();
let (f, c, _n, gc) = frame_with_child(&mut s);
let sib = id(&ex(&mut s, "shape.rectangle", json!({"x": 90, "y": 90, "width": 30, "height": 30})));
let at = |s: &Session, i: NodeId| s.doc().unwrap().world_bounds(i).unwrap().origin();
let local = |s: &Session, i: NodeId| {
let d = s.doc().unwrap();
let n = d.node(i).unwrap();
let c = n.transform.as_coeffs();
(c[4], c[5])
};
let c_local = local(&s, c);
// (selection before, press point, modifiers, selection after, the layers that move by (10, 10), derivation)
let rows: Vec<(Vec<NodeId>, (f64, f64), Mods, Vec<NodeId>, Vec<NodeId>, &str)> = vec![
(vec![f], (60.0, 60.0), NONE, vec![f], vec![f, c, gc], "a drag from a child of the selected frame moves the frame"),
(vec![f], (220.0, 220.0), NONE, vec![f], vec![f, c, gc], "a drag from a grandchild moves the top-level frame"),
(vec![], (60.0, 60.0), NONE, vec![c], vec![c], "with nothing selected the child is picked and moved"),
(vec![f], (60.0, 60.0), CMD, vec![c], vec![c], "Cmd picks the deepest layer and moves it"),
(vec![f], (100.0, 100.0), NONE, vec![sib], vec![sib], "a sibling painted above the frame takes the press"),
];
for (before, from, m, after, moved, why) in rows {
let all = [f, c, gc, sib];
let home: Vec<Point> = all.iter().map(|i| at(&s, *i)).collect();
ex(&mut s, "select.set", json!({"ids": before}));
drag(&mut s, from, (from.0 + 10.0, from.1 + 10.0), m);
assert_eq!(sorted(s.selection()), sorted(after), "{why}");
for (i, h) in all.iter().zip(&home) {
// The frame carries its children: they move in the world, not in their local space.
let d = if moved.contains(i) { 10.0 } else { 0.0 };
assert_eq!(at(&s, *i), Point::new(h.x + d, h.y + d), "{why}");
}
assert_eq!(local(&s, c), if moved == [c] { (c_local.0 + 10.0, c_local.1 + 10.0) } else { c_local }, "{why}: the child's local position");
assert!(s.undo().unwrap(), "{why}: one undo step");
for (i, h) in all.iter().zip(&home) {
assert_eq!(at(&s, *i), *h, "{why}: undo restores");
}
}
}
#[test]
fn a_click_on_a_child_of_a_selected_frame_selects_the_child() {
let mut s = Session::new();
let (f, c, n, gc) = frame_with_child(&mut s);
let home = s.doc().unwrap().world_bounds(c).unwrap().origin();
for (p, want) in [((60.0, 60.0), c), ((190.0, 190.0), n)] {
ex(&mut s, "select.set", json!({"ids": [f]}));
click(&mut s, p.0, p.1, NONE);
assert_eq!(s.selection(), vec![want], "a click selects the layer inside the selected frame");
}
assert_eq!(s.doc().unwrap().world_bounds(c).unwrap().origin(), home, "nothing moved");
let _ = gc;
s.tool.dev_mode = true;
ex(&mut s, "select.set", json!({"ids": [f]}));
click(&mut s, 60.0, 60.0, NONE);
assert_eq!(s.selection(), vec![c], "in Dev Mode too");
}
@@ -98,10 +98,13 @@ fn library(w: &mut Wire, req: LibraryReq) -> LibraryReply {
LibraryReply::Published { version: 1 }
}
(LibraryReq::Usage, _) => LibraryReply::Usage(Vec::new()),
(LibraryReq::ReportDetached(_) | LibraryReq::ReportInserted(_) | LibraryReq::ReportAssets(_), _) => LibraryReply::Noted,
(LibraryReq::ReportDetached(_) | LibraryReq::ReportInserted(_) | LibraryReq::ReportAssets(_) | LibraryReq::ReportAssetActions(_), _) => {
LibraryReply::Noted
}
(LibraryReq::Detached, _) => LibraryReply::Detached(Vec::new()),
(LibraryReq::Actions, _) => LibraryReply::Actions(Vec::new()),
(LibraryReq::Assets, _) => LibraryReply::Assets(Vec::new()),
(LibraryReq::AssetActions, _) => LibraryReply::AssetActions(Vec::new()),
}
}
@@ -0,0 +1,58 @@
//! A set's component properties belong to all its variants, as `component.addProperty` on a set
//! gives them: one made on a component before it was combined goes to every variant, so another
//! variant's layer can be bound to it and an instance switched to that variant keeps its value.
use serde_json::{Value, json};
use crate::Session;
use crate::components::tests::{ex, healthy, idv};
use figcraft_doc::NodeId;
/// A main component named `name` at `x`, made from a 120×40 frame holding a "Button" text: the
/// component and the text.
fn component(s: &mut Session, name: &str, x: f64) -> (NodeId, NodeId) {
let f = idv(&ex(s, "frame.create", json!({"x": x, "y": 0, "width": 120, "height": 40, "name": name})));
let t = idv(&ex(s, "text.create", json!({"text": "Button", "x": 8, "y": 8, "parent": f})));
(idv(&ex(s, "component.create", json!({"ids": [f]}))), t)
}
/// `id`'s component property `name` as `component.properties` lists it.
fn property(s: &mut Session, id: NodeId, name: &str) -> Option<Value> {
let all = ex(s, "component.properties", json!({"id": id}));
all["properties"].as_array().and_then(|l| l.iter().find(|p| p["name"] == name).cloned())
}
#[test]
fn a_property_made_before_combining_goes_to_every_variant() {
let mut s = Session::new();
let (a, label) = component(&mut s, "State=Default", 0.0);
let (b, b_label) = component(&mut s, "State=Hover", 200.0);
ex(&mut s, "component.addProperty", json!({"id": a, "name": "Text", "type": "text", "layer": label}));
let of_b = idv(&ex(&mut s, "instance.create", json!({"component": b, "x": 0, "y": 300})));
ex(&mut s, "component.combineVariants", json!({"ids": [a, b]}));
healthy(&s);
let shared = property(&mut s, b, "Text").expect("the other variant has the property");
assert_eq!((shared["type"].clone(), shared["default"].clone()), (json!("text"), json!("Button")));
// The other variant's text can be bound to it, and its instance then shows the default.
ex(&mut s, "component.bindProperty", json!({"layer": b_label, "property": "Text"}));
assert_eq!(property(&mut s, of_b, "Text").map(|p| p["value"].clone()), Some(json!("Button")));
// An instance switched to the other variant keeps the value it was given.
let of_a = idv(&ex(&mut s, "instance.create", json!({"component": a, "x": 200, "y": 300})));
ex(&mut s, "instance.setProperties", json!({"ids": [of_a], "properties": {"Text": "Buy"}}));
ex(&mut s, "instance.setProperties", json!({"ids": [of_a], "properties": {"State": "Hover"}}));
assert_eq!(property(&mut s, of_a, "Text").map(|p| p["value"].clone()), Some(json!("Buy")));
healthy(&s);
}
#[test]
fn a_variant_keeps_its_own_property_of_the_same_name() {
let mut s = Session::new();
let (a, _) = component(&mut s, "State=Default", 0.0);
let (b, _) = component(&mut s, "State=Hover", 200.0);
ex(&mut s, "component.addProperty", json!({"id": a, "name": "Icon", "type": "text", "default": "Star"}));
ex(&mut s, "component.addProperty", json!({"id": b, "name": "Icon", "type": "boolean", "default": false}));
ex(&mut s, "component.combineVariants", json!({"ids": [a, b]}));
healthy(&s);
assert_eq!(property(&mut s, a, "Icon").map(|p| p["type"].clone()), Some(json!("text")));
assert_eq!(property(&mut s, b, "Icon").map(|p| p["type"].clone()), Some(json!("boolean")));
}
+2
View File
@@ -20,6 +20,8 @@ ruzstd = { workspace = true }
sha1 = { workspace = true }
sha2 = { workspace = true }
image = { workspace = true }
craft-penpot = { workspace = true }
craft-sketch = { workspace = true }
craft-fig = { workspace = true }
craft-figcraft-format = { workspace = true }
craft-figma-rest = { workspace = true }
+2
View File
@@ -25,6 +25,8 @@ mod export;
#[cfg(test)]
mod export_tests;
#[cfg(test)]
mod guides_tests;
#[cfg(test)]
mod interop_tests;
#[cfg(test)]
mod layer_cap_tests;
@@ -8,18 +8,20 @@ use serde_json::{Value, json};
use super::kiwi::{Kv, Schema};
const SCHEMA: &str = "
enum NodeType NONE DOCUMENT CANVAS FRAME TEXT SYMBOL INSTANCE
enum NodeType NONE DOCUMENT CANVAS FRAME TEXT SYMBOL INSTANCE ROUNDED_RECTANGLE
enum StackMode NONE HORIZONTAL VERTICAL
enum StackSize FIXED RESIZE_TO_FIT RESIZE_TO_FIT_WITH_IMPLICIT_SIZE
enum StackJustify MIN CENTER MAX SPACE_EVENLY SPACE_BETWEEN SPACE_AROUND SPACE_EVENLY_CSS
enum StackCounterAlign MIN CENTER MAX STRETCH AUTO BASELINE
enum TextAutoResize NONE WIDTH_AND_HEIGHT HEIGHT
struct GUID uint sessionID, uint localID
struct Vector float x, float y
struct Matrix float m00, float m01, float m02, float m10, float m11, float m12
message ParentIndex GUID guid, string position
message GUIDPath GUID[] guids
message TextData string characters
message SymbolData GUID symbolID
message NodeChange GUID guid, ParentIndex parentIndex, NodeType type, string name, Vector size, Matrix transform, StackMode stackMode, StackSize stackPrimarySizing, StackSize stackCounterSizing, StackJustify stackPrimaryAlignItems, TextAutoResize textAutoResize, float fontSize, TextData textData, SymbolData symbolData
message NodeChange GUID guid, ParentIndex parentIndex, NodeType type, string name, Vector size, Matrix transform, StackMode stackMode, StackSize stackPrimarySizing, StackSize stackCounterSizing, StackJustify stackPrimaryAlignItems, TextAutoResize textAutoResize, float fontSize, TextData textData, SymbolData symbolData, StackCounterAlign stackChildAlignSelf, NodeChange[] derivedSymbolData, GUIDPath guidPath
message Message NodeChange[] nodeChanges
";
@@ -216,3 +218,120 @@ fn distributed_alignment_reads_the_older_evenly_name_as_space_between() {
assert_eq!(n.layout.as_ref().map(|l| l.main_align), Some(want), "{name}");
}
}
/// Issue 2091 item 3: a child with `stackChildAlignSelf: STRETCH` fills the cross axis.
#[test]
fn stretch_children_import_as_fill_on_the_cross_axis() {
use Sizing::Fill;
let stretch = || vec![("stackChildAlignSelf", Kv::Enum("STRETCH"))];
let mut nodes = Vec::new();
// (a) plain frame / (b) component, fixed and hug cross axis (d)
for (k, (ty, counter)) in
[("FRAME", "FIXED"), ("SYMBOL", "FIXED"), ("FRAME", "RESIZE_TO_FIT"), ("SYMBOL", "RESIZE_TO_FIT")].into_iter().enumerate()
{
let id = 100 * (k as u64 + 1);
let mut f = vec![("size", xy(100.0, 40.0)), ("transform", at(0.0, 60.0 * k as f64))];
f.extend(stack("HORIZONTAL", Some("FIXED"), Some(counter)));
nodes.push(node(id, 1, &format!("{id}"), ty, &format!("Row{k}"), f));
// (e) a rectangle and a text
nodes.push(node(
id + 1,
id,
"!",
"ROUNDED_RECTANGLE",
&format!("Bar{k}"),
[vec![("size", xy(3.0, 20.0)), ("transform", at(0.0, 0.0))], stretch()].concat(),
));
let mut t = label(id + 2, id, &format!("Msg{k}"), Some("WIDTH_AND_HEIGHT"));
if let Kv::Object(fields) = &mut t {
fields.extend(stretch());
}
nodes.push(t);
}
// (c) an instance of Row1 (a component) and its copy of the bar
nodes.push(node(
900,
1,
"~",
"INSTANCE",
"Inst",
vec![("size", xy(100.0, 40.0)), ("transform", at(200.0, 0.0)), ("symbolData", o(vec![("symbolID", g(200))]))],
));
// (c2) same-size instance whose derived data gives the bar Figma's stretched 40 px; (c3) a taller
// instance (60) whose derived data gives 60.
for (id, name, h, bar_h) in [(901, "InstDerived", 40.0, 40.0), (902, "InstTall", 60.0, 60.0)] {
let row = o(vec![("guidPath", o(vec![("guids", Kv::Array(vec![g(201)]))])), ("size", xy(3.0, bar_h))]);
nodes.push(node(
id,
1,
&format!("~{id}"),
"INSTANCE",
name,
vec![
("size", xy(100.0, h)),
("transform", at(300.0, 0.0)),
("symbolData", o(vec![("symbolID", g(200))])),
("derivedSymbolData", Kv::Array(vec![row])),
],
));
}
let doc = import(nodes);
let get = |n: &str| doc.nodes().find(|x| x.name == n).unwrap_or_else(|| panic!("no layer {n}"));
let mut bad = Vec::new();
for k in 0..4 {
for what in ["Bar", "Msg text"] {
let n = get(&if what == "Bar" { format!("Bar{k}") } else { format!("Msg{k} text") });
if n.child_layout.sizing_v != Fill {
bad.push(format!("{what}{k} (row {k}): sizing_v {:?}, h {}", n.child_layout.sizing_v, n.size().1));
}
}
}
let inst = get("Inst");
let copy = inst.children.first().and_then(|c| doc.node(*c)).unwrap();
if copy.child_layout.sizing_v != Fill {
bad.push(format!("instance copy of the bar: sizing_v {:?}, h {}", copy.child_layout.sizing_v, copy.size().1));
}
for (name, want_h) in [("InstDerived", 40.0), ("InstTall", 60.0)] {
let inst = get(name);
let bar = inst.children.first().and_then(|c| doc.node(*c)).unwrap();
if bar.child_layout.sizing_v != Fill || (bar.size().1 - want_h).abs() > 1e-6 {
bad.push(format!("{name} copy of the bar: sizing_v {:?}, h {} (want Fill, {want_h})", bar.child_layout.sizing_v, bar.size().1));
}
}
assert!(bad.is_empty(), "{bad:#?}");
}
/// Issue 2091 item 3, after a layout pass: the stretched bar takes the row's cross size, also
/// when the row hugs (the bar next to a two-line text, whose height makes the row's).
#[test]
fn stretch_children_take_the_row_height_after_a_layout_pass() {
let mut nodes = Vec::new();
// (name, counter sizing, row height, expected bar height after layout)
let rows = [("Fixed row", "FIXED", 40.0, 40.0), ("Hug row", "RESIZE_TO_FIT", 16.0, 16.0)];
for (k, (name, counter, h, _)) in rows.iter().enumerate() {
let id = 100 * (k as u64 + 1);
let mut f = vec![("size", xy(100.0, *h)), ("transform", at(0.0, 60.0 * k as f64))];
f.extend(stack("HORIZONTAL", Some("FIXED"), Some(counter)));
nodes.push(node(id, 1, &format!("{id}"), "FRAME", name, f));
let bar = vec![("size", xy(3.0, 10.0)), ("transform", at(0.0, 0.0)), ("stackChildAlignSelf", Kv::Enum("STRETCH"))];
nodes.push(node(id + 1, id, "!", "ROUNDED_RECTANGLE", &format!("Bar {name}"), bar));
// The text sets the row's height: 16 px tall, fixed box.
let mut t = label(id + 2, id, name, Some("NONE"));
if let Kv::Object(fields) = &mut t {
fields.push(("transform", at(10.0, 0.0)));
}
nodes.push(t);
}
let mut doc = import(nodes);
let page = doc.first_page().unwrap();
figcraft_layout::layout_page(&mut doc, page, &figcraft_layout::NoMeasure);
let mut bad = Vec::new();
for (name, _, _, want) in rows {
let bar = doc.nodes().find(|n| n.name == format!("Bar {name}")).unwrap();
let got = bar.size().1;
if (got - want).abs() > 1e-6 {
bad.push(format!("{name}: bar sizing_v {:?}, height {got}, want {want}", bar.child_layout.sizing_v));
}
}
assert!(bad.is_empty(), "{bad:#?}");
}
+22 -1
View File
@@ -154,6 +154,7 @@ message VectorData uint vectorNetworkBlob=1, Vector normalizedSize=2, NodeChange
message TextPathStart float tValue=1, bool forward=2
message ArcData float startingAngle=1, float endingAngle=2, float innerRadius=3
message OptionalVector Vector value=1
message Guide Axis axis=1, float offset=2, GUID guid=3
message LayoutGrid LayoutGridType type=1, Axis axis=2, bool visible=3, int numSections=4, float offset=5, float sectionSize=6, float gutterSize=7, Color color=8, LayoutGridPattern pattern=9, VariableData numSectionsVar=10, VariableData offsetVar=11, VariableData sectionSizeVar=12, VariableData gutterSizeVar=13
struct ExportConstraint ExportConstraintType type, float value
message ExportSettings string suffix=1, ImageType imageType=2, ExportConstraint constraint=3
@@ -191,7 +192,7 @@ message GridTrackSizingFunction GridTrackSizingType type=1, float value=2
message GridTrackSize GridTrackSizingFunction minSizing=1, GridTrackSizingFunction maxSizing=2
message GUIDGridTrackSizeMapEntry GUID id=1, GridTrackSize trackSize=2
message GUIDGridTrackSizeMap GUIDGridTrackSizeMapEntry[] entries=1
message NodeChange GUID guid=1, NodePhase phase=2, ParentIndex parentIndex=3, NodeType type=4, string name=5, bool visible=6, bool locked=7, float opacity=8, BlendMode blendMode=9, Vector size=11, Matrix transform=12, bool mask=16, MaskType maskType=317, float backgroundOpacity=19, bool backgroundEnabled=15, bool internalOnly=142, string description=318, StyleType styleType=163, string sortPosition=320, StyleId styleIdForFill=332, StyleId styleIdForStrokeFill=333, StyleId styleIdForText=334, StyleId styleIdForEffect=335, StyleId styleIdForGrid=336, VariableDataMap variableConsumptionMap=307, VariableModeBySetMap variableModeBySetMap=316, VariableSetMode[] variableSetModes=312, VariableSetID variableSetID=313, VariableResolvedDataType variableResolvedType=314, VariableDataValues variableDataValues=315, VariableScope[] variableScopes=353, DocumentColorProfile documentColorProfile=349, Paint[] fillPaints=38, Paint[] strokePaints=39, float strokeWeight=26, StrokeAlign strokeAlign=29, StrokeJoin strokeJoin=31, StrokeCap strokeCap=30, float[] dashPattern=13, float miterLimit=25, bool borderStrokeWeightsIndependent=299, float borderTopWeight=295, float borderRightWeight=298, float borderBottomWeight=296, float borderLeftWeight=297, Effect[] effects=43, float cornerRadius=20, float cornerSmoothing=160, bool rectangleCornerRadiiIndependent=149, float rectangleTopLeftCornerRadius=145, float rectangleTopRightCornerRadius=146, float rectangleBottomRightCornerRadius=148, float rectangleBottomLeftCornerRadius=147, ConstraintType horizontalConstraint=28, ConstraintType verticalConstraint=37, bool frameMaskDisabled=115, bool resizeToFit=117, bool isStateGroup=225, StateGroupPropertyValueOrder[] stateGroupPropertyValueOrders=238, bool sectionContentsHidden=283, Color backgroundColor=50, StackMode stackMode=105, float stackSpacing=107, float stackCounterSpacing=324, StackWrap stackWrap=323, StackCounterAlignContent stackCounterAlignContent=343, float stackHorizontalPadding=209, float stackVerticalPadding=210, float stackPaddingRight=233, float stackPaddingBottom=234, StackJustify stackPrimaryAlignItems=230, StackAlign stackCounterAlignItems=231, StackSize stackPrimarySizing=229, StackSize stackCounterSizing=221, bool bordersTakeSpace=294, bool stackReverseZIndex=271, float gridColumnGap=438, float gridRowGap=437, GUIDPositionMap gridColumns=436, GUIDPositionMap gridRows=435, GUIDGridTrackSizeMap gridColumnsSizing=474, GUIDGridTrackSizeMap gridRowsSizing=475, float stackChildPrimaryGrow=232, StackCounterAlign stackChildAlignSelf=236, StackPositioning stackPositioning=269, OptionalVector minSize=325, OptionalVector maxSize=326, GUID gridColumnAnchor=440, GUID gridRowAnchor=439, uint gridColumnSpan=442, uint gridRowSpan=441, LayoutGrid[] layoutGrids=47, ExportSettings[] exportSettings=45, TextData textData=42, FontName fontName=41, float fontSize=21, Number lineHeight=40, Number letterSpacing=165, TextCase textCase=34, TextDecoration textDecoration=35, TextAlignHorizontal textAlignHorizontal=32, TextAlignVertical textAlignVertical=33, TextAutoResize textAutoResize=46, TextTruncation textTruncation=280, int maxLines=351, float paragraphSpacing=23, float paragraphIndent=22, float listSpacing=264, LeadingTrim leadingTrim=322, bool hangingPunctuation=337, bool hangingList=339, Hyperlink hyperlink=223, bool autoRename=14, bool fontVariantCommonLigatures=127, bool fontVariantContextualLigatures=128, string fontVersion=202, uint textUserLayoutVersion=203, uint textExplicitLayoutVersion=396, uint textBidiVersion=279, float textTracking=27, bool textDecorationSkipInk=412, EmojiImageSet emojiImageSet=391, uint styleID=49, Path[] fillGeometry=51, Path[] strokeGeometry=52, VectorData vectorData=48, TextPathStart textPathStart=432, VectorMirror handleMirroring=44, uint count=10, float starInnerScale=24, ArcData arcData=195, BooleanOperation booleanOperation=36, string symbolDescription=144, VariableWidthPoint[] variableWidthPoints=447, PluginData[] pluginData=204, SymbolData symbolData=113, NodeChange[] derivedSymbolData=125, GUID overriddenSymbolID=143, ComponentPropDef[] componentPropDefs=266, ComponentPropRef[] componentPropRefs=267, ComponentPropAssignment[] componentPropAssignments=268, VariantPropSpec[] variantPropSpecs=483, VariableDataMap parameterConsumptionMap=445, GUIDPath guidPath=111, PrototypeInteraction[] prototypeInteractions=226, PrototypeStartingPoint prototypeStartingPoint=249, ScrollDirection scrollDirection=159, ScrollBehavior scrollBehavior=186, OverlayPositionType overlayPositionType=198, OverlayBackgroundInteraction overlayBackgroundInteraction=200, OverlayBackgroundAppearance overlayBackgroundAppearance=201, Color prototypeBackgroundColor=141
message NodeChange GUID guid=1, NodePhase phase=2, ParentIndex parentIndex=3, NodeType type=4, string name=5, bool visible=6, bool locked=7, float opacity=8, BlendMode blendMode=9, Vector size=11, Matrix transform=12, bool mask=16, MaskType maskType=317, float backgroundOpacity=19, bool backgroundEnabled=15, bool internalOnly=142, string description=318, StyleType styleType=163, string sortPosition=320, StyleId styleIdForFill=332, StyleId styleIdForStrokeFill=333, StyleId styleIdForText=334, StyleId styleIdForEffect=335, StyleId styleIdForGrid=336, VariableDataMap variableConsumptionMap=307, VariableModeBySetMap variableModeBySetMap=316, VariableSetMode[] variableSetModes=312, VariableSetID variableSetID=313, VariableResolvedDataType variableResolvedType=314, VariableDataValues variableDataValues=315, VariableScope[] variableScopes=353, DocumentColorProfile documentColorProfile=349, Paint[] fillPaints=38, Paint[] strokePaints=39, float strokeWeight=26, StrokeAlign strokeAlign=29, StrokeJoin strokeJoin=31, StrokeCap strokeCap=30, float[] dashPattern=13, float miterLimit=25, bool borderStrokeWeightsIndependent=299, float borderTopWeight=295, float borderRightWeight=298, float borderBottomWeight=296, float borderLeftWeight=297, Effect[] effects=43, float cornerRadius=20, float cornerSmoothing=160, bool rectangleCornerRadiiIndependent=149, float rectangleTopLeftCornerRadius=145, float rectangleTopRightCornerRadius=146, float rectangleBottomRightCornerRadius=148, float rectangleBottomLeftCornerRadius=147, ConstraintType horizontalConstraint=28, ConstraintType verticalConstraint=37, bool frameMaskDisabled=115, bool resizeToFit=117, bool isStateGroup=225, StateGroupPropertyValueOrder[] stateGroupPropertyValueOrders=238, bool sectionContentsHidden=283, Color backgroundColor=50, StackMode stackMode=105, float stackSpacing=107, float stackCounterSpacing=324, StackWrap stackWrap=323, StackCounterAlignContent stackCounterAlignContent=343, float stackHorizontalPadding=209, float stackVerticalPadding=210, float stackPaddingRight=233, float stackPaddingBottom=234, StackJustify stackPrimaryAlignItems=230, StackAlign stackCounterAlignItems=231, StackSize stackPrimarySizing=229, StackSize stackCounterSizing=221, bool bordersTakeSpace=294, bool stackReverseZIndex=271, float gridColumnGap=438, float gridRowGap=437, GUIDPositionMap gridColumns=436, GUIDPositionMap gridRows=435, GUIDGridTrackSizeMap gridColumnsSizing=474, GUIDGridTrackSizeMap gridRowsSizing=475, float stackChildPrimaryGrow=232, StackCounterAlign stackChildAlignSelf=236, StackPositioning stackPositioning=269, OptionalVector minSize=325, OptionalVector maxSize=326, GUID gridColumnAnchor=440, GUID gridRowAnchor=439, uint gridColumnSpan=442, uint gridRowSpan=441, LayoutGrid[] layoutGrids=47, ExportSettings[] exportSettings=45, TextData textData=42, FontName fontName=41, float fontSize=21, Number lineHeight=40, Number letterSpacing=165, TextCase textCase=34, TextDecoration textDecoration=35, TextAlignHorizontal textAlignHorizontal=32, TextAlignVertical textAlignVertical=33, TextAutoResize textAutoResize=46, TextTruncation textTruncation=280, int maxLines=351, float paragraphSpacing=23, float paragraphIndent=22, float listSpacing=264, LeadingTrim leadingTrim=322, bool hangingPunctuation=337, bool hangingList=339, Hyperlink hyperlink=223, bool autoRename=14, bool fontVariantCommonLigatures=127, bool fontVariantContextualLigatures=128, string fontVersion=202, uint textUserLayoutVersion=203, uint textExplicitLayoutVersion=396, uint textBidiVersion=279, float textTracking=27, bool textDecorationSkipInk=412, EmojiImageSet emojiImageSet=391, uint styleID=49, Path[] fillGeometry=51, Path[] strokeGeometry=52, VectorData vectorData=48, TextPathStart textPathStart=432, VectorMirror handleMirroring=44, uint count=10, float starInnerScale=24, ArcData arcData=195, BooleanOperation booleanOperation=36, string symbolDescription=144, VariableWidthPoint[] variableWidthPoints=447, PluginData[] pluginData=204, SymbolData symbolData=113, NodeChange[] derivedSymbolData=125, GUID overriddenSymbolID=143, ComponentPropDef[] componentPropDefs=266, ComponentPropRef[] componentPropRefs=267, ComponentPropAssignment[] componentPropAssignments=268, VariantPropSpec[] variantPropSpecs=483, VariableDataMap parameterConsumptionMap=445, GUIDPath guidPath=111, PrototypeInteraction[] prototypeInteractions=226, PrototypeStartingPoint prototypeStartingPoint=249, ScrollDirection scrollDirection=159, ScrollBehavior scrollBehavior=186, OverlayPositionType overlayPositionType=198, OverlayBackgroundInteraction overlayBackgroundInteraction=200, OverlayBackgroundAppearance overlayBackgroundAppearance=201, Color prototypeBackgroundColor=141, Guide[] guides=138
struct Blob byte[] bytes
message Message MessageType type=1, uint sessionID=2, NodeChange[] nodeChanges=4, Blob[] blobs=6
";
@@ -418,6 +419,8 @@ struct Exporter<'d> {
/// Grid tracks of written grid frames: (columns, rows) local ids (session [`AUX`]).
tracks: BTreeMap<NodeId, (Vec<u32>, Vec<u32>)>,
aux: u32,
/// Session of the last guide's GUID: guides count from the session after [`AUX`], one session each, local id 1.
guide_session: u32,
overlays: BTreeMap<NodeId, Overlay>,
trigger_size: [f64; 2],
/// Flow starting points: layer → (order, name).
@@ -458,6 +461,7 @@ impl<'d> Exporter<'d> {
child_defs: BTreeMap::new(),
tracks: BTreeMap::new(),
aux: 0,
guide_session: AUX,
overlays: BTreeMap::new(),
trigger_size: [0.0, 0.0],
starts: BTreeMap::new(),
@@ -475,6 +479,23 @@ impl<'d> Exporter<'d> {
}
}
/// A node's ruler `guides` field: Y is a horizontal guide and X a vertical one, the offset the ruler's reading (a
/// page's in page coordinates, a frame's in the frame's own).
fn guides(&mut self, guides: &[figcraft_doc::Guide], f: &mut Fields) {
// A guide whose offset isn't finite shows nowhere in the document: it is left out, not written at 0.
let list: Vec<Kv<'static>> = guides
.iter()
.filter(|g| g.offset.is_finite())
.map(|g| {
self.guide_session = self.guide_session.saturating_add(1);
o(vec![("axis", e(if g.vertical { "X" } else { "Y" })), ("offset", fl(g.offset)), ("guid", guid(self.guide_session, 1))])
})
.collect();
if !list.is_empty() {
f.push(("guides", arr(list)));
}
}
fn next_aux(&mut self) -> u32 {
self.aux += 1;
self.aux
+20 -4
View File
@@ -111,11 +111,22 @@ pub(super) fn scaled(a: &Kv<'static>, b: &Kv<'static>, k: f64, slack: f64) -> bo
}
}
/// A `guides` list without its guids. Every guide written has a guid of its own, so two layers' guides are the same
/// when their axes and offsets are.
fn bare_guides(v: &Kv<'static>) -> Vec<Kv<'static>> {
let bare = |g: &Kv<'static>| match g {
Kv::Object(f) => o(f.iter().filter(|(k, _)| *k != "guid").cloned().collect()),
other => other.clone(),
};
v.list().iter().map(bare).collect()
}
/// The fields of `mine` that differ from `theirs` (a layer and the main's layer it mirrors), and
/// the ones only `theirs` has at their empty values.
pub(super) fn changed(mine: Fields, theirs: &Fields) -> Fields {
let same = |k: &str, a: &Kv<'static>, b: &Kv<'static>| a == b || (k == "guides" && bare_guides(a) == bare_guides(b));
let cleared: Fields = theirs.iter().filter(|(k, _)| !mine.iter().any(|(mk, _)| mk == k)).filter_map(|(k, _)| Some((*k, unset(k)?))).collect();
let mut out: Fields = mine.into_iter().filter(|(k, v)| !theirs.iter().any(|(tk, tv)| tk == k && tv == v)).collect();
let mut out: Fields = mine.into_iter().filter(|(k, v)| !theirs.iter().any(|(tk, tv)| tk == k && same(k, tv, v))).collect();
out.extend(cleared);
out
}
@@ -181,9 +192,14 @@ fn unset(key: &str) -> Option<Kv<'static>> {
}
"variableConsumptionMap" | "variableModeBySetMap" | "gridColumnsSizing" | "gridRowsSizing" => o(vec![("entries", arr(Vec::new()))]),
"mask" | "rectangleCornerRadiiIndependent" | "borderStrokeWeightsIndependent" => b(false),
"effects" | "dashPattern" | "layoutGrids" | "exportSettings" | "prototypeInteractions" | "fillGeometry" | "variableWidthPoints" => {
arr(Vec::new())
}
"effects"
| "dashPattern"
| "layoutGrids"
| "exportSettings"
| "prototypeInteractions"
| "fillGeometry"
| "variableWidthPoints"
| "guides" => arr(Vec::new()),
"cornerSmoothing" | "stackChildPrimaryGrow" => fl(0.0),
"stackMode" => e("NONE"),
"stackChildAlignSelf" | "stackPositioning" => e("AUTO"),
+2 -6
View File
@@ -23,9 +23,7 @@ impl<'d> Exporter<'d> {
f.extend([("type", e("CANVAS")), ("name", s(&n.name))]);
f.extend(root_fields());
f.extend([("backgroundColor", color(*background)), ("backgroundOpacity", fl(background.a.into())), ("backgroundEnabled", b(true))]);
if !n.guides.is_empty() {
self.warn("ruler guides were left out");
}
self.guides(&n.guides, &mut f);
let defaults = figcraft_doc::proto::PrototypeSettings::default();
// Every page writes its colour, so Figma shows the same one (a page without the field shows Figma's own default).
// The colour is written opaque: the record measured has alpha 1, and the import reads the colour as opaque and
@@ -318,9 +316,7 @@ impl<'d> Exporter<'d> {
f.push(("variableConsumptionMap", o(vec![("entries", arr(bound.entries))])));
}
self.modes(n, f);
if !n.guides.is_empty() {
self.warn("ruler guides were left out");
}
self.guides(&n.guides, f);
if !n.annotations.is_empty()
|| !n.dev_resources.is_empty()
|| !n.code_links.is_empty()
+162
View File
@@ -0,0 +1,162 @@
//! Ruler guides in `.fig` exports: a page's and a frame's `guides`, as a synthetic file saved from
//! Figma's web app wrote them.
use std::collections::BTreeMap;
use figcraft_doc::{Document, Guide, NodeId, NodeKind};
use super::kiwi::Kv;
use super::{Archive, decode_canvas, export};
/// A document with a page guide at `page` and a frame guide at `frame` (both vertical and
/// horizontal), and the frame's id.
fn doc_with(page: &[Guide], frame: &[Guide]) -> (Document, NodeId) {
let mut doc = Document::new("t");
let p = doc.first_page().unwrap();
let f = doc.create(p, NodeKind::Frame, "Frame 1", 1000.0, 500.0, 400.0, 300.0).unwrap();
doc.node_mut(p).unwrap().guides = page.to_vec();
doc.node_mut(f).unwrap().guides = frame.to_vec();
(doc, f)
}
fn vertical(offset: f64) -> Guide {
Guide { vertical: true, offset }
}
fn horizontal(offset: f64) -> Guide {
Guide { vertical: false, offset }
}
/// The `guides` of the CANVAS record and of the FRAME record, as (axis, offset, sessionID, localID).
type Written = Option<Vec<(String, f32, u64, u64)>>;
fn written(doc: &Document) -> (Written, Written, Vec<String>) {
let (bytes, warnings) = export(doc, None).unwrap();
let archive = Archive::open(&bytes).unwrap();
let (schema, message) = decode_canvas(&archive.canvas).unwrap();
let msg = schema.decode_message(schema.find("Message").unwrap(), &message).unwrap();
let nodes = msg.get("nodeChanges").unwrap().list();
let of = |ty: &str| {
let n = nodes
.iter()
.find(|n| n.get("type").and_then(Kv::str) == Some(ty) && n.get("name").and_then(Kv::str) != Some("Internal Only Canvas"))
.unwrap();
n.get("guides").map(|g| {
g.list()
.iter()
.map(|x| {
let id = x.get("guid").unwrap();
(
x.get("axis").and_then(Kv::str).unwrap().to_string(),
x.get("offset").and_then(Kv::f64).unwrap() as f32,
id.get("sessionID").and_then(Kv::f64).unwrap() as u64,
id.get("localID").and_then(Kv::f64).unwrap() as u64,
)
})
.collect()
})
};
(of("CANVAS"), of("FRAME"), warnings)
}
/// A component with a vertical guide at 24 that holds a frame with a vertical guide at 7, and an instance of it as the
/// engine makes one: its root a copy of the main's, guides included, and its layer mirroring the main's. Returns the
/// instance.
fn component_and_instance() -> (Document, NodeId) {
let mut doc = Document::new("t");
let p = doc.first_page().unwrap();
let kind = NodeKind::Component { description: String::new(), props: BTreeMap::new(), prop_order: Vec::new() };
let main = doc.create(p, kind, "Card", 0.0, 0.0, 200.0, 100.0).unwrap();
let inner = doc.create(main, NodeKind::Frame, "Inner", 20.0, 30.0, 100.0, 50.0).unwrap();
doc.node_mut(main).unwrap().guides = vec![vertical(24.0)];
doc.node_mut(inner).unwrap().guides = vec![vertical(7.0)];
let inst = doc.alloc_id();
let mut root = doc.node(main).unwrap().clone();
(root.id, root.kind, root.parent, root.source) = (inst, NodeKind::Instance { component: main, props: BTreeMap::new() }, None, Some(main));
root.children.clear();
doc.insert(root, p, None).unwrap();
let mut layer = doc.node(inner).unwrap().clone();
(layer.id, layer.parent, layer.source) = (doc.alloc_id(), None, Some(inner));
doc.insert(layer, inst, None).unwrap();
(doc, inst)
}
/// The `guides` of every instance override row in the file, as (axis, offset).
fn overridden(doc: &Document) -> Vec<Vec<(String, f32)>> {
let (bytes, _) = export(doc, None).unwrap();
let archive = Archive::open(&bytes).unwrap();
let (schema, message) = decode_canvas(&archive.canvas).unwrap();
let msg = schema.decode_message(schema.find("Message").unwrap(), &message).unwrap();
let nodes = msg.get("nodeChanges").unwrap().list();
let rows = nodes.iter().flat_map(|n| n.get("symbolData").and_then(|d| d.get("symbolOverrides")).map(Kv::list).unwrap_or_default());
rows.filter_map(|row| row.get("guides"))
.map(|g| {
g.list()
.iter()
.map(|x| (x.get("axis").and_then(Kv::str).unwrap().to_string(), x.get("offset").and_then(Kv::f64).unwrap() as f32))
.collect()
})
.collect()
}
#[test]
fn a_page_guide_at_120_and_a_frame_guide_at_40_are_written_as_figma_writes_them() {
let (doc, _) = doc_with(&[horizontal(120.0), vertical(120.0)], &[horizontal(40.0), vertical(40.0)]);
let (page, frame, warnings) = written(&doc);
// Axis Y is a horizontal guide and X a vertical one; the offsets are the ruler readings (a frame's in its own
// coordinates); localID is 1 and sessionID counts the file's guides from 3.
assert_eq!(page, Some(vec![("Y".into(), 120.0, 3, 1), ("X".into(), 120.0, 4, 1)]));
assert_eq!(frame, Some(vec![("Y".into(), 40.0, 5, 1), ("X".into(), 40.0, 6, 1)]));
assert!(warnings.iter().all(|w| !w.contains("ruler guides")), "{warnings:?}");
}
#[test]
fn a_frame_without_guides_and_a_page_without_guides_write_no_field() {
let (doc, _) = doc_with(&[], &[]);
let (page, frame, warnings) = written(&doc);
assert_eq!(page, None);
assert_eq!(frame, None);
assert!(warnings.iter().all(|w| !w.contains("ruler guides")), "{warnings:?}");
}
#[test]
fn a_frame_guide_is_not_shifted_by_the_frames_position() {
let (doc, _) = doc_with(&[], &[vertical(78.0)]);
let (_, frame, _) = written(&doc);
assert_eq!(frame, Some(vec![("X".into(), 78.0, 3, 1)]));
}
#[test]
fn an_instance_overrides_guides_only_where_they_differ_from_its_mains() {
let (mut doc, inst) = component_and_instance();
// Untouched: the instance's guides and its layer's are the main's.
assert_eq!(overridden(&doc), Vec::<Vec<(String, f32)>>::new());
// Its own guide: one override, on the instance.
doc.node_mut(inst).unwrap().guides = vec![horizontal(60.0)];
assert_eq!(overridden(&doc), vec![vec![("Y".to_string(), 60.0)]]);
// Its guides removed: an empty list, or it would show the main's.
doc.node_mut(inst).unwrap().guides.clear();
assert_eq!(overridden(&doc), vec![Vec::new()]);
}
#[test]
fn a_guide_whose_offset_is_not_finite_is_left_out() {
let (doc, _) = doc_with(&[vertical(f64::NAN), vertical(10.0), horizontal(f64::INFINITY)], &[horizontal(f64::NEG_INFINITY)]);
let (page, frame, _) = written(&doc);
assert_eq!(page, Some(vec![("X".into(), 10.0, 3, 1)]));
assert_eq!(frame, None);
}
#[test]
fn the_schema_numbers_the_guides() {
let s = super::kiwi::Schema::parse(super::export::SCHEMA).unwrap();
let def = |n: &str| s.defs.iter().find(|d| d.name == n).unwrap();
let field = |d: &str, f: &str| def(d).fields.iter().find(|x| x.name == f).unwrap().value;
assert_eq!(field("NodeChange", "guides"), 138);
assert_eq!(field("Guide", "axis"), 1);
assert_eq!(field("Guide", "offset"), 2);
assert_eq!(field("Guide", "guid"), 3);
let axis = def("Axis");
assert_eq!(axis.fields.iter().find(|x| x.name == "X").unwrap().value, 0);
assert_eq!(axis.fields.iter().find(|x| x.name == "Y").unwrap().value, 1);
}
+3 -1
View File
@@ -47,6 +47,7 @@ pub use craft_figcraft_format::{
MAX_VERSION_INDEX, MAX_VERSION_NAME, MAX_VERSIONS, ReadBudget, VERSION, VersionEntry as NativeVersionEntry, VersionIndex as NativeVersionIndex,
clip, document_limit, is_valid_version_id,
};
#[cfg(test)]
const JSON_LEVEL: i64 = 3;
/// The export warning for colour calculations that resolve to nothing (an operand missing, or more
/// than 32 variables to read), shared by the Penpot and `.fig` exports.
@@ -411,7 +412,8 @@ pub(crate) fn io_err(e: impl std::fmt::Display) -> FormatError {
FormatError::Io(e.to_string())
}
/// JSON compression for Penpot and external ZIP exporters.
/// JSON compression for legacy Penpot test fixtures.
#[cfg(test)]
pub(crate) fn json_options() -> zip::write::SimpleFileOptions {
zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated).compression_level(Some(JSON_LEVEL))
}
+14 -22
View File
@@ -1,5 +1,5 @@
use std::collections::{BTreeMap, BTreeSet};
use std::io::{Cursor, Write};
use std::io::Cursor;
use figcraft_doc::color::{BlendMode, Color, Gradient, GradientKind, ImageScaleMode, Paint, PaintKind};
use figcraft_doc::geom::kurbo::PathEl;
@@ -13,7 +13,7 @@ use figcraft_doc::{
use serde_json::{Map, Value, json};
use super::{ROOT_ID, fingerprint, layout_fingerprint, strokes_fingerprint, text_fingerprint, tokens_fingerprint, uuid};
use crate::{FormatError, io_err, json_options};
use crate::{FormatError, io_err};
const DEFAULT_FEATURES: &[&str] = &["fdata/path-data", "design-tokens/v1", "variants/v1", "layout/grid", "components/v2", "fdata/shape-data-type"];
@@ -565,27 +565,19 @@ impl<'a> Exporter<'a> {
"files": [{"id": self.file_id, "name": name, "features": file.get("features").cloned().unwrap_or(Value::Null)}],
"relations": [],
});
let mut buf = Cursor::new(Vec::new());
{
let mut z = zip::ZipWriter::new(&mut buf);
let mut put = |path: &str, bytes: &[u8]| -> Result<(), FormatError> {
z.start_file(path, json_options()).map_err(io_err)?;
z.write_all(bytes).map_err(io_err)
};
put("manifest.json", &serde_json::to_vec_pretty(&manifest).map_err(io_err)?)?;
put(&format!("{base}.json"), &serde_json::to_vec_pretty(&file).map_err(io_err)?)?;
if let Some(tokens) = tokens {
put(&format!("{base}/tokens.json"), tokens.as_bytes())?;
}
for (path, value) in &entries {
put(path, &serde_json::to_vec_pretty(value).map_err(io_err)?)?;
}
for (path, bytes) in &blobs {
put(path, bytes)?;
}
z.finish().map_err(io_err)?;
let mut writer = craft_penpot::Writer::new();
writer.add("manifest.json", &serde_json::to_vec_pretty(&manifest).map_err(io_err)?).map_err(io_err)?;
writer.add(&format!("{base}.json"), &serde_json::to_vec_pretty(&file).map_err(io_err)?).map_err(io_err)?;
if let Some(tokens) = tokens {
writer.add(&format!("{base}/tokens.json"), tokens.as_bytes()).map_err(io_err)?;
}
Ok((buf.into_inner(), self.warnings))
for (path, value) in &entries {
writer.add(path, &serde_json::to_vec_pretty(value).map_err(io_err)?).map_err(io_err)?;
}
for (path, bytes) in &blobs {
writer.add(path, bytes).map_err(io_err)?;
}
Ok((writer.finish().map_err(io_err)?, self.warnings))
}
fn page_json(&self, page: NodeId, page_id: &str, index: usize, background: Color) -> Value {
+16
View File
@@ -1027,3 +1027,19 @@ fn stored_variable_ids_keep_penpot_token_identity() {
assert_eq!(width, &expected);
}
}
#[test]
fn shared_writer_keeps_manifest_first_and_deflated_members() {
let doc = Document::new("Shared container");
let (bytes, _) = export(&doc).unwrap();
let mut zip = zip::ZipArchive::new(Cursor::new(bytes.as_slice())).unwrap();
assert_eq!(zip.by_index(0).unwrap().name(), "manifest.json");
for index in 0..zip.len() {
assert_eq!(zip.by_index(index).unwrap().compression(), zip::CompressionMethod::Deflated);
}
let archive = craft_penpot::Archive::open(&bytes).unwrap();
assert_eq!(archive.files.len(), 1);
assert_eq!(archive.files[0].name.as_deref(), Some("Shared container"));
assert_eq!(archive.manifest["generatedBy"], format!("figcraft/{}", env!("CARGO_PKG_VERSION")));
assert!(import(&bytes).is_ok());
}
@@ -188,6 +188,62 @@ fn bound_variables_and_explicit_modes() {
assert!(has(&warnings, "pass the local variables JSON"), "{warnings:?}");
}
/// #2441: a variable bound to one or more stroke sides (`individualStrokeWeights`) binds that
/// side's weight. The live API names the sides `BORDER_TOP_WEIGHT` …, the published spec `top` …;
/// both are read, and neither is reported as skipped.
#[test]
fn variables_bound_to_stroke_sides_bind_each_sides_weight() {
const TOP: &str = "VariableID:9:1";
const RIGHT: &str = "VariableID:9:2";
const BOTTOM: &str = "VariableID:9:3";
const LEFT: &str = "VariableID:9:4";
let rect = |id: &str, name: &str, sides: Value| {
json!({"id": id, "name": name, "type": "RECTANGLE", "relativeTransform": at(0.0, 0.0), "size": {"x": 40, "y": 20},
"strokes": [{"type": "SOLID", "color": rgba(0.0, 0.0, 0.0)}], "strokeWeight": 1,
"individualStrokeWeights": {"top": 1, "right": 1, "bottom": 1, "left": 1},
"boundVariables": {"individualStrokeWeights": sides}})
};
let file = json!({"name": "Sides", "document": {"id": "0:0", "type": "DOCUMENT", "children": [
{"id": "0:1", "name": "Page", "type": "CANVAS", "children": [
rect("1:1", "Row", json!({"BORDER_BOTTOM_WEIGHT": alias(SPACE)})),
rect("1:2", "Card", json!({"BORDER_TOP_WEIGHT": alias(TOP), "BORDER_RIGHT_WEIGHT": alias(RIGHT),
"BORDER_BOTTOM_WEIGHT": alias(BOTTOM), "BORDER_LEFT_WEIGHT": alias(LEFT)})),
rect("1:3", "Spec", json!({"top": alias(TOP), "right": alias(RIGHT), "bottom": alias(BOTTOM), "left": alias(LEFT)})),
rect("1:4", "Colour", json!({"BORDER_LEFT_WEIGHT": alias(BRAND)}))
]}
]}});
// A variable of its own for each of Card's sides, so a side read into another's field fails.
let mut vars = variables_json();
for id in [TOP, RIGHT, BOTTOM, LEFT] {
vars["meta"]["variables"][id] = json!({"id": id, "name": id, "variableCollectionId": THEME, "resolvedType": "FLOAT",
"valuesByMode": {"1:0": 1}, "scopes": ["ALL_SCOPES"]});
}
let (doc, warnings) = import_with(&file, Some(&vars), &no_images).unwrap();
let sides = |name: &str| -> Vec<(String, String)> {
let n = named(&doc, name);
["strokeTopWeight", "strokeRightWeight", "strokeBottomWeight", "strokeLeftWeight"]
.iter()
.filter_map(|f| n.bound.get(*f).map(|v| (f.to_string(), v.clone())))
.collect()
};
let b = |f: &str| (f.to_string(), SPACE.to_string());
let on = |f: &str, v: &str| (f.to_string(), v.to_string());
assert_eq!(sides("Row"), [b("strokeBottomWeight")], "one side bound");
assert_eq!(
sides("Card"),
[on("strokeTopWeight", TOP), on("strokeRightWeight", RIGHT), on("strokeBottomWeight", BOTTOM), on("strokeLeftWeight", LEFT)]
);
assert_eq!(
sides("Spec"),
[on("strokeTopWeight", TOP), on("strokeRightWeight", RIGHT), on("strokeBottomWeight", BOTTOM), on("strokeLeftWeight", LEFT)],
"the spec's names"
);
assert_eq!(sides("Colour"), [], "a colour variable can't be a weight");
assert!(!has(&warnings, "`individualStrokeWeights`"), "{warnings:?}");
assert!(has(&warnings, "type doesn't fit"), "{warnings:?}");
assert!(doc.validate().is_empty(), "{:?}", doc.validate());
}
#[test]
fn embedded_variables_match_separate_ones() {
let mut embedded = file_json();
+13
View File
@@ -427,6 +427,19 @@ fn node_binding<'v>(k: &str, v: &'v Value, n: &Node, out: &mut Vec<(String, &'v
push(f, v.get(key).and_then(alias));
}
}
// Each stroke side's weight (#2441). The live `/nodes` response names the sides
// `BORDER_TOP_WEIGHT` and so on, as `rectangleCornerRadii` names its corners; Figma's
// published OpenAPI spec names them `top` … `left`. Either is read.
"individualStrokeWeights" => {
for (keys, f) in [
(["BORDER_TOP_WEIGHT", "top"], "strokeTopWeight"),
(["BORDER_RIGHT_WEIGHT", "right"], "strokeRightWeight"),
(["BORDER_BOTTOM_WEIGHT", "bottom"], "strokeBottomWeight"),
(["BORDER_LEFT_WEIGHT", "left"], "strokeLeftWeight"),
] {
push(f, keys.iter().find_map(|key| v.get(*key)).and_then(alias));
}
}
"fills" | "strokes" => {
let field = if k == "fills" { "fill" } else { "stroke" };
match v.as_array().and_then(|a| a.first()).and_then(alias) {
Loaded 100 of 195 files, more files were not shown because too many files have changed in this diff. Show more