mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-25 20:22:39 +00:00
Merge pull request #2347 from OPUZZLES/opuzzles/docx-screentips
craft-docx: preserve bounded hyperlink ScreenTips
This commit is contained in:
@@ -165,6 +165,12 @@ impl Flavor {
|
||||
}
|
||||
}
|
||||
|
||||
/// Bound the tooltip at both file boundaries. A whole link can have many formatted runs.
|
||||
fn bounded_link_tooltip(text: &str) -> Option<&str> {
|
||||
const MAX_BYTES: usize = 4096;
|
||||
text.get(..text.floor_char_boundary(MAX_BYTES)).filter(|tip| !tip.is_empty())
|
||||
}
|
||||
|
||||
/// Errors from reading or writing a DOCX package.
|
||||
#[derive(Debug, thiserror::Error, Clone, PartialEq)]
|
||||
pub enum DocxError {
|
||||
|
||||
@@ -48,6 +48,7 @@ const MAX_FORM: usize = 64 * 1024;
|
||||
#[derive(Clone, Default)]
|
||||
pub struct RunCtx {
|
||||
link: Option<String>,
|
||||
link_tooltip: Option<std::sync::Arc<str>>,
|
||||
ins: Option<u32>,
|
||||
del: Option<u32>,
|
||||
}
|
||||
|
||||
@@ -23,12 +23,16 @@ impl Reader<'_> {
|
||||
let mut c = ctx.clone();
|
||||
let url = k.attr("r:id").and_then(|id| rels.by_id(id)).map(|r| r.target.trim().to_string()).filter(|u| !u.is_empty());
|
||||
let anchor = k.attr("w:anchor").filter(|a| !a.is_empty());
|
||||
c.link = match (url, anchor) {
|
||||
let link = match (url, anchor) {
|
||||
(Some(u), Some(a)) => Some(format!("{u}#{a}")),
|
||||
(Some(u), None) => Some(u),
|
||||
(None, Some(a)) => Some(format!("#{a}")),
|
||||
(None, None) => ctx.link.clone(),
|
||||
(None, None) => None,
|
||||
};
|
||||
if let Some(link) = link {
|
||||
c.link = Some(link);
|
||||
c.link_tooltip = k.attr("w:tooltip").and_then(crate::bounded_link_tooltip).map(std::sync::Arc::from);
|
||||
}
|
||||
self.read_inline_children(sc, pb, k, rels, &c, depth + 1);
|
||||
}
|
||||
"w:ins" | "w:moveTo" => {
|
||||
@@ -133,6 +137,7 @@ impl Reader<'_> {
|
||||
fn run_props(&mut self, rpr: &El, ctx: &RunCtx) -> CharProps {
|
||||
let mut p = self.pc.rpr(rpr);
|
||||
p.link = ctx.link.clone();
|
||||
p.link_tooltip = ctx.link_tooltip.clone();
|
||||
p.ins = ctx.ins;
|
||||
p.del = ctx.del;
|
||||
p.fmt_change = self.rpr_change(rpr);
|
||||
@@ -140,7 +145,7 @@ impl Reader<'_> {
|
||||
}
|
||||
|
||||
fn run_props_none(&self, ctx: &RunCtx) -> CharProps {
|
||||
CharProps { link: ctx.link.clone(), ins: ctx.ins, del: ctx.del, ..Default::default() }
|
||||
CharProps { link: ctx.link.clone(), link_tooltip: ctx.link_tooltip.clone(), ins: ctx.ins, del: ctx.del, ..Default::default() }
|
||||
}
|
||||
|
||||
fn read_run(&mut self, sc: &mut StoryCtx, pb: &mut PB, r: &El, rels: &Rels, ctx: &RunCtx, depth: usize) {
|
||||
@@ -395,7 +400,10 @@ impl Reader<'_> {
|
||||
/// [`Self::emit_obj`] for a drawing that carries its own `link`: a link around the run wins.
|
||||
fn emit_linked_obj(&mut self, sc: &mut StoryCtx, pb: &mut PB, o: InlineObject, props: &CharProps, link: Option<String>) {
|
||||
match link.filter(|_| props.link.is_none()) {
|
||||
Some(link) => self.emit_obj(sc, pb, o, &CharProps { link: Some(link), ..props.clone() }),
|
||||
Some(link) => {
|
||||
let link_tooltip = if props.link.as_deref() == Some(link.as_str()) { props.link_tooltip.clone() } else { None };
|
||||
self.emit_obj(sc, pb, o, &CharProps { link: Some(link), link_tooltip, ..props.clone() });
|
||||
}
|
||||
None => self.emit_obj(sc, pb, o, props),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -192,7 +192,7 @@ impl Writer<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
let mut open_link: Option<String> = None;
|
||||
let mut open_link = None;
|
||||
let mut i = 0;
|
||||
while i < pieces.len() {
|
||||
let Some((piece, props)) = pieces.get(i) else { break };
|
||||
@@ -213,21 +213,31 @@ impl Writer<'_> {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
// Hyperlink grouping.
|
||||
if props.link != open_link {
|
||||
// Hyperlinks with different ScreenTips stay separate even if their target is shared.
|
||||
let link = props
|
||||
.link
|
||||
.as_deref()
|
||||
.filter(|target| !target.is_empty())
|
||||
.map(|target| (target, props.link_tooltip.as_deref().and_then(crate::bounded_link_tooltip)));
|
||||
if link != open_link {
|
||||
if open_link.is_some() {
|
||||
w.close("w:hyperlink");
|
||||
}
|
||||
open_link = None;
|
||||
if let Some(l) = props.link.as_deref().filter(|l| !l.is_empty()) {
|
||||
if let Some(anchor) = l.strip_prefix('#') {
|
||||
w.open("w:hyperlink", &[("w:anchor", anchor), ("w:history", "1")]);
|
||||
if let Some((link, tip)) = link {
|
||||
let id;
|
||||
let target = if let Some(anchor) = link.strip_prefix('#') {
|
||||
("w:anchor", anchor)
|
||||
} else {
|
||||
let id = rels.add(rt::HYPERLINK, l, true);
|
||||
w.open("w:hyperlink", &[("r:id", &id), ("w:history", "1")]);
|
||||
id = rels.add(rt::HYPERLINK, link, true);
|
||||
("r:id", id.as_str())
|
||||
};
|
||||
if let Some(tip) = tip {
|
||||
w.open("w:hyperlink", &[target, ("w:history", "1"), ("w:tooltip", tip)]);
|
||||
} else {
|
||||
w.open("w:hyperlink", &[target, ("w:history", "1")]);
|
||||
}
|
||||
open_link = Some(l.to_string());
|
||||
}
|
||||
open_link = link;
|
||||
}
|
||||
match piece {
|
||||
Piece::Obj(o, _) => {
|
||||
|
||||
@@ -142,6 +142,7 @@ fn every_char_prop_round_trips() {
|
||||
vert_compress: Some(true),
|
||||
}),
|
||||
link: None,
|
||||
link_tooltip: None,
|
||||
ins: None,
|
||||
del: None,
|
||||
fmt_change: None,
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
//! Original OOXML fixtures. ScreenTips are hyperlink data, not run formatting.
|
||||
use std::io::{Read, Write};
|
||||
|
||||
use craft_wordmodel::{CharProps, Pos};
|
||||
|
||||
fn package() -> Vec<u8> {
|
||||
let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
for (name, xml) in [
|
||||
(
|
||||
"word/document.xml",
|
||||
r#"<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><w:body><w:p><w:r><w:t>Before. </w:t></w:r><w:hyperlink r:id="external" w:tooltip="Original café & "Ω""><w:r><w:t>First</w:t></w:r></w:hyperlink><w:hyperlink r:id="external" w:tooltip="Different hint"><w:r><w:t>Second</w:t></w:r></w:hyperlink><w:hyperlink w:anchor="target" w:tooltip="Internal hint"><w:r><w:t>Internal</w:t></w:r></w:hyperlink></w:p><w:p><w:bookmarkStart w:id="0" w:name="target"/><w:r><w:t>Target.</w:t></w:r><w:bookmarkEnd w:id="0"/></w:p><w:sectPr/></w:body></w:document>"#,
|
||||
),
|
||||
(
|
||||
"_rels/.rels",
|
||||
r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="main" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#,
|
||||
),
|
||||
(
|
||||
"word/_rels/document.xml.rels",
|
||||
r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="external" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink" Target="https://example.invalid/reference" TargetMode="External"/></Relationships>"#,
|
||||
),
|
||||
] {
|
||||
zip.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zip.write_all(xml.as_bytes()).unwrap();
|
||||
}
|
||||
zip.finish().unwrap().into_inner()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hyperlink_screentips_survive_edited_saves_without_merging_different_hints() {
|
||||
let mut doc = craft_docx::read(&package()).unwrap();
|
||||
for _ in 0..2 {
|
||||
doc.insert_text(&Pos::body(0, 0), "Edit. ", &CharProps::default()).unwrap();
|
||||
let bytes = craft_docx::write(&doc).unwrap();
|
||||
let mut xml = String::new();
|
||||
zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap().by_name("word/document.xml").unwrap().read_to_string(&mut xml).unwrap();
|
||||
assert_eq!(xml.matches("w:tooltip=").count(), 3, "{xml}");
|
||||
for tip in ["Original café & "Ω"", "Different hint", "Internal hint"] {
|
||||
assert!(xml.contains(&format!("w:tooltip=\"{tip}\"")), "{xml}");
|
||||
}
|
||||
assert!(xml.contains("w:anchor=\"target\""));
|
||||
doc = craft_docx::read(&bytes).unwrap();
|
||||
let paragraph = doc.body[0].as_para().unwrap();
|
||||
for (text, tip) in [("First", "Original café & \"Ω\""), ("Second", "Different hint"), ("Internal", "Internal hint")] {
|
||||
let offset = paragraph.text.find(text).unwrap();
|
||||
assert_eq!(paragraph.props_of_char(offset).link_tooltip.as_deref(), Some(tip), "{text}");
|
||||
}
|
||||
assert!(doc.body[0].as_para().unwrap().plain_text().ends_with("FirstSecondInternal"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oversized_screentips_share_one_utf8_bounded_value_and_save_at_the_same_size() {
|
||||
use std::sync::Arc;
|
||||
|
||||
let kept = "a".repeat(4095);
|
||||
let tip = format!("{kept}Ω trailing text");
|
||||
let runs: String = (0..32).map(|i| format!("<w:r><w:rPr><w:b w:val=\"{}\"/></w:rPr><w:t>word </w:t></w:r>", i % 2)).collect();
|
||||
let xml = format!(
|
||||
r##"<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body><w:p><w:hyperlink w:anchor="target" w:tooltip="{tip}">{runs}</w:hyperlink></w:p></w:body></w:document>"##
|
||||
);
|
||||
let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
zip.start_file("word/document.xml", zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zip.write_all(xml.as_bytes()).unwrap();
|
||||
let mut doc = craft_docx::read(&zip.finish().unwrap().into_inner()).unwrap();
|
||||
let p = doc.body[0].as_para().unwrap();
|
||||
assert_eq!(p.runs.len(), 32);
|
||||
let first = p.runs[0].props.link_tooltip.as_ref().unwrap();
|
||||
assert_eq!(first.as_ref(), kept);
|
||||
assert!(p.runs.iter().all(|run| Arc::ptr_eq(first, run.props.link_tooltip.as_ref().unwrap())));
|
||||
|
||||
// Native model data can arrive without going through the XML reader.
|
||||
let props = CharProps { link: Some("#target".into()), link_tooltip: Some(Arc::from(tip)), ..CharProps::default() };
|
||||
doc.insert_text(&Pos::body(0, 0), "Native ", &props).unwrap();
|
||||
let saved = craft_docx::write(&doc).unwrap();
|
||||
let mut xml = String::new();
|
||||
zip::ZipArchive::new(std::io::Cursor::new(&saved)).unwrap().by_name("word/document.xml").unwrap().read_to_string(&mut xml).unwrap();
|
||||
assert_eq!(xml.matches("w:tooltip=").count(), 1);
|
||||
assert!(xml.contains(&format!("w:tooltip=\"{kept}\"")));
|
||||
assert!(!xml.contains("trailing text"));
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use super::color::{Rgb, TextColor};
|
||||
use super::para_props::Border;
|
||||
use super::{Deserialize, Serialize};
|
||||
@@ -430,6 +432,9 @@ pub struct CharProps {
|
||||
/// Hyperlink target: a URL, or `#bookmark` for an internal link.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub link: Option<String>,
|
||||
/// Optional ScreenTip for the hyperlink. Runs from one link can share its text.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub link_tooltip: Option<Arc<str>>,
|
||||
/// Tracked insertion: index into `Document::revisions`.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub ins: Option<u32>,
|
||||
@@ -566,6 +571,7 @@ impl CharProps {
|
||||
if c.link.take().is_some() && c.style.as_deref() == Some("Hyperlink") {
|
||||
c.style = None;
|
||||
}
|
||||
c.link_tooltip = None;
|
||||
c
|
||||
}
|
||||
|
||||
@@ -626,7 +632,11 @@ impl CharProps {
|
||||
}
|
||||
|
||||
fn minus_document_marks(&mut self, base: &CharProps) {
|
||||
drop_same_fields!(self, base; link, ins, del, ligatures);
|
||||
if self.link == base.link && self.link_tooltip == base.link_tooltip {
|
||||
self.link = None;
|
||||
self.link_tooltip = None;
|
||||
}
|
||||
drop_same_fields!(self, base; ins, del, ligatures);
|
||||
}
|
||||
|
||||
/// Apply every `Some` field of `patch` on top of `self`.
|
||||
@@ -676,7 +686,11 @@ impl CharProps {
|
||||
}
|
||||
|
||||
fn overlay_document_marks(&mut self, patch: &CharProps) {
|
||||
overlay_fields!(self, patch; link, ins, del, fmt_change, ligatures);
|
||||
if let Some(link) = &patch.link {
|
||||
self.link = Some(link.clone());
|
||||
self.link_tooltip = patch.link_tooltip.clone();
|
||||
}
|
||||
overlay_fields!(self, patch; ins, del, fmt_change, ligatures);
|
||||
}
|
||||
pub fn overlaid(mut self, patch: &CharProps) -> CharProps {
|
||||
self.overlay(patch);
|
||||
@@ -701,6 +715,7 @@ impl CharProps {
|
||||
pub fn cleared(&self) -> CharProps {
|
||||
CharProps {
|
||||
link: self.link.clone(),
|
||||
link_tooltip: self.link_tooltip.clone(),
|
||||
ins: self.ins,
|
||||
del: self.del,
|
||||
fmt_change: self.fmt_change.clone(),
|
||||
@@ -711,6 +726,6 @@ impl CharProps {
|
||||
}
|
||||
/// Just the formatting: without the link, revision marks and tracked formatting change.
|
||||
pub fn formatting(&self) -> CharProps {
|
||||
CharProps { link: None, ins: None, del: None, fmt_change: None, ..self.clone() }
|
||||
CharProps { link: None, link_tooltip: None, ins: None, del: None, fmt_change: None, ..self.clone() }
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user