Skip to content

DesignCraft: An open-source page and layout design editor written by scratch in pure Rust

M7: cross-references and text anchors; menus expose engine features

Brandon Thomas01b360375103
diff --git a/ROADMAP.md b/ROADMAP.md
index 2fd501ff1..6938cb3f8 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -18,13 +18,15 @@ DesignCraft aims at full Adobe InDesign parity — and to be better: faster, ope
- EPUB 3 (reflowable) export: stories in reading order, CSS from paragraph/character styles, images, navigation (`file.exportEpub`, CLI `--export x.epub`).
- Data Merge (CSV or JSON rows, `<<Field>>` placeholders), spell checking (public-domain Moby list + document dictionary, suggestions), Step and Repeat (count or grid), snippets, object styles, Numbering & Section Options.
- Footnotes: Type › Insert Footnote (caret moves into the note), Document Footnote Options (numbering style incl. symbols, start/restart per page/spread/section, prefix/suffix, reference position/character style, paragraph style, separator, spacing, first baseline, rule above); notes composed at the bottom of the referencing column with the body text making room; edited in place on the canvas; rendered, exported to PDF (real text) and IDML (InDesign's structure, verified opening in InDesign 2026) and imported from IDML; `footnote.*` commands.
+- Cross-references and text anchors: Insert Cross-Reference (paragraph by style, or text anchor), 11 formats with InDesign's building blocks (full/partial paragraph, paragraph text/number, page number, anchor name, chapter, file name) plus user formats; resolved live at composition — never out of date, no Update step; unresolved destinations show `??`; PDF link annotations to the destination page; IDML export/import as InDesign cross-reference sources, hyperlinks, text destinations and formats (verified in InDesign 2026); `xref.*` / `anchor.*` commands.
+- Menus expose the engine's features (TOC, numbering & sections, text variables, hyperlinks, cross-references, footnotes, step and repeat, spelling, fitting/content, effects, Data Merge, Preflight, EPUB); any menu command with parameters gets a dialog generated from its parameter documentation.
- Table of contents (generate/update, dot leaders) and text variables (running headers, last page number, chapter number, file name, dates, custom) resolved per page.
- Soft effects: blurred drop shadow, inner shadow, outer glow, basic feather.
- ~200 commands, all reachable through the JSON control channel; headless CLI rendering to PNG.
- MCP server (`designcraft-cli mcp [--connect PORT]`, docs/mcp.md): headless engine or the running app; commands, batch, document/story inspection, page renders as images, window screenshots, pointer/keyboard/dialog input.
- Web build (`apps/designcraft-web`, trunk): the same UI on WebGPU with a WebGL2 fallback; open/place via the browser file picker or drag-and-drop, save/export as downloads.
-**Next (in order):** cross-references, index, footnotes in EPUB / span columns / split footnotes · table/cell styles, text rotation in cells · PDF/X-4 output intent, tagged PDF · Links panel + relink · UI for Data Merge/spelling/hyperlinks.
+**Next (in order):** index, footnotes in EPUB / span columns / split footnotes · table/cell styles, text rotation in cells · PDF/X-4 output intent, tagged PDF · Links panel + relink · UI for Data Merge/spelling/hyperlinks.
## Milestones
@@ -37,7 +39,7 @@ DesignCraft aims at full Adobe InDesign parity — and to be better: faster, ope
| M4 | Color & effects | started |
| M5 | Graphics & links | started |
| M6 | Files & export (native, IDML, PDF, PNG/JPEG) | in progress (IDML ✅, PDF export) |
-| M7 | Long documents (sections, TOC, index, footnotes, books) | in progress (sections, TOC, text variables/running heads, hyperlinks, bookmarks, footnotes) |
+| M7 | Long documents (sections, TOC, index, footnotes, books) | in progress (sections, TOC, text variables/running heads, hyperlinks, bookmarks, footnotes, cross-references) |
| M8 | Tables | ✅ core (table/cell styles, rotation, diagonal lines pending) |
| M9 | Performance (MT composition, tiles) | in progress (glyph path cache, culling, parallel compose 6.7× faster, perf harness) |
| M10 | Find/Change, spelling, Preflight | in progress (Find/Change ✅, spelling ✅, Preflight) |
diff --git a/crates/compose/src/cache.rs b/crates/compose/src/cache.rs
index 4171d2aa2..408724913 100644
--- a/crates/compose/src/cache.rs
+++ b/crates/compose/src/cache.rs
@@ -27,6 +27,8 @@ pub struct Cache {
map: Mutex<(HashMap<Key, Entry>, u64)>,
/// Running-header index with the document signature it was built for.
running: Mutex<Option<(u64, Arc<RunningIndex>)>>,
+ /// Cross-reference anchor pages with the document signature they were built for.
+ xrefs: Mutex<Option<(u64, Arc<crate::xref::XrefIndex>)>>,
}
/// Identity of everything a running header can depend on (stories, spreads, styles, variables).
@@ -68,6 +70,14 @@ impl Cache {
sig.push(doc_signature(doc) as usize);
}
}
+ let with_xrefs = crate::xref::has_xrefs(story);
+ if with_xrefs {
+ // Cross-references show other stories' text and pages.
+ use std::hash::{Hash, Hasher};
+ let mut h = std::collections::hash_map::DefaultHasher::new();
+ format!("{:?}", doc.xref_formats).hash(&mut h);
+ sig.extend([doc_signature(doc) as usize, h.finish() as usize]);
+ }
if !story.notes.is_empty() {
// Footnote numbers continue from earlier stories; layout follows the options.
use std::hash::{Hash, Hasher};
@@ -92,7 +102,11 @@ impl Cache {
_ => None,
};
let running = running.then(|| self.running_index(doc));
- let out = Arc::new(crate::compose_story(doc, sid, &ComposeOptions { page_name: page_name.map(str::to_string), page, running, label: None }));
+ let out = Arc::new(crate::compose_story(
+ doc,
+ sid,
+ &ComposeOptions { page_name: page_name.map(str::to_string), page, running, label: None, xrefs: with_xrefs.then(|| self.xref_index(doc)) },
+ ));
let mut g = self.map.lock().unwrap_or_else(|e| e.into_inner());
let stamp = g.1;
if g.0.len() > 4096 {
@@ -105,6 +119,20 @@ impl Cache {
pub fn clear(&self) {
self.map.lock().unwrap_or_else(|e| e.into_inner()).0.clear();
*self.running.lock().unwrap_or_else(|e| e.into_inner()) = None;
+ *self.xrefs.lock().unwrap_or_else(|e| e.into_inner()) = None;
+ }
+
+ /// Anchor pages for cross-references (rebuilt when the document changes).
+ pub fn xref_index(&self, doc: &Document) -> Arc<crate::xref::XrefIndex> {
+ let sig = doc_signature(doc);
+ if let Some((s, r)) = &*self.xrefs.lock().unwrap_or_else(|e| e.into_inner())
+ && *s == sig
+ {
+ return r.clone();
+ }
+ let r = Arc::new(crate::xref::XrefIndex::build(doc, &|sid| self.get(doc, sid, None)));
+ *self.xrefs.lock().unwrap_or_else(|e| e.into_inner()) = Some((sig, r.clone()));
+ r
}
/// The running-header index for `doc` (rebuilt when the document changes).
diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs
index 22f05c3e5..b062422c9 100644
--- a/crates/compose/src/lib.rs
+++ b/crates/compose/src/lib.rs
@@ -16,6 +16,7 @@ mod notes;
pub mod shape;
pub mod table;
pub mod vars;
+pub mod xref;
use std::collections::HashMap;
use std::ops::Range;
@@ -208,6 +209,8 @@ pub struct ComposeOptions {
pub running: Option<std::sync::Arc<vars::RunningIndex>>,
/// Generated text before the first paragraph (a footnote's number and separator).
pub label: Option<String>,
+ /// Anchor pages for cross-references (needed when the story contains cross-references).
+ pub xrefs: Option<Arc<xref::XrefIndex>>,
}
/// Build the frame specs of a story from the document (geometry, wrap, page names, grid).
@@ -355,6 +358,9 @@ pub fn compose(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &Compo
vars: var_values,
..Default::default()
};
+ if !story.xrefs.is_empty() {
+ sub.xrefs = xref::texts_in(doc, story, prange.clone(), opts.xrefs.as_deref());
+ }
if notes.active() {
notes.number_refs(doc, prange.clone(), cur_frame.and_then(|f| f.page), &mut sub);
}
diff --git a/crates/compose/src/notes.rs b/crates/compose/src/notes.rs
index d4ca625b6..b0a561c7c 100644
--- a/crates/compose/src/notes.rs
+++ b/crates/compose/src/notes.rs
@@ -105,7 +105,13 @@ impl Notes {
grid: None,
left_page: f.left_page,
};
- let nopts = ComposeOptions { page_name: opts.page_name.clone(), page: opts.page, running: opts.running.clone(), label: Some(label) };
+ let nopts = ComposeOptions {
+ page_name: opts.page_name.clone(),
+ page: opts.page,
+ running: opts.running.clone(),
+ label: Some(label),
+ xrefs: opts.xrefs.clone(),
+ };
let cs = crate::compose(doc, &self.notes[k].text, std::slice::from_ref(&spec), &nopts);
let h = cs.frames.first().and_then(|ft| ft.lines.last()).map_or(0.0, |l| l.baseline + l.descent);
let v = (Arc::new(cs), h);
diff --git a/crates/compose/src/shape.rs b/crates/compose/src/shape.rs
index 0e1b15b69..6785f0fab 100644
--- a/crates/compose/src/shape.rs
+++ b/crates/compose/src/shape.rs
@@ -73,6 +73,8 @@ pub struct SubstCtx {
/// Footnote reference formatting: position and character style (`None` = the text's).
pub note_position: designcraft_doc::Position,
pub note_style: Option<String>,
+ /// Cross-reference texts by story byte of the cross-reference mark.
+ pub xrefs: HashMap<usize, String>,
}
pub(crate) struct StyleTable<'a> {
@@ -222,6 +224,8 @@ fn shape_run(
| story::RIGHT_INDENT_TAB
| story::TABLE_ANCHOR
| designcraft_doc::FOOTNOTE_REF
+ | designcraft_doc::XREF_MARK
+ | designcraft_doc::ANCHOR_MARK
) || designcraft_doc::vars::var_index(c).is_some();
if special {
flush(seg_start, i, &seg_face, out);
@@ -246,6 +250,14 @@ fn shape_run(
};
shape_segment(db, text, i..i + c.len_utf8(), Some(&s), p, &primary, auto_leading, style, out);
}
+ designcraft_doc::XREF_MARK => match sub.xrefs.get(&i).filter(|t| !t.is_empty()) {
+ Some(t) => shape_segment(db, text, i..i + c.len_utf8(), Some(t), p, &primary, auto_leading, style, out),
+ None => {
+ let mut g = control_glyph(&primary, p, auto_leading, style, i, c);
+ g.adv = 0.0;
+ out.push(g);
+ }
+ },
designcraft_doc::FOOTNOTE_REF => {
let s = sub.notes.get(&i).map_or("#", String::as_str);
shape_segment(db, text, i..i + c.len_utf8(), Some(s), p, &primary, auto_leading, style, out);
@@ -253,7 +265,7 @@ fn shape_run(
_ => {
// Zero-width control glyph carrying metrics (tabs get their width at line layout).
let mut g = control_glyph(&primary, p, auto_leading, style, i, c);
- if c == '\t' || c == story::RIGHT_INDENT_TAB || c == story::TABLE_ANCHOR {
+ if c == '\t' || c == story::RIGHT_INDENT_TAB || c == story::TABLE_ANCHOR || c == designcraft_doc::ANCHOR_MARK {
g.adv = 0.0;
}
out.push(g);
diff --git a/crates/compose/src/vars.rs b/crates/compose/src/vars.rs
index c3f178fde..e19170b17 100644
--- a/crates/compose/src/vars.rs
+++ b/crates/compose/src/vars.rs
@@ -32,7 +32,7 @@ fn clean(s: &str) -> String {
}
/// (absolute page, y, x) of story byte `pos` in a composed story.
-fn place(doc: &Document, cs: &ComposedStory, pos: usize) -> Option<(usize, i64, i64)> {
+pub(crate) fn place(doc: &Document, cs: &ComposedStory, pos: usize) -> Option<(usize, i64, i64)> {
let (fi, x, baseline, ..) = crate::caret(cs, pos)?;
let ft = cs.frames.get(fi)?;
let loc = doc.find(ft.frame)?;
diff --git a/crates/compose/src/xref.rs b/crates/compose/src/xref.rs
new file mode 100644
index 000000000..4bce48d27
--- /dev/null
+++ b/crates/compose/src/xref.rs
@@ -0,0 +1,74 @@
+//! Cross-reference resolution: the page each text anchor lands on (from composition) and the
+//! generated text of each cross-reference.
+
+use std::collections::HashMap;
+use std::sync::Arc;
+
+use designcraft_doc::{Document, Story, StoryId, XREF_MARK, xref};
+
+use crate::ComposedStory;
+
+/// Page name of every text anchor in the document.
+#[derive(Debug, Default)]
+pub struct XrefIndex {
+ pages: HashMap<u64, (usize, String)>,
+}
+
+pub fn has_xrefs(st: &Story) -> bool {
+ !st.xrefs.is_empty()
+}
+
+impl XrefIndex {
+ /// `get` composes a story (normally through the cache). Stories that themselves hold
+ /// cross-references are composed without resolving them (their anchors' pages hardly move).
+ pub fn build(doc: &Document, get: &dyn Fn(StoryId) -> Arc<ComposedStory>) -> XrefIndex {
+ let mut pages = HashMap::new();
+ for (sid, st) in &doc.stories {
+ if st.anchors.is_empty() {
+ continue;
+ }
+ let cs = if has_xrefs(st) { Arc::new(crate::compose_story(doc, *sid, &Default::default())) } else { get(*sid) };
+ for a in &st.anchors {
+ let Some(pos) = st.anchor_pos(a.id) else { continue };
+ if let Some((page, ..)) = crate::vars::place(doc, &cs, pos) {
+ pages.insert(a.id, (page, doc.page_name(page)));
+ }
+ }
+ }
+ XrefIndex { pages }
+ }
+
+ /// Page name of an anchor.
+ pub fn page(&self, anchor: u64) -> Option<&str> {
+ self.pages.get(&anchor).map(|p| p.1.as_str())
+ }
+
+ /// Absolute page index of an anchor.
+ pub fn page_index(&self, anchor: u64) -> Option<usize> {
+ self.pages.get(&anchor).map(|p| p.0)
+ }
+}
+
+/// The text a cross-reference shows ("??" when its destination is gone, like an unresolved
+/// reference in typesetting).
+pub fn xref_text(doc: &Document, x: &xref::CrossRef, index: Option<&XrefIndex>) -> String {
+ let Some(mut v) = doc.xref_values(x.target) else { return "??".into() };
+ v.page = index.and_then(|i| i.page(x.target)).unwrap_or("?").to_string();
+ let def = doc.xref_format(&x.format).map_or("<fullPara />", |f| f.definition.as_str());
+ xref::expand(def, &v)
+}
+
+/// Generated text of the cross-references in `range` of `story`, by byte of their mark.
+pub fn texts_in(doc: &Document, story: &Story, range: std::ops::Range<usize>, index: Option<&XrefIndex>) -> HashMap<usize, String> {
+ let mut out = HashMap::new();
+ if story.xrefs.is_empty() {
+ return out;
+ }
+ let before = story.text[..range.start].matches(XREF_MARK).count();
+ for (k, (i, _)) in story.text[range.clone()].match_indices(XREF_MARK).enumerate() {
+ if let Some(x) = story.xrefs.get(before + k) {
+ out.insert(range.start + i, xref_text(doc, x, index));
+ }
+ }
+ out
+}
diff --git a/crates/doc/src/build.rs b/crates/doc/src/build.rs
index d071b2171..55097c974 100644
--- a/crates/doc/src/build.rs
+++ b/crates/doc/src/build.rs
@@ -141,6 +141,7 @@ impl Document {
toc: None,
text_variables: crate::vars::defaults(),
footnote_options: Default::default(),
+ xref_formats: crate::xref::default_formats(),
created: crate::vars::now(),
modified: 0,
next_id: 0,
diff --git a/crates/doc/src/edit.rs b/crates/doc/src/edit.rs
index d4ef98c1a..890fffef1 100644
--- a/crates/doc/src/edit.rs
+++ b/crates/doc/src/edit.rs
@@ -231,6 +231,8 @@ impl Document {
let id = st.next_note_id();
st.notes.push(Arc::new(crate::Footnote { id, text: n.text.clone() }));
}
+ st.anchors.extend(other.anchors.iter().cloned());
+ st.xrefs.extend(other.xrefs.iter().cloned());
st.rev += 1;
}
let at = st.frames.iter().position(|f| *f == from).map_or(st.frames.len(), |p| p + 1);
@@ -358,6 +360,9 @@ impl Document {
st.tables.clear();
st.notes.clear();
st.fix_notes();
+ st.anchors.clear();
+ st.xrefs.clear();
+ st.fix_marks();
st.rev += 1;
Ok(())
}
diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs
index 6b6e38d8b..b91ac1901 100644
--- a/crates/doc/src/lib.rs
+++ b/crates/doc/src/lib.rs
@@ -20,6 +20,7 @@ pub mod story;
pub mod styles;
pub mod table;
pub mod vars;
+pub mod xref;
use std::collections::BTreeMap;
use std::sync::Arc;
@@ -36,6 +37,7 @@ pub use selection::*;
pub use story::*;
pub use styles::*;
pub use table::*;
+pub use xref::{ANCHOR_MARK, CrossRef, TextAnchor, XREF_MARK, XrefFormat};
use designcraft_color::Swatch;
use designcraft_geom::Unit;
@@ -252,6 +254,9 @@ pub struct Document {
/// Type › Document Footnote Options.
#[serde(default)]
pub footnote_options: FootnoteOptions,
+ /// Cross-reference formats (Type › Hyperlinks & Cross-References › Cross-Reference Formats).
+ #[serde(default = "xref::default_formats")]
+ pub xref_formats: Vec<XrefFormat>,
/// Creation / last save time (Unix seconds, UTC).
#[serde(default)]
pub created: i64,
diff --git a/crates/doc/src/story.rs b/crates/doc/src/story.rs
index 11de1d7fc..ea40e5fdf 100644
--- a/crates/doc/src/story.rs
+++ b/crates/doc/src/story.rs
@@ -10,7 +10,8 @@
//! Special characters: `\t` tab, `\u{2028}` forced line break, [`PAGE_NUMBER`], [`SECTION_MARKER`],
//! [`COLUMN_BREAK`], [`FRAME_BREAK`], [`PAGE_BREAK`], `\u{AD}` discretionary hyphen,
//! `\u{2011}` non-breaking hyphen, `\u{A0}` non-breaking space, [`INDENT_HERE`], [`RIGHT_INDENT_TAB`],
-//! [`TABLE_ANCHOR`] (a table, see [`crate::table`]), [`crate::notes::FOOTNOTE_REF`] (a footnote).
+//! [`TABLE_ANCHOR`] (a table, see [`crate::table`]), [`crate::notes::FOOTNOTE_REF`] (a footnote),
+//! [`crate::xref::ANCHOR_MARK`] / [`crate::xref::XREF_MARK`] (text anchor / cross-reference).
use std::collections::BTreeMap;
use std::sync::Arc;
@@ -97,6 +98,12 @@ pub struct Story {
/// Footnotes, one per [`crate::notes::FOOTNOTE_REF`] in text order (see [`crate::notes`]).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub notes: Vec<Arc<crate::notes::Footnote>>,
+ /// Text anchors, one per [`crate::xref::ANCHOR_MARK`] in text order.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub anchors: Vec<Arc<crate::xref::TextAnchor>>,
+ /// Cross-references, one per [`crate::xref::XREF_MARK`] in text order.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub xrefs: Vec<Arc<crate::xref::CrossRef>>,
}
impl Story {
@@ -110,6 +117,8 @@ impl Story {
rev: 0,
tables: BTreeMap::new(),
notes: Vec::new(),
+ anchors: Vec::new(),
+ xrefs: Vec::new(),
}
}
@@ -143,7 +152,7 @@ impl Story {
/// Index of the paragraph containing byte `pos`.
pub fn para_at(&self, pos: usize) -> usize {
- self.text[..pos.min(self.text.len())].bytes().filter(|b| *b == b'\n').count()
+ self.text[..floor_char_boundary(&self.text, pos)].bytes().filter(|b| *b == b'\n').count()
}
/// Character format at byte `pos` (the run containing it; at a boundary, the preceding run —
@@ -198,6 +207,9 @@ impl Story {
let k = self.notes_before(pos);
self.notes_inserted(k, refs);
}
+ if text.contains([crate::xref::ANCHOR_MARK, crate::xref::XREF_MARK]) {
+ self.marks_inserted(pos, text);
+ }
// Paragraph formats: each new '\n' splits the current paragraph; the new paragraphs copy it.
let pi = self.para_at(pos);
let newlines = text.bytes().filter(|b| *b == b'\n').count();
@@ -226,6 +238,7 @@ impl Story {
let k = self.notes_before(a);
self.notes.drain(k..(k + refs).min(self.notes.len()));
}
+ self.marks_deleted(a, b);
let pi = self.para_at(a);
let removed = self.text[a..b].bytes().filter(|c| *c == b'\n').count();
// Merged paragraphs keep a table whose anchor survives the deletion.
@@ -329,7 +342,8 @@ impl Story {
}
}
self.check_tables()?;
- self.check_notes()
+ self.check_notes()?;
+ self.check_marks()
}
// ---------- run helpers ----------
diff --git a/crates/doc/src/xref.rs b/crates/doc/src/xref.rs
new file mode 100644
index 000000000..b7a8b47a2
--- /dev/null
+++ b/crates/doc/src/xref.rs
@@ -0,0 +1,355 @@
+//! Text anchors and cross-references (Type › Hyperlinks & Cross-References).
+//!
+//! A text anchor is a zero-width [`ANCHOR_MARK`] character; the story's [`Story::anchors`] holds
+//! one [`TextAnchor`] per mark in text order (like footnotes). A cross-reference is an
+//! [`XREF_MARK`] character with one [`CrossRef`] per mark in [`Story::xrefs`]; it shows text
+//! generated from its format (paragraph text, page number, …) and is resolved at composition, so
+//! it never goes stale (InDesign's cross-references need Update Cross-References).
+//!
+//! Anchor ids are document-unique: `story id << 24 | n` when created, kept when text moves.
+
+use std::sync::Arc;
+
+use serde::{Deserialize, Serialize};
+
+use crate::Document;
+use crate::ids::StoryId;
+use crate::story::Story;
+
+/// A text anchor (destination of cross-references and hyperlinks).
+pub const ANCHOR_MARK: char = '\u{E00B}';
+/// A cross-reference source (generated text).
+pub const XREF_MARK: char = '\u{E00C}';
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct TextAnchor {
+ pub id: u64,
+ /// Shown in the Hyperlinks panel; paragraph destinations get a generated name.
+ pub name: String,
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct CrossRef {
+ /// The destination anchor (0 = unresolved, e.g. pasted without its destination).
+ pub target: u64,
+ /// Name of the format in [`Document::xref_formats`].
+ pub format: String,
+}
+
+/// A cross-reference format: building blocks between literal text.
+///
+/// Blocks: `<fullPara />`, `<paraText />` (without the list number), `<paraNum />`,
+/// `<pageNum />`, `<txtAnchrName />`, `<chapNum />`, `<fileName />`,
+/// `<partialPara delim="x" includeDelim="false" />`.
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct XrefFormat {
+ pub name: String,
+ pub definition: String,
+}
+
+pub fn default_formats() -> Vec<XrefFormat> {
+ let f = |name: &str, definition: &str| XrefFormat { name: name.into(), definition: definition.into() };
+ vec![
+ f("Full Paragraph & Page Number", "\"<fullPara />\" on page <pageNum />"),
+ f("Full Paragraph", "\"<fullPara />\""),
+ f("Paragraph Text & Page Number", "\"<paraText />\" on page <pageNum />"),
+ f("Paragraph Text", "\"<paraText />\""),
+ f("Paragraph Number & Page Number", "<paraNum /> on page <pageNum />"),
+ f("Paragraph Number", "<paraNum />"),
+ f("Text Anchor Name & Page Number", "\"<txtAnchrName />\" on page <pageNum />"),
+ f("Text Anchor Name", "\"<txtAnchrName />\""),
+ f("Page Number", "page <pageNum />"),
+ f("Partial Paragraph & Page Number", "\"<partialPara delim=\":\" includeDelim=\"false\" />\" on page <pageNum />"),
+ f("Partial Paragraph", "\"<partialPara delim=\":\" includeDelim=\"false\" />\""),
+ ]
+}
+
+/// Values a format can show for one destination.
+#[derive(Clone, Debug, Default, PartialEq)]
+pub struct XrefValues {
+ pub para: String,
+ pub para_num: String,
+ pub page: String,
+ pub anchor_name: String,
+ pub chapter: String,
+ pub file_name: String,
+}
+
+/// Expand a format definition.
+pub fn expand(definition: &str, v: &XrefValues) -> String {
+ let mut out = String::new();
+ let mut rest = definition;
+ while let Some(i) = rest.find('<') {
+ out.push_str(&rest[..i]);
+ let Some(j) = rest[i..].find('>') else {
+ out.push_str(&rest[i..]);
+ return out;
+ };
+ let tag = rest[i + 1..i + j].trim().trim_end_matches('/').trim();
+ let name = tag.split_whitespace().next().unwrap_or("");
+ match name {
+ "fullPara" => {
+ if !v.para_num.is_empty() {
+ out.push_str(&v.para_num);
+ out.push(' ');
+ }
+ out.push_str(&v.para);
+ }
+ "paraText" => out.push_str(&v.para),
+ "paraNum" => out.push_str(&v.para_num),
+ "pageNum" => out.push_str(&v.page),
+ "txtAnchrName" => out.push_str(&v.anchor_name),
+ "chapNum" => out.push_str(&v.chapter),
+ "fileName" => out.push_str(&v.file_name),
+ "partialPara" => {
+ let delim = attr(tag, "delim").unwrap_or_default();
+ let include = attr(tag, "includeDelim").is_some_and(|x| x == "true");
+ match (!delim.is_empty()).then(|| v.para.find(&delim)).flatten() {
+ Some(k) => out.push_str(&v.para[..if include { k + delim.len() } else { k }]),
+ None => out.push_str(&v.para),
+ }
+ }
+ _ => out.push_str(&rest[i..i + j + 1]),
+ }
+ rest = &rest[i + j + 1..];
+ }
+ out.push_str(rest);
+ typographic_quotes(&out)
+}
+
+/// Straight double quotes in format text become typographer's quotes.
+fn typographic_quotes(s: &str) -> String {
+ let mut out = String::with_capacity(s.len());
+ let mut prev = ' ';
+ for c in s.chars() {
+ out.push(match c {
+ '"' if prev.is_whitespace() || matches!(prev, '(' | '[') => '\u{201C}',
+ '"' => '\u{201D}',
+ c => c,
+ });
+ prev = c;
+ }
+ out
+}
+
+fn attr(tag: &str, key: &str) -> Option<String> {
+ let k = tag.find(&format!("{key}=\""))? + key.len() + 2;
+ let e = tag[k..].find('"')?;
+ Some(tag[k..k + e].to_string())
+}
+
+impl Story {
+ fn marks_before(&self, mark: char, pos: usize) -> usize {
+ let pos = crate::story::floor_char_boundary(&self.text, pos);
+ self.text[..pos].matches(mark).count()
+ }
+
+ /// Byte offset of an anchor's mark.
+ pub fn anchor_pos(&self, id: u64) -> Option<usize> {
+ let k = self.anchors.iter().position(|a| a.id == id)?;
+ self.text.match_indices(ANCHOR_MARK).nth(k).map(|(i, _)| i)
+ }
+
+ /// The cross-reference whose mark is at byte `pos`.
+ pub fn xref_at(&self, pos: usize) -> Option<&CrossRef> {
+ if !self.text[pos.min(self.text.len())..].starts_with(XREF_MARK) {
+ return None;
+ }
+ self.xrefs.get(self.marks_before(XREF_MARK, pos)).map(|x| &**x)
+ }
+
+ fn next_anchor_id(&self) -> u64 {
+ let base = self.id.0 << 24;
+ self.anchors.iter().filter(|a| a.id >> 24 == self.id.0).map(|a| a.id + 1).max().unwrap_or(base + 1).max(base + 1)
+ }
+
+ /// Insert a text anchor at `pos`. Returns its id.
+ pub fn insert_anchor(&mut self, pos: usize, name: &str) -> u64 {
+ let pos = crate::story::floor_char_boundary(&self.text, pos.min(self.len()));
+ self.insert(pos, &ANCHOR_MARK.to_string());
+ let k = self.marks_before(ANCHOR_MARK, pos);
+ let a = Arc::make_mut(&mut self.anchors[k]);
+ a.name = name.to_string();
+ a.id
+ }
+
+ /// Insert a cross-reference at `pos` (replacing nothing).
+ pub fn insert_xref(&mut self, pos: usize, xref: CrossRef) {
+ let pos = crate::story::floor_char_boundary(&self.text, pos.min(self.len()));
+ self.insert(pos, &XREF_MARK.to_string());
+ let k = self.marks_before(XREF_MARK, pos);
+ self.xrefs[k] = Arc::new(xref);
+ }
+
+ /// Keep anchor/xref lists in step with an insertion of `text` at `pos` (before it happens).
+ pub(crate) fn marks_inserted(&mut self, pos: usize, text: &str) {
+ let n = text.matches(ANCHOR_MARK).count();
+ if n > 0 {
+ let k = self.marks_before(ANCHOR_MARK, pos);
+ for i in 0..n {
+ let id = self.next_anchor_id();
+ self.anchors.insert(k + i, Arc::new(TextAnchor { id, name: format!("Anchor {}", id & 0xFF_FFFF) }));
+ }
+ }
+ let n = text.matches(XREF_MARK).count();
+ if n > 0 {
+ let k = self.marks_before(XREF_MARK, pos);
+ for i in 0..n {
+ self.xrefs.insert(k + i, Arc::new(CrossRef { target: 0, format: String::new() }));
+ }
+ }
+ }
+
+ /// Keep anchor/xref lists in step with a deletion of `a..b` (before it happens).
+ pub(crate) fn marks_deleted(&mut self, a: usize, b: usize) {
+ for mark in [ANCHOR_MARK, XREF_MARK] {
+ let n = self.text[a..b].matches(mark).count();
+ if n == 0 {
+ continue;
+ }
+ let k = self.marks_before(mark, a);
+ if mark == ANCHOR_MARK {
+ self.anchors.drain(k..(k + n).min(self.anchors.len()));
+ } else {
+ self.xrefs.drain(k..(k + n).min(self.xrefs.len()));
+ }
+ }
+ }
+
+ /// Make the lists match the marks after wholesale text changes.
+ pub fn fix_marks(&mut self) {
+ let n = self.text.matches(ANCHOR_MARK).count();
+ while self.anchors.len() > n {
+ self.anchors.pop();
+ }
+ while self.anchors.len() < n {
+ let id = self.next_anchor_id();
+ self.anchors.push(Arc::new(TextAnchor { id, name: format!("Anchor {}", id & 0xFF_FFFF) }));
+ }
+ let n = self.text.matches(XREF_MARK).count();
+ self.xrefs.truncate(n);
+ while self.xrefs.len() < n {
+ self.xrefs.push(Arc::new(CrossRef { target: 0, format: String::new() }));
+ }
+ }
+
+ pub(crate) fn check_marks(&self) -> Result<(), String> {
+ let (a, x) = (self.text.matches(ANCHOR_MARK).count(), self.text.matches(XREF_MARK).count());
+ if a != self.anchors.len() || x != self.xrefs.len() {
+ return Err(format!("story {}: {a} anchor / {x} xref marks for {} anchors / {} xrefs", self.id.0, self.anchors.len(), self.xrefs.len()));
+ }
+ Ok(())
+ }
+}
+
+impl Document {
+ /// (story, byte) of anchor `id`.
+ pub fn find_anchor(&self, id: u64) -> Option<(StoryId, usize)> {
+ if id == 0 {
+ return None;
+ }
+ // Fast path: the story the id was created in.
+ let home = StoryId(id >> 24);
+ if let Some(p) = self.story(home).and_then(|s| s.anchor_pos(id)) {
+ return Some((home, p));
+ }
+ self.stories.values().find_map(|s| s.anchor_pos(id).map(|p| (s.id, p)))
+ }
+
+ pub fn anchor(&self, id: u64) -> Option<&TextAnchor> {
+ self.stories.values().find_map(|s| s.anchors.iter().find(|a| a.id == id).map(|a| &**a))
+ }
+
+ /// The anchor at the start of paragraph containing `pos` in `sid`, creating one if needed
+ /// (cross-references to paragraphs point at such an anchor).
+ pub fn paragraph_anchor(&mut self, sid: StoryId, pos: usize) -> Option<u64> {
+ let st = self.story(sid)?;
+ let pi = st.para_at(pos);
+ let r = st.para_ranges()[pi].clone();
+ if st.text[r.clone()].starts_with(ANCHOR_MARK) {
+ let k = st.marks_before(ANCHOR_MARK, r.start);
+ return st.anchors.get(k).map(|a| a.id);
+ }
+ let name: String = clean(&st.text[r.clone()]).chars().take(40).collect();
+ let st = self.story_mut(sid)?;
+ Some(st.insert_anchor(r.start, &name))
+ }
+
+ /// Values for the paragraph holding anchor `id` (page left empty: it needs composition).
+ pub fn xref_values(&self, id: u64) -> Option<XrefValues> {
+ let (sid, pos) = self.find_anchor(id)?;
+ let st = self.story(sid)?;
+ let pi = st.para_at(pos);
+ let r = st.para_ranges()[pi].clone();
+ let (pp, _) = self.styles.resolve_para(&st.paras[pi]);
+ let para_num = match pp.list_type {
+ crate::ListType::Numbers => {
+ // Count the run of numbered paragraphs before this one.
+ let n = (0..=pi).rev().take_while(|&k| self.styles.resolve_para(&st.paras[k]).0.list_type == crate::ListType::Numbers).count();
+ format!("{}.", pp.number_style.format(n as u32))
+ }
+ _ => String::new(),
+ };
+ Some(XrefValues {
+ para: clean(&st.text[r]),
+ para_num,
+ page: String::new(),
+ anchor_name: self.anchor(id).map(|a| a.name.clone()).unwrap_or_default(),
+ chapter: self.settings.chapter_number.to_string(),
+ file_name: self.title.clone(),
+ })
+ }
+
+ pub fn xref_format(&self, name: &str) -> Option<&XrefFormat> {
+ self.xref_formats.iter().find(|f| f.name == name)
+ }
+}
+
+/// Paragraph text without markers, tabs and breaks.
+pub fn clean(s: &str) -> String {
+ let t: String =
+ s.chars().filter(|c| !('\u{E000}'..='\u{E1FF}').contains(c)).map(|c| if c == '\t' || c == '\u{2028}' { ' ' } else { c }).collect();
+ t.trim().to_string()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn formats_expand() {
+ let v =
+ XrefValues { para: "Intro: the start".into(), page: "7".into(), para_num: "2.".into(), anchor_name: "A".into(), ..Default::default() };
+ let fs = default_formats();
+ let get = |n: &str| expand(&fs.iter().find(|f| f.name == n).unwrap().definition, &v);
+ assert_eq!(get("Full Paragraph & Page Number"), "\u{201C}2. Intro: the start\u{201D} on page 7");
+ assert_eq!(get("Paragraph Text"), "\u{201C}Intro: the start\u{201D}");
+ assert_eq!(get("Partial Paragraph"), "\u{201C}Intro\u{201D}");
+ assert_eq!(get("Page Number"), "page 7");
+ assert_eq!(get("Text Anchor Name"), "\u{201C}A\u{201D}");
+ assert_eq!(expand("see <bogus /> x", &v), "see <bogus /> x");
+ }
+
+ #[test]
+ fn marks_follow_edits() {
+ let mut s = Story::with_text(StoryId(3), "Heading\nBody text.", Default::default());
+ let a = s.insert_anchor(0, "Heading");
+ assert_eq!(a >> 24, 3);
+ s.insert_xref(13, CrossRef { target: a, format: "Page Number".into() });
+ s.check().unwrap();
+ assert_eq!(s.anchor_pos(a), Some(0));
+ s.insert(0, "New ");
+ assert_eq!(s.anchor_pos(a), Some(4));
+ let x = s.text.find(XREF_MARK).unwrap();
+ assert_eq!(s.xref_at(x).unwrap().target, a);
+ s.delete(x..x + XREF_MARK.len_utf8());
+ s.check().unwrap();
+ assert!(s.xrefs.is_empty());
+ s.delete(0..8);
+ s.check().unwrap();
+ assert!(s.anchors.is_empty());
+ }
+}
diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs
index a93b9ab0a..b9253453c 100644
--- a/crates/engine/src/cmd/mod.rs
+++ b/crates/engine/src/cmd/mod.rs
@@ -18,6 +18,7 @@ pub mod table;
pub mod text;
mod toc;
mod variables;
+mod xref;
use designcraft_doc::{ItemId, SpreadRef};
use designcraft_geom::{Point, Rect};
@@ -124,6 +125,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(variables::specs());
v.extend(toc::specs());
v.extend(notes::specs());
+ v.extend(xref::specs());
v.extend(spelling::specs());
v.extend(datamerge::specs());
v.extend(interactive::specs());
diff --git a/crates/engine/src/cmd/xref.rs b/crates/engine/src/cmd/xref.rs
new file mode 100644
index 000000000..b0b97ebd2
--- /dev/null
+++ b/crates/engine/src/cmd/xref.rs
@@ -0,0 +1,217 @@
+//! Type › Hyperlinks & Cross-References: text anchors, cross-references and their formats.
+
+use designcraft_doc::{CrossRef, StoryId, TextSel, XrefFormat};
+use serde_json::{Value, json};
+
+use super::{CommandSpec, bad, cmd, has_doc, str_param};
+use crate::{Result, Session};
+
+pub fn specs() -> Vec<CommandSpec> {
+ vec![
+ cmd!(
+ "xref.insert",
+ "Insert Cross-Reference…",
+ ["Type", "Hyperlinks & Cross-References"],
+ None,
+ "{anchor? | paragraph?: text to find (first paragraph containing it) | story? + para? (0-based), format?: name (default Full Paragraph & Page Number)} — at the insertion point; the text updates itself as the destination moves",
+ in_story_text,
+ insert
+ ),
+ cmd!(
+ "anchor.create",
+ "New Hyperlink Destination…",
+ ["Type", "Hyperlinks & Cross-References"],
+ None,
+ "{name} — a text anchor at the insertion point",
+ in_story_text,
+ create_anchor
+ ),
+ cmd!(query "xref.list", "Cross-References", [], None, "{} → [{story, pos, target, format, text}]", has_doc, list),
+ cmd!(query "anchor.list", "Text Anchors", [], None, "{} → [{id, name, story, pos, page}]", has_doc, list_anchors),
+ cmd!(query "xref.formats", "Cross-Reference Formats", [], None, "{} → [{name, definition}]", has_doc, |s, _| {
+ Ok(serde_json::to_value(&s.doc()?.doc.xref_formats).unwrap_or_default())
+ }),
+ cmd!(
+ "xref.defineFormat",
+ "Define Cross-Reference Format…",
+ ["Type", "Hyperlinks & Cross-References"],
+ None,
+ "{name, definition} — building blocks: <fullPara />, <paraText />, <paraNum />, <pageNum />, <txtAnchrName />, <chapNum />, <fileName />, <partialPara delim=\":\" includeDelim=\"false\" />; creates or replaces",
+ has_doc,
+ define_format
+ ),
+ cmd!("xref.setFormat", "Set Cross-Reference Format", [], None, "{story, index, format}", has_doc, set_format),
+ ]
+}
+
+fn in_story_text(s: &Session) -> std::result::Result<(), String> {
+ super::has_text(s)?;
+ match s.active().and_then(|d| d.selection.text) {
+ Some(t) if t.cell.is_some() => Err("cross-references go in story text (not table cells or footnotes yet)".into()),
+ _ => Ok(()),
+ }
+}
+
+/// The destination anchor from params, creating a paragraph anchor when needed.
+fn destination(d: &mut designcraft_doc::Document, p: &Value) -> Result<u64> {
+ if let Some(a) = p.get("anchor").and_then(Value::as_u64) {
+ return d.find_anchor(a).map(|_| a).ok_or_else(|| bad("xref.insert", format!("no anchor {a}")));
+ }
+ let (sid, pos) = if let Some(text) = str_param(p, "paragraph") {
+ let hit = d.stories.values().find_map(|st| st.text.find(text).map(|i| (st.id, i)));
+ hit.ok_or_else(|| bad("xref.insert", format!("no paragraph contains `{text}`")))?
+ } else if let (Some(sid), Some(pi)) = (p.get("story").and_then(Value::as_u64), p.get("para").and_then(Value::as_u64)) {
+ let st = d.story(StoryId(sid)).ok_or_else(|| bad("xref.insert", "no such story"))?;
+ let r = st.para_ranges().get(pi as usize).cloned().ok_or_else(|| bad("xref.insert", "no such paragraph"))?;
+ (StoryId(sid), r.start)
+ } else {
+ return Err(bad("xref.insert", "give `anchor`, `paragraph` or `story` + `para`"));
+ };
+ d.paragraph_anchor(sid, pos).ok_or_else(|| bad("xref.insert", "could not anchor the paragraph"))
+}
+
+fn insert(s: &mut Session, p: &Value) -> Result<Value> {
+ let p = p.clone();
+ s.edit(|d, sel| {
+ let format = str_param(&p, "format").unwrap_or("Full Paragraph & Page Number").to_string();
+ if d.xref_format(&format).is_none() {
+ return Err(bad("xref.insert", format!("no cross-reference format `{format}`")));
+ }
+ let t = sel.text.ok_or_else(|| bad("xref.insert", "no insertion point"))?;
+ // A new paragraph anchor before the caret in the same story shifts the caret.
+ let len0 = d.story(t.story).map_or(0, |st| st.len());
+ let target = destination(d, &p)?;
+ let mut t2 = t;
+ if let Some((asid, apos)) = d.find_anchor(target)
+ && asid == t.story
+ && apos <= t.range().start
+ {
+ let grew = d.story(t.story).map_or(0, |st| st.len()) - len0;
+ t2.anchor += grew;
+ t2.focus += grew;
+ }
+ let st = d.story_mut(t.story).ok_or(designcraft_doc::DocError::NoStory(t.story))?;
+ let r = t2.range();
+ let r = r.start.min(st.len())..r.end.min(st.len());
+ st.delete(r.clone());
+ st.insert_xref(r.start, CrossRef { target, format });
+ let pos = r.start + designcraft_doc::XREF_MARK.len_utf8();
+ sel.text = Some(TextSel { anchor: pos, focus: pos, ..t2 });
+ Ok(json!({"target": target, "pos": r.start}))
+ })
+}
+
+fn create_anchor(s: &mut Session, p: &Value) -> Result<Value> {
+ let name = str_param(p, "name").ok_or_else(|| bad("anchor.create", "missing name"))?.to_string();
+ s.edit(|d, sel| {
+ let t = sel.text.ok_or_else(|| bad("anchor.create", "no insertion point"))?;
+ let st = d.story_mut(t.story).ok_or(designcraft_doc::DocError::NoStory(t.story))?;
+ let at = t.range().start.min(st.len());
+ let id = st.insert_anchor(at, &name);
+ let pos = t.focus + designcraft_doc::ANCHOR_MARK.len_utf8();
+ sel.text = Some(TextSel { anchor: pos, focus: pos, ..t });
+ Ok(json!({"id": id}))
+ })
+}
+
+fn list(s: &mut Session, _: &Value) -> Result<Value> {
+ let d = s.doc()?.doc.clone();
+ let index = s.cache.xref_index(&d);
+ let mut out = Vec::new();
+ for st in d.stories.values() {
+ for ((pos, _), x) in st.text.match_indices(designcraft_doc::XREF_MARK).zip(&st.xrefs) {
+ let text = designcraft_compose::xref::xref_text(&d, x, Some(&index));
+ out.push(json!({"story": st.id.0, "pos": pos, "target": x.target, "format": x.format, "text": text}));
+ }
+ }
+ Ok(Value::Array(out))
+}
+
+fn list_anchors(s: &mut Session, _: &Value) -> Result<Value> {
+ let d = s.doc()?.doc.clone();
+ let index = s.cache.xref_index(&d);
+ let mut out = Vec::new();
+ for st in d.stories.values() {
+ for a in &st.anchors {
+ out.push(json!({"id": a.id, "name": a.name, "story": st.id.0, "pos": st.anchor_pos(a.id), "page": index.page(a.id)}));
+ }
+ }
+ Ok(Value::Array(out))
+}
+
+fn define_format(s: &mut Session, p: &Value) -> Result<Value> {
+ let name = str_param(p, "name").ok_or_else(|| bad("xref.defineFormat", "missing name"))?.to_string();
+ let definition = str_param(p, "definition").ok_or_else(|| bad("xref.defineFormat", "missing definition"))?.to_string();
+ s.edit(|d, _| {
+ match d.xref_formats.iter_mut().find(|f| f.name == name) {
+ Some(f) => f.definition = definition.clone(),
+ None => d.xref_formats.push(XrefFormat { name: name.clone(), definition: definition.clone() }),
+ }
+ Ok(Value::Null)
+ })
+}
+
+fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
+ let sid = p.get("story").and_then(Value::as_u64).map(StoryId).ok_or_else(|| bad("xref.setFormat", "missing story"))?;
+ let k = p.get("index").and_then(Value::as_u64).ok_or_else(|| bad("xref.setFormat", "missing index"))? as usize;
+ let format = str_param(p, "format").ok_or_else(|| bad("xref.setFormat", "missing format"))?.to_string();
+ s.edit(|d, _| {
+ if d.xref_format(&format).is_none() {
+ return Err(bad("xref.setFormat", format!("no cross-reference format `{format}`")));
+ }
+ let st = d.story_mut(sid).ok_or(designcraft_doc::DocError::NoStory(sid))?;
+ let x = st.xrefs.get_mut(k).ok_or_else(|| bad("xref.setFormat", "no such cross-reference"))?;
+ std::sync::Arc::make_mut(x).format = format;
+ st.rev += 1;
+ Ok(Value::Null)
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn cross_reference_follows_its_destination() {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({"pages": 3, "facingPages": false})).unwrap();
+ // A heading on page 3 and a referring frame on page 1.
+ let sp = s.doc().unwrap().doc.page_loc(2).unwrap().0;
+ let r = s
+ .execute("frame.create", &json!({"spread": sp, "rect": [72, 72, 400, 200], "content": "text", "text": "Results: what we found"}))
+ .unwrap();
+ let head = s.doc().unwrap().doc.item(designcraft_doc::ItemId(r["id"].as_u64().unwrap())).unwrap().text_frame().unwrap().story;
+ let r = s.execute("frame.create", &json!({"rect": [72, 72, 400, 200], "content": "text", "text": "See ."})).unwrap();
+ let src = s.doc().unwrap().doc.item(designcraft_doc::ItemId(r["id"].as_u64().unwrap())).unwrap().text_frame().unwrap().story;
+ s.execute("text.select", &json!({"story": src.0, "anchor": 4, "focus": 4})).unwrap();
+ s.execute("xref.insert", &json!({"paragraph": "Results"})).unwrap();
+ let l = s.execute("xref.list", &json!({})).unwrap();
+ assert_eq!(l[0]["text"], "\u{201C}Results: what we found\u{201D} on page 3");
+ // Edit the heading: the reference follows without an update step.
+ // The paragraph now starts with its (zero-width) anchor mark.
+ let at = designcraft_doc::ANCHOR_MARK.len_utf8();
+ s.execute("text.select", &json!({"story": head.0, "anchor": at, "focus": at})).unwrap();
+ s.execute("text.insert", &json!({"text": "Key "})).unwrap();
+ let l = s.execute("xref.list", &json!({})).unwrap();
+ assert_eq!(l[0]["text"], "\u{201C}Key Results: what we found\u{201D} on page 3");
+ // Formats.
+ s.execute("xref.setFormat", &json!({"story": src.0, "index": 0, "format": "Partial Paragraph"})).unwrap();
+ assert_eq!(s.execute("xref.list", &json!({})).unwrap()[0]["text"], "\u{201C}Key Results\u{201D}");
+ s.execute("xref.defineFormat", &json!({"name": "Short", "definition": "(p. <pageNum />)"})).unwrap();
+ s.execute("xref.setFormat", &json!({"story": src.0, "index": 0, "format": "Short"})).unwrap();
+ assert_eq!(s.execute("xref.list", &json!({})).unwrap()[0]["text"], "(p. 3)");
+ // The generated text is composed into the source frame.
+ let d = s.doc().unwrap().doc.clone();
+ let cs = s.cache.get(&d, src, None);
+ let glyphs: usize = cs.frames[0].lines.iter().map(|l| l.glyphs.iter().filter(|g| g.visible && g.adv > 0.0).count()).sum();
+ assert!(glyphs >= "See (p. 3).".replace(' ', "").len(), "{glyphs}");
+ // Deleting the destination paragraph's anchor leaves an unresolved reference.
+ let a = s.execute("anchor.list", &json!({})).unwrap();
+ assert_eq!(a[0]["page"], "3");
+ s.execute("text.select", &json!({"story": head.0, "anchor": 0, "focus": 3})).unwrap();
+ s.execute("text.delete", &json!({})).unwrap();
+ assert_eq!(s.execute("xref.list", &json!({})).unwrap()[0]["text"], "??");
+ s.execute("edit.undo", &json!({})).unwrap();
+ assert_eq!(s.execute("xref.list", &json!({})).unwrap()[0]["text"], "(p. 3)");
+ }
+}
diff --git a/crates/idml/src/export.rs b/crates/idml/src/export.rs
index 4161a4d17..a707c2f00 100644
--- a/crates/idml/src/export.rs
+++ b/crates/idml/src/export.rs
@@ -131,11 +131,21 @@ struct Ex<'a> {
fonts: BTreeMap<String, BTreeSet<String>>,
/// Item id → (prev frame, next frame) for threaded text frames.
threads: HashMap<u64, (Option<u64>, Option<u64>)>,
+ /// Cross-reference sources written so far: (Self, target anchor).
+ xref_sources: Vec<(String, u64)>,
}
impl<'a> Ex<'a> {
fn new(d: &'a Document, opts: &'a ExportOptions) -> Self {
- let mut ex = Ex { d, opts, next: d.next_id + 0x100, swatch_ids: HashMap::new(), fonts: BTreeMap::new(), threads: HashMap::new() };
+ let mut ex = Ex {
+ d,
+ opts,
+ next: d.next_id + 0x100,
+ swatch_ids: HashMap::new(),
+ fonts: BTreeMap::new(),
+ threads: HashMap::new(),
+ xref_sources: Vec::new(),
+ };
ex.assign_swatch_ids();
for s in d.stories.values() {
for (i, f) in s.frames.iter().enumerate() {
@@ -272,6 +282,11 @@ impl<'a> Ex<'a> {
.attr("ContinueNumbersAcrossDocuments", "false"),
);
root.push(El::new("idPkg:Preferences").attr("src", "Resources/Preferences.xml"));
+ // Variables InDesign's cross-reference page/chapter blocks rely on.
+ for (name, ty) in [("XRefChapterNumber", "XrefChapterNumberType"), ("XRefPageNumber", "XrefPageNumberType")] {
+ let n = format!("<?AID 001b?>TV {name}");
+ root.push(El::new("TextVariable").attr("Self", format!("dTextVariablen{n}")).attr("Name", &n).attr("VariableType", ty));
+ }
for l in &d.layers {
let color = match names::layer_color_out(l.color) {
Some(n) => p("LayerColor", "enumeration", n),
@@ -337,9 +352,29 @@ impl<'a> Ex<'a> {
el = el.attr("Marker", &s.marker).attr("PageStart", uid(page.id.0)).attr("SectionPrefix", &s.prefix);
root.push(with_props(el, vec![p("PageNumberStyle", "enumeration", names::number_style_out(s.style))]));
}
+ // Formats before the stories whose sources apply them.
+ for (i, f) in d.xref_formats.iter().enumerate() {
+ root.push(xref_format_el(i, f));
+ }
for (name, _) in stories {
root.push(El::new("idPkg:Story").attr("src", name));
}
+ for (src, target) in self.xref_sources.clone() {
+ let mut h = El::new("Hyperlink")
+ .attr("Self", self.fresh())
+ .attr("Name", "Cross-Reference")
+ .attr("Source", &src)
+ .attr("Visible", "false")
+ .attr("Highlight", "None")
+ .attr("Width", "Thin")
+ .attr("BorderStyle", "Solid")
+ .attr("Hidden", "false")
+ .attr("DestinationUniqueKey", target & 0xFFFF_FFFF);
+ let mut props = El::new("Properties");
+ props.push(p("Destination", "object", anchor_self(target)));
+ h.push(props);
+ root.push(h);
+ }
// Root colour group: the Swatches panel order.
let mut cg =
El::new("ColorGroup").attr("Self", "ColorGroup/[Root Color Group]").attr("Name", "[Root Color Group]").attr("IsRootColorGroup", "true");
@@ -1385,6 +1420,49 @@ impl<'a> Ex<'a> {
if let Some(t) = s.para_table(pi) {
out.push(Node::El(self.table_el(t)));
}
+ } else if ch == designcraft_doc::ANCHOR_MARK {
+ flush_text(&mut cur, &mut pending);
+ flush_content(&mut pending, &mut out);
+ let k = s.text[..seg_start + ci].matches(designcraft_doc::ANCHOR_MARK).count();
+ if let Some(a) = s.anchors.get(k) {
+ out.push(Node::El(
+ El::new("HyperlinkTextDestination")
+ .attr("Self", anchor_self(a.id))
+ .attr("Name", &a.name)
+ .attr("Hidden", "false")
+ .attr("DestinationUniqueKey", a.id & 0xFFFF_FFFF),
+ ));
+ }
+ } else if ch == designcraft_doc::XREF_MARK {
+ // A source wrapping its current text (InDesign regenerates it on update).
+ flush_text(&mut cur, &mut pending);
+ flush_content(&mut pending, &mut out);
+ if !out.is_empty() {
+ let mut c = self.csr_el(&f);
+ c.children.append(&mut out);
+ csrs.push(c);
+ }
+ let k = s.text[..seg_start + ci].matches(designcraft_doc::XREF_MARK).count();
+ if let Some(x) = s.xrefs.get(k) {
+ let me = self.fresh();
+ let fmt = self.d.xref_formats.iter().position(|ff| ff.name == x.format).map_or("n".to_string(), xref_format_self);
+ let text = self.d.xref_values(x.target).map_or("??".into(), |mut v| {
+ v.page = "?".into();
+ designcraft_doc::xref::expand(self.d.xref_format(&x.format).map_or("<fullPara />", |ff| ff.definition.as_str()), &v)
+ });
+ let mut c = self.csr_el(&f);
+ let mut content = El::new("Content");
+ content.children.push(Node::Text(text));
+ c.push(content);
+ let mut src = El::new("CrossReferenceSource")
+ .attr("Self", &me)
+ .attr("AppliedFormat", fmt)
+ .attr("Name", format!("Cross-Reference {}", self.xref_sources.len() + 1))
+ .attr("Hidden", "false");
+ src.push(c);
+ csrs.push(src);
+ self.xref_sources.push((me, x.target));
+ }
} else if ch == designcraft_doc::FOOTNOTE_REF {
// The reference: its own range carrying the reference position.
flush_text(&mut cur, &mut pending);
@@ -1721,3 +1799,55 @@ const STROKE_STYLES: &[&str] = &[
"Dashed",
"Solid",
];
+
+fn anchor_self(id: u64) -> String {
+ format!("HyperlinkTextDestination/a{id}")
+}
+
+fn xref_format_self(i: usize) -> String {
+ format!("CrossReferenceFormat/f{i}")
+}
+
+/// A cross-reference format as InDesign building blocks.
+fn xref_format_el(i: usize, f: &designcraft_doc::XrefFormat) -> El {
+ let me = xref_format_self(i);
+ let mut el = El::new("CrossReferenceFormat").attr("Self", &me).attr("Name", &f.name).attr("AppliedCharacterStyle", "n");
+ let mut k = 0;
+ let mut block = |el: &mut El, kind: &str, text: &str, delim: &str, include: bool| {
+ el.push(
+ El::new("BuildingBlock")
+ .attr("Self", format!("{me}BuildingBlock{k}"))
+ .attr("BlockType", kind)
+ .attr("AppliedCharacterStyle", "n")
+ .attr("CustomText", if text.is_empty() { "$ID/" } else { text })
+ .attr("AppliedDelimiter", if delim.is_empty() { "$ID/" } else { delim })
+ .attr("IncludeDelimiter", bool_s(include)),
+ );
+ k += 1;
+ };
+ let mut rest = f.definition.as_str();
+ while let Some(a) = rest.find('<') {
+ if a > 0 {
+ block(&mut el, "CustomStringBuildingBlock", &rest[..a], "", false);
+ }
+ let Some(b) = rest[a..].find('>') else { break };
+ let tag = rest[a + 1..a + b].trim().trim_end_matches('/').trim();
+ let attr = |k: &str| tag.find(&format!("{k}=\"")).and_then(|i| tag[i + k.len() + 2..].split('"').next()).unwrap_or("").to_string();
+ match tag.split_whitespace().next().unwrap_or("") {
+ "fullPara" => block(&mut el, "FullParagraphBuildingBlock", "", "", false),
+ "paraText" => block(&mut el, "ParagraphTextBuildingBlock", "", "", false),
+ "paraNum" => block(&mut el, "ParagraphNumberBuildingBlock", "", "", false),
+ "pageNum" => block(&mut el, "PageNumberBuildingBlock", "", "", false),
+ "txtAnchrName" => block(&mut el, "BookmarkNameBuildingBlock", "", "", false),
+ "chapNum" => block(&mut el, "ChapterNumberBuildingBlock", "", "", false),
+ "fileName" => block(&mut el, "FileNameBuildingBlock", "", "", false),
+ "partialPara" => block(&mut el, "PartialParagraphBuildingBlock", "", &attr("delim"), attr("includeDelim") == "true"),
+ _ => block(&mut el, "CustomStringBuildingBlock", &rest[a..a + b + 1], "", false),
+ }
+ rest = &rest[a + b + 1..];
+ }
+ if !rest.is_empty() {
+ block(&mut el, "CustomStringBuildingBlock", rest, "", false);
+ }
+ el
+}
diff --git a/crates/idml/src/import.rs b/crates/idml/src/import.rs
index 060fa17e3..5e5126e90 100644
--- a/crates/idml/src/import.rs
+++ b/crates/idml/src/import.rs
@@ -116,6 +116,13 @@ struct Importer<'r> {
ctx: ItemCtx,
sections: Vec<Section>,
footnote_options: designcraft_doc::FootnoteOptions,
+ /// Text destination Self → anchor id.
+ anchor_ids: HashMap<String, u64>,
+ /// Cross-reference source Self → (story, index in its cross-references).
+ xref_srcs: HashMap<String, (StoryId, usize)>,
+ /// Cross-reference format Self → name.
+ xref_format_names: HashMap<String, String>,
+ xref_formats: Vec<designcraft_doc::XrefFormat>,
}
fn lab_to_color(l: f32, a: f32, b: f32) -> Color {
@@ -182,6 +189,10 @@ impl<'r> Importer<'r> {
ctx: ItemCtx { threads: Vec::new() },
sections: Vec::new(),
footnote_options: Default::default(),
+ anchor_ids: HashMap::new(),
+ xref_srcs: HashMap::new(),
+ xref_format_names: HashMap::new(),
+ xref_formats: designcraft_doc::xref::default_formats(),
}
}
@@ -265,6 +276,9 @@ impl<'r> Importer<'r> {
suppress_wrap_when_hidden: false,
});
}
+ for e in top.iter().filter(|e| e.local() == "CrossReferenceFormat") {
+ self.xref_format(e);
+ }
// Stories (ids first so frames can reference them).
for e in top.iter().filter(|e| e.local() == "Story") {
let id = StoryId(self.alloc());
@@ -274,6 +288,14 @@ impl<'r> Importer<'r> {
let story = self.story(id, e);
self.stories.insert(id, story);
}
+ // Cross-references point at their hyperlink's destination.
+ for h in top.iter().filter(|e| e.local() == "Hyperlink") {
+ let (Some(src), Some(dest)) = (h.get("Source"), h.prop("Destination")) else { continue };
+ let (Some(&(sid, k)), Some(&target)) = (self.xref_srcs.get(src), self.anchor_ids.get(dest.trim())) else { continue };
+ if let Some(x) = self.stories.get_mut(&sid).and_then(|st| st.xrefs.get_mut(k)) {
+ Arc::make_mut(x).target = target;
+ }
+ }
// Parent spreads: ids first (pages reference other parents).
let masters: Vec<&El> = top.iter().filter(|e| e.local() == "MasterSpread").collect();
let mut master_ids = Vec::new();
@@ -655,6 +677,38 @@ impl<'r> Importer<'r> {
}
}
+ /// `CrossReferenceFormat`: building blocks back to a format definition.
+ fn xref_format(&mut self, e: &El) {
+ let name = e.get("Name").unwrap_or("Format").to_string();
+ let mut def = String::new();
+ for b in e.find_all("BuildingBlock") {
+ let text = |k: &str| b.get(k).filter(|v| *v != "$ID/").unwrap_or("").to_string();
+ match b.get("BlockType").unwrap_or("") {
+ "CustomStringBuildingBlock" => def.push_str(&text("CustomText")),
+ "FullParagraphBuildingBlock" => def.push_str("<fullPara />"),
+ "ParagraphTextBuildingBlock" => def.push_str("<paraText />"),
+ "ParagraphNumberBuildingBlock" => def.push_str("<paraNum />"),
+ "PageNumberBuildingBlock" => def.push_str("<pageNum />"),
+ "BookmarkNameBuildingBlock" => def.push_str("<txtAnchrName />"),
+ "ChapterNumberBuildingBlock" => def.push_str("<chapNum />"),
+ "FileNameBuildingBlock" => def.push_str("<fileName />"),
+ "PartialParagraphBuildingBlock" => def.push_str(&format!(
+ "<partialPara delim=\"{}\" includeDelim=\"{}\" />",
+ text("AppliedDelimiter"),
+ b.get("IncludeDelimiter") == Some("true")
+ )),
+ _ => {}
+ }
+ }
+ if let Some(me) = e.get("Self") {
+ self.xref_format_names.insert(me.to_string(), name.clone());
+ }
+ match self.xref_formats.iter_mut().find(|f| f.name == name) {
+ Some(f) => f.definition = def,
+ None => self.xref_formats.push(designcraft_doc::XrefFormat { name, definition: def }),
+ }
+ }
+
/// Preferences › `FootnoteOption` (after styles: it names the footnote text and marker styles).
fn footnote_option(&mut self, e: &El) {
let mut o = designcraft_doc::FootnoteOptions::default();
@@ -881,9 +935,11 @@ impl<'r> Importer<'r> {
tables: Vec::new(),
after_table: None,
notes: Vec::new(),
+ anchors: Vec::new(),
+ xrefs: Vec::new(),
};
self.walk_story(e, &mut b, &ParaFormat::default(), &CharAttrs::default(), &CharFormat::default(), None);
- let StoryBuilder { text, mut paras, runs, last, tables: tbls, notes, .. } = b;
+ let StoryBuilder { text, mut paras, runs, last, tables: tbls, notes, anchors, xrefs, .. } = b;
let mut chars: Vec<CharRun> = runs.into_iter().filter(|r| r.len > 0).collect();
if chars.is_empty() {
chars.push(CharRun { len: 0, format: last });
@@ -896,8 +952,21 @@ impl<'r> Importer<'r> {
}
}
let notes = notes.into_iter().enumerate().map(|(i, text)| Arc::new(designcraft_doc::Footnote { id: i as u64 + 1, text })).collect();
- let mut st = Story { id, text, paras, chars, frames: vec![], rev: 0, tables, notes };
+ let mut anchor_list = Vec::new();
+ for (k, (me, name)) in anchors.into_iter().enumerate() {
+ let aid = (id.0 << 24) | (k as u64 + 1);
+ self.anchor_ids.insert(me, aid);
+ anchor_list.push(Arc::new(designcraft_doc::TextAnchor { id: aid, name }));
+ }
+ let mut xref_list = Vec::new();
+ for (k, (me, fmt)) in xrefs.into_iter().enumerate() {
+ self.xref_srcs.insert(me, (id, k));
+ let format = self.xref_format_names.get(&fmt).cloned().unwrap_or_else(|| "Full Paragraph & Page Number".into());
+ xref_list.push(Arc::new(designcraft_doc::CrossRef { target: 0, format }));
+ }
+ let mut st = Story { id, text, paras, chars, frames: vec![], rev: 0, tables, notes, anchors: anchor_list, xrefs: xref_list };
st.fix_notes();
+ st.fix_marks();
// Drop anything inconsistent (e.g. a table sharing a paragraph with another).
if st.check().is_err() {
st.tables.retain(|_, _| false);
@@ -1078,6 +1147,20 @@ impl<'r> Importer<'r> {
let t = self.table(c);
b.push_table(t, pf, cf);
}
+ "HyperlinkTextDestination" | "ParagraphDestination" => {
+ b.anchors.push((c.get("Self").unwrap_or("").to_string(), c.get("Name").unwrap_or("Anchor").to_string()));
+ b.push(&designcraft_doc::ANCHOR_MARK.to_string(), cf);
+ }
+ "CrossReferenceSource" => {
+ // The generated text is regenerated from the format.
+ b.xrefs.push((c.get("Self").unwrap_or("").to_string(), c.get("AppliedFormat").unwrap_or("").to_string()));
+ let inner = c.find("CharacterStyleRange");
+ let f = match inner.and_then(|r| r.get("AppliedCharacterStyle")) {
+ Some(r) => CharFormat { style: self.char_style_ref(r), over: pchars.clone() },
+ None => cf.clone(),
+ };
+ b.push(&designcraft_doc::XREF_MARK.to_string(), &f);
+ }
"Footnote" => {
// The text starts with the number marker (ACE 4, dropped) and the separator.
let mut note = self.story(StoryId(0), c);
@@ -1557,6 +1640,7 @@ impl<'r> Importer<'r> {
toc: None,
text_variables: designcraft_doc::vars::defaults(),
footnote_options: std::mem::take(&mut self.footnote_options),
+ xref_formats: std::mem::take(&mut self.xref_formats),
created: designcraft_doc::vars::now(),
modified: 0,
next_id: self.next_id,
@@ -1587,6 +1671,9 @@ struct StoryBuilder {
after_table: Option<ParaFormat>,
/// Footnote texts in reference order.
notes: Vec<Story>,
+ /// Text destinations (Self, name) and cross-reference sources (Self, format Self) in order.
+ anchors: Vec<(String, String)>,
+ xrefs: Vec<(String, String)>,
}
impl StoryBuilder {
diff --git a/crates/idml/src/tests.rs b/crates/idml/src/tests.rs
index 1c799e03b..633bf5ff7 100644
--- a/crates/idml/src/tests.rs
+++ b/crates/idml/src/tests.rs
@@ -426,3 +426,30 @@ fn imports_indesign_style_footnote() {
// One run: the reference takes its position from the options, not an override.
assert_eq!(s.chars.len(), 1);
}
+
+#[test]
+fn round_trips_cross_references() {
+ let mut d = Document::new(&NewDocument::default());
+ let lid = d.default_layer();
+ let (_, sid) =
+ d.add_text_frame(SpreadRef::Doc(0), Rect::new(40.0, 40.0, 400.0, 400.0), lid, "Results: found\nSee .", ParaFormat::default()).unwrap();
+ let target = d.paragraph_anchor(sid, 0).unwrap();
+ let at = d.story(sid).unwrap().text.find(" .").unwrap() + 1;
+ d.story_mut(sid).unwrap().insert_xref(at, designcraft_doc::CrossRef { target, format: "Paragraph Text".into() });
+ d.xref_formats.push(designcraft_doc::XrefFormat {
+ name: "Mine".into(),
+ definition: "(<partialPara delim=\":\" includeDelim=\"true\" />, p. <pageNum />)".into(),
+ });
+ d.check().unwrap();
+ let back = import_idml(&export_idml(&d)).unwrap();
+ back.check().unwrap();
+ let s = back.stories.values().next().unwrap();
+ assert_eq!(s.text, d.story(sid).unwrap().text);
+ assert_eq!(s.xrefs.len(), 1);
+ assert_eq!(s.xrefs[0].format, "Paragraph Text");
+ let (tsid, tpos) = back.find_anchor(s.xrefs[0].target).expect("target resolves");
+ assert_eq!((tsid, tpos), (s.id, 0));
+ let mine = back.xref_format("Mine").unwrap();
+ assert_eq!(mine.definition, d.xref_format("Mine").unwrap().definition);
+ assert_eq!(back.xref_formats.len(), d.xref_formats.len());
+}
diff --git a/crates/pdf/src/links.rs b/crates/pdf/src/links.rs
index d025e49f4..e63d70887 100644
--- a/crates/pdf/src/links.rs
+++ b/crates/pdf/src/links.rs
@@ -76,6 +76,28 @@ pub(crate) fn annotations(doc: &Document, cache: &designcraft_compose::Cache, sh
out.push(Annotation::new_link(LinkAnnotation::new(rect, target), Some(h.name.clone())));
}
}
+ // Cross-references link to their destination's page.
+ if doc.stories.values().any(|st| !st.xrefs.is_empty()) {
+ let index = cache.xref_index(doc);
+ for st in doc.stories.values().filter(|st| !st.xrefs.is_empty()) {
+ for ((pos, _), x) in st.text.match_indices(designcraft_doc::XREF_MARK).zip(&st.xrefs) {
+ let Some(i) = index.page_index(x.target).and_then(|p| sheet_of_page(doc, sheets, p)) else { continue };
+ let src = HyperlinkSource::Text { story: st.id, start: pos, end: pos + designcraft_doc::XREF_MARK.len_utf8() };
+ for r in source_rects(doc, cache, &src, sh.spread) {
+ let r = r.intersect(sh.bleed);
+ let rect = krilla::geom::Rect::from_ltrb(
+ (r.x0 - sh.media.x0) as f32,
+ (r.y0 - sh.media.y0) as f32,
+ (r.x1 - sh.media.x0) as f32,
+ (r.y1 - sh.media.y0) as f32,
+ );
+ let Some(rect) = rect.filter(|_| r.width() > 0.0 && r.height() > 0.0) else { continue };
+ let target = Target::Destination(XyzDestination::new(i, krilla::geom::Point::from_xy(0.0, 0.0)).into());
+ out.push(Annotation::new_link(LinkAnnotation::new(rect, target), Some(format!("Cross-reference: {}", x.format))));
+ }
+ }
+ }
+ }
out
}
diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs
index c50c38e6e..d26d894b7 100644
--- a/crates/ui-egui/src/dialogs.rs
+++ b/crates/ui-egui/src/dialogs.rs
@@ -27,6 +27,7 @@ impl Dialog {
}
"goToPage" => json!({"page": 1}),
"insertTable" => json!({"bodyRows": 4, "columns": 4, "headerRows": 0, "footerRows": 0}),
+ "insertXref" => json!({"linkTo": "paragraph", "style": "", "target": "", "format": ""}),
"findChange" => json!({"find": "", "change": "", "grep": false, "caseSensitive": false, "wholeWord": false, "scope": "document"}),
"textFrameOptions" => json!({"columns": 1, "gutter": "1p0", "inset": "0p0", "verticalJustification": "top"}),
"documentSetup" => json!({}),
@@ -121,6 +122,7 @@ pub fn show(app: &mut DesignApp, ctx: &egui::Context) {
"findChange" => "Find/Change",
"paragraphStyleOptions" => "Paragraph Style Options",
"footnoteOptions" => "Footnote Options",
+ "insertXref" => "New Cross-Reference",
id => match id.strip_prefix("cmd:").and_then(designcraft_engine::find_command) {
Some(c) => c.label.trim_end_matches('…'),
None => "Dialog",
@@ -128,6 +130,7 @@ pub fn show(app: &mut DesignApp, ctx: &egui::Context) {
};
egui::Modal::new(egui::Id::new("dialog")).show(ctx, |ui| {
ui.set_min_width(380.0);
+ ui.set_max_width(640.0);
ui.label(egui::RichText::new(title).font(semibold(16.0)));
ui.add_space(10.0);
match d.id.as_str() {
@@ -252,6 +255,7 @@ pub fn show(app: &mut DesignApp, ctx: &egui::Context) {
}
"paragraphStyleOptions" => paragraph_style_options(app, ui, &mut d),
"footnoteOptions" => footnote_options(app, ui, &mut d),
+ "insertXref" => insert_xref(app, ui, &mut d),
id if id.starts_with("cmd:") => command_form(ui, &mut d),
"goToPage" => {
ui.horizontal(|ui| {
@@ -401,6 +405,21 @@ pub fn confirm(app: &mut DesignApp) -> Result<Value, String> {
}
app.run("style.paragraph.edit", params)
}
+ "insertXref" => {
+ let format = d.s("format");
+ let target = d.s("target");
+ let params = match target.split_once(':') {
+ Some(("a", id)) => json!({"anchor": id.parse::<u64>().unwrap_or(0), "format": format}),
+ Some((sid, pi)) => json!({"story": sid.parse::<u64>().unwrap_or(0), "para": pi.parse::<u64>().unwrap_or(0), "format": format}),
+ None => {
+ let mut d = d.clone();
+ d.fields.insert("status".into(), json!("Choose a destination paragraph or text anchor."));
+ app.ui.dialog = Some(d);
+ return Err("no destination chosen".into());
+ }
+ };
+ app.run("xref.insert", params)
+ }
"footnoteOptions" => {
let pt = |k: &str| d.pt(k).map_or(Value::Null, |v| json!(v));
let mut p = json!({
@@ -929,6 +948,90 @@ fn command_form(ui: &mut egui::Ui, d: &mut Dialog) {
}
}
+/// New Cross-Reference: link to a paragraph (paragraph styles on the left, their paragraphs on
+/// the right) or a text anchor, with a cross-reference format.
+fn insert_xref(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) {
+ let Some(st) = app.session.active() else { return };
+ let doc = &st.doc;
+ let all = "[All Paragraphs]";
+ ui.horizontal(|ui| {
+ ui.label("Link To:");
+ combo(ui, d, "linkTo", &[("paragraph", "Paragraph"), ("anchor", "Text Anchor")]);
+ });
+ ui.add_space(6.0);
+ let dim = crate::theme::Tokens::get(ui.ctx()).text_dim;
+ if d.s("linkTo") == "anchor" {
+ egui::ScrollArea::vertical().id_salt("xr_anchors").max_height(220.0).max_width(460.0).show(ui, |ui| {
+ let mut any = false;
+ for st in doc.stories.values() {
+ for a in &st.anchors {
+ any = true;
+ let key = format!("a:{}", a.id);
+ if ui.selectable_label(d.s("target") == key, &a.name).clicked() {
+ d.fields.insert("target".into(), json!(key));
+ }
+ }
+ }
+ if !any {
+ ui.label(egui::RichText::new("No text anchors in this document.").color(dim));
+ }
+ });
+ } else {
+ let mut styles: Vec<String> = vec![all.to_string()];
+ styles.extend(doc.styles.paragraph.iter().map(|s| s.name.clone()));
+ let cur_style = if d.s("style").is_empty() { all.to_string() } else { d.s("style") };
+ ui.horizontal_top(|ui| {
+ let col = |w: f32| (egui::vec2(w, 240.0), egui::Layout::top_down(egui::Align::Min));
+ let (sz, lay) = col(180.0);
+ ui.allocate_ui_with_layout(sz, lay, |ui| {
+ egui::ScrollArea::vertical().id_salt("xr_styles").auto_shrink([false, false]).show(ui, |ui| {
+ for name in &styles {
+ if ui.selectable_label(*name == cur_style, name).clicked() {
+ d.fields.insert("style".into(), json!(name));
+ }
+ }
+ })
+ });
+ ui.add_space(8.0);
+ let (sz, lay) = col(330.0);
+ ui.allocate_ui_with_layout(sz, lay, |ui| {
+ egui::ScrollArea::vertical().id_salt("xr_paras").auto_shrink([false, false]).show(ui, |ui| {
+ for st in doc.stories.values().filter(|s| !s.frames.is_empty()) {
+ for (pi, r) in st.para_ranges().into_iter().enumerate() {
+ if cur_style != all && st.paras[pi].style != cur_style {
+ continue;
+ }
+ let text = designcraft_doc::xref::clean(&st.text[r]);
+ if text.is_empty() {
+ continue;
+ }
+ let short: String = text.chars().take(52).collect();
+ let key = format!("{}:{pi}", st.id.0);
+ if ui.selectable_label(d.s("target") == key, short).clicked() {
+ d.fields.insert("target".into(), json!(key));
+ }
+ }
+ }
+ })
+ });
+ });
+ }
+ ui.add_space(8.0);
+ ui.label(egui::RichText::new("Cross-Reference Format").font(semibold(12.0)));
+ let names: Vec<String> = doc.xref_formats.iter().map(|f| f.name.clone()).collect();
+ if d.s("format").is_empty() {
+ d.fields.insert("format".into(), json!(names.first().cloned().unwrap_or_default()));
+ }
+ let opts: Vec<(&str, &str)> = names.iter().map(|n| (n.as_str(), n.as_str())).collect();
+ ui.horizontal(|ui| {
+ ui.label("Format:");
+ combo(ui, d, "format", &opts);
+ });
+ if let Some(m) = d.fields.get("status").and_then(Value::as_str) {
+ ui.label(egui::RichText::new(m).color(dim));
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs
index 8733dd2cf..650c9e0a5 100644
--- a/crates/ui-egui/src/menus.rs
+++ b/crates/ui-egui/src/menus.rs
@@ -18,6 +18,9 @@ pub const UI_COMMANDS: &[(&str, &str, Option<&str>, &str)] = &[
("app.findChange", "Find/Change…", Some("Cmd+F"), "{}"),
("app.insertTableDialog", "Create Table…", None, "{} — Insert Table dialog (body/header/footer rows, columns)"),
("app.footnoteOptionsDialog", "Document Footnote Options…", None, "{} — numbering, formatting and layout of footnotes"),
+ ("app.insertXrefDialog", "Insert Cross-Reference…", None, "{} — New Cross-Reference dialog (paragraph or text anchor, format)"),
+ ("app.deletePage", "Delete Page", None, "{} — deletes the page in view"),
+ ("app.duplicateSpread", "Duplicate Spread", None, "{} — duplicates the spread in view (pages and items)"),
("app.tablePanel", "Table Panel", Some("Shift+F9"), "{}"),
("app.storyEditor", "Edit in Story Editor", Some("Cmd+Y"), "{story?}"),
("view.zoomIn", "Zoom In", Some("Cmd+="), "{}"),
@@ -78,6 +81,10 @@ pub const MENUS: &[(&str, &[&str])] = &[
"ui:app.exportPdf",
"ui:app.exportPng",
"ui:app.exportIdml",
+ "cmd:file.exportEpub",
+ ">Export",
+ "cmd:snippet.export",
+ "<",
"-",
"cmd:layout.documentSetup",
],
@@ -95,6 +102,7 @@ pub const MENUS: &[(&str, &[&str])] = &[
"cmd:edit.clear",
"-",
"cmd:edit.duplicate",
+ "cmd:edit.stepAndRepeat",
"-",
"cmd:edit.selectAll",
"cmd:edit.deselectAll",
@@ -103,10 +111,35 @@ pub const MENUS: &[(&str, &[&str])] = &[
"cmd:find.next",
"ui:app.storyEditor",
"-",
+ ">Spelling",
+ "cmd:spelling.check",
+ "cmd:spelling.addWord",
+ "<",
+ "-",
"ui:app.palette",
],
),
- ("Layout", &[">Pages", "cmd:layout.pages.insert", "cmd:layout.parents.new", "<", "cmd:layout.marginsAndColumns", "-", "ui:view.goToPage"]),
+ (
+ "Layout",
+ &[
+ ">Pages",
+ "cmd:layout.pages.insert",
+ "cmd:layout.pages.move",
+ "ui:app.duplicateSpread",
+ "ui:app.deletePage",
+ "-",
+ "cmd:layout.pages.applyParent",
+ "cmd:layout.parents.new",
+ "<",
+ "cmd:layout.marginsAndColumns",
+ "-",
+ "ui:view.goToPage",
+ "-",
+ "cmd:layout.section",
+ "cmd:toc.generate",
+ "cmd:toc.update",
+ ],
+ ),
(
"Type",
&[
@@ -127,6 +160,18 @@ pub const MENUS: &[(&str, &[&str])] = &[
"-",
"ui:view.hiddenCharacters",
"-",
+ ">Hyperlinks & Cross-References",
+ "cmd:hyperlink.create",
+ "cmd:anchor.create",
+ "-",
+ "ui:app.insertXrefDialog",
+ "cmd:xref.defineFormat",
+ "<",
+ ">Text Variables",
+ "cmd:variables.define",
+ "cmd:variables.insert",
+ "<",
+ "-",
"cmd:footnote.insert",
"ui:app.footnoteOptionsDialog",
"cmd:footnote.goToReference",
@@ -136,6 +181,11 @@ pub const MENUS: &[(&str, &[&str])] = &[
"Object",
&[
">Transform",
+ "cmd:transform.move",
+ "cmd:transform.scale",
+ "cmd:transform.rotate",
+ "cmd:transform.shear",
+ "-",
"cmd:transform.flip",
"<",
">Arrange",
@@ -157,6 +207,21 @@ pub const MENUS: &[(&str, &[&str])] = &[
"-",
">Effects",
"cmd:object.dropShadow",
+ "cmd:object.innerShadow",
+ "cmd:object.outerGlow",
+ "cmd:object.feather",
+ "<",
+ ">Fitting",
+ "cmd:object.fit|Fill Frame Proportionally|{\"mode\":\"fillProportionally\"}",
+ "cmd:object.fit|Fit Content Proportionally|{\"mode\":\"fitProportionally\"}",
+ "cmd:object.fit|Fit Frame to Content|{\"mode\":\"fitFrameToContent\"}",
+ "cmd:object.fit|Fit Content to Frame|{\"mode\":\"fitContentToFrame\"}",
+ "cmd:object.fit|Center Content|{\"mode\":\"centerContent\"}",
+ "<",
+ ">Content",
+ "cmd:object.content|Graphic|{\"type\":\"graphic\"}",
+ "cmd:object.content|Text|{\"type\":\"text\"}",
+ "cmd:object.content|Unassigned|{\"type\":\"unassigned\"}",
"<",
],
),
@@ -212,7 +277,25 @@ pub const MENUS: &[(&str, &[&str])] = &[
"ui:view.baselineGrid",
],
),
- ("Window", &["ui:window.controlBar", "ui:window.taskBar", "ui:window.toolsDoubleColumn", "-", "ui:window.panel", "-", "ui:window.brightness"]),
+ (
+ "Window",
+ &[
+ "ui:window.controlBar",
+ "ui:window.taskBar",
+ "ui:window.toolsDoubleColumn",
+ "-",
+ "ui:window.panel",
+ "-",
+ ">Utilities",
+ "cmd:data.merge",
+ "<",
+ ">Output",
+ "cmd:preflight.run",
+ "<",
+ "-",
+ "ui:window.brightness",
+ ],
+ ),
(
"Help",
&[
@@ -294,6 +377,24 @@ pub fn run_ui(app: &mut DesignApp, id: &str, p: &Value) -> Option<Result<Value,
app.ui.dialog = Some(crate::dialogs::Dialog::new("footnoteOptions", o));
Ok(Value::Null)
}
+ "app.insertXrefDialog" => {
+ if app.session.active().is_none_or(|d| d.selection.text.is_none()) {
+ return Some(Err("place the insertion point in text to insert a cross-reference".into()));
+ }
+ app.ui.dialog = Some(crate::dialogs::Dialog::new("insertXref", json!({})));
+ Ok(Value::Null)
+ }
+ "app.deletePage" | "app.duplicateSpread" => {
+ let Some(st) = app.session.active() else { return Some(Err("no document open".into())) };
+ let page = crate::canvas::current_page(app).unwrap_or(0);
+ let r = if id == "app.deletePage" {
+ app.run("layout.pages.delete", json!({"pages": [page]}))
+ } else {
+ let spread = st.doc.page_loc(page).map_or(0, |l| l.0);
+ app.run("layout.pages.duplicateSpread", json!({"spread": spread}))
+ };
+ return Some(r);
+ }
"app.tablePanel" => {
app.ui.open_panel = if app.ui.open_panel.as_deref() == Some("table") { None } else { Some("table".into()) };
Ok(Value::Null)
@@ -576,7 +677,19 @@ fn parse_entries(entries: &[&str]) -> Vec<Item> {
out.push(Item::Sub("Interface Color Theme".into(), items));
} else {
let (_, id) = e.split_once(':').unwrap_or(("cmd", e));
- out.push(cmd_item(id, Value::Null));
+ // `id|Label|{params}`: a fixed-parameter variant of a command.
+ let mut parts = id.splitn(3, '|');
+ let id = parts.next().unwrap_or(id);
+ match (parts.next(), parts.next().and_then(|j| serde_json::from_str::<Value>(j).ok())) {
+ (Some(label), Some(params)) => {
+ let mut it = cmd_item(id, params);
+ if let Item::Cmd { label: l, .. } = &mut it {
+ *l = label.to_string();
+ }
+ out.push(it);
+ }
+ _ => out.push(cmd_item(id, Value::Null)),
+ }
}
}
out
@@ -619,8 +732,8 @@ pub fn activate(app: &mut DesignApp, id: &str, params: &Value) {
if params.is_null()
&& ui_label(id).is_none()
&& let Some(c) = designcraft_engine::find_command(id)
- && c.label.ends_with('…')
&& !crate::dialogs::command_fields(c.params).is_empty()
+ && (c.label.ends_with('…') || crate::dialogs::command_fields(c.params).iter().any(|f| !f.optional))
{
app.ui.dialog = Some(crate::dialogs::Dialog::new(&format!("cmd:{id}"), json!({})));
return;
@@ -792,3 +905,36 @@ pub fn palette(app: &mut DesignApp, ctx: &egui::Context) {
let _ = app.run(&id, json!({}));
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn walk(items: &[Item], out: &mut Vec<(String, String, Value)>) {
+ for it in items {
+ match it {
+ Item::Sub(_, c) => walk(c, out),
+ Item::Cmd { label, id, params, .. } => out.push((label.clone(), id.clone(), params.clone())),
+ Item::Sep => {}
+ }
+ }
+ }
+
+ #[test]
+ fn every_menu_entry_is_a_command() {
+ let mut all = Vec::new();
+ for (_, items) in menu_tree() {
+ walk(&items, &mut all);
+ }
+ assert!(all.len() > 80, "{}", all.len());
+ for (label, id, params) in &all {
+ assert!(ui_label(id).is_some() || designcraft_engine::find_command(id).is_some(), "menu entry {label}: unknown command {id}");
+ assert!(!label.is_empty() && label != id, "menu entry {id} has no label");
+ if let Some(o) = params.as_object() {
+ assert!(!o.is_empty(), "{id}: empty fixed params");
+ }
+ }
+ // Fixed-parameter variants keep their own labels.
+ assert!(all.iter().any(|(l, id, p)| l == "Fill Frame Proportionally" && id == "object.fit" && p["mode"] == "fillProportionally"));
+ }
+}