Compare commits

...
Author SHA1 Message Date
autocraft-bot[bot] 95cff4e66a Merge pull request #8121 2026-12-02 07:39:07 +00:00
autocraft-bot[bot] e862c6ad51 Merge pull request #7880 2026-12-02 07:39:07 +00:00
Rees 14111658d1 fix(layout): keep indented tables readable in Read Mode (#8063) 2026-11-29 16:16:44 +01:00
codeiouandClaude Opus 5.5 6078524793 Content controls: a chosen entry or date takes the control's formatting
An entry chosen from a drop-down list or combo box, or a date set in a
date picker, in place of the control's placeholder kept the
placeholder's formatting minus its style: in a form whose placeholders
are grey and boxed, the values stayed grey and boxed, on the page and in
the saved file. Text typed over the placeholder has taken the control's
own run properties (w:sdtPr/w:rPr, ECMA-376 §17.5.2.27) since #3116.

The typing path's rule moves, unchanged, into replacement_props, and
Choose List Item, Set Date and Toggle Check Box use it too (a file can
mark a check box as showing its placeholder). A control that already
holds a value keeps that value's formatting, as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 01:45:54 +10:00
5 changed files with 151 additions and 12 deletions
+21 -11
View File
@@ -279,6 +279,22 @@ fn content_base(s: &Session, r: &ControlRange) -> CharProps {
content_props(&s.doc, &props)
}
/// The formatting of what replaces a control's content: typed text, a list entry, a date or a
/// check box's mark. In place of the placeholder, that is the control's own run properties
/// (ECMA-376 §17.5.2.27), else the content's formatting without the placeholder style: the
/// showing placeholder's own character style is that style, whatever a producer called it (Word
/// localizes only the id; another program may localize the name too). In place of a value, it is
/// that value's formatting.
fn replacement_props(s: &Session, r: &ControlRange) -> CharProps {
if !r.control.showing_placeholder {
return content_base(s, r);
}
match &r.control.run_props {
Some(rp) => content_props(&s.doc, rp),
None => CharProps { style: None, ..content_base(s, r) },
}
}
// ---------------------------------------------------------------------------------------------
// Rules for typing and deleting
@@ -327,14 +343,8 @@ pub fn prepare_edit(s: &mut Session) -> Result<Option<CharProps>, CmdError> {
if !r.control.showing_placeholder || !r.contains(&b) {
return Ok(None);
}
// Text typed in place of the placeholder takes the control's own run properties (Word, and
// ECMA-376 §17.5.2.27), else the content's formatting without the placeholder style. The
// showing placeholder's own character style is that style, whatever a producer called it
// (Word localizes only the id; another program may localize the name too).
let props = match &r.control.run_props {
Some(rp) => content_props(&s.doc, rp),
None => CharProps { style: None, ..content_base(s, &r) },
};
// Text typed in place of the placeholder takes the control's own run properties, as in Word.
let props = replacement_props(s, &r);
s.sel = Selection { anchor: r.content_start(), focus: r.end.clone() };
if let Some(c) = s.doc.control_mut(&r.start) {
c.showing_placeholder = false;
@@ -666,7 +676,7 @@ fn toggle_check_box(s: &mut Session, v: &Value) -> CmdResult {
}
let now = p::bool(v, "value").unwrap_or(!checked);
let (ch, font) = if now { (*checked_char, checked_font) } else { (*unchecked_char, unchecked_font) };
let mut props = content_base(s, &r);
let mut props = replacement_props(s, &r);
if !font.is_empty() {
props.font = Some(font.clone());
}
@@ -696,7 +706,7 @@ fn choose_item(s: &mut Session, v: &Value) -> CmdResult {
return Err(CmdError::Params("give index, value or text".into()));
};
let Some(item) = item.cloned() else { return Err(CmdError::Params("no such entry".into())) };
let props = content_base(s, &r);
let props = replacement_props(s, &r);
let end = set_content(s, &r, &item.display, &props)?;
if let Some(c) = s.doc.control_mut(&r.start) {
if let ControlKind::ComboBox { last_value, .. } | ControlKind::DropDown { last_value, .. } = &mut c.kind {
@@ -716,7 +726,7 @@ fn set_date(s: &mut Session, v: &Value) -> CmdResult {
}
let (y, m, d) = p::str(v, "date").and_then(parse_date).ok_or_else(|| CmdError::Params("date: YYYY-MM-DD".into()))?;
let text = format_date_value(format, y, m, d);
let props = content_base(s, &r);
let props = replacement_props(s, &r);
let end = set_content(s, &r, &text, &props)?;
if let Some(c) = s.doc.control_mut(&r.start) {
if let ControlKind::Date { full_date, .. } = &mut c.kind {
@@ -0,0 +1,90 @@
//! A value chosen in a content control in place of its placeholder (a list entry, a date, a check
//! box's mark) takes the control's own run properties (`w:sdtPr/w:rPr`, ECMA-376 Part 1
//! §17.5.2.27), as typed text does (#3116). Packages are hand-written: the controls WordCraft
//! inserts carry no run properties.
use serde_json::json;
use wordcraft_doc::StoryRef;
use wordcraft_doc::props::CharProps;
use wordcraft_engine::Session;
use wordcraft_engine::io::{open_bytes, save_bytes};
const W: &str =
r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml""#;
const RELS: &str = r#"xmlns="http://schemas.openxmlformats.org/package/2006/relationships""#;
const TYPE: &str = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
/// Opens a package with `body` and a grey Placeholder Text character style.
fn open(body: &str) -> wordcraft_doc::Document {
let styles = r#"<w:style w:type="character" w:styleId="PlaceholderText"><w:name w:val="Placeholder Text"/><w:rPr><w:color w:val="808080"/></w:rPr></w:style>"#;
let mut zip = craft_zip::Writer::new();
for (name, value) in [
(
"_rels/.rels",
format!(r#"<Relationships {RELS}><Relationship Id="rId1" Type="{TYPE}/officeDocument" Target="word/document.xml"/></Relationships>"#),
),
(
"word/_rels/document.xml.rels",
format!(r#"<Relationships {RELS}><Relationship Id="rId1" Type="{TYPE}/styles" Target="styles.xml"/></Relationships>"#),
),
("word/document.xml", format!(r#"<w:document {W}><w:body>{body}</w:body></w:document>"#)),
("word/styles.xml", format!(r#"<w:styles {W}>{styles}</w:styles>"#)),
] {
zip.add(name, value.as_bytes(), craft_zip::Compression::Deflated).unwrap();
}
open_bytes("form.docx", &zip.finish().unwrap()).unwrap()
}
/// A paragraph holding a control of `kind` (its `w:sdtPr` type element) tagged `tag`. Its
/// placeholder is grey and boxed; its run properties ask for blue Source Serif 4 at 14 pt.
fn control(tag: &str, kind: &str) -> String {
let own = r#"<w:rPr><w:rFonts w:ascii="Source Serif 4" w:hAnsi="Source Serif 4"/><w:color w:val="1F4E79"/><w:sz w:val="28"/></w:rPr>"#;
let shown =
r#"<w:rPr><w:rStyle w:val="PlaceholderText"/><w:color w:val="808080"/><w:bdr w:val="single" w:sz="4" w:space="0" w:color="808080"/></w:rPr>"#;
format!(
r#"<w:p><w:sdt><w:sdtPr>{own}<w:tag w:val="{tag}"/><w:showingPlcHdr/>{kind}</w:sdtPr><w:sdtContent><w:r>{shown}<w:t>Choose</w:t></w:r></w:sdtContent></w:sdt></w:p>"#
)
}
/// The formatting of the control's first character, and the control's own run properties.
fn formatting(d: &wordcraft_doc::Document, tag: &str) -> (CharProps, CharProps) {
let r = d.control_ranges(StoryRef::Body).into_iter().find(|r| r.control.tag == tag).unwrap();
let at = r.content_start();
(d.para_at(&at).unwrap().props_of_char(at.off).clone(), r.control.run_props.clone().unwrap())
}
/// What shows of a run's formatting here: colour, font, size and box.
fn look(p: &CharProps) -> impl PartialEq + std::fmt::Debug {
(p.color, p.font.clone(), p.size, p.border)
}
/// A list entry, a date or a check box's mark chosen in place of the placeholder takes the
/// control's run properties, as typed text does; it kept the placeholder's grey and box. A saved
/// file keeps the value's formatting.
#[test]
fn choosing_over_a_placeholder_takes_the_controls_formatting() {
let entries = r#"<w:listItem w:displayText="Small" w:value="S"/><w:listItem w:displayText="Large" w:value="L"/>"#;
let choices = [
("size", format!("<w:dropDownList>{entries}</w:dropDownList>"), "developer.chooseItem", json!({"control": "size", "index": 1})),
(
"due",
r#"<w:date><w:dateFormat w:val="d MMMM yyyy"/></w:date>"#.into(),
"developer.setDate",
json!({"control": "due", "date": "2026-12-01"}),
),
("ok", r#"<w14:checkbox><w14:checked w14:val="0"/></w14:checkbox>"#.into(), "developer.toggleCheckBox", json!({"control": "ok"})),
];
let body: String = choices.iter().map(|(tag, kind, ..)| control(tag, kind)).collect();
let mut s = Session::new(open(&body));
for (tag, _, command, params) in &choices {
let (placeholder, own) = formatting(&s.doc, tag);
assert_ne!(look(&placeholder), look(&own), "{tag}: the placeholder is formatted apart from its control");
s.run(command, params).unwrap_or_else(|e| panic!("{command}: {e}"));
assert_eq!(look(&formatting(&s.doc, tag).0), look(&own), "{tag}: {command} gives the control's run properties");
}
let saved = open_bytes("form.docx", &save_bytes("form.docx", &s.doc).unwrap()).unwrap();
for (tag, ..) in &choices {
let (value, own) = formatting(&saved, tag);
assert_eq!(look(&value), look(&own), "{tag}: the saved value keeps the control's run properties");
}
}
+1
View File
@@ -1,4 +1,5 @@
mod comment_ids;
mod content_controls;
mod date_fields;
mod macro_packages;
mod odt_charts;
+2 -1
View File
@@ -589,7 +589,8 @@ fn table_frame(ctx: &mut Ctx, t: &Table, avail: f32, depth: usize, style: Option
indent - first_cell_left_margin_in(t, margins_def)
};
// The reading view fits the table into what the start offset leaves of the column, mirrored or not (#7988).
let room = (avail - start_offset.max(0.0)).max(1.0);
// Keep at least half the fitted width so the position clamp can reduce an excessive indent (#8063).
let room = (avail - start_offset.max(0.0)).max(acc.min(avail) / 2.0).max(1.0);
if ctx.opts.view == ViewMode::Read && acc > room && !matches!(t.props.align, Some(Align::Center | Align::Right)) {
let k = room / acc;
colx.iter_mut().for_each(|c| *c *= k);
+37
View File
@@ -685,6 +685,43 @@ fn reading_layout_fits_a_wide_table_to_the_column() {
}
}
#[test]
fn reading_layout_preserves_table_width_with_an_excessive_indent() {
crate::test_fonts();
for rtl in [false, true] {
let frame = |indent, view| {
let mut doc = Document::from_text("Before.");
doc.settings.compat_mode = 15;
let mut table = Table::new(2, 4, 468.0);
table.props.fixed = true;
table.props.indent = Some(indent);
table.props.bidi_visual = rtl;
doc.insert_block(StoryRef::Body, &Path::top(1), Block::Table(table)).unwrap();
let opts = LayoutOptions { view, web_width: 360.0, read_height: 600.0, ..Default::default() };
let layout = layout(&doc, &mut LayoutCache::new(), &opts);
let page = &layout.pages[0];
let cells: Vec<_> = page.items.iter().filter_map(|item| if let Placed::Cell { rect, .. } = item { Some(*rect) } else { None }).collect();
assert_eq!(cells.len(), 8);
let (left, right) = cells.iter().fold((f32::INFINITY, f32::NEG_INFINITY), |(l, r), cell| (l.min(cell.x), r.max(cell.x + cell.w)));
let start = if rtl { page.body.x + page.body.w - right } else { left - page.body.x };
(start, right - left, page.body.w)
};
let (start, width, column) = frame(0.0, ViewMode::Read);
let (indented, _, _) = frame(36.0, ViewMode::Read);
assert!((indented - start - 36.0).abs() < 0.5, "ordinary indent is preserved");
for indent in [400.0, column - 12.0] {
let (start, fitted, _) = frame(indent, ViewMode::Read);
assert!(fitted + 0.5 >= width / 2.0, "rtl {rtl}, indent {indent}: table is only {fitted} pt wide vs {width} pt without indent");
assert!(start >= -0.5 && start + fitted <= column + 0.5, "table fits within the reading column");
assert!(start < indent, "reduce the indent to make space for the table");
}
let (print_start, print_width, _) = frame(0.0, ViewMode::Print);
let (print_indented, print_indented_width, _) = frame(400.0, ViewMode::Print);
assert!((print_indented - print_start - 400.0).abs() < 0.5, "print layout keeps the authored indent");
assert!((print_indented_width - print_width).abs() < 0.5, "print layout keeps the table width");
}
}
#[test]
fn hit_and_caret_agree() {
crate::test_fonts();