mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-25 20:22:39 +00:00
* idml: add reusable schema emission helpers for remaining IDML parts (#778) * fix(idml): remove duplicate push_prefixed_attrs on FillValues
This commit is contained in:
@@ -33,6 +33,36 @@ pub struct TocStyleValues {
|
||||
pub entries: Vec<TocStyleEntryValues>,
|
||||
}
|
||||
|
||||
impl TocStyleValues {
|
||||
/// Emits a `TOCStyle` element and its `TOCStyleEntry` children.
|
||||
pub fn to_el(&self, name: &str, mut fresh: impl FnMut() -> String) -> El {
|
||||
let mut el = El::new("TOCStyle")
|
||||
.with_attr("Self", self.self_id.as_deref().unwrap_or("TOCStyle/Table of Contents"))
|
||||
.with_attr("Name", name)
|
||||
.with_attr("Title", self.title.as_deref().unwrap_or(""))
|
||||
.with_attr("TitleStyle", self.title_style.as_deref().unwrap_or("ParagraphStyle/$ID/NormalParagraphStyle"))
|
||||
.with_attr("RunIn", "false")
|
||||
.with_attr("IncludeHidden", "false")
|
||||
.with_attr("IncludeBookDocuments", "false")
|
||||
.with_attr("CreateBookmarks", bool_str(self.create_bookmarks.unwrap_or(false)));
|
||||
for entry in &self.entries {
|
||||
el.push(
|
||||
El::new("TOCStyleEntry")
|
||||
.with_attr("Self", fresh())
|
||||
.with_attr("Name", entry.style.as_deref().unwrap_or(""))
|
||||
.with_attr("FormatStyle", entry.entry_style.as_deref().unwrap_or(""))
|
||||
.with_attr("Level", entry.level.unwrap_or(1).to_string())
|
||||
.with_attr("PageNumberPosition", entry.page_number_position.as_deref().unwrap_or("AfterEntry"))
|
||||
.with_attr("Separator", entry.separator.as_deref().unwrap_or("\t"))
|
||||
.with_attr("PageNumberStyle", entry.page_number_style.as_deref().unwrap_or("CharacterStyle/$ID/[No character style]"))
|
||||
.with_attr("SeparatorStyle", entry.separator_style.as_deref().unwrap_or("CharacterStyle/$ID/[No character style]"))
|
||||
.with_attr("Sort", bool_str(entry.sort.unwrap_or(false))),
|
||||
);
|
||||
}
|
||||
el
|
||||
}
|
||||
}
|
||||
|
||||
/// Date-based IDML text variable kinds.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum TextDateKind {
|
||||
@@ -259,6 +289,54 @@ impl CellStyleValues {
|
||||
edge_strokes: ["TopEdge", "LeftEdge", "BottomEdge", "RightEdge"].map(|edge| values.stroke_values(edge)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Emits a `CellStyle` element from these values.
|
||||
pub fn to_el(&self) -> El {
|
||||
let mut el = El::new("CellStyle");
|
||||
if let Some(self_id) = &self.self_id {
|
||||
el.attrs.push(("Self".into(), self_id.clone()));
|
||||
}
|
||||
if let Some(name) = &self.name {
|
||||
el.attrs.push(("Name".into(), name.clone()));
|
||||
}
|
||||
if let Some(fill) = &self.fill {
|
||||
el.attrs.push(("FillColor".into(), fill.clone()));
|
||||
}
|
||||
if let Some(tint) = self.fill_tint {
|
||||
el.attrs.push(("FillTint".into(), num(tint)));
|
||||
}
|
||||
for ((text, legacy), value) in
|
||||
[("TextTopInset", "TopInset"), ("TextLeftInset", "LeftInset"), ("TextBottomInset", "BottomInset"), ("TextRightInset", "RightInset")]
|
||||
.iter()
|
||||
.zip(self.insets)
|
||||
{
|
||||
if let Some(value) = value {
|
||||
let s = num(value);
|
||||
el.attrs.push(((*text).into(), s.clone()));
|
||||
el.attrs.push(((*legacy).into(), s));
|
||||
}
|
||||
}
|
||||
if let Some(vj) = &self.vertical_justification {
|
||||
el.attrs.push(("VerticalJustification".into(), vj.clone()));
|
||||
}
|
||||
if let Some(fb) = &self.first_baseline {
|
||||
el.attrs.push(("FirstBaselineOffset".into(), fb.clone()));
|
||||
}
|
||||
if let Some(min) = self.first_baseline_min {
|
||||
el.attrs.push(("MinimumFirstBaselineOffset".into(), num(min)));
|
||||
}
|
||||
for (side, stroke) in ["TopEdge", "LeftEdge", "BottomEdge", "RightEdge"].iter().zip(&self.edge_strokes) {
|
||||
stroke.push_prefixed_attrs(&mut el, side, false);
|
||||
}
|
||||
if let Some(ps) = &self.paragraph_style {
|
||||
el.attrs.push(("AppliedParagraphStyle".into(), ps.clone()));
|
||||
}
|
||||
let based_on = match &self.based_on {
|
||||
Some(base) if base != "$ID/[None]" => prop("BasedOn", "object", base.clone()),
|
||||
_ => prop("BasedOn", "string", "$ID/[None]"),
|
||||
};
|
||||
with_props(el, vec![based_on])
|
||||
}
|
||||
}
|
||||
|
||||
/// Parsed table-style assignments that are independent of DesignCraft's style resolution.
|
||||
@@ -309,6 +387,57 @@ impl TableStyleValues {
|
||||
column_strokes: values.alternating_stroke_values("Column"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Emits a `TableStyle` element from these values.
|
||||
pub fn to_el(&self, self_id: &str) -> El {
|
||||
let mut el = El::new("TableStyle").with_attr("Self", self_id);
|
||||
if let Some(name) = &self.name {
|
||||
el.attrs.push(("Name".into(), name.clone()));
|
||||
}
|
||||
for (key, value) in [
|
||||
("HeaderRegionCellStyle", &self.header_cell_style),
|
||||
("BodyRegionCellStyle", &self.body_cell_style),
|
||||
("FooterRegionCellStyle", &self.footer_cell_style),
|
||||
("LeftColumnRegionCellStyle", &self.left_column_cell_style),
|
||||
("RightColumnRegionCellStyle", &self.right_column_cell_style),
|
||||
] {
|
||||
if let Some(value) = value {
|
||||
el.attrs.push((key.into(), value.clone()));
|
||||
}
|
||||
}
|
||||
for (key, value) in [
|
||||
("HeaderRegionSameAsBodyRegion", self.header_same_as_body),
|
||||
("FooterRegionSameAsBodyRegion", self.footer_same_as_body),
|
||||
("LeftColumnRegionSameAsBodyRegion", self.left_column_same_as_body),
|
||||
("RightColumnRegionSameAsBodyRegion", self.right_column_same_as_body),
|
||||
] {
|
||||
if let Some(value) = value {
|
||||
el.attrs.push((key.into(), bool_str(value).into()));
|
||||
}
|
||||
}
|
||||
for (side, stroke) in ["TopBorder", "LeftBorder", "BottomBorder", "RightBorder"].iter().zip(&self.border_strokes) {
|
||||
stroke.push_prefixed_attrs(&mut el, side, false);
|
||||
}
|
||||
self.row_fills.push_attrs(&mut el, "Row");
|
||||
self.column_fills.push_attrs(&mut el, "Column");
|
||||
self.row_strokes.push_attrs(&mut el, "Row");
|
||||
self.column_strokes.push_attrs(&mut el, "Column");
|
||||
if let Some(value) = self.space_before {
|
||||
el.attrs.push(("SpaceBefore".into(), num(value)));
|
||||
}
|
||||
if let Some(value) = self.space_after {
|
||||
el.attrs.push(("SpaceAfter".into(), num(value)));
|
||||
}
|
||||
let mut props = Vec::new();
|
||||
if let Some(base) = &self.based_on {
|
||||
props.push(if base == "$ID/[No table style]" {
|
||||
prop("BasedOn", "string", "$ID/[No table style]")
|
||||
} else {
|
||||
prop("BasedOn", "object", base.clone())
|
||||
});
|
||||
}
|
||||
with_props(el, props)
|
||||
}
|
||||
}
|
||||
|
||||
impl NumberingListValues {
|
||||
@@ -342,6 +471,13 @@ impl EpubSplitValues {
|
||||
let values = Values::of(el);
|
||||
Self { break_document: values.boolean("BreakDocument") == Some(true), paragraph_style: values.get("ParagraphStyleName").map(str::to_owned) }
|
||||
}
|
||||
|
||||
/// Emits an `EPubExportPreference` element.
|
||||
pub fn to_el(&self) -> El {
|
||||
El::new("EPubExportPreference")
|
||||
.with_attr("BreakDocument", bool_str(self.break_document))
|
||||
.with_attr("ParagraphStyleName", self.paragraph_style.as_deref().unwrap_or(""))
|
||||
}
|
||||
}
|
||||
|
||||
impl TextVariableValues {
|
||||
|
||||
@@ -31,7 +31,10 @@ pub use effects::{
|
||||
DirectionalFeatherValues, DropShadowValues, FeatherValues, GradientFeatherValues, ObjectStyleStack, OpacityStopValues, TransparencySetting,
|
||||
};
|
||||
pub use geometry::{MAX_PATH_POINTS, PathGeometry, PathGeometryError, PathPoint, SubPath};
|
||||
pub use preferences::{DocumentPreferences, FootnotePreferences, GridPreferences, TextFramePreferences};
|
||||
pub use preferences::{
|
||||
DocumentPreferences, FootnotePreferences, GridPreferences, TextFramePreferences, TextPreferenceValues, ViewPreferenceValues,
|
||||
pasteboard_preference_el, transparency_preference_el,
|
||||
};
|
||||
pub use resources::{
|
||||
CharacterAppearanceValues, CharacterSpecialValues, CharacterTypographyValues, CjkCharacterValues, CjkParagraphValues, ColorDefinition,
|
||||
ColorGroup, ColorGroupDefinition, ColorGroupMember, ColorSpace, CompositeFontDefinition, CompositeFontEntryDefinition, EpubExportTagMap,
|
||||
@@ -39,18 +42,19 @@ pub use resources::{
|
||||
GrepStyleValue, Ink, InkDefinition, MojikumiRow, NestedLineStyleValue, NestedStyleValue, NestedStyleValues, ObjectStyleValues,
|
||||
OpenTypeFeatureValues, ParagraphAlignmentValues, ParagraphBoxValues, ParagraphFlowValues, ParagraphListValues, ParagraphSpanValues, RubyValues,
|
||||
StrokeDefinition, StrokeStyle, StrokeStyleKind, Style, StyleGroup, StyleGroupWriter, StyleKind, StyleNode, Swatch, SwatchKind, TabStopValues,
|
||||
TextDecorationValues, TintDefinition, color_groups, inks, named, preference, stroke_styles, style_groups, swatches,
|
||||
TextDecorationValues, TintDefinition, color_groups, inks, named, object_style_effects_category_settings, preference, stroke_styles, style_groups,
|
||||
swatches,
|
||||
};
|
||||
pub use spread::{
|
||||
BaselineFrameGridOption, BaselineFrameGridRelative, ClippingPathValues, FrameFittingOption, Graphic, GraphicChild, GraphicKind,
|
||||
GraphicLayerOptions, Guide, ItemChild, ItemKind, Link, MarginPreference, Page, PageChild, PageItem, PdfAttribute, Spread, SpreadChild, TextPath,
|
||||
TextWrapPreference, spreads,
|
||||
GraphicLayerOptions, Guide, GuideValues, ItemChild, ItemKind, Link, MarginPreference, Page, PageChild, PageItem, PdfAttribute, Spread,
|
||||
SpreadChild, TextPath, TextWrapPreference, spreads,
|
||||
};
|
||||
pub use story::{
|
||||
Ace, AnchoredObjectSetting, AnchoredObjectValues, CONTAINERS, Cell, CellOptions, Container, ContainerKind, ContentPart, CrossReferenceSource,
|
||||
IndexCrossReferenceValues, IndexDocument, IndexReference, IndexTopicPath, IndexValues, PageReference, Range, SavedCrossReference,
|
||||
SavedCrossReferencePart, Story, StoryAnchor, StoryPreference, Table, TableChild, TableColumn, TableLayout, TableRow, TextNode, TrackedChangeKind,
|
||||
stories,
|
||||
stories, text_variable_instance_el, tracked_change_el,
|
||||
};
|
||||
|
||||
use crate::value::{matrix, nums};
|
||||
@@ -145,6 +149,30 @@ impl StrokeValues {
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// Writes prefixed cell/table stroke attributes onto `el`. When `line_style_for_kind` is
|
||||
/// true, `kind` is written as `{prefix}LineStyle` (used for `EndColumnLineStyle`).
|
||||
pub fn push_prefixed_attrs(&self, el: &mut El, prefix: &str, line_style_for_kind: bool) {
|
||||
if let Some(value) = self.weight {
|
||||
el.attrs.push((format!("{prefix}StrokeWeight"), crate::value::num(value)));
|
||||
}
|
||||
if let Some(value) = &self.color {
|
||||
el.attrs.push((format!("{prefix}StrokeColor"), value.clone()));
|
||||
}
|
||||
if let Some(value) = self.tint {
|
||||
el.attrs.push((format!("{prefix}StrokeTint"), crate::value::num(value)));
|
||||
}
|
||||
if let Some(value) = &self.kind {
|
||||
let key = if line_style_for_kind { format!("{prefix}LineStyle") } else { format!("{prefix}StrokeType") };
|
||||
el.attrs.push((key, value.clone()));
|
||||
}
|
||||
if let Some(value) = &self.gap_color {
|
||||
el.attrs.push((format!("{prefix}StrokeGapColor"), value.clone()));
|
||||
}
|
||||
if let Some(value) = self.gap_tint {
|
||||
el.attrs.push((format!("{prefix}StrokeGapTint"), crate::value::num(value)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Raw fill properties before a caller resolves swatch names to its own colour model.
|
||||
@@ -201,6 +229,56 @@ pub struct AlternatingStrokeValues {
|
||||
pub skip_last: Option<f64>,
|
||||
}
|
||||
|
||||
impl AlternatingFillValues {
|
||||
/// Writes alternating row/column fill attributes onto `el`.
|
||||
pub fn push_attrs(&self, el: &mut El, kind: &str) {
|
||||
if let Some(value) = self.first_count {
|
||||
el.attrs.push((format!("Start{kind}FillCount"), crate::value::num(value)));
|
||||
}
|
||||
if let Some(value) = &self.first_color {
|
||||
el.attrs.push((format!("Start{kind}FillColor"), value.clone()));
|
||||
}
|
||||
if let Some(value) = self.first_tint {
|
||||
el.attrs.push((format!("Start{kind}FillTint"), crate::value::num(value)));
|
||||
}
|
||||
if let Some(value) = self.next_count {
|
||||
el.attrs.push((format!("End{kind}FillCount"), crate::value::num(value)));
|
||||
}
|
||||
if let Some(value) = &self.next_color {
|
||||
el.attrs.push((format!("End{kind}FillColor"), value.clone()));
|
||||
}
|
||||
if let Some(value) = self.next_tint {
|
||||
el.attrs.push((format!("End{kind}FillTint"), crate::value::num(value)));
|
||||
}
|
||||
if let Some(value) = self.skip_first {
|
||||
el.attrs.push((format!("SkipFirstAlternatingFill{kind}s"), crate::value::num(value)));
|
||||
}
|
||||
if let Some(value) = self.skip_last {
|
||||
el.attrs.push((format!("SkipLastAlternatingFill{kind}s"), crate::value::num(value)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AlternatingStrokeValues {
|
||||
/// Writes alternating row/column stroke attributes onto `el`.
|
||||
pub fn push_attrs(&self, el: &mut El, kind: &str) {
|
||||
if let Some(value) = self.first_count {
|
||||
el.attrs.push((format!("Start{kind}StrokeCount"), crate::value::num(value)));
|
||||
}
|
||||
if let Some(value) = self.next_count {
|
||||
el.attrs.push((format!("End{kind}StrokeCount"), crate::value::num(value)));
|
||||
}
|
||||
self.first.push_prefixed_attrs(el, &format!("Start{kind}"), false);
|
||||
self.next.push_prefixed_attrs(el, &format!("End{kind}"), kind == "Column");
|
||||
if let Some(value) = self.skip_first {
|
||||
el.attrs.push((format!("SkipFirstAlternatingStroke{kind}s"), crate::value::num(value)));
|
||||
}
|
||||
if let Some(value) = self.skip_last {
|
||||
el.attrs.push((format!("SkipLastAlternatingStroke{kind}s"), crate::value::num(value)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct TableOptions {
|
||||
pub direction: Option<String>,
|
||||
|
||||
@@ -418,3 +418,54 @@ fn inset(elements: &[&El]) -> Option<[f64; 4]> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Document view-unit and ruler-origin preferences.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct ViewPreferenceValues {
|
||||
pub horizontal_units: String,
|
||||
pub vertical_units: String,
|
||||
pub ruler_origin: String,
|
||||
pub cursor_key_increment: f64,
|
||||
}
|
||||
|
||||
impl ViewPreferenceValues {
|
||||
/// Emits a canonical `ViewPreference` element.
|
||||
pub fn to_el(&self) -> El {
|
||||
El::new("ViewPreference")
|
||||
.with_attr("HorizontalMeasurementUnits", &self.horizontal_units)
|
||||
.with_attr("VerticalMeasurementUnits", &self.vertical_units)
|
||||
.with_attr("RulerOrigin", &self.ruler_origin)
|
||||
.with_attr("CursorKeyIncrement", crate::value::num(self.cursor_key_increment))
|
||||
.with_attr("PointsPerInch", "72")
|
||||
}
|
||||
}
|
||||
|
||||
/// Document superscript and subscript text preferences.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct TextPreferenceValues {
|
||||
pub superscript_size: f64,
|
||||
pub superscript_position: f64,
|
||||
pub subscript_size: f64,
|
||||
pub subscript_position: f64,
|
||||
}
|
||||
|
||||
impl TextPreferenceValues {
|
||||
/// Emits a canonical `TextPreference` element.
|
||||
pub fn to_el(&self) -> El {
|
||||
El::new("TextPreference")
|
||||
.with_attr("SuperscriptSize", crate::value::num(self.superscript_size))
|
||||
.with_attr("SuperscriptPosition", crate::value::num(self.superscript_position))
|
||||
.with_attr("SubscriptSize", crate::value::num(self.subscript_size))
|
||||
.with_attr("SubscriptPosition", crate::value::num(self.subscript_position))
|
||||
}
|
||||
}
|
||||
|
||||
/// Emits a `PasteboardPreference` element with horizontal and vertical margins in points.
|
||||
pub fn pasteboard_preference_el(horizontal: f64, vertical: f64) -> El {
|
||||
El::new("PasteboardPreference").with_attr("PasteboardMargins", format!("{} {}", crate::value::num(horizontal), crate::value::num(vertical)))
|
||||
}
|
||||
|
||||
/// Emits a `TransparencyPreference` element for the given blending space (`"CMYK"` or `"RGB"`).
|
||||
pub fn transparency_preference_el(blending_space: &str) -> El {
|
||||
El::new("TransparencyPreference").with_attr("BlendingSpace", blending_space)
|
||||
}
|
||||
|
||||
@@ -1406,6 +1406,22 @@ impl ObjectStyleValues {
|
||||
}
|
||||
}
|
||||
|
||||
/// Emits an `ObjectStyleObjectEffectsCategorySettings` element for an object style.
|
||||
pub fn object_style_effects_category_settings(enable_drop_shadow: bool, enable_feather: bool) -> El {
|
||||
let bool_s = |b: bool| if b { "true" } else { "false" };
|
||||
El::new("ObjectStyleObjectEffectsCategorySettings")
|
||||
.with_attr("EnableTransparency", "false")
|
||||
.with_attr("EnableDropShadow", bool_s(enable_drop_shadow))
|
||||
.with_attr("EnableFeather", bool_s(enable_feather))
|
||||
.with_attr("EnableInnerShadow", "false")
|
||||
.with_attr("EnableOuterGlow", "false")
|
||||
.with_attr("EnableInnerGlow", "false")
|
||||
.with_attr("EnableBevelEmboss", "false")
|
||||
.with_attr("EnableSatin", "false")
|
||||
.with_attr("EnableDirectionalFeather", "false")
|
||||
.with_attr("EnableGradientFeather", "false")
|
||||
}
|
||||
|
||||
impl StyleGroup {
|
||||
/// The root group `el`; `None` when `el` is no root style group.
|
||||
pub fn from_el(el: &El) -> Option<StyleGroup> {
|
||||
|
||||
@@ -236,6 +236,20 @@ impl MarginPreference {
|
||||
let values: Option<Vec<f64>> = source.split_whitespace().take(limit).map(|v| v.parse::<f64>().ok().filter(|v| v.is_finite())).collect();
|
||||
values.filter(|values| !values.is_empty())
|
||||
}
|
||||
|
||||
/// Emits a `MarginPreference` element from resolved column and margin geometry.
|
||||
pub fn to_el(column_count: usize, column_gutter: f64, top: f64, bottom: f64, left: f64, right: f64, columns_positions: &[f64]) -> El {
|
||||
let positions: Vec<String> = columns_positions.iter().copied().map(crate::value::num).collect();
|
||||
El::new("MarginPreference")
|
||||
.with_attr("ColumnCount", column_count.max(1))
|
||||
.with_attr("ColumnGutter", crate::value::num(column_gutter))
|
||||
.with_attr("Top", crate::value::num(top))
|
||||
.with_attr("Bottom", crate::value::num(bottom))
|
||||
.with_attr("Left", crate::value::num(left))
|
||||
.with_attr("Right", crate::value::num(right))
|
||||
.with_attr("ColumnDirection", "Horizontal")
|
||||
.with_attr("ColumnsPositions", positions.join(" "))
|
||||
}
|
||||
}
|
||||
|
||||
/// A child of a page, in document order.
|
||||
@@ -324,6 +338,39 @@ pub struct Guide {
|
||||
pub rest: Vec<El>,
|
||||
}
|
||||
|
||||
/// Values for emitting an IDML `Guide` element.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct GuideValues {
|
||||
pub self_id: String,
|
||||
pub horizontal: bool,
|
||||
pub location: f64,
|
||||
pub fit_to_page: bool,
|
||||
pub locked: bool,
|
||||
pub page_index: usize,
|
||||
pub liquid: bool,
|
||||
pub item_layer: Option<String>,
|
||||
}
|
||||
|
||||
impl GuideValues {
|
||||
/// Emits a `Guide` element.
|
||||
pub fn to_el(&self) -> El {
|
||||
let bool_s = |b: bool| if b { "true" } else { "false" };
|
||||
let mut el = El::new("Guide")
|
||||
.with_attr("Self", &self.self_id)
|
||||
.with_attr("Orientation", if self.horizontal { "Horizontal" } else { "Vertical" })
|
||||
.with_attr("Location", crate::value::num(self.location))
|
||||
.with_attr("FitToPage", bool_s(self.fit_to_page))
|
||||
.with_attr("ViewThreshold", "5")
|
||||
.with_attr("Locked", bool_s(self.locked))
|
||||
.with_attr("PageIndex", self.page_index.to_string())
|
||||
.with_attr("GuideType", if self.liquid { "Liquid" } else { "Ruler" });
|
||||
if let Some(layer) = &self.item_layer {
|
||||
el.attrs.push(("ItemLayer".into(), layer.clone()));
|
||||
}
|
||||
el
|
||||
}
|
||||
}
|
||||
|
||||
impl Guide {
|
||||
/// `Orientation` is `Horizontal`; a guide is vertical otherwise.
|
||||
pub fn horizontal(&self) -> bool {
|
||||
|
||||
@@ -351,6 +351,22 @@ impl CrossReferenceSource {
|
||||
}
|
||||
}
|
||||
|
||||
/// Emits a `TextVariableInstance` element inside a story character range.
|
||||
pub fn text_variable_instance_el(self_id: &str, name: &str, result_text: &str, associated_var: &str) -> El {
|
||||
El::new("TextVariableInstance")
|
||||
.with_attr("Self", self_id)
|
||||
.with_attr("Name", name)
|
||||
.with_attr("ResultText", result_text)
|
||||
.with_attr("AssociatedTextVariable", associated_var)
|
||||
}
|
||||
|
||||
/// Emits a tracked-change `<Change>` element wrapping its story nodes.
|
||||
pub fn tracked_change_el(self_id: &str, change_type: &str, children: Vec<Node>) -> El {
|
||||
let mut el = El::new("Change").with_attr("Self", self_id).with_attr("ChangeType", change_type);
|
||||
el.children = children;
|
||||
el
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum SavedCrossReferencePart {
|
||||
Text(String),
|
||||
|
||||
@@ -408,3 +408,115 @@ fn designmap_layers_sections_and_hyperlinks_roundtrip_expected_attributes() {
|
||||
assert_eq!(cg.attr("IsRootColorGroup"), Some("true"));
|
||||
assert_eq!(cg.elements().count(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preferences_styles_spread_and_story_schema_helpers_roundtrip() {
|
||||
use craft_idml::Node;
|
||||
use craft_idml::model::{
|
||||
CellStyleValues, EpubSplitValues, GuideValues, MarginPreference, StrokeValues, TableStyleValues, TextPreferenceValues, TocStyleEntryValues,
|
||||
TocStyleValues, ViewPreferenceValues, object_style_effects_category_settings, pasteboard_preference_el, text_variable_instance_el,
|
||||
tracked_change_el, transparency_preference_el,
|
||||
};
|
||||
|
||||
let view = ViewPreferenceValues {
|
||||
horizontal_units: "Points".into(),
|
||||
vertical_units: "Points".into(),
|
||||
ruler_origin: "SpreadOrigin".into(),
|
||||
cursor_key_increment: 1.0,
|
||||
}
|
||||
.to_el();
|
||||
assert_eq!(view.attr("HorizontalMeasurementUnits"), Some("Points"));
|
||||
assert_eq!(view.attr("PointsPerInch"), Some("72"));
|
||||
|
||||
let text_pref =
|
||||
TextPreferenceValues { superscript_size: 58.3, superscript_position: 33.3, subscript_size: 58.3, subscript_position: 33.3 }.to_el();
|
||||
assert_eq!(text_pref.attr("SuperscriptSize"), Some("58.3"));
|
||||
|
||||
assert_eq!(pasteboard_preference_el(72.0, 36.0).attr("PasteboardMargins"), Some("72 36"));
|
||||
assert_eq!(transparency_preference_el("CMYK").attr("BlendingSpace"), Some("CMYK"));
|
||||
|
||||
let epub = EpubSplitValues { break_document: true, paragraph_style: Some("ParagraphStyle/H1".into()) };
|
||||
assert_eq!(EpubSplitValues::from_el(&epub.to_el()), epub);
|
||||
|
||||
let margin = MarginPreference::to_el(2, 12.0, 36.0, 36.0, 36.0, 36.0, &[0.0, 200.0, 212.0, 412.0]);
|
||||
let parsed_margin = MarginPreference::from_el(&margin);
|
||||
assert_eq!(parsed_margin.column_count(), Some(2.0));
|
||||
assert_eq!(parsed_margin.column_positions(4), Some(vec![0.0, 200.0, 212.0, 412.0]));
|
||||
|
||||
let guide = GuideValues {
|
||||
self_id: "u1g0".into(),
|
||||
horizontal: true,
|
||||
location: 100.0,
|
||||
fit_to_page: true,
|
||||
locked: false,
|
||||
page_index: 0,
|
||||
liquid: false,
|
||||
item_layer: Some("u2".into()),
|
||||
}
|
||||
.to_el();
|
||||
assert_eq!(guide.attr("Orientation"), Some("Horizontal"));
|
||||
assert_eq!(guide.attr("ItemLayer"), Some("u2"));
|
||||
|
||||
let cell_style = CellStyleValues {
|
||||
self_id: Some("CellStyle/Header".into()),
|
||||
name: Some("Header".into()),
|
||||
based_on: Some("$ID/[None]".into()),
|
||||
fill: Some("Color/Black".into()),
|
||||
fill_tint: Some(20.0),
|
||||
insets: [Some(4.0), Some(6.0), Some(4.0), Some(6.0)],
|
||||
edge_strokes: [
|
||||
StrokeValues { weight: Some(1.0), color: Some("Color/Black".into()), ..StrokeValues::default() },
|
||||
StrokeValues::default(),
|
||||
StrokeValues::default(),
|
||||
StrokeValues::default(),
|
||||
],
|
||||
..CellStyleValues::default()
|
||||
};
|
||||
let parsed_cell = CellStyleValues::from_el(&cell_style.to_el());
|
||||
assert_eq!(parsed_cell.insets, cell_style.insets);
|
||||
assert_eq!(parsed_cell.edge_strokes[0].weight, Some(1.0));
|
||||
|
||||
let mut table_style = TableStyleValues {
|
||||
name: Some("Grid".into()),
|
||||
based_on: Some("$ID/[No table style]".into()),
|
||||
space_before: Some(6.0),
|
||||
..TableStyleValues::default()
|
||||
};
|
||||
table_style.column_strokes.next.kind = Some("Solid".into());
|
||||
let table_el = table_style.to_el("TableStyle/Grid");
|
||||
assert_eq!(table_el.attr("EndColumnLineStyle"), Some("Solid"));
|
||||
assert_eq!(TableStyleValues::from_el(&table_el).column_strokes.next.kind.as_deref(), Some("Solid"));
|
||||
|
||||
let mut n = 0;
|
||||
let toc = TocStyleValues {
|
||||
self_id: Some("TOCStyle/Table of Contents".into()),
|
||||
title: Some("Contents".into()),
|
||||
title_style: Some("ParagraphStyle/Title".into()),
|
||||
create_bookmarks: Some(true),
|
||||
entries: vec![TocStyleEntryValues {
|
||||
style: Some("Heading 1".into()),
|
||||
level: Some(1),
|
||||
page_number_position: Some("AfterEntry".into()),
|
||||
separator: Some("\t".into()),
|
||||
entry_style: Some("ParagraphStyle/TOC 1".into()),
|
||||
page_number_style: None,
|
||||
separator_style: None,
|
||||
sort: Some(false),
|
||||
}],
|
||||
}
|
||||
.to_el("Table of Contents", || {
|
||||
n += 1;
|
||||
format!("u{n}")
|
||||
});
|
||||
assert_eq!(toc.attr("CreateBookmarks"), Some("true"));
|
||||
assert_eq!(toc.elements().count(), 1);
|
||||
|
||||
let obj_fx = object_style_effects_category_settings(true, false);
|
||||
assert_eq!(obj_fx.attr("EnableDropShadow"), Some("true"));
|
||||
assert_eq!(obj_fx.attr("EnableFeather"), Some("false"));
|
||||
|
||||
let tv = text_variable_instance_el("u9", "Chapter", "1", "dTextVariablenChapter");
|
||||
assert_eq!(tv.attr("ResultText"), Some("1"));
|
||||
let ch = tracked_change_el("u10", "InsertedText", vec![Node::El(craft_idml::El::new("Content"))]);
|
||||
assert_eq!(ch.attr("ChangeType"), Some("InsertedText"));
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user