Skip to content

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

Text frames: a custom baseline grid's Relative To (page, margin, frame or inset) (#1758)

aionggd767fcf41e4e
diff --git a/ROADMAP.md b/ROADMAP.md
index caec23486..3eff9dc1c 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -358,6 +358,7 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m
Newest first.
+- **2026-10-24** · Text frames: a custom baseline grid's Relative To (Text Frame Options › Baseline Options, `object.textFrameOptions {baselineGrid: {relativeTo}}`, IDML `BaselineFrameGridRelativeOption`) measures the grid's start from the top of the page, the top margin, the top of the frame or its top inset. Text Frame Options had no custom baseline grid controls, imports dropped the setting and every frame grid started from the page top, so grid-aligned text in a frame measured from its own top sat on the wrong lines. No readiness percentage change.
- **2026-10-24** · Paragraph Style Options › Indents and Spacing has an Align to Grid menu: None, All Lines or First Line Only. It shows the style's current setting. A First Line Only style could be set only in the CJK Grid Settings section, which shows only with CJK features on, or through commands. No readiness percentage change.
- **2026-10-24** · Anchored text frames, such as marginal notes, compose where their host story places them: they align to the baseline grid at that position, and page-number markers and spine-relative alignment inside them read the host's page. They composed against a grid measured from their stored position and on no page, so a note set to Only Align First Line to Grid could sit a fraction of a line off the body text's grid line. No readiness percentage change.
- **2026-10-24** · New documents start with Hyphenate Capitalized Words, Hyphenate Last Word and Hyphenate Across Column off in [Basic Paragraph], as in InDesign. Opened and imported files keep the values they carry. No readiness percentage change.
diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs
index fc166167d..687f4c7ea 100644
--- a/crates/compose/src/lib.rs
+++ b/crates/compose/src/lib.rs
@@ -731,9 +731,23 @@ pub(crate) fn frame_specs_placed(doc: &Document, sid: StoryId, placed: &[(ItemId
let under = spread.and_then(|sp| sp.page_at_x(center_x).and_then(|pi| sp.pages.get(pi)));
let page_rect = under.map(|pg| (inv.transform_rect_bbox(pg.bounds()), inv.transform_rect_bbox(pg.margin_rect())));
let g = &doc.settings.baseline_grid;
- let (start, inc) = tf.options.baseline_grid.map_or((under.map_or(g.start, |pg| g.origin(pg)), g.increment), |f| (f.start, f.increment));
// Grid lines are at spread y = start + n·inc (page tops are y = 0); map into inner space (translation only).
let ty = xf.translation().y;
+ let (start, inc) = match tf.options.baseline_grid {
+ None => (under.map_or(g.start, |pg| g.origin(pg)), g.increment),
+ Some(f) => {
+ use designcraft_doc::FrameGridRelative as R;
+ // The frame's own edges are in inner space; `ty` takes them to spread y as it takes
+ // the grid back, so a frame-relative grid keeps its place in a turned frame.
+ let from = match f.relative_to {
+ R::TopOfPage => 0.0,
+ R::TopMargin => under.map_or(0.0, |pg| pg.margins.top),
+ R::TopOfFrame => ty + item.inner_bounds().y0,
+ R::TopInset => ty + item.text_area().y0,
+ };
+ (from + f.start, f.increment)
+ }
+ };
let grid = (inc > 0.0 && inc.is_finite() && start.is_finite()).then_some((start - ty, inc));
// Type on a path: one line as long as the path (from the start offset).
let (area, opts) = match &tf.options.path {
diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs
index 444e34ebb..cd4783520 100644
--- a/crates/compose/src/tests.rs
+++ b/crates/compose/src/tests.rs
@@ -6697,7 +6697,7 @@ fn roman_word_break_breaks_inside_words_without_hyphens() {
fn grid_doc(text: &str, para: ParaAttrs, edit: impl FnOnce(&mut Document, StoryId)) -> (Vec<Line>, (f64, f64)) {
let (mut d, sid, fid) = doc_with(text, Rect::new(0.0, 0.0, 300.0, 400.0), para);
if let Some(tf) = d.item_mut(fid).and_then(|i| i.text_frame_mut()) {
- tf.options.baseline_grid = Some(designcraft_doc::FrameBaselineGrid { start: 0.0, increment: 12.0 });
+ tf.options.baseline_grid = Some(designcraft_doc::FrameBaselineGrid::new(0.0, 12.0));
}
edit(&mut d, sid);
// Vertical frames have no baseline grid.
@@ -7407,6 +7407,37 @@ fn baseline_grid_relative_to_the_top_margin_starts_at_each_pages_margin() {
assert_eq!(lines.len(), 41);
}
+/// A frame's custom grid (start 10, increment 13) measured from the page top, the top margin
+/// (36), the frame top (100) or the top inset (6 below it).
+#[test]
+fn frame_baseline_grid_relative_to_page_margin_frame_or_inset() {
+ use designcraft_doc::{FrameBaselineGrid, FrameGridRelative as R};
+ let first_baseline = |relative_to: Option<R>| {
+ let mut d = Document::new(&NewDocument { margins: designcraft_doc::Margins::uniform(36.0), ..Default::default() });
+ let lid = d.default_layer();
+ let para = ParaFormat { para: ParaAttrs { grid_align: Some(GridAlign::AllLines), ..Default::default() }, ..Default::default() };
+ let (fid, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 100.0, 336.0, 400.0), lid, "Grid", para).unwrap();
+ let st = d.story_mut(sid).unwrap();
+ st.paras[0].chars =
+ designcraft_doc::CharAttrs { size: Some(11.0), leading: Some(designcraft_doc::Leading::Points(13.0)), ..Default::default() };
+ let tf = d.item_mut(fid).unwrap().text_frame_mut().unwrap();
+ tf.options.inset = [6.0, 0.0, 0.0, 0.0];
+ tf.options.baseline_grid = relative_to.map(|r| FrameBaselineGrid { relative_to: r, ..FrameBaselineGrid::new(10.0, 13.0) });
+ // A document grid that matches none of the frame grids.
+ d.settings.baseline_grid.start = 0.0;
+ d.settings.baseline_grid.increment = 0.0;
+ compose_story(&d, sid, &ComposeOptions::default()).frames[0].lines[0].baseline
+ };
+ // Without a grid the first baseline sits an ascent below the top inset.
+ let natural = first_baseline(None);
+ assert!(natural > 106.0 && natural < 120.0, "{natural}");
+ for (r, origin) in [(R::TopOfPage, 10.0), (R::TopMargin, 46.0), (R::TopOfFrame, 110.0), (R::TopInset, 116.0)] {
+ let want = (0..).map(|n| origin + 13.0 * f64::from(n)).find(|y| *y >= natural - 1e-9).unwrap();
+ let got = first_baseline(Some(r));
+ assert!((got - want).abs() < 1e-6, "{r:?}: first baseline {got}, want {want} (natural {natural})");
+ }
+}
+
/// A group's transform moves a frame from the left page of a spread to the right one: the grid
/// starts at the right page's top margin.
#[test]
diff --git a/crates/doc/src/item.rs b/crates/doc/src/item.rs
index ab345e371..31d3a08d2 100644
--- a/crates/doc/src/item.rs
+++ b/crates/doc/src/item.rs
@@ -458,25 +458,87 @@ pub struct TextFrameOptions {
pub path: Option<PathType>,
}
-/// A text frame's custom baseline grid. Saved as `[start, increment]`.
-#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
-#[serde(from = "(f64, f64)", into = "(f64, f64)")]
+/// A text frame's custom baseline grid. Saved as `[start, increment]` when it starts from the
+/// top of the page, otherwise as `[start, increment, relativeTo]`.
+#[derive(Clone, Copy, Debug, PartialEq)]
pub struct FrameBaselineGrid {
- /// The first grid line, down from the top of the page.
+ /// The first grid line, down from the line `relative_to` names.
pub start: f64,
/// The distance between grid lines; 0 or less turns the grid off.
pub increment: f64,
+ pub relative_to: FrameGridRelative,
}
-impl From<(f64, f64)> for FrameBaselineGrid {
- fn from((start, increment): (f64, f64)) -> Self {
- FrameBaselineGrid { start, increment }
+impl FrameBaselineGrid {
+ /// A grid measured from the top of the page.
+ pub fn new(start: f64, increment: f64) -> Self {
+ FrameBaselineGrid { start, increment, relative_to: FrameGridRelative::TopOfPage }
}
}
-impl From<FrameBaselineGrid> for (f64, f64) {
- fn from(g: FrameBaselineGrid) -> Self {
- (g.start, g.increment)
+/// What a frame's custom baseline grid's start is measured from.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+pub enum FrameGridRelative {
+ #[default]
+ #[serde(rename = "page")]
+ TopOfPage,
+ #[serde(rename = "margin")]
+ TopMargin,
+ #[serde(rename = "frame")]
+ TopOfFrame,
+ #[serde(rename = "inset")]
+ TopInset,
+}
+
+impl FrameGridRelative {
+ pub const ALL: [FrameGridRelative; 4] =
+ [FrameGridRelative::TopOfPage, FrameGridRelative::TopMargin, FrameGridRelative::TopOfFrame, FrameGridRelative::TopInset];
+
+ /// The name commands and native files use: page, margin, frame or inset.
+ pub fn name(self) -> &'static str {
+ match self {
+ FrameGridRelative::TopOfPage => "page",
+ FrameGridRelative::TopMargin => "margin",
+ FrameGridRelative::TopOfFrame => "frame",
+ FrameGridRelative::TopInset => "inset",
+ }
+ }
+
+ pub fn from_name(name: &str) -> Option<Self> {
+ Self::ALL.into_iter().find(|r| r.name() == name)
+ }
+}
+
+impl Serialize for FrameBaselineGrid {
+ fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
+ // Files saved before Relative To existed hold two elements; a page-relative grid keeps that form.
+ match self.relative_to {
+ FrameGridRelative::TopOfPage => (self.start, self.increment).serialize(s),
+ r => (self.start, self.increment, r).serialize(s),
+ }
+ }
+}
+
+impl<'de> Deserialize<'de> for FrameBaselineGrid {
+ fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ struct Grid;
+ impl<'de> serde::de::Visitor<'de> for Grid {
+ type Value = FrameBaselineGrid;
+ fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+ f.write_str("[start, increment] or [start, increment, relativeTo]")
+ }
+ fn visit_seq<A: serde::de::SeqAccess<'de>>(self, mut a: A) -> Result<Self::Value, A::Error> {
+ use serde::de::Error;
+ let start = a.next_element()?.ok_or_else(|| A::Error::invalid_length(0, &self))?;
+ let increment = a.next_element()?.ok_or_else(|| A::Error::invalid_length(1, &self))?;
+ let relative_to = a.next_element()?.unwrap_or_default();
+ if a.next_element::<serde::de::IgnoredAny>()?.is_some() {
+ return Err(A::Error::invalid_length(4, &self));
+ }
+ Ok(FrameBaselineGrid { start, increment, relative_to })
+ }
+ }
+ d.deserialize_seq(Grid)
}
}
@@ -1686,10 +1748,24 @@ mod tests {
#[test]
fn frame_baseline_grid_saves_as_start_then_increment() {
+ // A file saved before Relative To existed: the grid starts from the top of the page and
+ // saves back unchanged.
let v = serde_json::json!({"baselineGrid": [6.0, 14.0]});
let o = serde_json::from_value::<TextFrameOptions>(v).unwrap();
- assert_eq!(o.baseline_grid, Some(FrameBaselineGrid { start: 6.0, increment: 14.0 }));
+ assert_eq!(o.baseline_grid, Some(FrameBaselineGrid { start: 6.0, increment: 14.0, relative_to: FrameGridRelative::TopOfPage }));
assert_eq!(serde_json::to_value(&o).unwrap()["baselineGrid"], serde_json::json!([6.0, 14.0]));
+ for r in [FrameGridRelative::TopMargin, FrameGridRelative::TopOfFrame, FrameGridRelative::TopInset] {
+ let o = TextFrameOptions {
+ baseline_grid: Some(FrameBaselineGrid { relative_to: r, ..FrameBaselineGrid::new(6.0, 14.0) }),
+ ..Default::default()
+ };
+ let v = serde_json::to_value(&o).unwrap();
+ assert_eq!(v["baselineGrid"], serde_json::json!([6.0, 14.0, r.name()]));
+ assert_eq!(serde_json::from_value::<TextFrameOptions>(v).unwrap().baseline_grid, o.baseline_grid);
+ }
+ for bad in [serde_json::json!([6.0]), serde_json::json!([6.0, 14.0, "frame", 1]), serde_json::json!([6.0, 14.0, "spine"])] {
+ assert!(serde_json::from_value::<TextFrameOptions>(serde_json::json!({"baselineGrid": bad})).is_err());
+ }
}
#[test]
diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs
index 87f601604..84881b067 100644
--- a/crates/engine/src/cmd/object.rs
+++ b/crates/engine/src/cmd/object.rs
@@ -598,7 +598,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Text Frame Options…",
["Object"],
Some("Cmd+B"),
- "{columns?, gutter?, inset?: number|[t,l,b,r] (null keeps that side), verticalJustification?: top|center|bottom|justify, columnsKind?: fixedNumber|fixedWidth, columnWidth? (pt, Fixed Width), firstBaseline?: ascent|capHeight|leading|xHeight|emboxHeight|fixed, firstBaselineMin? (pt), autoSize?: off|heightOnly|widthOnly|heightAndWidth|heightAndWidthProportionally, autoSizeReference?: topLeft|topCenter|topRight|leftCenter|center|rightCenter|bottomLeft|bottomCenter|bottomRight (the point that stays put), useMinimumHeight?: bool, minimumHeight? (pt), useMinimumWidth?: bool, minimumWidth? (pt), noLineBreaks?: bool, ignoreWrap?, balanceColumns?, columnRule?: bool, columnRuleWeight? (pt), columnRuleColor? (swatch name), columnRuleTint? (0..1), columnRuleOffset? (pt, horizontal), columnRuleTopInset? (pt), columnRuleBottomInset? (pt), vertical?: bool (sets the story direction of the frames' stories, as Type ▸ Story Direction), ids?}",
+ "{columns?, gutter?, inset?: number|[t,l,b,r] (null keeps that side), verticalJustification?: top|center|bottom|justify, columnsKind?: fixedNumber|fixedWidth, columnWidth? (pt, Fixed Width), firstBaseline?: ascent|capHeight|leading|xHeight|emboxHeight|fixed, firstBaselineMin? (pt), autoSize?: off|heightOnly|widthOnly|heightAndWidth|heightAndWidthProportionally, autoSizeReference?: topLeft|topCenter|topRight|leftCenter|center|rightCenter|bottomLeft|bottomCenter|bottomRight (the point that stays put), useMinimumHeight?: bool, minimumHeight? (pt), useMinimumWidth?: bool, minimumWidth? (pt), noLineBreaks?: bool, ignoreWrap?, balanceColumns?, columnRule?: bool, columnRuleWeight? (pt), columnRuleColor? (swatch name), columnRuleTint? (0..1), columnRuleOffset? (pt, horizontal), columnRuleTopInset? (pt), columnRuleBottomInset? (pt), baselineGrid?: {start? (pt), increment? (pt), relativeTo?: page|margin|frame|inset} (the frame's custom baseline grid; fields not given keep the frame's, or come from the document grid; null turns it off), vertical?: bool (sets the story direction of the frames' stories, as Type ▸ Story Direction), ids?}",
has_selection,
text_frame_options
),
@@ -2506,6 +2506,41 @@ fn text_frame_options(s: &mut Session, p: &Value) -> Result<Value> {
as u8,
),
};
+ // `Some(None)` turns the frame's custom baseline grid off.
+ let custom_grid = match p.get("baselineGrid") {
+ None => None,
+ Some(Value::Null) => Some(None),
+ Some(Value::Object(g)) => {
+ let num = |key: &str, lo: f64, hi: f64| match g.get(key) {
+ None | Some(Value::Null) => Ok(None),
+ Some(v) => match v.as_f64() {
+ Some(x) if x.is_finite() && (lo..=hi).contains(&x) => Ok(Some(x)),
+ _ => Err(bad(ID, format!("baselineGrid.{key} must be a number of points from {lo} to {hi}, not {v}"))),
+ },
+ };
+ let start = num("start", -15552.0, 15552.0)?;
+ let increment = num("increment", 0.0, 15552.0)?;
+ let relative_to = match g.get("relativeTo") {
+ None | Some(Value::Null) => None,
+ Some(v) => Some(
+ v.as_str()
+ .and_then(designcraft_doc::FrameGridRelative::from_name)
+ .ok_or_else(|| bad(ID, format!("baselineGrid.relativeTo must be page|margin|frame|inset, not {v}")))?,
+ ),
+ };
+ Some(Some((start, increment, relative_to)))
+ }
+ Some(v) => return Err(bad(ID, format!("baselineGrid must be an object or null, not {v}"))),
+ };
+ // A frame without a custom grid starts from the document's.
+ let doc_grid = {
+ let g = &st.doc.settings.baseline_grid;
+ let relative_to = match g.relative_to {
+ designcraft_doc::GridRelative::TopOfPage => designcraft_doc::FrameGridRelative::TopOfPage,
+ designcraft_doc::GridRelative::TopMargin => designcraft_doc::FrameGridRelative::TopMargin,
+ };
+ designcraft_doc::FrameBaselineGrid { start: g.start, increment: g.increment, relative_to }
+ };
let rule_color = match p.get("columnRuleColor") {
None | Some(Value::Null) => None,
Some(Value::String(c)) if st.doc.swatch(c).is_some() => Some(c.clone()),
@@ -2596,6 +2631,17 @@ fn text_frame_options(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(v) = rule_bottom {
o.column_rule_bottom_inset = v;
}
+ match custom_grid {
+ Some(Some((start, increment, relative_to))) => {
+ let mut g = o.baseline_grid.unwrap_or(doc_grid);
+ g.start = start.unwrap_or(g.start);
+ g.increment = increment.unwrap_or(g.increment);
+ g.relative_to = relative_to.unwrap_or(g.relative_to);
+ o.baseline_grid = Some(g);
+ }
+ Some(None) => o.baseline_grid = None,
+ None => {}
+ }
// Fixed Width columns set the frame's width: n columns, the gutters between them and
// the left and right insets.
let fixed_width = o.columns_kind == designcraft_doc::ColumnsKind::FixedWidth && o.column_width > 0.0;
@@ -5609,3 +5655,33 @@ mod fill_tint_tests {
assert!(stroke_of(&s, b).is_none());
}
}
+
+#[cfg(test)]
+mod frame_baseline_grid_tests {
+ use super::*;
+ use designcraft_doc::{FrameBaselineGrid, FrameGridRelative};
+
+ #[test]
+ fn text_frame_options_set_a_custom_baseline_grid_relative_to() {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({})).unwrap();
+ let r = s.execute("frame.create", &json!({"rect": [36, 36, 300, 300], "content": "text", "text": "Hello"})).unwrap();
+ let id = ItemId(r["id"].as_u64().unwrap());
+ let grid = |s: &Session| s.doc().unwrap().doc.item(id).and_then(|i| i.text_frame()).and_then(|t| t.options.baseline_grid);
+ // Turning it on with only Relative To takes the document grid's start and increment.
+ let doc = s.doc().unwrap().doc.settings.baseline_grid.clone();
+ s.execute("object.textFrameOptions", &json!({"ids": [id.0], "baselineGrid": {"relativeTo": "frame"}})).unwrap();
+ assert_eq!(grid(&s), Some(FrameBaselineGrid { start: doc.start, increment: doc.increment, relative_to: FrameGridRelative::TopOfFrame }));
+ s.execute("object.textFrameOptions", &json!({"ids": [id.0], "baselineGrid": {"start": 10, "increment": 13, "relativeTo": "inset"}})).unwrap();
+ assert_eq!(grid(&s), Some(FrameBaselineGrid { start: 10.0, increment: 13.0, relative_to: FrameGridRelative::TopInset }));
+ // Fields not given keep the frame's.
+ s.execute("object.textFrameOptions", &json!({"ids": [id.0], "baselineGrid": {"relativeTo": "margin"}})).unwrap();
+ assert_eq!(grid(&s), Some(FrameBaselineGrid { start: 10.0, increment: 13.0, relative_to: FrameGridRelative::TopMargin }));
+ for bad in [json!({"relativeTo": "spine"}), json!({"start": f64::MAX}), json!({"increment": -1}), json!(3)] {
+ assert!(s.execute("object.textFrameOptions", &json!({"ids": [id.0], "baselineGrid": bad})).is_err(), "{bad}");
+ }
+ assert_eq!(grid(&s).map(|g| g.relative_to), Some(FrameGridRelative::TopMargin));
+ s.execute("object.textFrameOptions", &json!({"ids": [id.0], "baselineGrid": null})).unwrap();
+ assert_eq!(grid(&s), None);
+ }
+}
diff --git a/crates/idml/src/export.rs b/crates/idml/src/export.rs
index 6bc4d30ca..0106364e2 100644
--- a/crates/idml/src/export.rs
+++ b/crates/idml/src/export.rs
@@ -1949,6 +1949,15 @@ impl<'a> Ex<'a> {
El::new("BaselineFrameGridOption")
.attr("UseCustomBaselineFrameGrid", "true")
.attr("StartingOffsetForBaselineFrameGrid", num(g.start))
+ .attr(
+ "BaselineFrameGridRelativeOption",
+ match g.relative_to {
+ designcraft_doc::FrameGridRelative::TopOfPage => "TopOfPageOfBaselineFrameGridRelativeOption",
+ designcraft_doc::FrameGridRelative::TopMargin => "TopOfMarginOfBaselineFrameGridRelativeOption",
+ designcraft_doc::FrameGridRelative::TopOfFrame => "TopOfFrameOfBaselineFrameGridRelativeOption",
+ designcraft_doc::FrameGridRelative::TopInset => "TopOfInsetOfBaselineFrameGridRelativeOption",
+ },
+ )
.attr("BaselineFrameGridIncrement", num(g.increment)),
);
}
diff --git a/crates/idml/src/import.rs b/crates/idml/src/import.rs
index 3dbb67901..77d730fa0 100644
--- a/crates/idml/src/import.rs
+++ b/crates/idml/src/import.rs
@@ -2977,6 +2977,7 @@ impl<'r> Importer<'r> {
options.baseline_grid = Some(designcraft_doc::FrameBaselineGrid {
start: g.num("StartingOffsetForBaselineFrameGrid").unwrap_or(0.0),
increment: g.num("BaselineFrameGridIncrement").unwrap_or(12.0),
+ relative_to: g.get("BaselineFrameGridRelativeOption").map(frame_grid_relative).unwrap_or_default(),
});
}
it.content = Content::Text(TextFrame { story, options });
@@ -3518,6 +3519,19 @@ fn fit_columns(mut columns: Columns, margins: &Margins, page_width: f64) -> Colu
columns
}
+/// A `BaselineFrameGridRelativeOption` value (`TopOfInsetOfBaselineFrameGridRelativeOption`, or a
+/// short form such as `TopOfInset`); unknown values measure from the top of the page.
+fn frame_grid_relative(v: &str) -> designcraft_doc::FrameGridRelative {
+ use designcraft_doc::FrameGridRelative as R;
+ let v = v.strip_suffix("OfBaselineFrameGridRelativeOption").unwrap_or(v);
+ match v {
+ "TopOfMargin" | "TopMargin" => R::TopMargin,
+ "TopOfFrame" => R::TopOfFrame,
+ "TopOfInset" | "TopInset" => R::TopInset,
+ _ => R::TopOfPage,
+ }
+}
+
/// Text Frame Options from `TextFramePreference` elements: each attribute from the first that sets it.
fn text_frame_options(prefs: &[&El]) -> TextFrameOptions {
let e = Prefs(prefs);
diff --git a/crates/idml/src/tests/frame_grid.rs b/crates/idml/src/tests/frame_grid.rs
index 93c081377..99f57b4ea 100644
--- a/crates/idml/src/tests/frame_grid.rs
+++ b/crates/idml/src/tests/frame_grid.rs
@@ -6,6 +6,12 @@ const NS: &str = r#"xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/pack
/// 14 pt increment; its four paragraphs align to the grid. The frame's top is the page's top, so
/// the grid lines are 6 + n·14 pt down from the frame top whatever the grid is measured from.
fn frame_grid_doc() -> Document {
+ frame_grid_doc_relative(None)
+}
+
+/// [`frame_grid_doc`] with `BaselineFrameGridRelativeOption` set to `relative` when given.
+fn frame_grid_doc_relative(relative: Option<&str>) -> Document {
+ let relative = relative.map(|r| format!(r#" BaselineFrameGridRelativeOption="{r}""#)).unwrap_or_default();
let designmap = format!(
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Document {NS} Self="d" StoryList="s1" Name="grid.indd"><idPkg:Graphic src="Resources/Graphic.xml"/><idPkg:Styles src="Resources/Styles.xml"/><idPkg:Preferences src="Resources/Preferences.xml"/><Layer Self="L1" Name="Layer 1" Visible="true" Locked="false"/><idPkg:Spread src="Spreads/Spread_sp1.xml"/><idPkg:Story src="Stories/Story_s1.xml"/></Document>"#
@@ -17,7 +23,7 @@ fn frame_grid_doc() -> Document {
.collect();
let spread = format!(
r#"<idPkg:Spread {NS}><Spread Self="sp1" PageCount="1" ItemTransform="1 0 0 1 0 0"><Page Self="p1" GeometricBounds="0 0 600 400" ItemTransform="1 0 0 1 0 -300"/>
-<TextFrame Self="t1" ParentStory="s1" PreviousTextFrame="n" NextTextFrame="n" ItemLayer="L1" ItemTransform="1 0 0 1 0 -300"><Properties><PathGeometry><GeometryPathType PathOpen="false"><PathPointArray>{pts}</PathPointArray></GeometryPathType></PathGeometry></Properties><TextFramePreference InsetSpacing="0"/><BaselineFrameGridOption UseCustomBaselineFrameGrid="true" StartingOffsetForBaselineFrameGrid="6" BaselineFrameGridIncrement="14"/></TextFrame>
+<TextFrame Self="t1" ParentStory="s1" PreviousTextFrame="n" NextTextFrame="n" ItemLayer="L1" ItemTransform="1 0 0 1 0 -300"><Properties><PathGeometry><GeometryPathType PathOpen="false"><PathPointArray>{pts}</PathPointArray></GeometryPathType></PathGeometry></Properties><TextFramePreference InsetSpacing="0"/><BaselineFrameGridOption UseCustomBaselineFrameGrid="true" StartingOffsetForBaselineFrameGrid="6" BaselineFrameGridIncrement="14"{relative}/></TextFrame>
</Spread></idPkg:Spread>"#
);
let story = format!(
@@ -46,7 +52,7 @@ fn baselines(d: &Document) -> Vec<f64> {
fn custom_frame_grid_sets_lines_from_its_start_by_its_increment() {
let d = frame_grid_doc();
let grid = d.spreads[0].items[0].text_frame().unwrap().options.baseline_grid;
- assert_eq!(grid, Some(designcraft_doc::FrameBaselineGrid { start: 6.0, increment: 14.0 }));
+ assert_eq!(grid, Some(designcraft_doc::FrameBaselineGrid::new(6.0, 14.0)));
let b = baselines(&d);
assert_eq!(b.len(), 4, "{b:?}");
for y in &b {
@@ -69,3 +75,24 @@ fn custom_frame_grid_round_trips() {
assert_eq!(grid(&back), grid(&d));
assert_eq!(baselines(&back), baselines(&d));
}
+
+#[test]
+fn custom_frame_grid_relative_to_round_trips() {
+ use designcraft_doc::FrameGridRelative as R;
+ let relative = |d: &Document| d.spreads[0].items[0].text_frame().unwrap().options.baseline_grid.map(|g| g.relative_to);
+ for (attr, want) in [
+ ("TopOfPageOfBaselineFrameGridRelativeOption", R::TopOfPage),
+ ("TopOfMarginOfBaselineFrameGridRelativeOption", R::TopMargin),
+ ("TopOfFrameOfBaselineFrameGridRelativeOption", R::TopOfFrame),
+ ("TopOfInsetOfBaselineFrameGridRelativeOption", R::TopInset),
+ ("TopOfInset", R::TopInset),
+ ("SomethingNew", R::TopOfPage),
+ ] {
+ let d = frame_grid_doc_relative(Some(attr));
+ assert_eq!(relative(&d), Some(want), "{attr}");
+ let back = import_idml(&export_idml(&d)).unwrap();
+ assert_eq!(relative(&back), Some(want), "{attr} after export");
+ }
+ // A frame without the attribute measures from the top of the page.
+ assert_eq!(relative(&frame_grid_doc()), Some(R::TopOfPage));
+}
diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs
index e9ad8ca60..5245e00be 100644
--- a/crates/ui-egui/src/dialogs.rs
+++ b/crates/ui-egui/src/dialogs.rs
@@ -527,6 +527,15 @@ fn seed_text_frame_options(app: &DesignApp, d: &mut Dialog) {
_ => ((inner - o.gutter * (n - 1.0)) / n).max(0.0),
};
let kind = |v: Value| v.as_str().unwrap_or_default().to_string();
+ // A frame without a custom baseline grid shows the document grid's start and increment.
+ let grid = o.baseline_grid.unwrap_or_else(|| {
+ let g = app.session.active().map(|s| s.doc.settings.baseline_grid.clone()).unwrap_or_default();
+ let relative_to = match g.relative_to {
+ designcraft_doc::GridRelative::TopOfPage => designcraft_doc::FrameGridRelative::TopOfPage,
+ designcraft_doc::GridRelative::TopMargin => designcraft_doc::FrameGridRelative::TopMargin,
+ };
+ designcraft_doc::FrameBaselineGrid { start: g.start, increment: g.increment, relative_to }
+ });
let shown = json!({
"columns": o.columns, "gutter": fm(o.gutter),
"columnsKind": kind(serde_json::to_value(o.columns_kind).unwrap_or_default()), "columnWidth": fm(width),
@@ -542,6 +551,8 @@ fn seed_text_frame_options(app: &DesignApp, d: &mut Dialog) {
"useMinimumHeight": o.auto_size_use_min_height, "minimumHeight": fm(o.auto_size_min_height),
"useMinimumWidth": o.auto_size_use_min_width, "minimumWidth": fm(o.auto_size_min_width),
"noLineBreaks": o.auto_size_no_line_breaks,
+ "customGrid": o.baseline_grid.is_some(), "gridStart": fm(grid.start), "gridIncrement": fm(grid.increment),
+ "gridRelativeTo": grid.relative_to.name(),
});
if let Value::Object(m) = &shown {
for (k, v) in m {
@@ -593,6 +604,28 @@ fn text_frame_options_dialog(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog)
text_field(ui, d, "firstBaselineMin", 70.0);
ui.end_row();
});
+ ui.add_space(8.0);
+ crate::rtl::label(ui, egui::RichText::new(tr("Baseline Grid")).font(semibold(12.0)));
+ check(ui, d, "customGrid", tr("Use Custom Baseline Grid"));
+ ui.add_enabled_ui(d.b("customGrid"), |ui| {
+ egui::Grid::new("tfo_grid").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {
+ crate::rtl::label(ui, tr("Start:"));
+ text_field(ui, d, "gridStart", 70.0);
+ ui.end_row();
+ crate::rtl::label(ui, tr("Relative To:"));
+ translated_combo(
+ &lang,
+ ui,
+ d,
+ "gridRelativeTo",
+ &[("page", "Top of Page"), ("margin", "Top Margin"), ("frame", "Top of Frame"), ("inset", "Top Inset")],
+ );
+ ui.end_row();
+ crate::rtl::label(ui, tr("Increment Every:"));
+ text_field(ui, d, "gridIncrement", 70.0);
+ ui.end_row();
+ });
+ });
}
"autosize" => auto_size(&lang, ui, d),
"rules" => column_rules(app, ui, d),
@@ -857,6 +890,30 @@ fn confirm_text_frame_options(app: &mut DesignApp, d: &mut Dialog) -> Result<Val
p.insert(key.into(), json!(d.m(key).filter(|v| *v >= 0.0).ok_or_else(|| bad(what))?));
}
}
+ // The custom baseline grid: off, or the fields the user changed (all of them when it is
+ // turned on, since it shows the document grid's).
+ let grid_keys = ["customGrid", "gridStart", "gridIncrement", "gridRelativeTo"];
+ if grid_keys.iter().any(|k| edited(d, k)) {
+ if d.b("customGrid") {
+ let all = edited(d, "customGrid");
+ let mut g = Map::new();
+ if all || edited(d, "gridStart") {
+ g.insert("start".into(), json!(d.m("gridStart").ok_or_else(|| bad("the baseline grid start is not a measure"))?));
+ }
+ if all || edited(d, "gridIncrement") {
+ g.insert(
+ "increment".into(),
+ json!(d.m("gridIncrement").filter(|v| *v > 0.0).ok_or_else(|| bad("the baseline grid increment is not a measure"))?),
+ );
+ }
+ if all || edited(d, "gridRelativeTo") {
+ g.insert("relativeTo".into(), json!(d.s("gridRelativeTo")));
+ }
+ p.insert("baselineGrid".into(), Value::Object(g));
+ } else {
+ p.insert("baselineGrid".into(), Value::Null);
+ }
+ }
if p.is_empty() {
return Ok(Value::Null);
}
@@ -8323,6 +8380,35 @@ mod tests {
assert_eq!((opts(&app).columns_kind, opts(&app).column_width), (designcraft_doc::ColumnsKind::FixedNumber, 120.0));
}
+ #[test]
+ fn text_frame_options_set_a_custom_baseline_grid_relative_to() {
+ use designcraft_doc::{FrameBaselineGrid, FrameGridRelative};
+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ app.run("file.new", json!({})).unwrap();
+ let r = app.run("frame.create", json!({"rect": [36, 36, 336, 236], "content": "text", "text": "Hello"})).unwrap();
+ let id = designcraft_doc::ItemId(r["id"].as_u64().unwrap());
+ let grid = |app: &DesignApp| app.session.doc().unwrap().doc.item(id).unwrap().text_frame().unwrap().options.baseline_grid;
+ let open = |app: &mut DesignApp, fields: &[(&str, Value)]| {
+ let mut d = Dialog::new("textFrameOptions", json!({}));
+ seed_text_frame_options(app, &mut d);
+ for (k, v) in fields {
+ d.fields.insert((*k).into(), v.clone());
+ }
+ app.ui.dialog = Some(d);
+ confirm(app)
+ };
+ app.run("selection.set", json!({"ids": [id.0]})).unwrap();
+ // Turned on, the grid takes the shown start and increment (the document grid's: 3p0 and 1p0).
+ open(&mut app, &[("customGrid", json!(true)), ("gridRelativeTo", json!("frame"))]).unwrap();
+ assert_eq!(grid(&app), Some(FrameBaselineGrid { start: 36.0, increment: 12.0, relative_to: FrameGridRelative::TopOfFrame }));
+ // The dialog shows the frame's grid; changing Relative To keeps its start and increment.
+ open(&mut app, &[("gridStart", json!("0p10"))]).unwrap();
+ open(&mut app, &[("gridRelativeTo", json!("inset"))]).unwrap();
+ assert_eq!(grid(&app), Some(FrameBaselineGrid { start: 10.0, increment: 12.0, relative_to: FrameGridRelative::TopInset }));
+ open(&mut app, &[("customGrid", json!(false))]).unwrap();
+ assert_eq!(grid(&app), None);
+ }
+
#[test]
fn text_frame_options_change_only_what_was_edited() {
let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
diff --git a/docs/typography-parity.md b/docs/typography-parity.md
index 12a9dd071..9d3f7d4d0 100644
--- a/docs/typography-parity.md
+++ b/docs/typography-parity.md
@@ -46,7 +46,7 @@ Fidelity: **unmeasured** unless stated.
| Leading | auto (120%), absolute, leading model | ✓ | ✓ | CJK leading models in cjk-typography.md |
| First baseline | ascent, cap height, x-height, leading, fixed, min | ✓ | ✓ | |
| Frame fit / overset | baseline of the last line must fit | descenders must fit | ~ | **differs** (#180): frames go overset where InDesign fits |
-| Baseline grid | document grid relative to the top of the page or each page's top margin; frame grids | ✓ | ✓ | |
+| Baseline grid | document grid relative to the top of the page or each page's top margin; frame grids relative to the top of the page, top margin, top of frame or top inset | ✓ | ✓ | |
| Vertical justification | top, centre, bottom, justify, paragraph spacing limit | ✓ | ✓ | |
| Text in shaped frames | lines follow oval, polygon and freeform frame outlines, one inset from the outline | ✓ | ~ | concave shapes set one slot per line (the widest); vertical justification and paragraph shading use the frame's rectangle (#646) |
| Columns, span / split columns | ✓ | ✓ | ✓ | split columns within a column (#295); text after a span flows below it (#276) |