text-document-common 1.16.0

Shared entities, database, events, and undo/redo infrastructure for text-document
Documentation
//! Per-feature selection for djot import/export.
//!
//! The djot importer and exporter round-trip a set of *optional* block-level
//! attributes — paragraph alignment, line height, text direction, non-breakable
//! lines and background color — through djot's native `{key=value}` block
//! attribute syntax (e.g. `{alignment=center}` on the line before a paragraph).
//! These two option structs let a caller choose which of those attributes are
//! carried. Everything else (headings, lists, tables, blockquotes, code blocks
//! and all inline formatting) is always imported/exported and is not gated.
//!
//! Both structs default to **all enabled** — the fully lossless round-trip. Use
//! [`DjotImportOptions::none`] / [`DjotExportOptions::none`] to restrict the
//! round-trip to the core structural and inline feature set only.
//!
//! The attribute keys used on the wire are the model field names:
//! `alignment`, `line_height`, `direction`, `non_breakable_lines`,
//! `page_break_before`, `front_matter`, `background_color`, `top_margin`,
//! `text_indent` and `semantic_role`. Block attributes are only emitted/read for standalone
//! paragraphs and headings; list items, code blocks and table cells normalise
//! their block styling away (the same boundary the other targets observe).

use serde::{Deserialize, Serialize};

/// The serde default of an attribute added after the options were first serialized: on,
/// as [`DjotImportOptions::all`] and [`DjotExportOptions::all`], the two `Default`s, have it.
const fn enabled() -> bool {
    true
}

/// Selects which optional block attributes the djot **importer** applies to the
/// document model. An attribute present in the source but disabled here is
/// parsed and discarded, exactly like an unrepresentable construct.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct DjotImportOptions {
    /// Apply paragraph alignment from `{alignment=left|right|center|justify}`.
    pub alignment: bool,
    /// Apply line height from `{line_height=<int>}`.
    pub line_height: bool,
    /// Apply text direction from `{direction=ltr|rtl}`.
    pub direction: bool,
    /// Apply non-breakable lines from `{non_breakable_lines=true|false}`.
    pub non_breakable_lines: bool,
    /// Apply "start on a new page" from `{page_break_before=true|false}`.
    pub page_break_before: bool,
    /// Mark the block as front matter from `{front_matter=true|false}` (see
    /// `Block::fmt_front_matter`).
    ///
    /// Unlike its older neighbours, which a serialized value must state, this one may be
    /// missing from a value written before it existed, and is then on, as in
    /// [`Self::default`]: off would drop the mark on every import that value configures.
    #[serde(default = "enabled")]
    pub front_matter: bool,
    /// Apply block background color from `{background_color="<value>"}`.
    pub background_color: bool,
    /// Apply the block's own space-above from `{top_margin=<int>}`, overriding
    /// the document-wide paragraph spacing for that one block.
    pub top_margin: bool,
    /// Apply the block's own first-line indent from `{text_indent=<int>}`,
    /// overriding the document-wide first-line indent for that one block.
    pub text_indent: bool,
    /// Carry the frame's semantic role from `{semantic_role=epigraph}`. Unlike its
    /// neighbours this one describes the enclosing **blockquote**, not the paragraph it
    /// is written on: it rides the quote's first block because that is the only channel
    /// djot block attributes have, and the importer moves it onto the frame.
    pub semantic_role: bool,
}

impl DjotImportOptions {
    /// Every optional block attribute enabled — the lossless default.
    pub const fn all() -> Self {
        Self {
            alignment: true,
            line_height: true,
            direction: true,
            non_breakable_lines: true,
            page_break_before: true,
            front_matter: true,
            background_color: true,
            top_margin: true,
            text_indent: true,
            semantic_role: true,
        }
    }

    /// No optional block attributes — import only the core structural and
    /// inline feature set, discarding any block-attribute styling.
    pub const fn none() -> Self {
        Self {
            alignment: false,
            line_height: false,
            direction: false,
            non_breakable_lines: false,
            page_break_before: false,
            front_matter: false,
            background_color: false,
            top_margin: false,
            text_indent: false,
            semantic_role: false,
        }
    }
}

