mirror of
https://github.com/storytold/wordcraft.git
synced 2026-12-05 12:16:55 -06:00
Merge pull request #7725
This commit is contained in:
@@ -20,7 +20,8 @@ use fields::caption;
|
||||
#[cfg(test)]
|
||||
use fields::output_fields_with;
|
||||
pub use fields::{
|
||||
CHAPTER_SEPARATORS, REFERENCE_NOT_FOUND, output_fields, refresh_date_fields, seq_format, update_fields, update_fields_in, update_seq,
|
||||
CHAPTER_SEPARATORS, REFERENCE_NOT_FOUND, caption_preview, output_fields, refresh_date_fields, seq_format, update_fields, update_fields_in,
|
||||
update_seq,
|
||||
};
|
||||
pub(crate) use fields::{page_at, page_formats, page_label, page_text};
|
||||
pub(super) use notes::note_options;
|
||||
|
||||
@@ -27,12 +27,29 @@ pub const CHAPTER_SEPARATORS: [&str; 5] = ["-", ".", ":", "\u{2014}", "\u{2013}"
|
||||
/// a chapter number (`STYLEREF n \s` and a separator) and a `SEQ label \* format \s n` number
|
||||
/// (ECMA-376 §17.16.5.56, §17.16.5.59).
|
||||
pub(super) fn caption(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let (story, at) = caption_site(s, v);
|
||||
let text = p::str(v, "text").unwrap_or("");
|
||||
s.doc.insert_block(story, &at, Block::Para(caption_paragraph(v, text)?))?;
|
||||
update_seq(s)?;
|
||||
let off = s.doc.para(story, &at).map_or(0, |p| p.len());
|
||||
s.sel = Selection::caret(Pos { story, path: at, off });
|
||||
sel_result(s)
|
||||
}
|
||||
|
||||
/// Number a prospective caption at its insertion site without changing the document or selection.
|
||||
pub fn caption_preview(s: &Session, v: &Value) -> Result<String, CmdError> {
|
||||
let (story, at) = caption_site(s, v);
|
||||
let mut doc = s.doc.clone();
|
||||
doc.insert_block(story, &at, Block::Para(caption_paragraph(v, "")?))?;
|
||||
update_seq_in(&mut doc)?;
|
||||
Ok(doc.para(story, &at).map_or_else(String::new, Paragraph::plain_text))
|
||||
}
|
||||
|
||||
fn caption_paragraph(v: &Value, text: &str) -> Result<Paragraph, CmdError> {
|
||||
let label: String = p::str(v, "label").unwrap_or("Figure").chars().filter(|c| !matches!(c, '"' | '\\') && !c.is_control()).take(40).collect();
|
||||
let label = if label.trim().is_empty() { "Figure".to_string() } else { label.trim().to_string() };
|
||||
// SEQ identifiers are one word: Word joins a multi-word label with underscores.
|
||||
let ident = label.split_whitespace().collect::<Vec<_>>().join("_");
|
||||
let text = p::str(v, "text").unwrap_or("").to_string();
|
||||
let above = p::str(v, "position") == Some("above");
|
||||
let format = seq_format(p::str(v, "format").unwrap_or("ARABIC"));
|
||||
let chapter = p::u64(v, "chapter").filter(|l| (1..=9).contains(l));
|
||||
let sep = p::str(v, "separator").and_then(|x| CHAPTER_SEPARATORS.iter().find(|s| **s == x)).copied().unwrap_or("-");
|
||||
@@ -51,10 +68,15 @@ pub(super) fn caption(s: &mut Session, v: &Value) -> CmdResult {
|
||||
if !text.is_empty() {
|
||||
para.insert_text(para.len(), &format!(": {text}"), &CharProps::default())?;
|
||||
}
|
||||
Ok(para)
|
||||
}
|
||||
|
||||
fn caption_site(s: &Session, v: &Value) -> (StoryRef, Path) {
|
||||
// A selected picture, shape or chart: next to the paragraph holding it, in the same cell or
|
||||
// text box (#1230). Otherwise next to the caret's top-level block: a paragraph, or the whole
|
||||
// table it is in.
|
||||
let f = s.sel.focus.clone();
|
||||
let f = &s.sel.focus;
|
||||
let above = p::str(v, "position") == Some("above");
|
||||
let at = match crate::cmd::objects::object_selection(s) {
|
||||
Some((pos, _)) => {
|
||||
let k = pos.path.last();
|
||||
@@ -65,11 +87,7 @@ pub(super) fn caption(s: &mut Session, v: &Value) -> CmdResult {
|
||||
Path::top(if above { top } else { top.saturating_add(1) })
|
||||
}
|
||||
};
|
||||
s.doc.insert_block(f.story, &at, Block::Para(para))?;
|
||||
update_seq(s)?;
|
||||
let off = s.doc.para(f.story, &at).map_or(0, |p| p.len());
|
||||
s.sel = Selection::caret(Pos { story: f.story, path: at, off });
|
||||
sel_result(s)
|
||||
(f.story, at)
|
||||
}
|
||||
|
||||
/// Renumber the body's SEQ fields in document order, honouring `\* format`, `\s level` (restart
|
||||
@@ -78,11 +96,15 @@ pub(super) fn caption(s: &mut Session, v: &Value) -> CmdResult {
|
||||
/// the last level-n heading's number, or its count when the heading isn't numbered) and the
|
||||
/// text or number of the nearest paragraph of a style.
|
||||
pub fn update_seq(s: &mut Session) -> Result<(), CmdError> {
|
||||
update_seq_in(&mut s.doc)
|
||||
}
|
||||
|
||||
fn update_seq_in(doc: &mut wordcraft_doc::Document) -> Result<(), CmdError> {
|
||||
// Numbers first: a STYLEREF to a heading that holds a SEQ field shows its new number.
|
||||
let numbers = seq_results(&s.doc);
|
||||
apply_results(&mut s.doc, numbers)?;
|
||||
let refs = styleref_results(&s.doc);
|
||||
apply_results(&mut s.doc, refs)
|
||||
let numbers = seq_results(doc);
|
||||
apply_results(doc, numbers)?;
|
||||
let refs = styleref_results(doc);
|
||||
apply_results(doc, refs)
|
||||
}
|
||||
|
||||
/// A field's fresh result: its story and paragraph, its object index there and the text.
|
||||
|
||||
@@ -12,6 +12,7 @@ use craft::ui::text::TextField;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
use wordcraft_doc::Block;
|
||||
use wordcraft_engine::Selection;
|
||||
|
||||
use super::labels::{BUILT_IN_LABELS, NUMBER_FORMATS, SEPARATORS, own_labels};
|
||||
use crate::WordApp;
|
||||
@@ -39,6 +40,17 @@ pub struct CaptionForm {
|
||||
/// Heading level that starts a chapter (1–9).
|
||||
pub chapter_level: u8,
|
||||
pub separator: String,
|
||||
#[serde(skip)]
|
||||
preview: Option<CaptionPreview>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
struct CaptionPreview {
|
||||
document: u64,
|
||||
revision: u64,
|
||||
selection: Selection,
|
||||
number_options: Value,
|
||||
prefix: String,
|
||||
}
|
||||
|
||||
impl CaptionForm {
|
||||
@@ -65,11 +77,15 @@ impl CaptionForm {
|
||||
chapter: false,
|
||||
chapter_level: 1,
|
||||
separator: "-".into(),
|
||||
preview: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The number as it will show (`Figure 1-A`).
|
||||
pub fn preview(&self) -> String {
|
||||
if let Some(preview) = &self.preview {
|
||||
return preview.prefix.clone();
|
||||
}
|
||||
let n = match self.format.as_str() {
|
||||
"alphabetic" => "a",
|
||||
"ALPHABETIC" => "A",
|
||||
@@ -82,11 +98,9 @@ impl CaptionForm {
|
||||
format!("{label}{chapter}{n}")
|
||||
}
|
||||
|
||||
/// `references.caption` parameters.
|
||||
pub fn params(&self) -> Value {
|
||||
fn number_options(&self) -> Value {
|
||||
let mut v = json!({
|
||||
"label": self.label,
|
||||
"text": self.text.trim(),
|
||||
"position": self.position,
|
||||
"excludeLabel": self.exclude_label,
|
||||
"format": self.format,
|
||||
@@ -97,6 +111,13 @@ impl CaptionForm {
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
/// `references.caption` parameters.
|
||||
pub fn params(&self) -> Value {
|
||||
let mut options = self.number_options();
|
||||
options["text"] = json!(self.text.trim());
|
||||
options
|
||||
}
|
||||
}
|
||||
|
||||
impl WordForm for CaptionForm {
|
||||
@@ -112,6 +133,20 @@ impl WordForm for CaptionForm {
|
||||
vec![("references.caption".to_string(), self.params())]
|
||||
}
|
||||
|
||||
fn prepare(&mut self, app: &WordApp) {
|
||||
let session = &app.session;
|
||||
let options = self.number_options();
|
||||
let document = session.document_id();
|
||||
let revision = session.rev();
|
||||
if self.preview.as_ref().is_some_and(|cached| {
|
||||
cached.document == document && cached.revision == revision && cached.selection == session.sel && cached.number_options == options
|
||||
}) {
|
||||
return;
|
||||
}
|
||||
let prefix = wordcraft_engine::cmd::references::caption_preview(session, &options).unwrap_or_default();
|
||||
self.preview = Some(CaptionPreview { document, revision, selection: session.sel.clone(), number_options: options, prefix });
|
||||
}
|
||||
|
||||
fn body(&mut self, ui: &mut Ui, _cx: &mut FormCx<'_, '_>, asks: &mut Vec<Asks>) -> bool {
|
||||
let caption = Label::from(tl!("Caption:").to_string());
|
||||
if let Some(text) = Field::new(caption.clone())
|
||||
@@ -137,8 +172,10 @@ impl WordForm for CaptionForm {
|
||||
.show(ui, |ui, _| Select::new(label_title.clone(), Bind::given(Mixed::Same(self.label.clone())), &labels).show(ui).value().cloned())
|
||||
.inner
|
||||
.flatten()
|
||||
&& label != self.label
|
||||
{
|
||||
self.label = label;
|
||||
ui.ctx().request_repaint();
|
||||
}
|
||||
let position_title = Label::from(tl!("Position:").to_string());
|
||||
let positions = [
|
||||
@@ -151,12 +188,17 @@ impl WordForm for CaptionForm {
|
||||
})
|
||||
.inner
|
||||
.flatten()
|
||||
&& position != self.position
|
||||
{
|
||||
self.position = position;
|
||||
ui.ctx().request_repaint();
|
||||
}
|
||||
let exclude = Label::from(tl!("Leave the label out of the caption").to_string());
|
||||
if let Some(on) = Checkbox::new(Bind::given(self.exclude_label)).label(exclude).show(ui).value().copied() {
|
||||
if let Some(on) = Checkbox::new(Bind::given(self.exclude_label)).label(exclude).show(ui).value().copied()
|
||||
&& on != self.exclude_label
|
||||
{
|
||||
self.exclude_label = on;
|
||||
ui.ctx().request_repaint();
|
||||
}
|
||||
if Button::new(Label::from(tl!("New Label…").to_string())).show(ui).clicked() {
|
||||
asks.push(Asks::Open("newLabel".to_string(), Value::Null));
|
||||
|
||||
@@ -65,6 +65,37 @@ fn caption_dialog_numbers_with_chapters() {
|
||||
assert_eq!(a.prefs().caption_labels, vec!["Plate".to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn caption_preview_matches_the_inserted_sequence_after_changing_label() {
|
||||
let mut a = app("Results\nA chart\nAnother chart");
|
||||
a.ui.caption_labels.push("Plate".into());
|
||||
a.run("select.text", json!({"text": "Results"})).unwrap();
|
||||
a.run("styles.apply", json!({"style": "Heading 1"})).unwrap();
|
||||
a.run("select.text", json!({"text": "A chart"})).unwrap();
|
||||
a.run("references.caption", json!({"label": "Plate", "text": "First chart", "chapter": 1, "separator": ".", "format": "ALPHABETIC"})).unwrap();
|
||||
a.run("select.text", json!({"text": "Another chart"})).unwrap();
|
||||
|
||||
let mut f = CaptionForm::read(&a);
|
||||
f.label = "Figure".into();
|
||||
f.format = "ALPHABETIC".into();
|
||||
f.chapter = true;
|
||||
f.separator = ".".into();
|
||||
f.prepare(&a);
|
||||
assert_eq!(f.preview(), "Figure 1.A");
|
||||
|
||||
f.label = "Plate".into();
|
||||
f.text = "Second chart".into();
|
||||
let before = a.session.doc.plain_text(StoryRef::Body);
|
||||
let selection = a.session.sel.clone();
|
||||
f.prepare(&a);
|
||||
let prefix = f.preview();
|
||||
assert_eq!(prefix, "Plate 1.B");
|
||||
assert_eq!(a.session.doc.plain_text(StoryRef::Body), before);
|
||||
assert_eq!(a.session.sel, selection);
|
||||
a.run("references.caption", f.params()).unwrap();
|
||||
assert!(a.session.doc.plain_text(StoryRef::Body).contains(&format!("{prefix}: Second chart")));
|
||||
}
|
||||
|
||||
/// #3120: Insert Caption picks the label used last, and saves it with the preferences.
|
||||
#[test]
|
||||
fn caption_dialog_remembers_the_last_label() {
|
||||
|
||||
Reference in New Issue
Block a user