Skip to content

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

Tables: cell strokes in the Stroke panel and Cell Options › Strokes and Fills

aiongg57d9761c6910
diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs
index 2ab7a3bad..18e9e4b4d 100644
--- a/crates/ui-egui/src/dialogs.rs
+++ b/crates/ui-egui/src/dialogs.rs
@@ -1125,6 +1125,7 @@ pub fn show(app: &mut DesignApp, ctx: &egui::Context) {
"frameSize" => crate::i18n::tr(&app.ui.language, "Rectangle"),
"goToPage" => crate::i18n::tr(&app.ui.language, "Go to Page"),
"insertTable" => crate::i18n::tr(&app.ui.language, "Create Table"),
+ "cellOptions" => crate::i18n::tr(&app.ui.language, "Cell Options"),
"textFrameOptions" => crate::i18n::tr(&app.ui.language, "Text Frame Options"),
"documentSetup" => crate::i18n::tr(&app.ui.language, "Document Setup"),
"findChange" => crate::i18n::tr(&app.ui.language, "Find/Change"),
@@ -1685,6 +1686,7 @@ pub fn show(app: &mut DesignApp, ctx: &egui::Context) {
ui.end_row();
});
}
+ "cellOptions" => cell_options(app, ui, &mut d),
"textFrameOptions" => {
seed_text_frame_options(app, &mut d);
text_frame_options_dialog(app, ui, &mut d);
@@ -1741,6 +1743,99 @@ pub fn show(app: &mut DesignApp, ctx: &egui::Context) {
}
}
+/// Cell Options keys (`table.getCellStroke` names) and whether each belongs to the stroke.
+const CELL_OPTION_KEYS: [(&str, bool); 8] =
+ [("weight", true), ("type", true), ("color", true), ("tint", true), ("gapColor", true), ("gapTint", true), ("fill", false), ("fillTint", false)];
+
+/// Table › Cell Options › Strokes and Fills… for the target cells. The fields start from the
+/// cells' values (`seed`); OK applies the fields that differ from it.
+pub fn open_cell_options(app: &mut DesignApp) -> Result<Value, String> {
+ let edges = crate::panels::cell_stroke::edges_param(&[true; 6]);
+ let cur = app.session.execute("table.getCellStroke", &json!({"edges": edges})).map_err(|e| e.to_string())?;
+ let mut fields = Map::new();
+ for (k, _) in CELL_OPTION_KEYS {
+ fields.insert(k.into(), cur[k].clone());
+ }
+ fields.insert("seed".into(), Value::Object(fields.clone()));
+ fields.insert("edges".into(), edges);
+ app.ui.dialog = Some(Dialog::new("cellOptions", Value::Object(fields)));
+ Ok(Value::Null)
+}
+
+/// Cell Options › Strokes and Fills: the edge proxy and stroke fields, then the cell fill.
+fn cell_options(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) {
+ use crate::panels::cell_stroke;
+ let lang = app.ui.language.clone();
+ crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&lang, "Cell Stroke")).font(semibold(12.0)));
+ let mut edges = cell_stroke::edges_from(d.fields.get("edges").unwrap_or(&Value::Null));
+ if cell_stroke::edge_proxy(ui, "cell_options", &mut edges, &lang) {
+ d.fields.insert("edges".into(), cell_stroke::edges_param(&edges));
+ // Fields the user hasn't changed follow the chosen edges.
+ let cur = cell_stroke::current(app, &edges);
+ let seed = d.fields.get("seed").cloned().unwrap_or(Value::Null);
+ let mut next = seed.clone();
+ for (k, stroke) in CELL_OPTION_KEYS {
+ if stroke && d.fields.get(k) == seed.get(k) {
+ d.fields.insert(k.into(), cur[k].clone());
+ next[k] = cur[k].clone();
+ }
+ }
+ d.fields.insert("seed".into(), next);
+ }
+ ui.add_space(6.0);
+ let values = Value::Object(d.fields.clone());
+ let any = edges.iter().any(|on| *on);
+ if let Some((k, v)) = ui.add_enabled_ui(any, |ui| cell_stroke::stroke_fields(app, ui, "cell_options", &values)).inner {
+ d.fields.insert(k.into(), v);
+ }
+ ui.add_space(10.0);
+ crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&lang, "Cell Fill")).font(semibold(12.0)));
+ egui::Grid::new("cell_fill").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {
+ crate::rtl::label(ui, crate::i18n::tr(&lang, "Color:"));
+ let mut picked = None;
+ crate::panels::swatch_picker(app, ui, "cell_fill_color", values["fill"].as_str().map(str::to_string), |_, n| picked = Some(n));
+ if let Some(n) = picked {
+ d.fields.insert("fill".into(), json!(n));
+ }
+ ui.end_row();
+ crate::rtl::label(ui, crate::i18n::tr(&lang, "Tint:"));
+ let tint = values["fillTint"].as_f64().map(|t| (t * 100.0).round());
+ if let Some(t) = crate::widgets::NumField::number("cell_fill_tint", tint, "%", 0).width(60.0).range(0.0, 100.0).show(ui) {
+ d.fields.insert("fillTint".into(), json!(t / 100.0));
+ }
+ ui.end_row();
+ });
+}
+
+/// Apply the Cell Options fields that differ from the cells' values, as one `table.setCell`.
+fn confirm_cell_options(app: &mut DesignApp, d: &Dialog) -> Result<Value, String> {
+ let seed = d.fields.get("seed").cloned().unwrap_or(Value::Null);
+ let mut stroke = Map::new();
+ let mut params = Map::new();
+ for (k, is_stroke) in CELL_OPTION_KEYS {
+ let Some(v) = d.fields.get(k).filter(|v| !v.is_null() && seed.get(k) != Some(*v)) else { continue };
+ match (is_stroke, k) {
+ (true, _) => {
+ stroke.insert(k.into(), v.clone());
+ }
+ (false, "fillTint") => {
+ params.insert("tint".into(), v.clone());
+ }
+ _ => {
+ params.insert(k.into(), v.clone());
+ }
+ }
+ }
+ if !stroke.is_empty() {
+ stroke.insert("edges".into(), d.fields.get("edges").cloned().unwrap_or(json!("all")));
+ params.insert("stroke".into(), Value::Object(stroke));
+ }
+ if params.is_empty() {
+ return Ok(Value::Null);
+ }
+ app.run("table.setCell", Value::Object(params))
+}
+
/// Apply the open dialog.
pub fn confirm(app: &mut DesignApp) -> Result<Value, String> {
let Some(d) = app.ui.dialog.take() else { return Err("no dialog open".into()) };
@@ -1788,6 +1883,15 @@ pub fn confirm(app: &mut DesignApp) -> Result<Value, String> {
json!({"rows": d.n("bodyRows").unwrap_or(4.0).max(1.0) as u64, "cols": d.n("columns").unwrap_or(4.0).max(1.0) as u64,
"headerRows": d.n("headerRows").unwrap_or(0.0).max(0.0) as u64, "footerRows": d.n("footerRows").unwrap_or(0.0).max(0.0) as u64}),
),
+ "cellOptions" => {
+ // On an error the dialog stays open to be corrected.
+ let r = confirm_cell_options(app, &d);
+ if let Err(e) = &r {
+ app.status(e.clone());
+ app.ui.dialog = Some(d);
+ }
+ r
+ }
"textFrameOptions" => {
// On an error the dialog stays open to be corrected.
let mut d = d;
@@ -3741,6 +3845,33 @@ fn find_font(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) {
mod tests {
use super::*;
+ #[test]
+ fn cell_options_dialog_draws_and_applies_only_changed_values_to_the_chosen_edges() {
+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ app.run("file.new", json!({})).unwrap();
+ app.run("frame.create", json!({"rect": [72, 72, 400, 400], "content": "text", "caret": true})).unwrap();
+ let tid = app.run("table.insert", json!({"rows": 2, "cols": 2})).unwrap()["table"].as_u64().unwrap();
+ app.run("table.select", json!({"what": "table"})).unwrap();
+ app.run("app.cellOptionsDialog", json!({})).unwrap();
+ let ctx = dialog_context("");
+ dialog_frame(&mut app, &ctx, egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(900.0, 700.0)), vec![]);
+ let d = app.ui.dialog.as_mut().unwrap();
+ assert_eq!(d.id, "cellOptions");
+ assert_eq!(d.fields["weight"], json!(1.0));
+ d.fields.insert("edges".into(), json!(["top", "bottom", "left", "right"]));
+ d.fields.insert("gapColor".into(), json!("[Paper]"));
+ d.fields.insert("fill".into(), json!("[Black]"));
+ d.fields.insert("fillTint".into(), json!(0.2));
+ confirm(&mut app).unwrap();
+ let st = app.session.active().unwrap();
+ let t = st.doc.stories.values().find_map(|s| s.tables.get(&tid)).unwrap();
+ let gap = |r: usize, c: usize, side: usize| t.cell(r, c).unwrap().strokes[side].gap_color.clone();
+ assert_eq!([gap(0, 0, 0), gap(0, 0, 1), gap(1, 1, 2), gap(1, 1, 3)], ["[Paper]"; 4].map(String::from), "outer edges");
+ assert_eq!([gap(0, 0, 2), gap(0, 0, 3)], ["[None]"; 2].map(String::from), "inner edges keep theirs");
+ assert!(t.cells.iter().all(|c| c.fill == "[Black]" && (c.fill_tint - 0.2).abs() < 1e-6));
+ assert!(t.cells.iter().all(|c| c.strokes.iter().all(|e| e.weight == 1.0)), "unchanged values are not applied");
+ }
+
fn dialog_context(language: &str) -> egui::Context {
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx, language);
diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs
index e5e8a8d08..85cc122fc 100644
--- a/crates/ui-egui/src/i18n.rs
+++ b/crates/ui-egui/src/i18n.rs
@@ -2811,6 +2811,22 @@ const TABLE: &[(&str, [&str; 5])] = &[
("Rule Below", ["Linie unterhalb", "Filet après", "Filete después", "後境界線", "下方横线"]),
("Tint:", ["Farbton:", "Teinte:", "Matiz:", "濃淡:", "色调:"]),
("Column", ["Spalte", "Colonne", "Columna", "段", "栏"]),
+ // Cell strokes.
+ ("Gap Tint:", ["Lückenfarbton:", "Teinte de l'espace:", "Matiz del hueco:", "すき間の濃淡:", "间隙色调:"]),
+ ("Strokes and Fills…", ["Konturen und Flächen …", "Contours et fonds…", "Trazos y rellenos…", "線と塗り…", "描边和填色…"]),
+ ("Cell Stroke", ["Zellkontur", "Contour de cellule", "Trazo de celda", "セルの線", "单元格描边"]),
+ ("Cell Fill", ["Zellfläche", "Fond de cellule", "Relleno de celda", "セルの塗り", "单元格填色"]),
+ ("Cell edges", ["Zellkanten", "Bords de cellule", "Bordes de celda", "セルの境界線", "单元格边缘"]),
+ (
+ "Click a line to include or exclude it. Double-click selects all outer or all inner lines; triple-click selects or clears all.",
+ [
+ "Klicken Sie auf eine Linie, um sie ein- oder auszuschließen. Doppelklick wählt alle äußeren oder alle inneren Linien; Dreifachklick wählt alle aus oder hebt die Auswahl auf.",
+ "Cliquez sur une ligne pour l'inclure ou l'exclure. Un double-clic sélectionne toutes les lignes extérieures ou intérieures ; un triple-clic sélectionne ou désélectionne tout.",
+ "Haga clic en una línea para incluirla o excluirla. Doble clic selecciona todas las líneas exteriores o interiores; triple clic selecciona o borra todas.",
+ "線をクリックすると、含めるか除外するかを切り替えます。ダブルクリックで外側または内側の線をすべて選択し、トリプルクリックですべてを選択または解除します。",
+ "单击线条可将其包含或排除。双击选择所有外侧或所有内侧线条;三击选择或清除全部。",
+ ],
+ ),
];
/// Interface direction; independent of document binding and paragraph direction.
diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs
index 10e393cd2..663ededfa 100644
--- a/crates/ui-egui/src/i18n/ar.rs
+++ b/crates/ui-egui/src/i18n/ar.rs
@@ -1469,4 +1469,13 @@ pub(super) const TABLE: &[(&str, &str)] = &[
("Paragraph Rules…", "خطوط الفقرة…"),
("Paragraph Rules", "خطوط الفقرة"),
("Rule Below", "خط سفلي"),
+ ("Gap Tint:", "صبغة الفجوة:"),
+ ("Strokes and Fills…", "الحدود والتعبئة…"),
+ ("Cell Stroke", "حد الخلية"),
+ ("Cell Fill", "تعبئة الخلية"),
+ ("Cell edges", "حواف الخلية"),
+ (
+ "Click a line to include or exclude it. Double-click selects all outer or all inner lines; triple-click selects or clears all.",
+ "انقر على خط لتضمينه أو استبعاده. النقر المزدوج يحدد كل الخطوط الخارجية أو كل الخطوط الداخلية؛ والنقر الثلاثي يحدد الكل أو يلغي تحديده.",
+ ),
];
diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs
index c91afd6ba..ff79159ed 100644
--- a/crates/ui-egui/src/i18n/it.rs
+++ b/crates/ui-egui/src/i18n/it.rs
@@ -1492,4 +1492,13 @@ pub(super) const TABLE: &[(&str, &str)] = &[
("Paragraph Rules", "Filetti paragrafo"),
("Rule Below", "Filetto sotto"),
("Tint:", "Tinta:"),
+ ("Gap Tint:", "Tinta spazio:"),
+ ("Strokes and Fills…", "Tracce e riempimenti…"),
+ ("Cell Stroke", "Traccia cella"),
+ ("Cell Fill", "Riempimento cella"),
+ ("Cell edges", "Bordi cella"),
+ (
+ "Click a line to include or exclude it. Double-click selects all outer or all inner lines; triple-click selects or clears all.",
+ "Fai clic su una linea per includerla o escluderla. Il doppio clic seleziona tutte le linee esterne o interne; il triplo clic seleziona o deseleziona tutte.",
+ ),
];
diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs
index be6e2c4da..b927f0f48 100644
--- a/crates/ui-egui/src/i18n/ja.rs
+++ b/crates/ui-egui/src/i18n/ja.rs
@@ -1670,6 +1670,16 @@ pub(super) const TABLE: &[(&str, &str)] = &[
("Vertical:", "垂直方向:"),
("Working CMYK", "作業用 CMYK"),
("Yellow", "イエロー"),
+ ("Gap Tint:", "すき間の濃淡:"),
+ ("Strokes and Fills…", "線と塗り…"),
+ ("Cell Stroke", "セルの線"),
+ ("Cell Fill", "セルの塗り"),
+ ("Cell edges", "セルの境界線"),
+ (
+ "Click a line to include or exclude it. Double-click selects all outer or all inner lines; triple-click selects or clears all.",
+ "線をクリックすると、含めるか除外するかを切り替えます。ダブルクリックで外側または内側の線をすべて選択し、トリプルクリックですべてを選択または解除します。",
+ ),
+ ("Tint:", "濃淡:"),
];
#[cfg(test)]
diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs
index d25717dc6..7ffe3986c 100644
--- a/crates/ui-egui/src/i18n/pt_br.rs
+++ b/crates/ui-egui/src/i18n/pt_br.rs
@@ -1073,4 +1073,13 @@ pub(super) const TABLE: &[(&str, &str)] = &[
("Paragraph Rules…", "Linhas de parágrafo…"),
("Paragraph Rules", "Linhas de parágrafo"),
("Rule Below", "Linha abaixo"),
+ ("Gap Tint:", "Matiz do espaço:"),
+ ("Strokes and Fills…", "Traçados e preenchimentos…"),
+ ("Cell Stroke", "Traçado da célula"),
+ ("Cell Fill", "Preenchimento da célula"),
+ ("Cell edges", "Bordas da célula"),
+ (
+ "Click a line to include or exclude it. Double-click selects all outer or all inner lines; triple-click selects or clears all.",
+ "Clique em uma linha para incluí-la ou excluí-la. Clique duas vezes para selecionar todas as linhas externas ou internas; clique três vezes para selecionar ou limpar todas.",
+ ),
];
diff --git a/crates/ui-egui/src/i18n/uk.rs b/crates/ui-egui/src/i18n/uk.rs
index 9a9fb89ba..b896a5759 100644
--- a/crates/ui-egui/src/i18n/uk.rs
+++ b/crates/ui-egui/src/i18n/uk.rs
@@ -1455,6 +1455,16 @@ pub(super) const TABLE: &[(&str, &str)] = &[
("Selection", "Виділення"),
("All Documents", "Усі документи"),
("On", "Увімкнено"),
+ ("Gap Tint:", "Відтінок проміжку:"),
+ ("Strokes and Fills…", "Обведення та заливки…"),
+ ("Cell Stroke", "Обведення клітинки"),
+ ("Cell Fill", "Заливка клітинки"),
+ ("Cell edges", "Краї клітинки"),
+ (
+ "Click a line to include or exclude it. Double-click selects all outer or all inner lines; triple-click selects or clears all.",
+ "Клацніть лінію, щоб увімкнути або вимкнути її. Подвійне клацання вибирає всі зовнішні або всі внутрішні лінії; потрійне — вибирає всі або знімає вибір.",
+ ),
+ ("Tint:", "Відтінок:"),
];
/// Contexts whose Ukrainian noun differs from the shared action/text-layout label.
diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs
index 94e5c0971..6a462723d 100644
--- a/crates/ui-egui/src/menus.rs
+++ b/crates/ui-egui/src/menus.rs
@@ -60,6 +60,12 @@ pub const UI_COMMANDS: &[(&str, &str, Option<&str>, &str)] = &[
("window.resetShortcuts", "Reset Shortcuts", None, "{} — every command back to its default shortcut"),
("app.findChange", "Find/Change…", Some("Cmd+F"), "{}"),
("app.insertTableDialog", "Create Table…", None, "{} — Insert Table dialog (body/header/footer rows, columns)"),
+ (
+ "app.cellOptionsDialog",
+ "Strokes and Fills…",
+ None,
+ "{} — Cell Options › Strokes and Fills of the target cells: edge proxy, stroke weight, type, colour, tint, gap colour, gap tint, and cell fill (table.setCell)",
+ ),
("app.footnoteOptionsDialog", "Document Footnote Options…", None, "{} — numbering, formatting and layout of footnotes"),
("app.rubyDialog", "Ruby…", None, "{} — the reading set over the selected text"),
(
@@ -586,6 +592,9 @@ pub const MENUS: &[(&str, &[&str])] = &[
"cmd:table.selectTable",
"<",
"-",
+ ">Cell Options",
+ "ui:app.cellOptionsDialog",
+ "<",
"cmd:table.merge",
"cmd:table.unmerge",
">Convert Cell Type",
@@ -779,6 +788,7 @@ pub fn run_ui(app: &mut DesignApp, id: &str, p: &Value) -> Option<Result<Value,
app.ui.dialog = Some(crate::dialogs::Dialog::new("menus", json!({"query": ""})));
Ok(Value::Null)
}
+ "app.cellOptionsDialog" => crate::dialogs::open_cell_options(app),
"window.hideMenuItem" => {
let Some(item) = p.get("item").and_then(Value::as_str) else { return Some(Err("missing item".into())) };
let hide = p.get("hidden").and_then(Value::as_bool).unwrap_or(true);
diff --git a/crates/ui-egui/src/panels/cell_stroke.rs b/crates/ui-egui/src/panels/cell_stroke.rs
new file mode 100644
index 000000000..d8b412ea2
--- /dev/null
+++ b/crates/ui-egui/src/panels/cell_stroke.rs
@@ -0,0 +1,286 @@
+//! Cell strokes: the edge proxy (a drawn 2 × 2 cell grid whose lines choose the cell edges a change
+//! applies to) and the stroke fields shared by the Stroke panel and Cell Options › Strokes and Fills.
+//!
+//! The proxy's lines are the target range's top, bottom, left and right sides and the lines
+//! between its rows (inner horizontal) and columns (inner vertical). A click toggles a line; a
+//! double-click on a line chooses all outer or all inner lines; a triple-click chooses all lines,
+//! or none when all were chosen.
+
+use designcraft_doc::StrokeType;
+use egui::{Pos2, Rect, Sense, Stroke, StrokeKind, Ui, pos2, vec2};
+use serde_json::{Value, json};
+
+use crate::DesignApp;
+use crate::i18n::tr;
+use crate::theme::Tokens;
+use crate::widgets::{NumField, caption};
+
+/// Edge names of the proxy lines, in proxy order; `table.setCell` takes them as `stroke.edges`.
+pub const EDGE_NAMES: [&str; 6] = ["top", "bottom", "left", "right", "innerHorizontal", "innerVertical"];
+
+/// Proxy line choice, in [`EDGE_NAMES`] order.
+pub type Edges = [bool; 6];
+
+pub const PROXY_SIZE: f32 = 64.0;
+const PROXY_INSET: f32 = 8.0;
+
+const WEIGHTS: &[f64] = &[0.0, 0.25, 0.5, 0.75, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 20.0, 30.0, 40.0, 50.0, 100.0];
+
+/// Stroke types offered for cell edges (all of them draw on table edges).
+const TYPES: &[&str] =
+ &["solid", "dashed", "dotted", "thickThin", "thinThick", "thinThin", "thickThick", "thinThickThin", "thickThinThick", "wavy", "hashed"];
+
+/// Whether the selection is table cells (or the text cursor is in a cell).
+pub fn in_cells(app: &DesignApp) -> bool {
+ app.session.active().is_some_and(|d| d.selection.cells.is_some() || d.selection.text.is_some_and(|t| t.cell.is_some()))
+}
+
+/// The chosen edges as the `edges` parameter.
+pub fn edges_param(edges: &Edges) -> Value {
+ json!(EDGE_NAMES.iter().zip(edges).filter(|(_, on)| **on).map(|(name, _)| *name).collect::<Vec<_>>())
+}
+
+/// Edges from an `edges` parameter (names); anything else chooses all.
+pub fn edges_from(v: &Value) -> Edges {
+ match v.as_array() {
+ Some(names) => std::array::from_fn(|i| names.iter().any(|n| n.as_str() == EDGE_NAMES.get(i).copied())),
+ None => [true; 6],
+ }
+}
+
+/// The proxy's lines (start, end) inside its rect, in [`EDGE_NAMES`] order.
+pub fn proxy_lines(r: Rect) -> [(Pos2, Pos2); 6] {
+ let i = r.shrink(PROXY_INSET);
+ let c = i.center();
+ [
+ (i.left_top(), i.right_top()),
+ (i.left_bottom(), i.right_bottom()),
+ (i.left_top(), i.left_bottom()),
+ (i.right_top(), i.right_bottom()),
+ (pos2(i.left(), c.y), pos2(i.right(), c.y)),
+ (pos2(c.x, i.top()), pos2(c.x, i.bottom())),
+ ]
+}
+
+/// The line under `p`, if any is within reach.
+fn line_at(r: Rect, p: Pos2) -> Option<usize> {
+ proxy_lines(r)
+ .iter()
+ .enumerate()
+ .map(|(i, (a, b))| {
+ let t = if a == b { 0.0 } else { ((p - *a).dot(*b - *a) / (*b - *a).length_sq()).clamp(0.0, 1.0) };
+ (i, p.distance(*a + (*b - *a) * t))
+ })
+ .filter(|(_, d)| *d <= PROXY_INSET - 1.0)
+ .min_by(|a, b| a.1.total_cmp(&b.1))
+ .map(|(i, _)| i)
+}
+
+/// The edge proxy. Returns whether the choice changed.
+pub fn edge_proxy(ui: &mut Ui, id: &str, edges: &mut Edges, lang: &str) -> bool {
+ let t = Tokens::get(ui.ctx());
+ let (r, resp) = ui.allocate_exact_size(vec2(PROXY_SIZE, PROXY_SIZE), Sense::click());
+ let label = tr(lang, "Cell edges").to_string();
+ resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Other, true, &label));
+ let resp = resp.on_hover_text(tr(
+ lang,
+ "Click a line to include or exclude it. Double-click selects all outer or all inner lines; triple-click selects or clears all.",
+ ));
+ let hit = resp.interact_pointer_pos().or_else(|| resp.hover_pos()).and_then(|p| line_at(r, p));
+ let mut changed = false;
+ if resp.clicked() {
+ // A double-click counts only on the line of the click before it.
+ let last_key = ui.id().with((id, "proxy_last"));
+ let last: Option<usize> = ui.data(|d| d.get_temp(last_key)).flatten();
+ if resp.triple_clicked() {
+ let all = edges.iter().all(|on| *on);
+ *edges = [!all; 6];
+ changed = true;
+ } else if let Some(h) = hit {
+ if resp.double_clicked() && last == Some(h) {
+ let outer = h < 4;
+ for (i, on) in edges.iter_mut().enumerate() {
+ *on = (i < 4) == outer;
+ }
+ } else if let Some(on) = edges.get_mut(h) {
+ *on = !*on;
+ }
+ changed = true;
+ }
+ ui.data_mut(|d| d.insert_temp(last_key, hit));
+ }
+ let p = ui.painter();
+ p.rect_filled(r, 0.0, t.input);
+ p.rect_filled(r.shrink(PROXY_INSET), 0.0, egui::Color32::from_gray(0xf2));
+ p.rect_stroke(r, 0.0, Stroke::new(1.0, t.field_border), StrokeKind::Inside);
+ for (i, (a, b)) in proxy_lines(r).into_iter().enumerate() {
+ let on = edges.get(i).copied().unwrap_or(false);
+ let w = if hit == Some(i) {
+ 3.0
+ } else if on {
+ 2.5
+ } else {
+ 1.0
+ };
+ p.line_segment([a, b], Stroke::new(w, if on { t.accent } else { egui::Color32::from_gray(0x9a) }));
+ }
+ changed
+}
+
+/// A built-in type by its `type` parameter name.
+fn builtin(kind: &str) -> StrokeType {
+ match kind {
+ "dashed" => StrokeType::Dashed { pattern: Vec::new() },
+ "dotted" => StrokeType::Dotted,
+ "thickThin" => StrokeType::ThickThin,
+ "thinThick" => StrokeType::ThinThick,
+ "thinThin" => StrokeType::ThinThin,
+ "thickThick" => StrokeType::ThickThick,
+ "thinThickThin" => StrokeType::ThinThickThin,
+ "thickThinThick" => StrokeType::ThickThinThick,
+ "wavy" => StrokeType::Wavy,
+ "hashed" => StrokeType::Hashed,
+ _ => StrokeType::Solid,
+ }
+}
+
+/// The type's menu label (named styles by name).
+fn type_label(lang: &str, v: &Value) -> String {
+ match serde_json::from_value::<StrokeType>(v.clone()) {
+ Ok(StrokeType::Style { name }) => name,
+ Ok(k) => tr(lang, k.label()).to_string(),
+ Err(_) => String::new(),
+ }
+}
+
+/// Weight, type, colour, tint, gap colour and gap tint for the stroke attributes in `v`
+/// (`table.getCellStroke` keys; null shows as mixed). Returns the attribute the user changed.
+pub fn stroke_fields(app: &mut DesignApp, ui: &mut Ui, id: &str, v: &Value) -> Option<(&'static str, Value)> {
+ let lang = app.ui.language.clone();
+ let custom: Vec<String> = app.session.active().map(|d| d.doc.stroke_styles.iter().map(|x| x.name.clone()).collect()).unwrap_or_default();
+ let mut out = None;
+ let percent = |key: &str| v[key].as_f64().map(|t| (t * 100.0).round());
+ egui::Grid::new((id, "cell_stroke")).num_columns(2).spacing(vec2(8.0, 6.0)).show(ui, |ui| {
+ caption(ui, tr(&lang, "Weight:"));
+ let wid = format!("{id}_weight");
+ if let Some(w) = NumField::number(&wid, v["weight"].as_f64(), " pt", 3).width(86.0).spinner().presets(WEIGHTS).range(0.0, 1000.0).show(ui) {
+ out = Some(("weight", json!(w)));
+ }
+ ui.end_row();
+ caption(ui, tr(&lang, "Type:"));
+ let shown = type_label(&lang, &v["type"]);
+ egui::ComboBox::from_id_salt((id, "type")).selected_text(crate::rtl::widget(ui, &shown)).width(140.0).show_ui(ui, |ui| {
+ for kind in TYPES {
+ let text = tr(&lang, builtin(kind).label());
+ if ui.selectable_label(shown == text, crate::rtl::widget(ui, text)).clicked() {
+ out = Some(("type", json!(kind)));
+ }
+ }
+ if !custom.is_empty() {
+ ui.separator();
+ }
+ for n in &custom {
+ if ui.selectable_label(shown == *n, n).clicked() {
+ out = Some(("type", json!({"kind": "style", "name": n})));
+ }
+ }
+ });
+ ui.end_row();
+ for (label, key, tint_label, tint_key) in [("Color:", "color", "Tint:", "tint"), ("Gap Color:", "gapColor", "Gap Tint:", "gapTint")] {
+ caption(ui, tr(&lang, label));
+ let mut picked = None;
+ super::swatch_picker(app, ui, &format!("{id}_{key}"), v[key].as_str().map(str::to_string), |_, n| picked = Some(n));
+ if let Some(n) = picked {
+ out = Some((key, json!(n)));
+ }
+ ui.end_row();
+ caption(ui, tr(&lang, tint_label));
+ let tid = format!("{id}_{tint_key}");
+ if let Some(t) = NumField::number(&tid, percent(tint_key), "%", 0).width(60.0).range(0.0, 100.0).show(ui) {
+ out = Some((tint_key, json!(t / 100.0)));
+ }
+ ui.end_row();
+ }
+ });
+ out
+}
+
+/// The shown stroke attributes of `edges` of the target cells (null where they differ).
+pub fn current(app: &mut DesignApp, edges: &Edges) -> Value {
+ if !edges.iter().any(|on| *on) {
+ return Value::Null;
+ }
+ app.session.execute("table.getCellStroke", &json!({"edges": edges_param(edges)})).unwrap_or(Value::Null)
+}
+
+/// The Stroke panel for table cells: the proxy and the stroke fields, applied at once.
+pub fn panel(app: &mut DesignApp, ui: &mut Ui) {
+ let key = egui::Id::new("cell_stroke_edges");
+ let mut edges: Edges = ui.data(|d| d.get_temp(key)).unwrap_or([true; 6]);
+ let lang = app.ui.language.clone();
+ if edge_proxy(ui, "stroke_panel", &mut edges, &lang) {
+ ui.data_mut(|d| d.insert_temp(key, edges));
+ }
+ ui.add_space(6.0);
+ let values = current(app, &edges);
+ let any = edges.iter().any(|on| *on);
+ let changed = ui.add_enabled_ui(any, |ui| stroke_fields(app, ui, "csp", &values)).inner;
+ if let Some((k, v)) = changed
+ && let Err(e) = app.run("table.setCell", json!({"stroke": {k: v, "edges": edges_param(&edges)}}))
+ {
+ app.status(format!("Stroke: {e}"));
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use egui_kittest::{Harness, kittest::Queryable};
+
+ use super::*;
+
+ #[test]
+ fn stroke_panel_proxy_limits_a_weight_change_to_the_chosen_cell_edges() {
+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ app.run("file.new", json!({})).unwrap();
+ app.run("frame.create", json!({"rect": [72, 72, 400, 400], "content": "text", "caret": true})).unwrap();
+ let tid = app.run("table.insert", json!({"rows": 2, "cols": 2})).unwrap()["table"].as_u64().unwrap();
+ app.run("table.select", json!({"what": "table"})).unwrap();
+ let mut h = Harness::builder().with_size(vec2(320.0, 600.0)).build_ui_state(
+ |ui, app: &mut DesignApp| {
+ let id = egui::Id::new("test_fonts");
+ if ui.data(|d| d.get_temp::<bool>(id)).is_none() {
+ crate::theme::install_fonts(ui.ctx(), "");
+ ui.data_mut(|d| d.insert_temp(id, true));
+ return;
+ }
+ crate::panels::properties::stroke_panel(app, ui);
+ },
+ app,
+ );
+ h.run_steps(3);
+ // Leave only the inner horizontal line chosen: click the others off.
+ let lines = proxy_lines(h.get_by_label("Cell edges").rect());
+ for i in [0, 1, 2, 3, 5] {
+ let (a, b) = lines[i];
+ let at = a + (b - a) * 0.3;
+ h.hover_at(at);
+ h.drag_at(at);
+ h.drop_at(at);
+ h.run_steps(3);
+ }
+ let weight = h.get_by(|n| n.role() == egui::accesskit::Role::TextInput && n.value().as_deref() == Some("1 pt")).rect();
+ h.hover_at(weight.center());
+ h.drag_at(weight.center());
+ h.drop_at(weight.center());
+ h.run_steps(2);
+ h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);
+ h.event(egui::Event::Text("4".into()));
+ h.key_press(egui::Key::Enter);
+ h.run_steps(3);
+ let st = h.state().session.active().unwrap();
+ let t = st.doc.stories.values().find_map(|s| s.tables.get(&tid)).unwrap();
+ let w = |r: usize, c: usize, side: usize| t.cell(r, c).unwrap().strokes[side].weight;
+ assert_eq!([w(0, 0, 2), w(0, 1, 2), w(1, 0, 0), w(1, 1, 0)], [4.0; 4], "inner horizontal edges");
+ assert_eq!([w(0, 0, 0), w(0, 0, 1), w(0, 0, 3), w(0, 1, 1), w(1, 1, 2), w(1, 1, 3)], [1.0; 6], "the other edges keep their weight");
+ }
+}
diff --git a/crates/ui-egui/src/panels/mod.rs b/crates/ui-egui/src/panels/mod.rs
index 05a73395b..7f4a562cc 100644
--- a/crates/ui-egui/src/panels/mod.rs
+++ b/crates/ui-egui/src/panels/mod.rs
@@ -1,5 +1,6 @@
//! Panels and shared panel helpers.
+pub mod cell_stroke;
pub mod conditions;
pub mod datamerge;
pub mod glyphs;
diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs
index 49cb920f2..32e706236 100644
--- a/crates/ui-egui/src/panels/properties.rs
+++ b/crates/ui-egui/src/panels/properties.rs
@@ -1537,6 +1537,10 @@ pub fn paragraph_panel(app: &mut DesignApp, ui: &mut egui::Ui) {
/// Stroke panel: weight, cap, miter limit, join, alignment, type, arrowheads, gap colour.
pub fn stroke_panel(app: &mut DesignApp, ui: &mut egui::Ui) {
+ if super::cell_stroke::in_cells(app) {
+ super::cell_stroke::panel(app, ui);
+ return;
+ }
let Some(i) = sel_info(app) else {
crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Select an object."));
return;
diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md
index 8044ed51b..18909ab02 100644
--- a/docs/target-app-parity.md
+++ b/docs/target-app-parity.md
@@ -351,6 +351,7 @@ It is evidence of breadth: each item exists. It is not a claim of InDesign-level
- Track Changes (`changes.track/list/acceptAll/rejectAll`, Type ▸ Track Changes): typing is marked added (highlighted on screen), deletions are kept but hidden from layout and exports until accepted or rejected. Per-change accept/reject and authors aren't there yet.
- Track Changes: per-change Accept / Reject (`changes.accept`, `changes.reject`) and a Track Changes panel listing every change.
- Move table rows and columns (`table.moveRow`, `table.moveColumn`, Table panel buttons; with whole rows or columns selected, drag them with the Type tool — `table.dropCells`).
+- Cell strokes: with cells selected (or the cursor in a cell) the Stroke panel edits the chosen cell edges, picked on a drawn edge proxy (top, bottom, left, right, inner horizontal, inner vertical); Table › Cell Options › Strokes and Fills… does the same with the cell fill. Weight, every stroke type, colour, tint, gap colour and gap tint draw on screen and in PDF and round-trip through IDML (`table.setCell` `stroke.edges`, `table.getCellStroke`).
- Distribute Rows Evenly (`table.distributeRows`, Table menu and panel): selected rows receive equal fixed heights preserving their composed total height, with undo/redo. Row-spanning merges and rows outside the composed frames are rejected; shrinking tall cells can overset their text.
- Object States (`states.create/show/rename/release/list`, Object States panel): multi-state objects show one state on screen and in PDF.
- Buttons (`button.set/clear/list`, Buttons and Forms panel): go to page / next / previous / first / last / URL as PDF link annotations. Form fields too (`form.set/clear/list`: text fields, check boxes, combo and list boxes, signature fields; required, multiline, defaults) exported as AcroForm widgets through an incremental update (not in PDF/X).