Skip to content

DesignCraft: An open-source page and layout design editor written by scratch in pure Rust

Merge PR #973

Brandon Thomasee498ac68f26
diff --cc ROADMAP.md
index 6a412a42f,bfb80c482..8b51f9f00
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@@ -135,14 -132,7 +135,15 @@@ list) · [roadmap.md](docs/roadmap.md)
Newest first.
+- **2026-10-14** · The Type tool draws a new text frame over a locked empty frame, as InDesign does, instead of turning the locked frame into a text frame. No readiness percentage change.
+- **2026-10-14** · 100% black shows as pure black on screen by default, as InDesign's Appearance of Black does out of the box (Display All Blacks as Rich Black); Preferences › Appearance of Black › Display All Blacks Accurately still shows it as the dark grey it prints, and a saved choice is kept. No readiness percentage change.
+- **2026-10-14** · Pathfinder keeps the frontmost object, as InDesign does: a photo placed over shapes and intersected with them shows through the shapes (it was dropped, and the shapes kept their black fill); Add, Exclude Overlap and Minus Back take the front object's fill too, Subtract still keeps the back one. No readiness percentage change.
+- **2026-10-14** · The Color panel's Tint field keeps what is typed while it has focus and applies it on Enter or when it loses focus, clamped to 0–100 %. Typing 60 over 100 % no longer snaps back to 100 after the first digit (10060), and a typed tint is no longer ignored. No readiness percentage change.
+- **2026-10-15** · IDML: ruler guides import and export (they were dropped). Each page's guides come in measured from the document's ruler origin (spread, page or spine), with Fit to Page, Locked and their layer, parent pages' included, and go out again under their pages. No readiness percentage change.
+- **2026-10-15** · Find Font no longer reports a style missing when it differs from the installed one only in spacing or case (InDesign files can name `Regular ` with a trailing space); the text was already drawn in the right face. No readiness percentage change.
+- **2026-10-15** · A line of text is set when its baseline fits in the frame, as in InDesign: descenders may hang below the frame's bottom. A frame sized to the cap height of a big heading (103 pt in a 2.77 cm frame, as Zero2Graphic's magazine tutorial draws them) no longer oversets. No readiness percentage change.
+- **2026-10-15** · A story that ends with a return is no longer overset when only its empty last paragraph doesn't fit, as in InDesign (Preflight said "Overset text: 0 characters" for a caption InDesign shows with no errors). No readiness percentage change.
+ - **2026-10-15** · Flex Layout (InDesign 2026): Object › Flex Layout (Add to, Convert to, Remove) and a Flex Layout panel laid out as InDesign's, also in Properties. A container lays out its objects by direction, wrap, justification, the alignment grid, Fixed/Auto width and height, padding and spacing, after every edit; Add detects aligned objects (direction, Auto size, Space Between at their spacing); resizing a container reflows its objects instead of scaling them; dragging an object in one reorders it. Montilla Design's tutorial replays step for step. No readiness percentage change.
- **2026-10-13** · Object › Fitting has InDesign's shortcuts: Fill Frame Proportionally ⌘⌥⇧C, Fit Content Proportionally ⌘⌥⇧E, Fit Frame to Content ⌘⌥C, Fit Content to Frame ⌘⌥E, Center Content ⌘⇧E. No readiness percentage change.
- **2026-10-13** · Gradients between process colours blend as inks, as InDesign shows them: magenta to cyan passes through C 50 M 50 (a light lilac) on screen instead of the darker RGB mix, and a midpoint between CMYK or grey stops no longer turns the PDF shading RGB. No readiness percentage change.
- **2026-10-14** · The Swatches panel has InDesign's header: a Fill/Stroke proxy, Formatting Affects Container/Text and the Tint of the colour in front (a tint alone keeps each object's own swatch). Clicking a swatch applies it to the fill or stroke in front (of the text, when formatting affects text), and the bottom row has New Color Group, New Swatch and Delete Swatch. No readiness percentage change.
diff --cc crates/ui-egui/src/i18n.rs
index 68ee69351,cc171865c..5da8baff6
--- a/crates/ui-egui/src/i18n.rs
+++ b/crates/ui-egui/src/i18n.rs
@@@ -57,23 -55,75 +57,92 @@@ const TABLE: &[(&str, [&str; 5])] = &
("Cut", ["Ausschneiden", "Couper", "Cortar", "カット", "剪切"]),
("Copy", ["Kopieren", "Copier", "Copiar", "コピー", "复制"]),
("Paste", ["Einfügen", "Coller", "Pegar", "ペースト", "粘贴"]),
+ (
+ "Bulleted & Numbered Lists",
+ [
+ "Aufzählungszeichen und nummerierte Listen",
+ "Listes à puces et numérotées",
+ "Listas con viñetas y numeradas",
+ "箇条書き",
+ "项目符号列表和编号列表",
+ ],
+ ),
+ ("Current Page Number", ["Aktuelle Seitenzahl", "Numéro de page actuelle", "Número de página actual", "現在のページ番号", "当前页码"]),
+ ("Apply Color (,)", ["Farbe anwenden (,)", "Appliquer la couleur (,)", "Aplicar color (,)", "カラーを適用 (,)", "应用颜色 (,)"]),
+ ("Apply Gradient (.)", ["Verlauf anwenden (.)", "Appliquer le dégradé (.)", "Aplicar degradado (.)", "グラデーションを適用 (.)", "应用渐变 (.)"]),
+ ("View Options", ["Ansichtsoptionen", "Options d’affichage", "Opciones de visualización", "表示オプション", "视图选项"]),
+ ("Frame Edges", ["Rahmenkanten", "Bords du bloc", "Bordes del marco", "フレーム枠", "框架边缘"]),
+ ("Rulers", ["Lineale", "Règles", "Reglas", "定規", "标尺"]),
+ ("Hidden Characters", ["Verborgene Zeichen", "Caractères masqués", "Caracteres ocultos", "制御文字", "隐藏字符"]),
+ ("Flex Layout", ["Flex-Layout", "Mise en page flexible", "Diseño flexible", "フレックスレイアウト", "弹性布局"]),
+ (
+ "Create Flex Layout",
+ ["Flex-Layout erstellen", "Créer une mise en page flexible", "Crear diseño flexible", "フレックスレイアウトを作成", "创建弹性布局"],
+ ),
+ (
+ "Add to Flex Layout",
+ [
+ "Zu Flex-Layout hinzufügen",
+ "Ajouter à la mise en page flexible",
+ "Añadir a diseño flexible",
+ "フレックスレイアウトに追加",
+ "添加到弹性布局",
+ ],
+ ),
+ (
+ "Convert to Flex Layout",
+ [
+ "In Flex-Layout umwandeln",
+ "Convertir en mise en page flexible",
+ "Convertir en diseño flexible",
+ "フレックスレイアウトに変換",
+ "转换为弹性布局",
+ ],
+ ),
+ (
+ "Remove Flex Layout",
+ ["Flex-Layout entfernen", "Supprimer la mise en page flexible", "Quitar diseño flexible", "フレックスレイアウトを削除", "移除弹性布局"],
+ ),
+ (
+ "Show Flex Controls",
+ [
+ "Flex-Steuerelemente einblenden",
+ "Afficher les commandes flexibles",
+ "Mostrar controles flexibles",
+ "フレックスコントロールを表示",
+ "显示弹性控件",
+ ],
+ ),
+ (
+ "Flex Layout Options",
+ ["Flex-Layout-Optionen", "Options de mise en page flexible", "Opciones de diseño flexible", "フレックスレイアウトオプション", "弹性布局选项"],
+ ),
+ (
+ "Reorder in Flex Layout",
+ [
+ "Im Flex-Layout umordnen",
+ "Réorganiser dans la mise en page flexible",
+ "Reordenar en diseño flexible",
+ "フレックスレイアウト内で並べ替え",
+ "在弹性布局中重新排序",
+ ],
+ ),
+ ("Flex Start", ["Flex-Anfang", "Début flexible", "Inicio flexible", "フレックス開始", "弹性起点"]),
+ ("Flex End", ["Flex-Ende", "Fin flexible", "Fin flexible", "フレックス終了", "弹性终点"]),
+ ("Space Between", ["Abstand dazwischen", "Espace entre", "Espacio entre", "間隔を均等", "两端对齐"]),
+ ("Space Around", ["Abstand ringsum", "Espace autour", "Espacio alrededor", "周囲に間隔", "周围间距"]),
+ ("Space Evenly", ["Gleichmäßig verteilen", "Espace uniforme", "Espacio uniforme", "均等に配置", "均匀分布"]),
+ ("Row", ["Zeile", "Ligne", "Fila", "行", "行"]),
+ ("Reverse Row", ["Zeile umgekehrt", "Ligne inversée", "Fila invertida", "行(逆方向)", "反向行"]),
+ ("Reverse Column", ["Spalte umgekehrt", "Colonne inversée", "Columna invertida", "列(逆方向)", "反向列"]),
+ ("Wrap Content", ["Inhalt umbrechen", "Renvoyer le contenu à la ligne", "Ajustar contenido", "コンテンツを折り返す", "内容换行"]),
+ ("Spacing", ["Abstände", "Espacement", "Espaciado", "間隔", "间距"]),
+ ("Horizontal Spacing", ["Horizontaler Abstand", "Espacement horizontal", "Espaciado horizontal", "水平方向の間隔", "水平间距"]),
+ ("Vertical Spacing", ["Vertikaler Abstand", "Espacement vertical", "Espaciado vertical", "垂直方向の間隔", "垂直间距"]),
+ ("Constrain proportions", ["Proportionen beibehalten", "Conserver les proportions", "Restringir proporciones", "縦横比を固定", "约束比例"]),
+ ("Auto", ["Automatisch", "Automatique", "Automático", "自動", "自动"]),
+ ("W:", ["B:", "L :", "An.:", "幅:", "宽:"]),
+ ("H:", ["H:", "H :", "Al.:", "高さ:", "高:"]),
("Reverse Path", ["Pfadrichtung umkehren", "Inverser le tracé", "Invertir trazado", "パスの方向反転", "反转路径"]),
("Set Anchor", ["Ankerpunkt festlegen", "Définir le point d’ancrage", "Definir punto de ancla", "アンカーポイントを設定", "设置锚点"]),
("Clear", ["Löschen", "Effacer", "Borrar", "消去", "清除"]),
diff --cc crates/ui-egui/src/i18n/ar.rs
index 66e70faf6,a1c5824db..4eb68ef5c
--- a/crates/ui-egui/src/i18n/ar.rs
+++ b/crates/ui-egui/src/i18n/ar.rs
@@@ -30,13 -30,28 +30,35 @@@ pub(super) const TABLE: &[(&str, &str)
("Cut", "قص"),
("Copy", "نسخ"),
("Paste", "لصق"),
+ ("Bulleted & Numbered Lists", "القوائم ذات التعداد النقطي والرقمي"),
+ ("Current Page Number", "رقم الصفحة الحالية"),
+ ("Apply Color (,)", "تطبيق اللون (,)"),
+ ("Apply Gradient (.)", "تطبيق التدرج (.)"),
+ ("View Options", "خيارات العرض"),
+ ("Frame Edges", "حواف الإطار"),
+ ("Hidden Characters", "الأحرف المخفية"),
+ ("Create Flex Layout", "إنشاء تخطيط مرن"),
+ ("Add to Flex Layout", "إضافة إلى التخطيط المرن"),
+ ("Convert to Flex Layout", "تحويل إلى تخطيط مرن"),
+ ("Remove Flex Layout", "إزالة التخطيط المرن"),
+ ("Show Flex Controls", "إظهار عناصر التحكم المرنة"),
+ ("Flex Layout Options", "خيارات التخطيط المرن"),
+ ("Reorder in Flex Layout", "إعادة الترتيب في التخطيط المرن"),
+ ("Flex Start", "بداية مرنة"),
+ ("Flex End", "نهاية مرنة"),
+ ("Space Between", "مسافة بينية"),
+ ("Space Around", "مسافة حول"),
+ ("Space Evenly", "توزيع متساوٍ"),
+ ("Reverse Row", "صف معكوس"),
+ ("Reverse Column", "عمود معكوس"),
+ ("Wrap Content", "التفاف المحتوى"),
+ ("Spacing", "التباعد"),
+ ("Horizontal Spacing", "التباعد الأفقي"),
+ ("Vertical Spacing", "التباعد الرأسي"),
+ ("Constrain proportions", "تقييد النسب"),
+ ("Auto", "تلقائي"),
+ ("W:", "ع:"),
+ ("H:", "ا:"),
("Reverse Path", "عكس المسار"),
("Set Anchor", "تعيين نقطة الارتساء"),
("Clear", "مسح"),
diff --cc crates/ui-egui/src/i18n/it.rs
index 440d64fce,bf2783769..67bdb8f0f
--- a/crates/ui-egui/src/i18n/it.rs
+++ b/crates/ui-egui/src/i18n/it.rs
@@@ -28,13 -28,28 +28,35 @@@ pub(super) const TABLE: &[(&str, &str)
("Cut", "Taglia"),
("Copy", "Copia"),
("Paste", "Incolla"),
+ ("Bulleted & Numbered Lists", "Elenchi puntati e numerati"),
+ ("Current Page Number", "Numero di pagina corrente"),
+ ("Apply Color (,)", "Applica colore (,)"),
+ ("Apply Gradient (.)", "Applica sfumatura (.)"),
+ ("View Options", "Opzioni di visualizzazione"),
+ ("Frame Edges", "Bordi cornice"),
+ ("Hidden Characters", "Caratteri nascosti"),
+ ("Create Flex Layout", "Crea Layout Flex"),
+ ("Add to Flex Layout", "Aggiungi a Layout Flex"),
+ ("Convert to Flex Layout", "Converti in Layout Flex"),
+ ("Remove Flex Layout", "Rimuovi Layout Flex"),
+ ("Show Flex Controls", "Mostra controlli Flex"),
+ ("Flex Layout Options", "Opzioni Layout Flex"),
+ ("Reorder in Flex Layout", "Riordina nel Layout Flex"),
+ ("Flex Start", "Inizio Flex"),
+ ("Flex End", "Estremità Flex"),
+ ("Space Between", "Spazio tra"),
+ ("Space Around", "Spazio intorno"),
+ ("Space Evenly", "Disponi lo spazio in modo uniforme"),
+ ("Reverse Row", "Riga inversa"),
+ ("Reverse Column", "Colonna inversa"),
+ ("Wrap Content", "Disponi testo"),
+ ("Spacing", "Spaziatura"),
+ ("Horizontal Spacing", "Spaziatura orizzontale"),
+ ("Vertical Spacing", "Spaziatura verticale"),
+ ("Constrain proportions", "Vincola proporzioni"),
+ ("Auto", "Automatico"),
+ ("W:", "L:"),
+ ("H:", "A:"),
("Reverse Path", "Inverti tracciato"),
("Set Anchor", "Imposta ancoraggio"),
("Clear", "Cancella"),
diff --cc crates/ui-egui/src/i18n/ja.rs
index 9cb7a9370,d422b45a7..e97852d4f
--- a/crates/ui-egui/src/i18n/ja.rs
+++ b/crates/ui-egui/src/i18n/ja.rs
@@@ -30,12 -30,28 +30,34 @@@ pub(super) const TABLE: &[(&str, &str)
("Cut", "カット"),
("Copy", "コピー"),
("Paste", "ペースト"),
+ ("Bulleted & Numbered Lists", "箇条書き"),
+ ("Apply Color (,)", "カラーを適用 (,)"),
+ ("Apply Gradient (.)", "グラデーションを適用 (.)"),
+ ("View Options", "表示オプション"),
+ ("Frame Edges", "フレーム枠"),
+ ("Hidden Characters", "制御文字"),
+ ("Create Flex Layout", "フレックスレイアウトを作成"),
+ ("Add to Flex Layout", "フレックスレイアウトに追加"),
+ ("Convert to Flex Layout", "フレックスレイアウトに変換"),
+ ("Remove Flex Layout", "フレックスレイアウトを削除"),
+ ("Show Flex Controls", "フレックスコントロールを表示"),
+ ("Flex Layout Options", "フレックスレイアウトオプション"),
+ ("Reorder in Flex Layout", "フレックスレイアウト内で並べ替え"),
+ ("Flex Start", "フレックス開始"),
+ ("Flex End", "フレックス終了"),
+ ("Space Between", "間隔を均等"),
+ ("Space Around", "周囲に間隔"),
+ ("Space Evenly", "均等に配置"),
+ ("Reverse Row", "行(逆方向)"),
+ ("Reverse Column", "列(逆方向)"),
+ ("Wrap Content", "コンテンツを折り返す"),
+ ("Spacing", "間隔"),
+ ("Horizontal Spacing", "水平方向の間隔"),
+ ("Vertical Spacing", "垂直方向の間隔"),
+ ("Constrain proportions", "縦横比を固定"),
+ ("Auto", "自動"),
+ ("W:", "幅:"),
+ ("H:", "高さ:"),
("Reverse Path", "パスの方向反転"),
("Set Anchor", "アンカーポイントを設定"),
("Clear", "消去"),
diff --cc crates/ui-egui/src/i18n/pt_br.rs
index 085b2add5,625863e4d..52d5f14e8
--- a/crates/ui-egui/src/i18n/pt_br.rs
+++ b/crates/ui-egui/src/i18n/pt_br.rs
@@@ -31,16 -31,28 +31,38 @@@ pub(super) const TABLE: &[(&str, &str)
("Cut", "Recortar"),
("Copy", "Copiar"),
("Paste", "Colar"),
+ ("Bulleted & Numbered Lists", "Listas com marcadores e numeradas"),
+ ("Show Hidden Characters", "Mostrar caracteres ocultos"),
+ ("Current Page Number", "Número da página atual"),
+ ("New Note", "Nova nota"),
+ ("Insert Endnote", "Inserir nota de fim"),
+ ("Apply Color (,)", "Aplicar cor (,)"),
+ ("Apply Gradient (.)", "Aplicar degradê (.)"),
+ ("View Options", "Opções de visualização"),
+ ("Frame Edges", "Bordas do quadro"),
+ ("Hidden Characters", "Caracteres ocultos"),
+ ("Create Flex Layout", "Criar layout flexível"),
+ ("Add to Flex Layout", "Adicionar ao layout flexível"),
+ ("Convert to Flex Layout", "Converter em layout flexível"),
+ ("Remove Flex Layout", "Remover layout flexível"),
+ ("Show Flex Controls", "Mostrar controles flexíveis"),
+ ("Flex Layout Options", "Opções de layout flexível"),
+ ("Reorder in Flex Layout", "Reordenar no layout flexível"),
+ ("Flex Start", "Início flexível"),
+ ("Flex End", "Fim flexível"),
+ ("Space Between", "Espaço entre"),
+ ("Space Around", "Espaço ao redor"),
+ ("Space Evenly", "Espaço uniforme"),
+ ("Reverse Row", "Linha invertida"),
+ ("Reverse Column", "Coluna invertida"),
+ ("Wrap Content", "Quebrar conteúdo"),
+ ("Spacing", "Espaçamento"),
+ ("Horizontal Spacing", "Espaçamento horizontal"),
+ ("Vertical Spacing", "Espaçamento vertical"),
+ ("Constrain proportions", "Restringir proporções"),
+ ("Auto", "Automático"),
+ ("W:", "L:"),
+ ("H:", "A:"),
("Reverse Path", "Inverter demarcador"),
("Set Anchor", "Definir ponto de ancoragem"),
("Clear", "Limpar"),
diff --cc crates/ui-egui/src/i18n/uk.rs
index 0d372cc75,87cbe15c0..9238fb8fd
--- a/crates/ui-egui/src/i18n/uk.rs
+++ b/crates/ui-egui/src/i18n/uk.rs
@@@ -31,13 -31,28 +31,35 @@@ pub(super) const TABLE: &[(&str, &str)
("Cut", "Вирізати"),
("Copy", "Копіювати"),
("Paste", "Вставити"),
+ ("Bulleted & Numbered Lists", "Марковані й нумеровані списки"),
+ ("Current Page Number", "Номер поточної сторінки"),
+ ("Apply Color (,)", "Застосувати колір (,)"),
+ ("Apply Gradient (.)", "Застосувати градієнт (.)"),
+ ("View Options", "Параметри перегляду"),
+ ("Frame Edges", "Краї фреймів"),
+ ("Hidden Characters", "Приховані символи"),
+ ("Create Flex Layout", "Створити гнучкий макет"),
+ ("Add to Flex Layout", "Додати до гнучкого макета"),
+ ("Convert to Flex Layout", "Перетворити на гнучкий макет"),
+ ("Remove Flex Layout", "Прибрати гнучкий макет"),
+ ("Show Flex Controls", "Показати елементи гнучкого макета"),
+ ("Flex Layout Options", "Параметри гнучкого макета"),
+ ("Reorder in Flex Layout", "Змінити порядок у гнучкому макеті"),
+ ("Flex Start", "Початок"),
+ ("Flex End", "Кінець"),
+ ("Space Between", "Простір між"),
+ ("Space Around", "Простір навколо"),
+ ("Space Evenly", "Рівномірно"),
+ ("Reverse Row", "Рядок у зворотному порядку"),
+ ("Reverse Column", "Стовпець у зворотному порядку"),
+ ("Wrap Content", "Переносити вміст"),
+ ("Spacing", "Відступи"),
+ ("Horizontal Spacing", "Горизонтальний відступ"),
+ ("Vertical Spacing", "Вертикальний відступ"),
+ ("Constrain proportions", "Зберігати пропорції"),
+ ("Auto", "Авто"),
+ ("W:", "Ш:"),
+ ("H:", "В:"),
("Reverse Path", "Розвернути контур"),
("Set Anchor", "Задати прив’язку"),
("Clear", "Очистити"),
diff --cc crates/ui-egui/src/panels/properties.rs
index 599dd4956,52eecfc32..0d12b4260
--- a/crates/ui-egui/src/panels/properties.rs
+++ b/crates/ui-egui/src/panels/properties.rs
@@@ -2769,46 -2524,281 +2772,325 @@@ mod effects_panel_tests
}
}
+#[cfg(test)]
+mod wrap_panel_tests {
+ use super::*;
+
+ /// One frame of the Text Wrap panel: the text painted and where.
+ fn frame(app: &mut DesignApp, ctx: &egui::Context, events: Vec<egui::Event>) -> Vec<(String, egui::Rect)> {
+ let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(360.0, 300.0));
+ let time = ctx.input(|i| i.time) + 1.0 / 60.0;
+ let mut out =
+ ctx.run_ui(egui::RawInput { screen_rect: Some(screen), time: Some(time), events, ..Default::default() }, |ui| wrap_panel(app, ui));
+ out.textures_delta.clear();
+ out.shapes
+ .into_iter()
+ .filter_map(|s| if let egui::Shape::Text(t) = s.shape { Some((t.galley.job.text.clone(), t.visual_bounding_rect())) } else { None })
+ .collect()
+ }
+
+ #[test]
+ fn the_text_wrap_panel_shows_each_offset_and_invert() {
+ let mut app = DesignApp::new(designcraft_engine::Session::new(), Default::default());
+ app.run("file.new", json!({})).unwrap();
+ let id = app.run("frame.create", json!({"rect": [72, 72, 144, 144]})).unwrap()["id"].as_u64().unwrap();
+ app.run("object.textWrap", json!({"mode": "boundingBox", "offset": [1, 2, 3, 4]})).unwrap();
+ let ctx = egui::Context::default();
+ crate::theme::install_fonts(&ctx, "en");
+ // Top and Left, then Bottom and Right, each with its own value (picas here: 0p1 = 1 pt).
+ let t: Vec<String> = frame(&mut app, &ctx, vec![]).into_iter().map(|(t, _)| t).filter(|t| !t.is_empty()).collect();
+ assert_eq!(t, ["Invert", "Top", "0p1", "Left", "0p2", "Bottom", "0p3", "Right", "0p4"]);
+ // Invert, next to the wrap buttons.
+ let pos = frame(&mut app, &ctx, vec![]).into_iter().find(|(t, _)| t == "Invert").unwrap().1.center();
+ for pressed in [true, false] {
+ frame(
+ &mut app,
+ &ctx,
+ vec![
+ egui::Event::PointerMoved(pos),
+ egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE },
+ ],
+ );
+ }
+ assert!(app.session.doc().unwrap().doc.item(designcraft_doc::ItemId(id)).unwrap().wrap.invert);
+ }
+}
++
+ // ---------------------------------------------------------------- Flex Layout
+
+ /// (justification, icon, label) in the Justification menu's order.
+ const FLEX_JUSTIFY: [(&str, &str, &str); 6] = [
+ ("flexStart", "flex-start", "Flex Start"),
+ ("center", "flex-center", "Center"),
+ ("flexEnd", "flex-end", "Flex End"),
+ ("spaceBetween", "flex-between", "Space Between"),
+ ("spaceAround", "flex-around", "Space Around"),
+ ("spaceEvenly", "flex-evenly", "Space Evenly"),
+ ];
+
+ /// The selected Flex Layout container (the first), with its objects' bounds.
+ fn selected_container(app: &DesignApp) -> Option<(designcraft_doc::Item, Vec<designcraft_geom::Rect>)> {
+ let st = app.session.active()?;
+ let it = st.selection.items.iter().filter_map(|i| st.doc.item(*i)).find(|it| it.flex.is_some())?.clone();
+ let kids = match &it.content {
+ designcraft_doc::Content::Group { items } => items.iter().map(|c| c.bounds()).collect(),
+ _ => Vec::new(),
+ };
+ Some((it, kids))
+ }
+
+ /// The alignment grid: 3 × 3 cells (one column or row of three when a space justification spreads
+ /// the objects along the main axis); the chosen cell shows the direction's arrow.
+ fn flex_grid(ui: &mut Ui, r: Rect, f: Option<&designcraft_doc::FlexLayout>) -> Option<u8> {
+ use designcraft_doc::{FlexAlign, FlexJustify};
+ let t = Tokens::get(ui.ctx());
+ let resp = ui.interact(r, ui.id().with("flex_grid"), Sense::click());
+ ui.painter().rect_stroke(r, 2.0, Stroke::new(1.0, t.field_border), StrokeKind::Inside);
+ let cell = r.width() / 3.0;
+ let pos = |a: FlexAlign| match a {
+ FlexAlign::Start => 0,
+ FlexAlign::Center => 1,
+ FlexAlign::End => 2,
+ };
+ // The chosen (column, row), and whether a space justification leaves only one axis.
+ let (chosen, spread_row) = match f {
+ Some(f) => {
+ let main = match f.justify {
+ FlexJustify::Center => 1,
+ FlexJustify::FlexEnd => 2,
+ _ => 0,
+ };
+ let main = if f.direction.is_reverse() { 2 - main } else { main };
+ let cross = pos(f.align);
+ (if f.direction.is_row() { (main, cross) } else { (cross, main) }, f.justify.distributes().then_some(f.direction.is_row()))
+ }
+ None => ((0, 0), None),
+ };
+ let mut picked = None;
+ for row in 0..3usize {
+ for col in 0..3usize {
+ match spread_row {
+ Some(true) if col != 0 => continue,
+ Some(false) if row != 0 => continue,
+ _ => {}
+ }
+ let c = Rect::from_min_size(r.min + vec2(col as f32 * cell, row as f32 * cell), vec2(cell, cell));
+ let on = match spread_row {
+ Some(true) => row == chosen.1,
+ Some(false) => col == chosen.0,
+ None => (col, row) == chosen,
+ };
+ if on && f.is_some() {
+ ui.painter().rect_filled(c.shrink(2.0), 2.0, t.well);
+ let icon = match f.map(|f| f.direction) {
+ Some(designcraft_doc::FlexDirection::RowReverse) => "flex-left",
+ Some(designcraft_doc::FlexDirection::Column) => "flex-down",
+ Some(designcraft_doc::FlexDirection::ColumnReverse) => "flex-up",
+ _ => "flex-right",
+ };
+ icons::paint(ui.painter(), c.shrink(3.0), icon, t.text_strong);
+ } else {
+ ui.painter().circle_filled(c.center(), 1.5, t.icon);
+ }
+ if resp.clicked() && resp.interact_pointer_pos().is_some_and(|p| c.contains(p)) {
+ picked = Some((row * 3 + col) as u8);
+ }
+ }
+ }
+ picked
+ }
+
+ /// Flex Layout controls, as InDesign's panel: Create Flex Layout; alignment grid, width and height
+ /// (Auto/Fixed); justification, direction and wrap; padding and spacing.
+ fn flex_section(app: &mut DesignApp, ui: &mut Ui) {
+ use designcraft_doc::{FlexSize, flex};
+ let t = Tokens::get(ui.ctx());
+ let lang = app.ui.language.clone();
+ let tr = |s: &str| crate::i18n::tr(&lang, s).to_string();
+ let u = units(app);
+ let has_sel = app.session.active().is_some_and(|s| !s.selection.items.is_empty());
+ let container = selected_container(app);
+ let f = container.as_ref().and_then(|(it, _)| it.flex.clone());
+ let mut on = f.is_some();
+ let resp = ui.add_enabled_ui(has_sel, |ui| widgets::checkbox(ui, &mut on, &tr("Create Flex Layout"))).inner;
+ if resp.changed() {
+ let _ = app.run(if on { "flex.add" } else { "flex.remove" }, json!({}));
+ return;
+ }
+ ui.add_space(4.0);
+ let enabled = f.is_some();
+ let rect = container.as_ref().map(|(it, _)| it.inner_bounds());
+ let arranged = container.as_ref().and_then(|(it, kids)| it.flex.as_ref().map(|f| flex::arrange(f, it.inner_bounds(), kids)));
+ let mut set: Option<Value> = None;
+ // Alignment grid, W and H with Auto/Fixed, constrain proportions.
+ let b = block(ui, 2.0 * FIELD_H + 5.0);
+ ui.add_enabled_ui(enabled, |ui| {
+ if let Some(c) = flex_grid(ui, sub(b, 0.0, 0.0, 48.0, 48.0), f.as_ref()) {
+ set = Some(json!({"cell": c}));
+ }
+ let linked = temp_bool(ui, "flex_size_linked", false);
+ for (k, (label, key, mode, len)) in [
+ ("W:", "width", f.as_ref().map(|f| f.width), rect.map(|r| r.width())),
+ ("H:", "height", f.as_ref().map(|f| f.height), rect.map(|r| r.height())),
+ ]
+ .into_iter()
+ .enumerate()
+ {
+ let y = k as f32 * (FIELD_H + 5.0);
+ ui.painter().text(
+ sub(b, 56.0, y, 18.0, FIELD_H).right_center(),
+ egui::Align2::RIGHT_CENTER,
+ tr(label),
+ egui::FontId::proportional(11.5),
+ t.text,
+ );
+ let nv = place(ui, sub(b, 78.0, y, 66.0, FIELD_H), |ui| NumField::measure(key, len, u).width(66.0).range(0.0, 100_000.0).show(ui));
+ if let Some(v) = nv {
+ let mut p = json!({ key: v });
+ if linked
+ && let (Some(r), Some(len)) = (rect, len)
+ && len > 1e-9
+ {
+ let other = if key == "width" { ("height", r.height()) } else { ("width", r.width()) };
+ p[other.0] = json!(other.1 * v / len);
+ }
+ set = Some(p);
+ }
+ let names = [tr("Fixed"), tr("Auto")];
+ let cur = if mode == Some(FlexSize::Auto) { 1 } else { 0 };
+ if let Some(i) = place(ui, sub(b, 148.0, y, 62.0, FIELD_H), |ui| widgets::dropdown_list(ui, &names[cur], 62.0, &names, Some(cur))) {
+ set = Some(json!({ key: if i == 1 { "auto" } else { "fixed" } }));
+ }
+ }
+ let clicked = place(ui, sub(b, 214.0, 12.5, 22.0, FIELD_H), |ui| {
+ widgets::icon_toggle_sized(ui, if linked { "link" } else { "link-broken" }, linked, &tr("Constrain proportions"), vec2(22.0, 21.0))
+ .clicked()
+ });
+ if clicked {
+ set_temp_bool(ui, "flex_size_linked", !linked);
+ }
+ });
+ ui.add_space(6.0);
+ // Justification, direction, wrap.
+ let b = block(ui, FIELD_H);
+ ui.add_enabled_ui(enabled, |ui| {
+ let cur = f.as_ref().map(|f| f.justify).unwrap_or_default();
+ let cur = serde_json::to_value(cur).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default();
+ let icon = FLEX_JUSTIFY.iter().find(|j| j.0 == cur).map(|j| j.1).unwrap_or("flex-start");
+ let resp = place(ui, sub(b, 0.0, 0.0, 58.0, FIELD_H), |ui| {
+ preview_dropdown(ui, 58.0, |p, r| icons::paint(p, r.shrink2(vec2(6.0, 2.0)), icon, egui::Color32::from_gray(60)))
+ });
+ egui::Popup::menu(&resp).show(|ui| {
+ ui.set_min_width(150.0);
+ for (id, icon, label) in FLEX_JUSTIFY {
+ let r = ui.horizontal(|ui| {
+ let (ir, _) = ui.allocate_exact_size(vec2(22.0, 16.0), Sense::hover());
+ icons::paint(ui.painter(), ir, icon, t.icon);
+ ui.selectable_label(id == cur, crate::rtl::widget(ui, tr(label)))
+ });
+ if r.inner.clicked() {
+ set = Some(json!({"justify": id}));
+ ui.close();
+ }
+ }
+ });
+ let dir = f.as_ref().map(|f| f.direction).unwrap_or_default();
+ place(ui, sub(b, 78.0, 0.0, 132.0, FIELD_H), |ui| {
+ ui.spacing_mut().item_spacing.x = 2.0;
+ for (d, icon, tip) in [
+ (designcraft_doc::FlexDirection::Row, "flex-right", "Row"),
+ (designcraft_doc::FlexDirection::RowReverse, "flex-left", "Reverse Row"),
+ (designcraft_doc::FlexDirection::Column, "flex-down", "Column"),
+ (designcraft_doc::FlexDirection::ColumnReverse, "flex-up", "Reverse Column"),
+ ] {
+ if widgets::icon_toggle_sized(ui, icon, enabled && dir == d, &tr(tip), vec2(31.0, 21.0)).clicked() {
+ set = Some(json!({"direction": d}));
+ }
+ }
+ });
+ let wrap = f.as_ref().is_some_and(|f| f.wrap);
+ if place(ui, sub(b, 214.0, 0.0, 22.0, FIELD_H), |ui| {
+ widgets::icon_toggle_sized(ui, "flex-wrap", wrap, &tr("Wrap Content"), vec2(22.0, 21.0)).clicked()
+ }) {
+ set = Some(json!({"wrap": !wrap}));
+ }
+ });
+ // Spacing: padding (linked by default) and the spacing between objects.
+ section(ui, &tr("Spacing"), true);
+ let b = block(ui, 3.0 * FIELD_H + 10.0);
+ ui.add_enabled_ui(enabled, |ui| {
+ let pad = f.as_ref().map(|f| f.padding).unwrap_or_default();
+ let linked = temp_bool(ui, "flex_padding_linked", true);
+ for (k, (icon, tip, x, y)) in [
+ ("margin-top", "Top", 0.0, 0.0),
+ ("margin-inside", "Left", 112.0, 0.0),
+ ("margin-bottom", "Bottom", 0.0, 26.0),
+ ("margin-outside", "Right", 112.0, 26.0),
+ ]
+ .into_iter()
+ .enumerate()
+ {
+ let ir = sub(b, x, y + 2.0, 17.0, 17.0);
+ icons::paint(ui.painter(), ir, icon, t.icon);
+ ui.interact(ir, ui.id().with(("flex_pad", k)), Sense::hover()).on_hover_ui(|ui| {
+ crate::rtl::label(ui, tr(tip));
+ });
+ let value = f.as_ref().map(|_| pad[k]);
+ let nv = place(ui, sub(b, x + 20.0, y, 76.0, FIELD_H), |ui| {
+ NumField::measure(tip, value, u).width(76.0).spinner().range(0.0, 8000.0).show(ui)
+ });
+ if let Some(v) = nv {
+ let p = if linked {
+ [v; 4]
+ } else {
+ let mut p = pad;
+ p[k] = v;
+ p
+ };
+ set = Some(json!({"padding": p}));
+ }
+ }
+ if place(ui, sub(b, 214.0, 12.5, 22.0, FIELD_H), |ui| {
+ widgets::icon_toggle_sized(ui, if linked { "link" } else { "link-broken" }, linked, &tr("Make all settings the same"), vec2(22.0, 21.0))
+ .clicked()
+ }) {
+ set_temp_bool(ui, "flex_padding_linked", !linked);
+ }
+ // Spacing between objects: a space justification works the main axis' out (shown greyed);
+ // the cross axis' only counts when objects wrap.
+ let (row, distributes, wrap) = f.as_ref().map(|f| (f.direction.is_row(), f.justify.distributes(), f.wrap)).unwrap_or((true, false, false));
+ let main_gap = arranged.as_ref().map(|a| a.main_gap);
+ for (k, (icon, key, tip, x)) in
+ [("gap-h", "gapH", "Horizontal Spacing", 0.0), ("gap-v", "gapV", "Vertical Spacing", 112.0)].into_iter().enumerate()
+ {
+ let main = (k == 0) == row;
+ let live = if main { !distributes } else { wrap };
+ let value = match &f {
+ Some(_) if main && distributes => main_gap,
+ Some(f) => Some(if k == 0 { f.gap_h } else { f.gap_v }),
+ None => None,
+ };
+ let y = 2.0 * FIELD_H + 10.0;
+ let ir = sub(b, x, y + 2.0, 17.0, 17.0);
+ icons::paint(ui.painter(), ir, icon, if live { t.icon } else { t.text_dim });
+ ui.interact(ir, ui.id().with(("flex_gap", k)), Sense::hover()).on_hover_ui(|ui| {
+ crate::rtl::label(ui, tr(tip));
+ });
+ let nv = place(ui, sub(b, x + 20.0, y, 76.0, FIELD_H), |ui| {
+ NumField::measure(key, value, u).width(76.0).spinner().range(0.0, 8000.0).enabled(live).show(ui)
+ });
+ if let Some(v) = nv {
+ set = Some(json!({ key: v }));
+ }
+ }
+ });
+ if let Some(p) = set {
+ let _ = app.run("flex.set", p);
+ }
+ }
+
+ /// Window › Flex Layout.
+ pub fn flex_panel(app: &mut DesignApp, ui: &mut egui::Ui) {
+ ui.spacing_mut().item_spacing = vec2(6.0, 5.0);
+ flex_section(app, ui);
+ }