Skip to main content

jubarte_edit/edit/
controls.rs

1// SPDX-FileCopyrightText: 2026 Jandira Technologies, LLC
2//
3// SPDX-License-Identifier: Apache-2.0
4
5//! `fill_control`: write a value into one content control (`w:sdt`) of the
6//! body. The control is found by id, tag or alias; its `w:sdtPr` survives
7//! (only `w:showingPlcHdr` goes, as when a person types into it) and its
8//! `w:sdtContent` is replaced by one run, or one paragraph for a block-level
9//! control.
10//!
11//! Backs the `fill_control` plan operation: [`ControlSelector`] is its
12//! `control` field, and exactly one of `text`, `choice`, `checked`, `date`
13//! names the value.
14
15use serde::{Deserialize, Serialize};
16
17use super::tracked::{COMMENT_RANGE_END, RANGE_ENDS, RANGE_STARTS};
18use super::{
19    EditError, EditOutcome, ExistingRevisions, Resolution, Resolved, Transaction, check_text, err,
20    excerpt,
21};
22use crate::namespaces::{W, W14};
23use crate::xmllinq::{Dom, NodeId, XNamespace};
24
25/// Which content control to fill; every form must match exactly one.
26#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
27#[serde(untagged, deny_unknown_fields)]
28pub enum ControlSelector {
29    /// `"p3.cc0"` or `"cc1"`, the same as `{"id": "p3.cc0"}`.
30    Name(String),
31    /// `{"id": "p3.cc0"}`.
32    Id {
33        /// `ccN` (a block control) or `pN.ccK` (one in paragraph `pN`)
34        /// from `inspect`'s `controls`.
35        id: String,
36    },
37    /// `{"tag": "Name"}`: the control's `w:tag`.
38    Tag {
39        /// The tag, matched exactly.
40        tag: String,
41    },
42    /// `{"alias": "Full name"}`: the control's `w:alias` (its title).
43    Alias {
44        /// The alias, matched exactly.
45        alias: String,
46    },
47}
48
49/// What a resolved fill writes.
50#[derive(Clone, Debug)]
51#[doc(hidden)]
52pub enum FillValue {
53    /// Plain text (a `text` value or a choice's display text).
54    Text(String),
55    /// A checkbox state and the glyph that shows it.
56    Checked { on: bool, glyph: char, font: String },
57    /// `w:fullDate` and the text in the control's date format.
58    Date { full: String, text: String },
59}
60
61/// The value fields of a `fill_control` operation.
62pub(super) struct FillRequest<'a> {
63    pub(super) control: &'a ControlSelector,
64    pub(super) text: Option<&'a str>,
65    pub(super) choice: Option<&'a str>,
66    pub(super) checked: Option<bool>,
67    pub(super) date: Option<&'a str>,
68}
69
70/// Kinds a fill cannot write.
71const UNFILLABLE: &[&str] = &["picture", "group", "repeating", "building_block"];
72
73impl Transaction<'_> {
74    pub(super) fn resolve_fill_control(
75        &self,
76        id: &str,
77        request: &FillRequest<'_>,
78    ) -> Resolution<Vec<Resolved>> {
79        let mut outcome = EditOutcome {
80            id: id.to_string(),
81            kind: String::new(),
82            status: String::new(),
83            paragraph: None,
84            matches: 0,
85            context: None,
86            comment_id: None,
87            code: None,
88            message: None,
89            anchor_given: None,
90            anchor_read_as: None,
91            near: None,
92            candidates: Vec::new(),
93        };
94        let fail = |code: &str, msg: String, outcome: EditOutcome| {
95            Box::new((err(code, Some(id), msg), outcome))
96        };
97        let control = match self.select_control(request.control) {
98            Ok(n) => n,
99            Err((code, msg, matches)) => {
100                outcome.matches = matches;
101                return Err(fail(code, msg, outcome));
102            }
103        };
104        let record = &self.control_records[control];
105        outcome.matches = 1;
106        outcome.paragraph = record.paragraph_ids.first().cloned();
107        let dom = &self.opened.dom;
108        let sdt = self.controls[control];
109        if self.plan.existing_revisions == ExistingRevisions::Keep {
110            return Err(fail(
111                "UNSUPPORTED_STRUCTURE",
112                "fill_control is not emitted as tracked changes under existing_revisions \"keep\" yet; accept or reject the existing revisions first".into(),
113                outcome,
114            ));
115        }
116        if record.locked {
117            return Err(fail(
118                "LOCKED_CONTROL",
119                format!("{} is locked against editing (w:lock)", record.id),
120                outcome,
121            ));
122        }
123        if UNFILLABLE.contains(&record.kind.as_str()) {
124            return Err(fail(
125                "UNSUPPORTED_STRUCTURE",
126                format!(
127                    "{} is a {} control, which fill_control cannot write",
128                    record.id, record.kind
129                ),
130                outcome,
131            ));
132        }
133        let content = dom.element(sdt, &W::sdt_content());
134        let block = dom.ancestors(sdt, Some(&W::p())).is_empty();
135        if let Some(content) = content
136            && dom.elements(content, None).into_iter().any(|c| {
137                [W::tr(), W::tc(), W::tbl()]
138                    .iter()
139                    .any(|n| dom.name_is(c, n))
140            })
141        {
142            return Err(fail(
143                "UNSUPPORTED_STRUCTURE",
144                format!("{} holds table rows, cells or tables", record.id),
145                outcome,
146            ));
147        }
148        if let Some(content) = content
149            && ["footnoteReference", "endnoteReference", "commentReference"]
150                .iter()
151                .any(|r| !dom.descendants(content, Some(&W::name(r))).is_empty())
152        {
153            return Err(fail(
154                "UNSUPPORTED_STRUCTURE",
155                format!(
156                    "{} holds a footnote, endnote or comment reference the fill would remove",
157                    record.id
158                ),
159                outcome,
160            ));
161        }
162        if block && content.is_some_and(|c| !dom.descendants(c, Some(&W::sect_pr())).is_empty()) {
163            return Err(fail(
164                "UNSUPPORTED_STRUCTURE",
165                format!("{} holds a section break", record.id),
166                outcome,
167            ));
168        }
169        let value = match self.fill_value(record, sdt, request) {
170            Ok(value) => value,
171            Err(msg) => return Err(fail("INVALID_EDIT", msg, outcome)),
172        };
173        let new_text = match &value {
174            FillValue::Text(text) | FillValue::Date { text, .. } => text.clone(),
175            FillValue::Checked { glyph, .. } => glyph.to_string(),
176        };
177        outcome.context = Some(format!(
178            "{{⌷ {} \"{}\"→\"{}\"}}",
179            record.id,
180            excerpt(&record.text, 40),
181            excerpt(&new_text, 40)
182        ));
183        let paragraphs = self
184            .paragraph_nodes
185            .iter()
186            .enumerate()
187            .filter(|&(g, _)| {
188                let (story, local) = self.paragraph_story[g];
189                story == 0
190                    && record
191                        .paragraph_ids
192                        .iter()
193                        .any(|p| p == &crate::ids::paragraph_id("body", local))
194            })
195            .map(|(g, _)| g)
196            .collect();
197        Ok((
198            vec![Resolved::FillControl {
199                control,
200                paragraphs,
201                block,
202                value,
203            }],
204            outcome,
205        ))
206    }
207
208    /// The control index, or `(code, message, matches)`.
209    fn select_control(
210        &self,
211        selector: &ControlSelector,
212    ) -> Result<usize, (&'static str, String, usize)> {
213        let records = &self.control_records;
214        let origin = self.origin.as_ref();
215        // Ids are the source's: once the plan's revisions are settled, a
216        // control id names the source control the author read.
217        let ids: Vec<&str> = match origin {
218            Some(origin) => origin.control_ids().iter().map(String::as_str).collect(),
219            None => records.iter().map(|r| r.id.as_str()).collect(),
220        };
221        let name_of = |n: usize| -> &str {
222            origin
223                .and_then(|o| o.control_source(n))
224                .unwrap_or(records[n].id.as_str())
225        };
226        let (what, hits): (String, Vec<usize>) = match selector {
227            ControlSelector::Name(given) | ControlSelector::Id { id: given } => {
228                if let Some(refused) = super::origin::source_only(given) {
229                    return Err(("ANCHOR_NOT_FOUND", refused, 0));
230                }
231                // The spec's cell spelling `t0.row1.cell2.cc0` names a
232                // control of the cell's first paragraph, `p40.cc0`.
233                let spelled = self.cell_control(given);
234                let id = spelled.as_ref().unwrap_or(given);
235                match origin {
236                    Some(origin) => match origin.control(id) {
237                        Some(Ok(n)) => return Ok(n),
238                        Some(Err(gone)) => return Err(("ANCHOR_NOT_FOUND", gone, 0)),
239                        None => {}
240                    },
241                    None => {
242                        if let Some(n) = ids.iter().position(|c| c == id) {
243                            return Ok(n);
244                        }
245                    }
246                }
247                // The expired `body:sdt:N` names the Nth control: refused,
248                // with the id it now has.
249                let settled = id
250                    .strip_prefix("body:sdt:")
251                    .and_then(|n| n.parse::<usize>().ok())
252                    .and_then(|n| ids.get(n))
253                    .map(|c| format!("; the settled spelling is {c}"))
254                    .unwrap_or_default();
255                let known = match ids.as_slice() {
256                    [] => "the body has none".to_string(),
257                    [only] => format!("the body has {only}"),
258                    [first, .., last] => {
259                        format!("the body has {} (first {first}, last {last})", ids.len())
260                    }
261                };
262                return Err((
263                    "ANCHOR_NOT_FOUND",
264                    format!("no content control {given:?}; {known}{settled}"),
265                    0,
266                ));
267            }
268            ControlSelector::Tag { tag } => (
269                format!("tag {tag:?}"),
270                (0..records.len())
271                    .filter(|&n| records[n].tag.as_deref() == Some(tag))
272                    .collect(),
273            ),
274            ControlSelector::Alias { alias } => (
275                format!("alias {alias:?}"),
276                (0..records.len())
277                    .filter(|&n| records[n].alias.as_deref() == Some(alias))
278                    .collect(),
279            ),
280        };
281        match hits.as_slice() {
282            [n] => Ok(*n),
283            [] => Err((
284                "ANCHOR_NOT_FOUND",
285                format!("no content control has {what}"),
286                0,
287            )),
288            many => Err((
289                "AMBIGUOUS_ANCHOR",
290                format!(
291                    "{} content controls have {what}: {}; select one by id",
292                    many.len(),
293                    many.iter()
294                        .map(|&n| name_of(n))
295                        .collect::<Vec<_>>()
296                        .join(", ")
297                ),
298                many.len(),
299            )),
300        }
301    }
302
303    /// `t0.row1.cell2[.pK].ccN` as the `pM.ccN` of the paragraph its
304    /// cell spelling names; `None` for any other id.
305    fn cell_control(&self, id: &str) -> Option<String> {
306        let (paragraph, n) = id.rsplit_once(".cc")?;
307        n.parse::<usize>().ok()?;
308        if !paragraph.starts_with('t') {
309            return None;
310        }
311        let ids = match &self.origin {
312            Some(origin) => origin.ids(),
313            None => self.ids(),
314        };
315        let p = ids.paragraph_id(paragraph)?.ok()?;
316        Some(format!("{p}.cc{n}"))
317    }
318
319    /// Check the value form against the control and compute what to write.
320    fn fill_value(
321        &self,
322        record: &crate::inspect::ContentControl,
323        sdt: NodeId,
324        request: &FillRequest<'_>,
325    ) -> Result<FillValue, String> {
326        let dom = &self.opened.dom;
327        let given = [
328            request.text.is_some(),
329            request.choice.is_some(),
330            request.checked.is_some(),
331            request.date.is_some(),
332        ]
333        .iter()
334        .filter(|&&g| g)
335        .count();
336        if given != 1 {
337            return Err(format!(
338                "fill_control takes exactly one of text, choice, checked, date (got {given})"
339            ));
340        }
341        let kind = record.kind.as_str();
342        let form_for = |kind: &str| match kind {
343            "drop_down" => "choice",
344            "checkbox" => "checked",
345            "date" => "date",
346            _ => "text",
347        };
348        let wrong = |form: &str| {
349            format!(
350                "{} is a {kind} control; fill it with {}, not {form}",
351                record.id,
352                form_for(kind)
353            )
354        };
355        let pr = dom.element(sdt, &W::sdt_pr());
356        if let Some(text) = request.text {
357            if matches!(kind, "drop_down" | "checkbox" | "date") {
358                return Err(wrong("text"));
359            }
360            check_text(text)?;
361            return Ok(FillValue::Text(text.to_string()));
362        }
363        if let Some(choice) = request.choice {
364            if !matches!(kind, "drop_down" | "combo_box") {
365                return Err(wrong("choice"));
366            }
367            let list = pr.and_then(|pr| {
368                dom.element(pr, &W::name("dropDownList"))
369                    .or_else(|| dom.element(pr, &W::name("comboBox")))
370            });
371            let items = list.map_or_else(Vec::new, |l| dom.elements(l, Some(&W::name("listItem"))));
372            for item in items {
373                let value = dom.attribute(item, &W::name("value"));
374                let display = dom.attribute(item, &W::name("displayText"));
375                if value == Some(choice) || display == Some(choice) {
376                    let shown = display.or(value).unwrap_or(choice);
377                    return Ok(FillValue::Text(shown.to_string()));
378                }
379            }
380            return Err(format!(
381                "choice {choice:?} is not one of {} for {}",
382                record.choices.join(", "),
383                record.id
384            ));
385        }
386        if let Some(on) = request.checked {
387            if kind != "checkbox" {
388                return Err(wrong("checked"));
389            }
390            let checkbox = pr.and_then(|pr| dom.element(pr, &W14::name("checkbox")));
391            let state = checkbox.and_then(|c| {
392                dom.element(
393                    c,
394                    &W14::name(if on { "checkedState" } else { "uncheckedState" }),
395                )
396            });
397            let glyph = state
398                .and_then(|s| dom.attribute(s, &W14::name("val")))
399                .and_then(|v| u32::from_str_radix(v, 16).ok())
400                .and_then(char::from_u32)
401                .filter(|c| !c.is_control())
402                .unwrap_or(if on { '\u{2612}' } else { '\u{2610}' });
403            let font = state
404                .and_then(|s| dom.attribute(s, &W14::name("font")))
405                .unwrap_or("MS Gothic")
406                .to_string();
407            return Ok(FillValue::Checked { on, glyph, font });
408        }
409        let date = request.date.unwrap_or_default();
410        if kind != "date" {
411            return Err(wrong("date"));
412        }
413        let (y, m, d) = parse_date(date)
414            .ok_or_else(|| format!("date {date:?} is not a calendar date in YYYY-MM-DD form"))?;
415        let pattern = pr
416            .and_then(|pr| dom.element(pr, &W::date()))
417            .and_then(|e| dom.element(e, &W::name("dateFormat")))
418            .and_then(|f| dom.attribute(f, &W::val()))
419            .unwrap_or("yyyy-MM-dd");
420        Ok(FillValue::Date {
421            full: format!("{date}T00:00:00Z"),
422            text: format_date(pattern, y, m, d),
423        })
424    }
425
426    /// Fills against each other and against paragraph operations.
427    pub(super) fn check_control_conflicts(&self, deleted: &[usize]) -> Result<(), EditError> {
428        let dom = &self.opened.dom;
429        let fills: Vec<(usize, usize, &Vec<usize>, bool)> = self
430            .resolved
431            .iter()
432            .filter_map(|(i, r)| match r {
433                Resolved::FillControl {
434                    control,
435                    paragraphs,
436                    block,
437                    ..
438                } => Some((*i, *control, paragraphs, *block)),
439                _ => None,
440            })
441            .collect();
442        for (k, &(i, control, _, _)) in fills.iter().enumerate() {
443            for &(_, other, _, _) in &fills[..k] {
444                if other == control {
445                    return Err(self.conflict(i, "fills a control another operation fills"));
446                }
447                let (a, b) = (self.controls[control], self.controls[other]);
448                if dom.ancestors(a, None).contains(&b) || dom.ancestors(b, None).contains(&a) {
449                    return Err(
450                        self.conflict(i, "fills a control nested in another filled control")
451                    );
452                }
453            }
454        }
455        for &(i, _, paragraphs, block) in &fills {
456            for (j, r) in &self.resolved {
457                let touched: Vec<usize> = match r {
458                    Resolved::Text { para, .. }
459                    | Resolved::CommentRange { para, .. }
460                    | Resolved::FormatParagraph { para, .. }
461                        if block =>
462                    {
463                        vec![*para]
464                    }
465                    Resolved::InsertParagraph { anchor, like, .. } if block => {
466                        vec![*anchor, *like]
467                    }
468                    Resolved::InsertTable { anchor, .. } if block => vec![*anchor],
469                    Resolved::List { paras, .. } if block => paras.clone(),
470                    Resolved::CommentSpan { para, last, .. } if block => (*para..=*last).collect(),
471                    Resolved::MergeParagraphs { para, next, .. } => vec![*para, *next],
472                    _ => Vec::new(),
473                };
474                if touched.iter().any(|p| paragraphs.contains(p)) {
475                    return Err(self.conflict(
476                        i.max(*j),
477                        "fills a control whose paragraph another operation changes",
478                    ));
479                }
480            }
481            if paragraphs.iter().any(|p| deleted.contains(p)) {
482                return Err(self.conflict(i, "fills a control in a deleted paragraph"));
483            }
484        }
485        Ok(())
486    }
487
488    /// Apply step 1b: write every fill. Text edits (step 1) never touch
489    /// content-control runs, so the controls' nodes are still in place.
490    pub(super) fn apply_fills(&mut self) {
491        let fills: Vec<(usize, bool, FillValue)> = self
492            .resolved
493            .iter()
494            .filter_map(|(_, r)| match r {
495                Resolved::FillControl {
496                    control,
497                    block,
498                    value,
499                    ..
500                } => Some((*control, *block, value.clone())),
501                _ => None,
502            })
503            .collect();
504        for (control, block, value) in fills {
505            fill(&mut self.opened.dom, self.controls[control], block, &value);
506        }
507    }
508}
509
510/// Write `value` into the control `sdt`.
511fn fill(dom: &mut Dom, sdt: NodeId, block: bool, value: &FillValue) {
512    let pr = match dom.element(sdt, &W::sdt_pr()) {
513        Some(pr) => pr,
514        None => {
515            let pr = dom.new_element(W::sdt_pr());
516            dom.add_first(sdt, pr);
517            pr
518        }
519    };
520    if let Some(plc) = dom.element(pr, &W::name("showingPlcHdr")) {
521        dom.remove(plc);
522    }
523    let content = match dom.element(sdt, &W::sdt_content()) {
524        Some(content) => content,
525        None => {
526            let content = dom.new_element(W::sdt_content());
527            dom.add(sdt, content);
528            content
529        }
530    };
531    let rpr = first_run_properties(dom, content);
532    let text = match value {
533        FillValue::Text(text) => text.clone(),
534        FillValue::Date { full, text } => {
535            if let Some(date) = dom.element(pr, &W::date()) {
536                dom.set_attribute_value(date, &W::name("fullDate"), Some(full));
537            }
538            text.clone()
539        }
540        FillValue::Checked { on, glyph, font } => {
541            if let Some(checkbox) = dom.element(pr, &W14::name("checkbox")) {
542                let checked = match dom.element(checkbox, &W14::name("checked")) {
543                    Some(checked) => checked,
544                    None => {
545                        let checked = dom.new_element(W14::name("checked"));
546                        dom.add_first(checkbox, checked);
547                        checked
548                    }
549                };
550                dom.set_attribute_value(
551                    checked,
552                    &W14::name("val"),
553                    Some(if *on { "1" } else { "0" }),
554                );
555            }
556            let rpr = rpr.unwrap_or_else(|| dom.new_element(W::r_pr()));
557            set_glyph_font(dom, rpr, font);
558            return write_content(dom, content, block, Some(rpr), &glyph.to_string());
559        }
560    };
561    write_content(dom, content, block, rpr, &text);
562}
563
564/// The range markers under `content`, detached: `(starts, ends)` in
565/// document order. A fill puts the starts before its new run and the ends
566/// after it, so bookmarks, comment ranges, permissions and move ranges keep
567/// both halves: the markers an insertion beside them reads (#1156).
568fn take_range_markers(dom: &mut Dom, content: NodeId) -> (Vec<NodeId>, Vec<NodeId>) {
569    let (mut starts, mut ends) = (Vec::new(), Vec::new());
570    for node in dom.descendants(content, None) {
571        let Some(name) = dom.name(node) else { continue };
572        if name.namespace_name() != W::URI {
573            continue;
574        }
575        if RANGE_STARTS.contains(&name.local_name()) {
576            starts.push(node);
577        } else if RANGE_ENDS.contains(&name.local_name()) || name.local_name() == COMMENT_RANGE_END
578        {
579            ends.push(node);
580        }
581    }
582    for &node in starts.iter().chain(&ends) {
583        dom.remove(node);
584    }
585    (starts, ends)
586}
587
588/// Replace `content`'s children with one run (or one paragraph holding it,
589/// keeping the first paragraph's properties, for a block-level control).
590/// Range markers inside the old content surround the new run.
591fn write_content(dom: &mut Dom, content: NodeId, block: bool, rpr: Option<NodeId>, text: &str) {
592    let (starts, ends) = take_range_markers(dom, content);
593    let r = dom.new_element(W::r());
594    if let Some(rpr) = rpr
595        && !dom.elements(rpr, None).is_empty()
596    {
597        dom.add(r, rpr);
598    }
599    let t = dom.new_element(W::t());
600    dom.set_attribute_value(t, &XNamespace::xml().name("space"), Some("preserve"));
601    dom.add_text(t, text);
602    dom.add(r, t);
603    let ppr = dom
604        .descendants(content, Some(&W::p()))
605        .first()
606        .and_then(|&first| dom.element(first, &W::p_pr()))
607        .map(|ppr| dom.clone_subtree(ppr));
608    dom.remove_nodes(content);
609    let holder = if block {
610        let p = dom.new_element(W::p());
611        if let Some(ppr) = ppr {
612            for child in dom.elements(ppr, None) {
613                if dom.name_is(child, &W::p_pr_change()) || dom.name_is(child, &W::sect_pr()) {
614                    dom.remove(child);
615                }
616            }
617            dom.add(p, ppr);
618        }
619        dom.add(content, p);
620        p
621    } else {
622        content
623    };
624    for node in starts.into_iter().chain([r]).chain(ends) {
625        dom.add(holder, node);
626    }
627}
628
629/// A copy of the first run's properties in `content`, without the
630/// placeholder style and revision marks.
631fn first_run_properties(dom: &mut Dom, content: NodeId) -> Option<NodeId> {
632    let source = dom
633        .descendants(content, Some(&W::r()))
634        .into_iter()
635        .find_map(|r| dom.element(r, &W::r_pr()))?;
636    let rpr = dom.clone_subtree(source);
637    for child in dom.elements(rpr, None) {
638        let placeholder = dom.name_is(child, &W::name("rStyle"))
639            && dom.attribute(child, &W::val()) == Some("PlaceholderText");
640        if placeholder
641            || dom.name_is(child, &W::r_pr_change())
642            || dom.name_is(child, &W::ins())
643            || dom.name_is(child, &W::del())
644        {
645            dom.remove(child);
646        }
647    }
648    Some(rpr)
649}
650
651/// Point every script's font at `font`, as Word does for a checkbox glyph.
652fn set_glyph_font(dom: &mut Dom, rpr: NodeId, font: &str) {
653    let fonts = match dom.element(rpr, &W::name("rFonts")) {
654        Some(fonts) => fonts,
655        None => {
656            let fonts = dom.new_element(W::name("rFonts"));
657            super::insert_rpr_child(dom, rpr, fonts);
658            fonts
659        }
660    };
661    for slot in ["ascii", "hAnsi", "eastAsia", "cs"] {
662        dom.set_attribute_value(fonts, &W::name(slot), Some(font));
663    }
664    dom.set_attribute_value(fonts, &W::name("hint"), Some("eastAsia"));
665}
666
667/// `YYYY-MM-DD` with a real calendar day.
668fn parse_date(date: &str) -> Option<(i32, u32, u32)> {
669    let bytes = date.as_bytes();
670    if bytes.len() != 10 || bytes[4] != b'-' || bytes[7] != b'-' {
671        return None;
672    }
673    let digits = |s: &str| -> Option<u32> {
674        s.bytes()
675            .all(|b| b.is_ascii_digit())
676            .then(|| s.parse().ok())?
677    };
678    let y = i32::try_from(digits(&date[..4])?).ok()?;
679    let m = digits(&date[5..7])?;
680    let d = digits(&date[8..])?;
681    ((1..=12).contains(&m) && (1..=days_in_month(y, m)).contains(&d)).then_some((y, m, d))
682}
683
684fn days_in_month(y: i32, m: u32) -> u32 {
685    match m {
686        2 if (y % 4 == 0 && y % 100 != 0) || y % 400 == 0 => 29,
687        2 => 28,
688        4 | 6 | 9 | 11 => 30,
689        _ => 31,
690    }
691}
692
693/// Day of the week, 0 = Sunday (Sakamoto's method).
694fn weekday(y: i32, m: u32, d: u32) -> usize {
695    const T: [i32; 12] = [0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4];
696    let y = if m < 3 { y - 1 } else { y };
697    let w = y + y / 4 - y / 100 + y / 400 + T[m as usize - 1] + d as i32;
698    w.rem_euclid(7) as usize
699}
700
701const MONTHS: [&str; 12] = [
702    "January",
703    "February",
704    "March",
705    "April",
706    "May",
707    "June",
708    "July",
709    "August",
710    "September",
711    "October",
712    "November",
713    "December",
714];
715const DAYS: [&str; 7] = [
716    "Sunday",
717    "Monday",
718    "Tuesday",
719    "Wednesday",
720    "Thursday",
721    "Friday",
722    "Saturday",
723];
724
725/// Format a date with a Word date pattern (`yyyy`, `yy`, `MMMM`, `MMM`,
726/// `MM`, `M`, `dddd`, `ddd`, `dd`, `d`; `'quoted'` text is literal; other
727/// characters are copied). Names are English; `w:lid` is not consulted.
728fn format_date(pattern: &str, y: i32, m: u32, d: u32) -> String {
729    let chars: Vec<char> = pattern.chars().collect();
730    let mut out = String::new();
731    let mut i = 0;
732    while i < chars.len() {
733        let c = chars[i];
734        if c == '\'' {
735            let close = chars[i + 1..].iter().position(|&q| q == '\'');
736            let end = close.map_or(chars.len(), |p| i + 1 + p);
737            out.extend(&chars[i + 1..end]);
738            i = end + 1;
739            continue;
740        }
741        let run = chars[i..].iter().take_while(|&&x| x == c).count();
742        match c {
743            'y' => {
744                if run >= 3 {
745                    out.push_str(&format!("{y:04}"));
746                } else {
747                    out.push_str(&format!("{:02}", y.rem_euclid(100)));
748                }
749            }
750            'M' => match run {
751                1 => out.push_str(&m.to_string()),
752                2 => out.push_str(&format!("{m:02}")),
753                3 => out.push_str(&MONTHS[m as usize - 1][..3]),
754                _ => out.push_str(MONTHS[m as usize - 1]),
755            },
756            'd' => match run {
757                1 => out.push_str(&d.to_string()),
758                2 => out.push_str(&format!("{d:02}")),
759                3 => out.push_str(&DAYS[weekday(y, m, d)][..3]),
760                _ => out.push_str(DAYS[weekday(y, m, d)]),
761            },
762            _ => out.extend(std::iter::repeat_n(c, run)),
763        }
764        i += run;
765    }
766    out
767}
768
769#[cfg(test)]
770#[cfg_attr(all(coverage_nightly, test), coverage(off))]
771mod tests {
772    use super::*;
773
774    #[test]
775    fn dates_parse_only_real_days() {
776        assert_eq!(parse_date("2024-02-29"), Some((2024, 2, 29)));
777        assert_eq!(parse_date("2000-02-29"), Some((2000, 2, 29)));
778        for bad in [
779            "2023-02-29",
780            "1900-02-29",
781            "2026-13-01",
782            "2026-00-10",
783            "2026-04-31",
784            "2026-1-01",
785            "2026/10/02",
786            "+026-10-02",
787            "abcd-10-02",
788        ] {
789            assert_eq!(parse_date(bad), None, "{bad}");
790        }
791    }
792
793    #[test]
794    fn word_date_patterns_format_in_english() {
795        assert_eq!(format_date("yyyy-MM-dd", 2026, 10, 2), "2026-10-02");
796        assert_eq!(format_date("d MMMM yyyy", 2027, 1, 5), "5 January 2027");
797        assert_eq!(format_date("M/d/yy", 2026, 3, 9), "3/9/26");
798        assert_eq!(format_date("dddd, MMM dd", 2026, 10, 2), "Friday, Oct 02");
799        assert_eq!(format_date("ddd 'the' d", 2026, 10, 4), "Sun the 4");
800        assert_eq!(format_date("'open", 2026, 10, 4), "open");
801        assert_eq!(format_date("yyyy.MM", 2026, 10, 4), "2026.10");
802    }
803}
804
805#[cfg(test)]
806#[cfg_attr(all(coverage_nightly, test), coverage(off))]
807mod control_source_boundary_tests {
808    use super::*;
809    use crate::edit::{EditPlan, apply_plan, preview_plan};
810    use crate::opc::PartFs;
811    fn parse(body: &str) -> (Dom, NodeId) {
812        let mut dom = Dom::new();
813        let document = dom.parse_xdocument(&format!("<w:document xmlns:w='{}' xmlns:w14='{}'><w:body>{body}<w:sectPr><w:pgSz w:w='12240' w:h='15840'/></w:sectPr></w:body></w:document>",W::URI,W14::URI));
814        let root = dom.root(document).unwrap();
815        (dom, root)
816    }
817    fn package(body: &str) -> Vec<u8> {
818        let (dom, root) = parse(body);
819        let mut pkg = PartFs::open(include_bytes!(
820            "../../../../tests/fixtures/word_probes/tokens/cell_a.docx"
821        ))
822        .unwrap();
823        pkg.set_part(
824            "word/document.xml",
825            dom.serialize_element(root).into_bytes(),
826        );
827        pkg.to_zip().unwrap()
828    }
829    fn plan(operations: &str) -> EditPlan {
830        EditPlan::from_json(&format!(r#"{{"schema_version":1,"author":"Editor","date":"2001-02-03T04:05:06Z","operations":[{operations}]}}"#)).unwrap()
831    }
832    #[test]
833    fn filling_empty_authored_controls_creates_only_missing_metadata_and_payload() {
834        for block in [false, true] {
835            for properties in [false, true] {
836                for content in [false, true] {
837                    let props = if properties {
838                        "<w:sdtPr><w:alias w:val='Clause'/><w:tag w:val='stable-clause'/><w:id w:val='31'/><w:richText/></w:sdtPr>"
839                    } else {
840                        ""
841                    };
842                    let content = if content { "<w:sdtContent/>" } else { "" };
843                    let sdt = format!("<w:sdt>{props}{content}</w:sdt>");
844                    let body = if block {
845                        sdt
846                    } else {
847                        format!("<w:p>{sdt}</w:p>")
848                    };
849                    let (mut dom, root) = parse(&body);
850                    let sdt = dom.descendants(root, Some(&W::sdt()))[0];
851                    let parent = dom.parent(sdt);
852                    let metadata = dom
853                        .element(sdt, &W::sdt_pr())
854                        .map(|pr| dom.serialize_element(pr));
855                    fill(&mut dom, sdt, block, &FillValue::Text("new clause".into()));
856                    assert_eq!(dom.parent(sdt), parent);
857                    let pr = dom.element(sdt, &W::sdt_pr()).unwrap();
858                    assert_eq!(dom.elements(sdt, Some(&W::sdt_pr())).len(), 1);
859                    if let Some(metadata) = metadata {
860                        assert_eq!(dom.serialize_element(pr), metadata);
861                    } else {
862                        assert!(dom.elements(pr, None).is_empty());
863                    }
864                    let content = dom.element(sdt, &W::sdt_content()).unwrap();
865                    assert_eq!(dom.elements(sdt, Some(&W::sdt_content())).len(), 1);
866                    let holder = if block {
867                        assert_eq!(dom.elements(content, None).len(), 1);
868                        dom.element(content, &W::p()).unwrap()
869                    } else {
870                        content
871                    };
872                    let runs = dom.elements(holder, Some(&W::r()));
873                    assert_eq!(runs.len(), 1);
874                    assert!(dom.element(runs[0], &W::r_pr()).is_none());
875                    let text = dom.element(runs[0], &W::t()).unwrap();
876                    assert_eq!(dom.value(text), "new clause");
877                    assert_eq!(
878                        dom.attribute(text, &XNamespace::xml().name("space")),
879                        Some("preserve")
880                    );
881                    assert_eq!(dom.value(root), "new clause");
882                }
883            }
884        }
885    }
886    #[test]
887    fn public_block_controls_refuse_section_loss_and_both_nested_fill_orders() {
888        let content = "<w:sdt><w:sdtPr><w:tag w:val='Section'/><w:richText/></w:sdtPr><w:sdtContent><w:p><w:pPr><w:sectPr><w:pgSz w:w='10000' w:h='14000'/></w:sectPr></w:pPr><w:r><w:t>owned section</w:t></w:r></w:p></w:sdtContent></w:sdt><w:p><w:r><w:t>independent tail</w:t></w:r></w:p>";
889        let source = package(content);
890        let operation =
891            plan(r#"{"kind":"fill_control","control":{"tag":"Section"},"text":"replacement"}"#);
892        assert_eq!(
893            apply_plan(&source, &operation).unwrap_err().code,
894            "UNSUPPORTED_STRUCTURE"
895        );
896        assert_eq!(
897            preview_plan(&source, &operation).unwrap_err().code,
898            "UNSUPPORTED_STRUCTURE"
899        );
900        let nested = "<w:sdt><w:sdtPr><w:tag w:val='Outer'/><w:richText/></w:sdtPr><w:sdtContent><w:p><w:sdt><w:sdtPr><w:tag w:val='Inner'/><w:text/></w:sdtPr><w:sdtContent><w:r><w:t>owned nested clause</w:t></w:r></w:sdtContent></w:sdt></w:p></w:sdtContent></w:sdt><w:p/>";
901        let source = package(nested);
902        for first in ["Outer", "Inner"] {
903            let second = if first == "Outer" { "Inner" } else { "Outer" };
904            let operations = plan(&format!(
905                r#"{{"kind":"fill_control","control":{{"tag":"{first}"}},"text":"first"}},{{"kind":"fill_control","control":{{"tag":"{second}"}},"text":"second"}}"#
906            ));
907            assert_eq!(
908                apply_plan(&source, &operations).unwrap_err().code,
909                "OVERLAPPING_EDITS"
910            );
911            assert_eq!(
912                preview_plan(&source, &operations).unwrap_err().code,
913                "OVERLAPPING_EDITS"
914            );
915        }
916        let source_pkg = PartFs::open(&source).unwrap();
917        let (dom, root) = parse(nested);
918        assert_eq!(
919            source_pkg.part_string("word/document.xml").unwrap(),
920            dom.serialize_element(root)
921        );
922    }
923}
924
925#[cfg(test)]
926#[cfg_attr(all(coverage_nightly, test), coverage(off))]
927mod calendar_branch_tests {
928    use super::*;
929
930    #[test]
931    fn dates_need_the_shape_and_a_real_day() {
932        assert_eq!(parse_date("2024-02-29"), Some((2024, 2, 29)));
933        assert_eq!(parse_date("2023-02-29"), None);
934        assert_eq!(parse_date("2000-02-29"), Some((2000, 2, 29)));
935        assert_eq!(parse_date("1900-02-29"), None);
936        assert_eq!(parse_date("2026-04-31"), None);
937        assert_eq!(parse_date("2026-13-01"), None);
938        for bad in [
939            "2026-1-01",
940            "2026/01/01",
941            "2026-01/01",
942            "20x6-01-01",
943            "2026-01-0x",
944        ] {
945            assert_eq!(parse_date(bad), None, "{bad}");
946        }
947    }
948
949    #[test]
950    fn weekdays_count_from_sunday() {
951        assert_eq!(weekday(2026, 1, 4), 0);
952        assert_eq!(weekday(2026, 2, 2), 1);
953        assert_eq!(weekday(2026, 11, 18), 3);
954        assert_eq!(weekday(2000, 3, 1), 3);
955    }
956
957    #[test]
958    fn run_properties_drop_the_placeholder_style_and_marks() {
959        let mut dom = Dom::new();
960        let doc = dom.parse_xdocument(&format!(
961            r#"<w:sdtContent xmlns:w="{}"><w:r><w:rPr><w:rStyle w:val="PlaceholderText"/><w:b/><w:rStyle w:val="Strong"/><w:ins w:id="1"/><w:del w:id="2"/><w:rPrChange w:id="3"/></w:rPr><w:t>x</w:t></w:r></w:sdtContent>"#,
962            W::URI
963        ));
964        let content = dom.root(doc).unwrap();
965        let rpr = first_run_properties(&mut dom, content).unwrap();
966        let kept: Vec<String> = dom
967            .elements(rpr, None)
968            .into_iter()
969            .map(|c| {
970                let local = dom.name(c).unwrap().local_name().to_string();
971                match dom.attribute(c, &W::val()) {
972                    Some(v) => format!("{local}={v}"),
973                    None => local,
974                }
975            })
976            .collect();
977        assert_eq!(kept, ["b", "rStyle=Strong"]);
978        let empty = dom.parse_xdocument(&format!(
979            r#"<w:sdtContent xmlns:w="{}"><w:r><w:t>x</w:t></w:r></w:sdtContent>"#,
980            W::URI
981        ));
982        let content = dom.root(empty).unwrap();
983        assert_eq!(first_run_properties(&mut dom, content), None);
984    }
985}