use super::select::{all_objects, edit_obj, picked_objects, selected, target_objects};
use super::{CmdError, CmdResult, InlineObject, Pos, Rgb, Session, StoryRef, TextBody, Value, json, p};
pub(super) const NO_TEXT_BOX: &str = "select a text box first";
pub(super) fn has_text_box(s: &Session) -> Option<&'static str> {
if text_box_targets(s).is_empty() { Some(NO_TEXT_BOX) } else { None }
}
fn is_text_box(s: &Session, id: u32) -> bool {
s.doc.parts.get(&id).is_some_and(|p| p.kind == wordcraft_doc::PartKind::TextBox)
}
/// Target text boxes for Shape Format › Text commands: all selected text boxes (including
/// those added with `select.addObject` or the active canvas text box member), falling back
/// to the text box containing the caret when no object is selected.
pub fn text_box_targets(s: &Session) -> Vec<(Pos, u32)> {
let mut targets: Vec<(Pos, u32)> = target_objects(s, |o| matches!(o, InlineObject::Shape { story: Some(id), .. } if is_text_box(s, *id)))
.into_iter()
.filter_map(|(pos, o)| match o {
InlineObject::Shape { story: Some(id), .. } => Some((pos, id)),
_ => None,
})
.collect();
if targets.is_empty()
&& selected(s).is_none()
&& picked_objects(s).is_empty()
&& let Some(t) = text_box_target(s)
{
targets.push(t);
}
targets
}
/// The text box the Shape Format › Text commands work on: the selected one, or the one whose
/// text the caret is in. Its U+FFFC's position and its story.
pub fn text_box_target(s: &Session) -> Option<(Pos, u32)> {
if let Some((pos, InlineObject::Shape { story: Some(id), .. })) = selected(s)
&& is_text_box(s, id)
{
return Some((pos, id));
}
let StoryRef::Part(id) = s.sel.focus.story else { return None };
if !is_text_box(s, id) {
return None;
}
let after = s.doc.text_box_anchor(id)?;
let off = after.off.checked_sub(wordcraft_doc::para::OBJ.len_utf8())?;
Some((Pos { off, ..after }, id))
}
/// Change the target text boxes' text direction, alignment or link.
pub(crate) fn set_text_body(s: &mut Session, f: impl Fn(&mut TextBody)) -> CmdResult {
let targets = text_box_targets(s);
if targets.is_empty() {
return Err(CmdError::Disabled(NO_TEXT_BOX.into()));
}
let mut last_id = 0;
let mut last_body = TextBody::default();
for (pos, id) in targets {
let part = s.doc.parts.get_mut(&id).ok_or_else(|| CmdError::Failed("text box vanished".into()))?;
f(&mut part.body);
(last_id, last_body) = (id, part.body);
// Its paragraph is laid out again.
edit_obj(s, &pos, |_| {})?;
}
Ok(json!({"textBox": last_id, "body": last_body}))
}
pub(super) fn can_link(s: &Session) -> Option<&'static str> {
match text_box_target(s) {
None => Some(NO_TEXT_BOX),
Some((_, id)) if s.doc.parts.get(&id).is_some_and(|p| p.body.next.is_some()) => Some("this text box is already linked: break the link first"),
Some(_) => None,
}
}
/// `shape.link`: the selected text box's text continues in the target box, which must be an
/// empty text box no other box links to, and not one of those the text already runs through.
pub(super) fn link_text_box(s: &mut Session, v: &Value) -> CmdResult {
let (pos, from) = text_box_target(s).ok_or_else(|| CmdError::Disabled(NO_TEXT_BOX.into()))?;
let target = v.get("target").ok_or_else(|| CmdError::Params("`target`: the text box to link to".into()))?;
let at = match target.as_u64() {
Some(n) => all_objects(s).into_iter().nth(usize::try_from(n).unwrap_or(usize::MAX)).map(|(p, _)| p),
None => crate::cmd::parse_pos(target),
}
.ok_or_else(|| CmdError::Params("no object there".into()))?;
let to = match s.doc.para_at(&at).and_then(|q| q.object_at(at.off)) {
Some(InlineObject::Shape { story: Some(id), .. }) if is_text_box(s, *id) => *id,
_ => return Err(CmdError::Params("the target isn't a text box".into())),
};
if s.doc.parts.get(&from).is_some_and(|p| p.body.next.is_some()) {
return Err(CmdError::Failed("this text box is already linked: break the link first".into()));
}
if to == from || s.doc.text_box_chain(from).is_some_and(|c| c.contains(&to)) {
return Err(CmdError::Failed("a text box can't link to itself or to a box its text already runs through".into()));
}
if s.doc.text_box_chains().iter().any(|c| c.iter().skip(1).any(|id| *id == to)) {
return Err(CmdError::Failed("another text box already links to that one".into()));
}
if !s.doc.plain_text(StoryRef::Part(to)).trim().is_empty() {
return Err(CmdError::Failed("the text box to link to must be empty".into()));
}
if let Some(p) = s.doc.parts.get_mut(&from) {
p.body.next = Some(to);
}
edit_obj(s, &pos, |_| {})?;
edit_obj(s, &at, |_| {})?;
Ok(json!({"textBox": from, "next": to}))
}
/// `shape.effects`: set or clear the shadow, glow and soft edges of the selected shapes.
pub(super) fn shape_effects(s: &mut Session, v: &Value) -> CmdResult {
use wordcraft_doc::effects::{Glow, Shadow, ShapeEffects};
let color = |o: &Value| p::str(o, "color").and_then(Rgb::parse);
// Each change is `None` (leave as it is) or `Some(new value)`.
let shadow: Option