mirror of
https://github.com/storytold/figcraft.git
synced 2026-11-29 01:34:37 +01:00
fix(dev): embed node-local vector assets
This commit is contained in:
1 parent
ab7c0e2225
commit
91de53c586
3 files changed
+54
-17
No files matched your search
@@ -577,6 +577,17 @@ mod tests {
|
||||
assert!(!css.contains("gradient"), "{css}");
|
||||
}
|
||||
|
||||
fn embedded_svgs(code: &str) -> Vec<String> {
|
||||
use base64::Engine as _;
|
||||
code.split("data:image/svg+xml;base64,")
|
||||
.skip(1)
|
||||
.map(|rest| {
|
||||
let b64 = rest.split('"').next().unwrap();
|
||||
String::from_utf8(base64::engine::general_purpose::STANDARD.decode(b64).unwrap()).unwrap()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vector_code_uses_its_svg_asset_not_a_box_border() {
|
||||
let mut s = Session::new();
|
||||
@@ -586,12 +597,16 @@ mod tests {
|
||||
s.doc_mut().unwrap().get_mut(check).unwrap().fills = vec![Paint::solid(Color::WHITE)];
|
||||
let doc = s.doc().unwrap();
|
||||
let html = code_for(doc, icon, CodeLang::Html);
|
||||
assert!(html.contains("<img class=\"check\" src=\"check.svg\" alt=\"check\" />"), "{html}");
|
||||
assert!(html.contains("<img class=\"check\" src=\"data:image/svg+xml;base64,"), "{html}");
|
||||
assert!(html.contains("alt=\"check\""), "{html}");
|
||||
assert!(!html.contains("border: 2px solid"), "{html}");
|
||||
assert!(!html.contains("background:"), "the vector's fill belongs to its SVG, not its box: {html}");
|
||||
let opaque = embedded_svgs(&html);
|
||||
assert_eq!(opaque.len(), 1, "{html}");
|
||||
assert!(opaque[0].contains("<path") && opaque[0].contains("#1F3A68"), "{:?}", opaque[0]);
|
||||
for lang in [CodeLang::React, CodeLang::Vue, CodeLang::Leptos, CodeLang::Tailwind] {
|
||||
let code = code_for(doc, icon, lang);
|
||||
assert!(code.contains("<img") && code.contains("src=\"check.svg\""), "{}: {code}", lang.id());
|
||||
assert!(code.contains("<img") && code.contains("src=\"data:image/svg+xml;base64,"), "{}: {code}", lang.id());
|
||||
assert!(!code.contains("border: 2px solid") && !code.contains("border-[2px]"), "{}: {code}", lang.id());
|
||||
}
|
||||
let css = code_for(doc, icon, CodeLang::Css);
|
||||
@@ -602,22 +617,29 @@ mod tests {
|
||||
let ark = code_for(doc, icon, CodeLang::ArkUi);
|
||||
assert!(!ark.contains(".border({"), "{ark}");
|
||||
|
||||
// CSS owns the node's rotation and opacity, so the embedded asset must not bake them in.
|
||||
s.doc_mut().unwrap().get_mut(check).unwrap().opacity = 0.5;
|
||||
s.doc_mut().unwrap().get_mut(check).unwrap().transform = figcraft_geom::Affine::rotate(30f64.to_radians());
|
||||
let transformed = code_for(s.doc().unwrap(), icon, CodeLang::Html);
|
||||
assert!(transformed.contains("opacity: 0.5;"), "{transformed}");
|
||||
assert!(transformed.contains("transform: rotate("), "{transformed}");
|
||||
assert_eq!(embedded_svgs(&transformed), opaque, "the asset stays node-local and opaque: {transformed}");
|
||||
|
||||
let rectangle =
|
||||
id_of(&s.execute("shape.rectangle", &json!({"parent": icon, "props": {"stroke": "#1F3A68", "strokeWeight": 2}})).unwrap()["id"]).unwrap();
|
||||
assert!(code_for(s.doc().unwrap(), rectangle, CodeLang::Css).contains("border: 2px solid"), "box strokes remain");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vector_asset_names_match_export_and_leptos_literals() {
|
||||
fn vector_assets_are_self_contained_and_leptos_literals_escape() {
|
||||
let mut s = Session::new();
|
||||
let icon = id_of(&s.execute("frame.create", &json!({"name": "Icons", "width": 24, "height": 24})).unwrap()["id"]).unwrap();
|
||||
for name in ["Check Icon", "Check Icon", r"icon\q"] {
|
||||
for name in ["Check Icon", "Check Icon", r"icon\q", "check#dark"] {
|
||||
s.execute("vector.create", &json!({"path": "M4 12 L10 18 L20 6", "parent": icon, "name": name, "props": {"fill": "none"}})).unwrap();
|
||||
}
|
||||
let html = code_for(s.doc().unwrap(), icon, CodeLang::Html);
|
||||
assert!(html.contains("src=\"Check Icon.svg\""), "{html}");
|
||||
assert!(html.contains("src=\"Check Icon 2.svg\""), "{html}");
|
||||
assert!(!html.contains("check-icon.svg"), "{html}");
|
||||
assert_eq!(embedded_svgs(&html).len(), 4, "nested vectors need no separate filesystem export: {html}");
|
||||
assert!(!html.contains("src=\"check#dark.svg\""), "{html}");
|
||||
let leptos = code_for(s.doc().unwrap(), icon, CodeLang::Leptos);
|
||||
assert!(leptos.contains("alt=\"icon\\\\q\""), "{leptos}");
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
use base64::Engine as _;
|
||||
|
||||
use super::css::{Tokens, css_decls};
|
||||
use super::{CodeLang, Ctx, Document, LayoutMode, Node, NodeId, NodeKind, Param, Sizing, indent, num, with_v_if};
|
||||
|
||||
@@ -90,6 +92,18 @@ fn attr_escape(s: &str) -> String {
|
||||
s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """).replace(['\n', '\r'], " ")
|
||||
}
|
||||
|
||||
/// A vector as a self-contained SVG asset. CSS owns the node's placement and opacity, so the
|
||||
/// embedded geometry is node-local and fully opaque. No filesystem export or URL escaping is
|
||||
/// needed, and nested vectors work exactly like top-level ones.
|
||||
fn vector_data_uri(doc: &mut Document, n: &Node) -> Option<String> {
|
||||
let node = doc.get_mut(n.id).ok()?;
|
||||
node.parent = None;
|
||||
node.transform = figcraft_geom::Affine::IDENTITY;
|
||||
node.opacity = 1.0;
|
||||
let svg = figcraft_svg::export_svg(doc, &[n.id], &Default::default())?;
|
||||
Some(format!("data:image/svg+xml;base64,{}", base64::engine::general_purpose::STANDARD.encode(svg)))
|
||||
}
|
||||
|
||||
/// Text as JSX children: HTML escapes, braces as expressions, line breaks as `<br />`.
|
||||
fn jsx_text(s: &str) -> String {
|
||||
let mut out = String::new();
|
||||
@@ -152,8 +166,8 @@ pub(crate) struct Markup<'c, 'a> {
|
||||
/// With `fluid`, other layers at least this share of the root's width are fluid too (a
|
||||
/// divider, a banner image); smaller ones (icons) keep their size. Default: none.
|
||||
pub fluid_leaves: f64,
|
||||
/// SVG asset names, resolved by the same policy as the filesystem exporter.
|
||||
asset_names: crate::cmd::file::ExportNames,
|
||||
/// Lazily cloned once for node-local SVG assets, not once per vector.
|
||||
asset_doc: Option<Document>,
|
||||
}
|
||||
|
||||
/// How `n` sits in its parent: in the flex flow, or placed at its position.
|
||||
@@ -199,7 +213,7 @@ impl<'c, 'a> Markup<'c, 'a> {
|
||||
inline: false,
|
||||
fluid: false,
|
||||
fluid_leaves: f64::INFINITY,
|
||||
asset_names: Default::default(),
|
||||
asset_doc: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -348,13 +362,14 @@ impl<'c, 'a> Markup<'c, 'a> {
|
||||
let open = |tag: &str| format!("{pad}<{tag} {attr}=\"{class}\"{attrs}>");
|
||||
match &n.kind {
|
||||
NodeKind::Vector { .. } => {
|
||||
// The exported SVG carries the path and its stroke; the class only places it.
|
||||
let src = self.asset_names.push(&n.name);
|
||||
// Leptos attributes are Rust string literals; the other targets use HTML escaping.
|
||||
let quote = |value: &str| if self.lang == CodeLang::Leptos { format!("{value:?}") } else { format!("\"{}\"", attr_escape(value)) };
|
||||
let src = quote(&format!("{src}.svg"));
|
||||
let root_doc = self.ctx.doc;
|
||||
let src = vector_data_uri(self.asset_doc.get_or_insert_with(|| root_doc.clone()), n)
|
||||
.map(|uri| format!(" src={}", quote(&uri)))
|
||||
.unwrap_or_default();
|
||||
let alt = quote(&n.name);
|
||||
self.markup.push_str(&format!("{pad}<img {attr}=\"{class}\" src={src} alt={alt}{attrs} />\n"));
|
||||
self.markup.push_str(&format!("{pad}<img {attr}=\"{class}\"{src} alt={alt}{attrs} />\n"));
|
||||
}
|
||||
NodeKind::Text(t) => {
|
||||
let body = self.text_body(n, t);
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
> **Last reviewed:** 2026-10-24 · **Last updated:** 2026-11-12 · **Change:** patch (SwiftUI, Compose and Flutter code write every visible colour and gradient fill of a frame, group, rectangle or ellipse in paint order, gradients as gradients, instead of one colour per layer (chained `.background` in SwiftUI, chained `Modifier.background` in Compose, a `DecoratedBox` for each fill under the top one in Flutter); CSS code export writes several fills as one layered `background`, top first, as the incumbent does (#2271): a solid above another fill becomes a one-colour gradient, the bottom solid stays a plain colour, Tailwind gets one `[background:...]` class; the Annotation tool (Shift+T, `tool.annotation {id?}`): with a layer selected (or an `id`) it asks the UI for that layer's note at once, and in the tool a press on a layer selects it and asks for its note, a press on empty canvas does nothing; the Inspect tab then opens (never toggles away) with the caret in that layer's new-note field, and the engine never writes the note itself (#1840); the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; class names transliterate non-ASCII layer names (#1235); measurements kept on the canvas; a read-only layers panel in Dev Mode; earlier: import lines in generated layer trees; compare with any saved version; Dev Mode behaviour suite: an inspect-only canvas, Changed in the ready list, statuses only on frames and sections; plugin panels from the Inspect tab) · **Target:** Figma Design Dev Mode (desktop app 126.10.7)
|
||||
>
|
||||
> **2026-11-24 patch:** vector code export uses the SVG asset instead of inventing a box around its bounds: web markup references the SVG, and CSS, SwiftUI and ArkUI no longer draw a rectangle from the path stroke (#2270).
|
||||
> **2026-11-24 patch:** vector code export uses a self-contained SVG asset instead of inventing a box around its bounds: web markup embeds the node-local SVG as a data URI, and CSS, SwiftUI and ArkUI no longer draw a rectangle from the path stroke (#2270).
|
||||
|
||||
**Breadth ~98%, ready ~78% (estimated).** The inspect surface is broad, components connect
|
||||
to the code components of a repository (with their imports, also inside generated layer trees),
|
||||
@@ -12,7 +12,7 @@ repository, third-party integrations. Remaining: 1–2 h.
|
||||
|
||||
| Feature | Status | Notes |
|
||||
|---|---|---|
|
||||
| 2026-11-24 | patch | Vector code export drew a path's stroke as a box border around its bounds (#2270). CSS, HTML, React, Vue, Leptos and Tailwind no longer invent that border; the markup targets write an `<img>` reference to the vector's SVG asset. SwiftUI and ArkUI no longer put a rectangle stroke around their vector image either. Ordinary box and ellipse strokes are unchanged. Test: `dev::codegen::tests::vector_code_uses_its_svg_asset_not_a_box_border`; real CLI exports the referenced SVG with the stroked path |
|
||||
| 2026-11-24 | patch | Vector code export drew a path's stroke as a box border around its bounds (#2270). CSS, HTML, React, Vue, Leptos and Tailwind no longer invent that border or a rectangular fill; the markup targets embed node-local SVG data URIs, so nested vectors need no external export and URL fragments cannot break them. CSS alone applies node rotation and opacity. SwiftUI and ArkUI no longer put a rectangle stroke around their vector image either. Ordinary box and ellipse strokes are unchanged. Tests: `dev::codegen::tests::vector_code_uses_its_svg_asset_not_a_box_border`, `dev::codegen::tests::vector_assets_are_self_contained_and_leptos_literals_escape`; real CLI decodes four nested SVGs and checks rotation/opacity |
|
||||
| 2026-11-12 | patch | SwiftUI, Compose and Flutter code export kept one colour per layer (the bottom visible solid, or a gradient's first stop) and dropped every other fill (#2271). Now each writes every visible solid and gradient fill of a frame, group, rectangle or ellipse, in paint order, and a gradient as a gradient. SwiftUI chains `.background(...)` with the top fill first, since each one goes behind the ones before it (a rectangle or ellipse fills with the bottom paint and lays a copy of the shape over it for each paint above). Compose chains `Modifier.background(...)` with the bottom fill first, since each one draws over the ones before it (a linear gradient snaps to eight directions, radial and angular ones sit at the box's centre). Flutter keeps the top fill in the `Container` and wraps each fill under it in a `DecoratedBox`, the bottom fill outermost and the drop shadow on the outermost box. A layer with one solid fill gives the same code as before; a lone gradient is now a gradient, not its first stop's colour. Still not written: image and pattern fills in the native targets, ArkUI (one background and one gradient per component, so a stack needs extra nodes) and text with several fills. The incumbent's iOS and Android output wasn't measured: the order follows how each platform paints. Percentages and hours unchanged |
|
||||
| 2026-11-07 | patch | Naming: the handoff mode is called Developer Mode in the interface, its shortcut row, its toasts, the control channel's refusal, the board refusal, the measurement parameter doc, the `.fig` export note, the CLI help and every catalog (24 languages, translations awaiting native review), since Figma holds a US registration for Dev Mode (7574348); command ids (`view.devMode`, `devMode.*`), preference keys and saved-document fields are unchanged, and the Actions palette still finds the command by the old name |
|
||||
| Dev Mode toggle (Shift+D), Inspect panel | done | the canvas only inspects: presses select, pan and comment but never move, resize, draw or edit text and vectors; menus and shortcuts refuse design edits with a note (Dev Mode's annotations, statuses, dev resources, measurements, code connections and comments still work); a drawing tool chosen in the toolbar goes back to the design. The layers panel only selects and expands (no renaming, reordering, hiding or locking; a double click says why), and the Pages list only opens pages (no adding, renaming, reordering, duplicating or deleting). Files dropped on the canvas aren't imported (a dropped document still opens as a file of its own), and the Assets panel places, swaps and applies nothing, doesn't change Hide when publishing, and doesn't accept library updates or add, remove or swap libraries; each says why |
|
||||
@@ -33,7 +33,7 @@ repository, third-party integrations. Remaining: 1–2 h.
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-24 | patch | Vector code export writes the SVG asset, not a rectangle made from the path's stroke (#2270). Percentages and hours unchanged. |
|
||||
| 2026-11-24 | patch | Vector code export embeds a self-contained SVG asset, not a rectangle made from the path's stroke (#2270). Percentages and hours unchanged. |
|
||||
| 2026-11-13 | patch | Rows that recent merges had duplicated or garbled are merged back into one row each (no behaviour change): Code: CSS, iOS (SwiftUI), Android (Compose), Flutter. |
|
||||
| 2026-11-12 | patch | CSS code export (#2271): a layer with several fills wrote one `background` per fill, so only the last survived. It now writes one `background` with every visible fill as a layer, top fill first, comma-separated: a solid above another fill is `linear-gradient(0deg, c, c)` (CSS allows a plain colour only as the last layer), the bottom solid stays a plain colour (with its variable), images and patterns keep their `url(...)` layers. Tailwind output carries the layered value as one `[background:...]` class. Text keeps one `color` per fill. Native targets unchanged. Percentages and hours unchanged |
|
||||
| 2026-11-09 | patch | The Annotation tool (Shift+T, `tool.annotation {id?}`): selects the layer pressed on (or the selection, or `id`) and asks the UI for its note, which the Inspect tab takes in its new-note field; the engine writes nothing itself, and Developer Mode lets the tool through its gates (#1840). Figma's placement, cursor and whether the tool stays selected are unmeasured (Developer Mode is paywalled in the web app); staying selected until V or Escape, like the Comment tool, is inferred, and there is no toolbar button or icon yet |
|
||||
|
||||
Reference in new issue
Block a user