Compare commits

...
Author SHA1 Message Date
Dylan M. Taylor 8a87c27990 fmt: format portable fit fixture 2026-11-15 06:15:48 +00:00
Dylan M. Taylor 7e01c6a93e test: choose a portable serialized fit scenario 2026-11-15 06:13:20 +00:00
Dylan M. Taylor a1292c91a1 test: make fit budget fixture portable 2026-11-15 05:55:03 +00:00
Dylan M. Taylor 175df0d437 test: pin fit layout test typography 2026-11-15 05:41:31 +00:00
Dylan M. Taylor 683985c57e test: stabilize fit one page layout fixtures 2026-11-15 05:13:08 +00:00
3d5a153e3d Keep TOC entries for tab-numbered headings on one line (#6738)
Fixes #6486

Co-authored-by: cute-johnny <269855522+cute-johnny@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 02:23:52 +01:00
Mex 52d17a91df M14: identify WordCraft correctly in the iframe title example (#6717)
Use word processor as the accessible iframe description instead of image editor.
2026-11-14 21:40:06 +01:00
4 changed files with 135 additions and 29 deletions
+25 -8
View File
@@ -67,13 +67,15 @@ pub fn toc_instr(v: &Value) -> String {
s
}
/// A TOC entry: the paragraph it points at, its level (0-based), its text, and the leading page
/// breaks of that paragraph (its page is where the text after them lands).
/// A TOC entry: the paragraph it points at, its level (0-based), its text, the leading page
/// breaks of that paragraph (its page is where the text after them lands), and, for a number
/// followed by a tab, how far the heading's text starts after where its number starts.
struct TocEntry {
path: Path,
level: u8,
text: String,
lead: usize,
number_gap: Option<f32>,
}
/// The headings of the body, in document order, as (body block, level 1–9, text, leading page
@@ -117,9 +119,13 @@ fn toc_entries(s: &Session, f: &FieldCode) -> Vec<TocEntry> {
.and_then(|n| counters.next_label(&s.doc.numbering, n.num, n.level))
.filter(|(label, def)| !label.is_empty() && !matches!(def.format, NumFormat::Bullet | NumFormat::None))
.map(|(label, def)| match def.suffix {
LevelSuffix::Tab => format!("{label}\t"),
LevelSuffix::Space => format!("{label} "),
LevelSuffix::Nothing => label,
LevelSuffix::Tab => {
let start = def.indent - def.hanging;
let gap = def.tab.filter(|t| *t > start).unwrap_or(def.indent) - start;
(format!("{label}\t"), Some(gap).filter(|g| g.is_finite() && *g > 0.0))
}
LevelSuffix::Space => (format!("{label} "), None),
LevelSuffix::Nothing => (label, None),
});
let style = p.props.style.as_deref().unwrap_or("Normal");
if style.starts_with("TOC") {
@@ -144,8 +150,9 @@ fn toc_entries(s: &Session, f: &FieldCode) -> Vec<TocEntry> {
if let Some(l) = by_style.or(by_outline).or(if hidden { None } else { by_heading }) {
let t = p.plain_text().replace(['\u{000C}', '\n', '\t'], " ").trim().to_string();
if !t.is_empty() {
let text = number.map_or_else(|| t.clone(), |n| format!("{n}{t}"));
v.push(TocEntry { path: path.clone(), level: l - 1, text, lead });
let text = number.as_ref().map_or_else(|| t.clone(), |(n, _)| format!("{n}{t}"));
let number_gap = number.as_ref().and_then(|(_, g)| *g);
v.push(TocEntry { path: path.clone(), level: l - 1, text, lead, number_gap });
}
}
if let Some(id) = &tc {
@@ -159,7 +166,7 @@ fn toc_entries(s: &Session, f: &FieldCode) -> Vec<TocEntry> {
let l = c.arg('l').and_then(|l| l.trim().parse::<u8>().ok()).unwrap_or(1).clamp(1, 9);
let text = c.args.first().map(|t| t.trim().to_string()).unwrap_or_default();
if (id.is_empty() || *id == kind) && (tc_levels.0..=tc_levels.1).contains(&l) && !text.is_empty() {
v.push(TocEntry { path: path.clone(), level: l - 1, text, lead: off });
v.push(TocEntry { path: path.clone(), level: l - 1, text, lead: off, number_gap: None });
}
}
}
@@ -595,6 +602,16 @@ fn regenerate_toc(s: &mut Session, leader: Option<TabLeader>, tabs: &[(String, V
para.mark = CharProps::default();
if e.text.contains('\t') {
para.props.tabs = tabs.iter().find(|(style, _)| Some(style) == para.props.style.as_ref()).map(|(_, tabs)| tabs.clone());
// Without a stop for the number (LibreOffice's Contents styles have only the page
// number's right stop), its tab would run to the page number: the entry gets a
// left stop as far after its indent as the heading's text is after its number.
let style = s.doc.styles.resolve_para(&para.props);
let has_stop =
style.tabs.iter().any(|t| t.pos < width - 1.0 && matches!(t.align, TabAlign::Left | TabAlign::Center | TabAlign::Decimal));
if let (None, false, Some(gap)) = (&para.props.tabs, has_stop, e.number_gap) {
let pos = style.indent_left.max(0.0) + gap;
para.props.tabs = (pos < width - 1.0).then(|| vec![TabStop { pos, align: TabAlign::Left, leader: TabLeader::None }]);
}
}
if show_page && sep.contains('\t') {
let right = TabStop { pos: width - 0.5, align: TabAlign::Right, leader };
+54 -20
View File
@@ -14,6 +14,14 @@ fn create_multiline_doc(lines: usize) -> Session {
Session::new(Document::from_text(&text))
}
/// Fit One Page boundary tests need stable glyph metrics across host font substitutes.
fn use_pagination_test_font(s: &mut Session) {
let defaults = &mut std::sync::Arc::make_mut(&mut s.doc.styles).default_chr;
defaults.font = Some(wordcraft_fonts::DEFAULT_FAMILY.into());
defaults.size = Some(12.0);
defaults.kern = Some(1.0);
}
#[test]
fn fit_one_page_fails_on_single_page() {
let mut s = create_multiline_doc(5);
@@ -122,6 +130,7 @@ fn fit_one_page_respects_step_pt() {
text.push_str(&format!("Line {i}: The quick brown fox jumps over the lazy dog.\n"));
}
let mut s = Session::new(Document::from_text(&text));
use_pagination_test_font(&mut s);
for b in &mut s.doc.body {
if let wordcraft_doc::Block::Para(p) = std::sync::Arc::make_mut(b) {
p.mark.size = Some(11.4);
@@ -130,6 +139,8 @@ fn fit_one_page_respects_step_pt() {
}
}
}
s.touch();
s.relayout();
assert_eq!(s.layout().pages.len(), 2, "must start as 2-page document at 11.4 pt");
// Both calls hold maxDeltaPt constant at 0.4 and disable spacing adjustments.
@@ -853,33 +864,56 @@ fn fit_one_page_tracks_reduced_complex_script_font_sizes() {
#[test]
fn fit_one_page_preserves_budget_across_document_serialization() {
let mut s = create_multiline_doc(27);
assert_eq!(s.layout().pages.len(), 2);
// Apply fit
let res = s.run("layout.fitOnePage", &json!({"maxDeltaPt": 0.5, "adjustSpacing": false}));
assert!(res.is_ok(), "fit must succeed: {res:?}");
// Find a two-page document that fits within this test's budget and has
// room for a small second overflow after serialization. Font metrics vary
// between CI hosts, so a fixed line count and added paragraph are brittle.
let mut fitted = None;
for lines in 20..=80 {
let mut candidate = create_multiline_doc(lines);
use_pagination_test_font(&mut candidate);
candidate.touch();
candidate.relayout();
if candidate.layout().pages.len() != 2 {
continue;
}
if candidate.run("layout.fitOnePage", &json!({"maxDeltaPt": 0.5, "adjustSpacing": false})).is_ok() {
let json_bytes = serde_json::to_vec(&candidate.doc).expect("serialization must succeed");
let reopened_doc: wordcraft_doc::Document = serde_json::from_slice(&json_bytes).expect("deserialization must succeed");
for extra_chars in 1..=64 {
let mut reopened = Session::new(reopened_doc.clone());
let extra_text = "x".repeat(extra_chars);
let extra_p = wordcraft_doc::Paragraph::with_text(
&extra_text,
CharProps { font: Some(wordcraft_fonts::DEFAULT_FAMILY.into()), size: Some(12.0), ..Default::default() },
);
reopened.doc.body.push(wordcraft_doc::para_block(extra_p));
reopened.touch();
reopened.relayout();
if reopened.layout().pages.len() <= 1 {
continue;
}
if reopened.run("layout.fitOnePage", &json!({"maxDeltaPt": 0.5, "adjustSpacing": false})).is_ok()
&& reopened.layout().pages.len() == 1
{
fitted = Some((candidate, reopened_doc, reopened));
break;
}
}
if fitted.is_some() {
break;
}
}
}
let (s, reopened_doc, mut s2) = fitted.expect("must find a portable two-step fit case within the cumulative budget");
assert_eq!(s.doc.fit_state.as_ref().map(|f| f.cum_delta), Some(0.5));
// Serialize and deserialize document (e.g. saving and reopening)
let json_bytes = serde_json::to_vec(&s.doc).expect("serialization must succeed");
let reopened_doc: wordcraft_doc::Document = serde_json::from_slice(&json_bytes).expect("deserialization must succeed");
// Verify fit_state is preserved outside custom properties
assert_eq!(reopened_doc.fit_state.as_ref().map(|f| f.cum_delta), Some(0.5));
assert!(reopened_doc.custom_props.is_empty(), "custom_props must remain empty");
// Reopen into a new session with additional spill
let mut s2 = Session::new(reopened_doc);
let extra_p = wordcraft_doc::Paragraph::with_text("Extra overflow paragraph.", CharProps::default());
s2.doc.body.push(wordcraft_doc::para_block(extra_p));
s2.touch();
s2.relayout();
// Second fit on reopened document preserves previous 0.5 delta, allowing only remaining 0.5 pt up to 1.0 cap
let res2 = s2.run("layout.fitOnePage", &json!({"maxDeltaPt": 0.5, "adjustSpacing": false}));
assert!(res2.is_ok(), "second fit within remaining budget must succeed");
// The second successful fit used only the remaining 0.5 pt on the reopened document.
assert_eq!(s2.doc.fit_state.as_ref().map(|f| f.cum_delta), Some(1.0));
assert_eq!(s2.layout().pages.len(), 1);
// Third fit exceeding the cumulative 1.0 limit must be refused
let res3 = s2.run("layout.fitOnePage", &json!({"maxDeltaPt": 0.5, "adjustSpacing": false}));
+55
View File
@@ -103,3 +103,58 @@ fn an_odt_bibliography_updates_from_its_citations_sources() {
assert!(text.iter().any(|t| t.contains("Kilns and Fire")), "{text:?}");
assert!(!text.iter().any(|t| t.contains("stale")), "{text:?}");
}
/// #6486: LibreOffice numbers headings through its outline style, the number followed by a tab,
/// and its Contents styles carry only the right-aligned dotted stop for the page number. After
/// Update Table, the tab after an entry's number stops near the number, not at the page-number
/// stop: the title stays at the left and each entry stays on one line.
#[test]
fn an_odt_toc_with_numbered_headings_keeps_its_entries_on_one_line() {
let outline = |level: u8, cm: f32| {
format!(
r#"<text:outline-level-style text:level="{level}" style:num-format="1" style:num-suffix="." text:display-levels="{level}"><style:list-level-properties text:list-level-position-and-space-mode="label-alignment"><style:list-level-label-alignment text:label-followed-by="listtab" text:list-tab-stop-position="{cm}cm" fo:text-indent="-{cm}cm" fo:margin-left="{cm}cm"/></style:list-level-properties></text:outline-level-style>"#
)
};
let contents = |n: u8, indent: f32| {
format!(
r#"<style:style style:name="Contents_20_{n}" style:display-name="Contents {n}" style:family="paragraph"><style:paragraph-properties fo:margin-left="{indent}cm"><style:tab-stops><style:tab-stop style:position="16.99cm" style:type="right" style:leader-style="dotted" style:leader-text="."/></style:tab-stops></style:paragraph-properties></style:style>"#
)
};
let styles = format!(
r#"<office:document-styles {NS}><office:styles>{}{}<text:outline-style style:name="Outline">{}{}</text:outline-style></office:styles><office:automatic-styles><style:page-layout style:name="pm1"><style:page-layout-properties fo:page-width="21.001cm" fo:page-height="29.7cm" fo:margin-left="2cm" fo:margin-right="2cm" fo:margin-top="2cm" fo:margin-bottom="2cm"/></style:page-layout></office:automatic-styles><office:master-styles><style:master-page style:name="Standard" style:page-layout-name="pm1"/></office:master-styles></office:document-styles>"#,
contents(1, 0.0),
contents(2, 0.499),
outline(1, 0.762),
outline(2, 1.016)
);
let content = format!(
r#"<office:document-content {NS}><office:body><office:text>
<text:table-of-content text:name="T"><text:table-of-content-source text:outline-level="2"/><text:index-body><text:p text:style-name="Contents_20_1">1. Planning<text:tab/>1</text:p><text:p text:style-name="Contents_20_2">1.1. Budget<text:tab/>1</text:p></text:index-body></text:table-of-content>
<text:h text:outline-level="1">Planning</text:h><text:p>Text.</text:p>
<text:h text:outline-level="2">Budget</text:h><text:p>More text.</text:p>
</office:text></office:body></office:document-content>"#
);
let mut z = craft_zip::Writer::new();
for (name, data) in [("mimetype", "application/vnd.oasis.opendocument.text"), ("styles.xml", styles.as_str()), ("content.xml", content.as_str())]
{
z.add(name, data.as_bytes(), craft_zip::Compression::Stored).unwrap();
}
let mut s = Session::new(io::open_bytes("toc.odt", &z.finish().unwrap()).unwrap());
s.run("references.updateToc", &json!({})).unwrap();
let layout = s.layout();
let mut checked = 0;
for (i, b) in s.doc.body.iter().enumerate() {
let Some(p) = b.as_para().filter(|p| p.props.style.as_deref().is_some_and(|st| st.starts_with("TOC") && st != "TOCHeading")) else {
continue;
};
let Some(tab) = p.text.find('\t') else { continue };
let pos = |off| wordcraft_doc::Pos { story: wordcraft_doc::StoryRef::Body, path: wordcraft_doc::Path::top(i), off };
let title = layout.caret(&pos(tab + 1)).unwrap();
let end = layout.caret(&pos(p.len())).unwrap();
assert!(p.plain_text().contains("Planning") || p.plain_text().contains("Budget"), "{:?}", p.text);
assert_eq!((title.page, title.top), (end.page, end.top), "{:?} wraps", p.text);
assert!(title.x < 200.0, "{:?}: the title starts at {}", p.text, title.x);
checked += 1;
}
assert_eq!(checked, 2);
}
+1 -1
View File
@@ -55,7 +55,7 @@ Local test: `python3 -m http.server 8765` inside the folder, then open http://lo
```html
<iframe
src="https://example.com/wordcraft/"
title="WordCraft image editor"
title="WordCraft word processor"
style="width: 100%; height: 720px; border: 0;"
allow="fullscreen; clipboard-read; clipboard-write"
allowfullscreen>