f-office-docx 0.2.4

DOCX model and Word's layout rules.
Documentation
//! The levels that the body's table of contents gives the paragraphs that it lists: by the
//! entries of its stored result, or by its switches when no stored entry links to a paragraph
//! of the body.

use std::collections::HashMap;

use crate::body::toc::{StoredEntry, TableOfContents};
use crate::body::{Block, Content, Paragraph, ParagraphId, all_paragraphs};
use crate::params;
use crate::styles::Styles;

/// The level from 0 of each paragraph of `blocks` that the table of contents `toc` lists, as
/// [`super::TextBlock::toc_level`] says; empty without a table of contents or when it lists
/// no paragraph.
pub(super) fn toc_levels(
    blocks: &[Block],
    styles: &Styles,
    toc: Option<&TableOfContents>,
) -> HashMap<ParagraphId, u8> {
    let Some(toc) = toc else {
        return HashMap::new();
    };
    let paragraphs = all_paragraphs(blocks);
    let stored = stored_levels(&paragraphs, styles, &toc.entries);
    if stored.is_empty() {
        switched_levels(&paragraphs, styles, toc)
    } else {
        stored
    }
}

/// The levels that the stored entries `entries` give the paragraphs whose bookmarks they link
/// to: the level of an entry's style `toc 1` to `toc 9`, or the top level for another style.
/// The first entry of a paragraph gives its level.
fn stored_levels(
    paragraphs: &[&Paragraph],
    styles: &Styles,
    entries: &[StoredEntry],
) -> HashMap<ParagraphId, u8> {
    // Word's bookmark names match without regard to case; the first start of a name counts.
    let mut bookmarks = HashMap::new();
    for paragraph in paragraphs {
        for content in paragraph.runs.iter().flat_map(|run| &run.content) {
            if let Content::Bookmark(name) = content {
                bookmarks.entry(name.to_lowercase()).or_insert(paragraph.id);
            }
        }
    }
    let mut out = HashMap::new();
    for entry in entries {
        if let Some(paragraph) = bookmarks.get(&entry.bookmark.to_lowercase()) {
            let level = entry_level(styles, entry.style.as_deref());
            out.entry(*paragraph).or_insert(level);
        }
    }
    out
}

/// The level from 0 of a stored entry whose paragraph has the style of ID `style`: `n - 1`
/// for the style named `toc n`, and 0 for any other style.
fn entry_level(styles: &Styles, style: Option<&str>) -> u8 {
    let Some(style) = style else {
        return 0;
    };
    (1..=params::BODY_TEXT_OUTLINE_LEVEL)
        .find(|level| {
            styles
                .id_of(&format!("toc {level}"))
                .eq_ignore_ascii_case(style)
        })
        .map_or(0, |level| level - 1)
}

/// The levels that the switches of `toc` give the paragraphs: of a style that `\t` names, of
/// an outline level in the range of `\o` or `\u`, or of a `TC` field that `\f` or `\l` lists,
/// in that order.
fn switched_levels(
    paragraphs: &[&Paragraph],
    styles: &Styles,
    toc: &TableOfContents,
) -> HashMap<ParagraphId, u8> {
    let switches = &toc.switches;
    let mut out = HashMap::new();
    for paragraph in paragraphs {
        let by_style = paragraph.props.style.as_deref().and_then(|style| {
            (switches.styles.iter())
                .find(|(name, _)| styles.id_of(name).eq_ignore_ascii_case(style))
                .map(|(_, level)| *level)
        });
        let by_outline = (switches.outline_levels.as_ref()).and_then(|range| {
            super::outline_level(paragraph, styles).filter(|level| range.contains(level))
        });
        let by_field = (switches.entry_fields.as_ref()).and_then(|fields| {
            (toc.entry_fields.iter())
                .find(|field| field.paragraph == paragraph.id && fields.lists(field))
                .map(|field| field.level)
        });
        if let Some(level) = by_style.or(by_outline).or(by_field) {
            out.insert(paragraph.id, level);
        }
    }
    out
}