f-office-docx 0.2.4

DOCX model and Word's layout rules.
Documentation
//! The hyperlinks of the text: where a `w:hyperlink` or a field that links goes, and the marks
//! on the runs where a link's text starts and ends, which the text map reads. Layout does not
//! read them.

use f_office_opc::Relationship;
use f_office_xml::{Document, NodeId};

use super::drawings::{DrawingMut, visit_drawings};
use super::{Block, field_code, paragraphs_mut};
use crate::ns::{R, W};

/// Where a hyperlink goes (**Link target**).
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum LinkTarget {
    /// An address outside the document, such as a web page, a mail address or a file, with
    /// the location in it after a `#` when the link names one.
    External(String),
    /// A bookmark of the document, by its name.
    Bookmark(String),
}

/// A hyperlink of the text, as the reader reads it (**Hyperlink**): a `w:hyperlink`, or a field
/// that links (`HYPERLINK`, and `REF` or `PAGEREF` with `\h`).
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct Hyperlink {
    /// The relationship of the part that names its external address (`r:id`), which
    /// [`give_addresses`] turns into `address`.
    pub(crate) relationship: Option<String>,
    /// Its external address: the target of its relationship, or the address of a `HYPERLINK`
    /// field.
    pub(crate) address: Option<String>,
    /// The bookmark that it goes to (`w:anchor`, the `\l` switch of a `HYPERLINK` field, or the
    /// bookmark of a `REF` or `PAGEREF` field), or with an address the location there.
    pub(crate) anchor: Option<String>,
    /// Its tooltip (`w:tooltip`, or the `\o` switch of a `HYPERLINK` field).
    pub(crate) tooltip: Option<String>,
}

impl Hyperlink {
    /// The hyperlink of the `w:hyperlink` element `node`.
    pub(crate) fn of_element(doc: &Document, node: NodeId) -> Self {
        let value = |namespace, name: &str| {
            doc.attribute(node, Some(namespace), name)
                .filter(|value| !value.is_empty())
                .map(str::to_owned)
        };
        Self {
            relationship: value(R, "id"),
            address: None,
            anchor: value(W, "anchor"),
            tooltip: value(W, "tooltip"),
        }
    }

    /// The hyperlink of a field of the code `code`, when the field links: a `HYPERLINK` field
    /// with its address, its `\l` location and its `\o` tooltip, or a `REF` or `PAGEREF` field
    /// with `\h`, which goes to its bookmark.
    pub(crate) fn of_code(code: &str) -> Option<Self> {
        if !field_code::links(code) {
            return None;
        }
        let kind = field_code::kind(code)?;
        if !kind.eq_ignore_ascii_case("HYPERLINK") {
            let bookmark = field_code::words_after_kind(code).next()?;
            let bookmark = field_code::word_argument(bookmark);
            return (!bookmark.is_empty() && !bookmark.starts_with('\\')).then(|| Self {
                anchor: Some(bookmark.to_owned()),
                ..Self::default()
            });
        }
        let mut link = Self::default();
        let mut rest = field_code::after_kind(code);
        loop {
            let word = field_code::quoted_argument(rest);
            if word.text.is_empty() && word.rest.trim().is_empty() {
                break;
            }
            rest = word.rest;
            let switch = word.text.strip_prefix('\\').map(str::to_ascii_lowercase);
            let Some(switch) = switch else {
                if link.address.is_none() && !word.text.is_empty() {
                    link.address = Some(word.text.to_owned());
                }
                continue;
            };
            // The switches with an argument: the location, the tooltip and the target frame.
            if matches!(switch.as_str(), "l" | "o" | "t") {
                let argument = field_code::quoted_argument(rest);
                rest = argument.rest;
                let text = Some(argument.text.to_owned()).filter(|text| !text.is_empty());
                match switch.as_str() {
                    "l" => link.anchor = text,
                    "o" => link.tooltip = text,
                    _ => {}
                }
            }
        }
        Some(link)
    }

    /// Where it goes: its external address, with its location after a `#`, or else its
    /// bookmark; none when it names neither.
    pub(crate) fn target(&self) -> Option<LinkTarget> {
        match (&self.address, &self.anchor) {
            (Some(address), Some(anchor)) => {
                Some(LinkTarget::External(format!("{address}#{anchor}")))
            }
            (Some(address), None) => Some(LinkTarget::External(address.clone())),
            (None, Some(anchor)) => Some(LinkTarget::Bookmark(anchor.clone())),
            (None, None) => None,
        }
    }
}

/// A mark on a run where a hyperlink's text starts or ends (**Link mark**).
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum LinkMark {
    /// The text of the hyperlink starts at the run: the run after a `w:hyperlink`'s start, or
    /// the run of a linking field's separator, and the runs after it are the link's text.
    Start(Box<Hyperlink>),
    /// The text of the innermost open hyperlink ends at the run.
    End,
}

/// Gives the hyperlinks of `blocks`, a story of one part, with those of its text boxes, the
/// external addresses that the part's `relationships` name.
pub(crate) fn give_addresses(blocks: &mut [Block], relationships: &[Relationship]) {
    give_own_addresses(blocks, relationships);
    visit_drawings(blocks, &mut |drawing| {
        if let DrawingMut::Floating(floating) = drawing {
            give_own_addresses(&mut floating.blocks, relationships);
        }
    });
}

/// Gives the hyperlinks of the paragraphs of `blocks` and of their table cells, but not of
/// their text boxes, the external addresses that `relationships` name.
fn give_own_addresses(blocks: &mut [Block], relationships: &[Relationship]) {
    for paragraph in paragraphs_mut(blocks) {
        for run in &mut paragraph.runs {
            for mark in &mut run.links {
                if let LinkMark::Start(link) = mark
                    && let Some(id) = link.relationship.take()
                {
                    // A hyperlink's relationship names an external target, which
                    // `Relationship::by_id` leaves out.
                    link.address = relationships
                        .iter()
                        .find(|relationship| relationship.id == id)
                        .map(|relationship| relationship.target.clone());
                }
            }
        }
    }
}

#[cfg(test)]
mod tests;