impl Default for DjotImportOptions {
    fn default() -> Self {
        Self::all()
    }
}

/// Selects which optional block attributes the djot **exporter** emits as
/// `{key=value}` block attributes. A disabled attribute is omitted from the
/// output even when the model carries a value for it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct DjotExportOptions {
    /// Emit paragraph alignment as `{alignment=…}`.
    pub alignment: bool,
    /// Emit line height as `{line_height=…}`.
    pub line_height: bool,
    /// Emit text direction as `{direction=…}`.
    pub direction: bool,
    /// Emit non-breakable lines as `{non_breakable_lines=…}`.
    pub non_breakable_lines: bool,
    /// Emit "start on a new page" as `{page_break_before=…}`.
    pub page_break_before: bool,
    /// Emit the front-matter mark as `{front_matter=…}`. Missing from a serialized value
    /// written before it existed, it is on, as in [`Self::default`]; see
    /// [`DjotImportOptions::front_matter`].
    #[serde(default = "enabled")]
    pub front_matter: bool,
    /// Emit block background color as `{background_color=…}`.
    pub background_color: bool,
    /// Emit the block's own space-above as `{top_margin=…}`.
    pub top_margin: bool,
    /// Emit the block's own first-line indent as `{text_indent=…}`.
    pub text_indent: bool,
    /// Emit the enclosing blockquote's semantic role as `{semantic_role=…}` on the
    /// quote's first block, so the model→djot→model round trip stays a fixpoint.
    pub semantic_role: bool,
    /// Drop inline images instead of emitting `![alt](src){width=… height=…}`.
    ///
    /// Unlike every other field here this one is not a block attribute and is
    /// **not** governed by [`Self::all`]/[`Self::none`]: an image is content, not
    /// styling, so "emit no optional attributes" must not quietly delete it.
    /// Only a caller that has decided not to place the image files beside the
    /// output turns it on.
    #[serde(default)]
    pub omit_images: bool,
}

impl DjotExportOptions {
    /// Every optional block attribute emitted — the lossless default.
    pub const fn all() -> Self {
        Self {
            alignment: true,
            line_height: true,
            direction: true,
            non_breakable_lines: true,
            page_break_before: true,
            front_matter: true,
            background_color: true,
            top_margin: true,
            text_indent: true,
            semantic_role: true,
            omit_images: false,
        }
    }

    /// No optional block attributes — emit only the core structural and inline
    /// feature set, dropping any block-attribute styling.
    pub const fn none() -> Self {
        Self {
            alignment: false,
            line_height: false,
            direction: false,
            non_breakable_lines: false,
            page_break_before: false,
            front_matter: false,
            background_color: false,
            top_margin: false,
            text_indent: false,
            semantic_role: false,
            // Content, not styling — see the field's own doc.
            omit_images: false,
        }
    }
}

impl Default for DjotExportOptions {
    fn default() -> Self {
        Self::all()
    }
}

#[cfg(test)]
mod tests {
    use super::{DjotExportOptions, DjotImportOptions};

    /// A value serialized before `front_matter` existed reads back with it on, as `Default`
    /// has it, and not silently off.
    #[test]
    fn options_serialized_before_front_matter_read_back_with_it_on() {
        let mut import = serde_json::to_value(DjotImportOptions::all()).unwrap();
        import.as_object_mut().unwrap().remove("front_matter");
        let import: DjotImportOptions = serde_json::from_value(import).unwrap();
        assert_eq!(import, DjotImportOptions::default());

        let mut export = serde_json::to_value(DjotExportOptions::all()).unwrap();
        export.as_object_mut().unwrap().remove("front_matter");
        let export: DjotExportOptions = serde_json::from_value(export).unwrap();
        assert_eq!(export, DjotExportOptions::default());

        // A value that states it is read as stated.
        let none: DjotImportOptions =
            serde_json::from_value(serde_json::to_value(DjotImportOptions::none()).unwrap())
                .unwrap();
        assert!(!none.front_matter);
    }
}