use serde::{Deserialize, Serialize};
pub use crate::schema_registry::SCAFFOLD_SCHEMA_VERSION;
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ScaffoldSpec {
pub version: String,
#[serde(default)]
pub title: Option<String>,
#[serde(default = "default_font")]
pub font: String,
#[serde(default = "default_page_size")]
pub page_size: PageSize,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub outline_numbering: Option<Vec<OutlineLevel>>,
#[serde(default)]
pub blocks: Vec<Block>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct OutlineLevel {
pub text: String,
#[serde(default)]
pub num_format: OutlineNumFormat,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum OutlineNumFormat {
#[default]
Digit,
CircledDigit,
RomanCapital,
RomanSmall,
LatinCapital,
LatinSmall,
HangulSyllable,
}
impl OutlineNumFormat {
pub fn code(self) -> u8 {
match self {
OutlineNumFormat::Digit => 0,
OutlineNumFormat::CircledDigit => 1,
OutlineNumFormat::RomanCapital => 2,
OutlineNumFormat::RomanSmall => 3,
OutlineNumFormat::LatinCapital => 4,
OutlineNumFormat::LatinSmall => 5,
OutlineNumFormat::HangulSyllable => 8,
}
}
}
pub const OUTLINE_DEFAULTS: [(&str, OutlineNumFormat); 7] = [
("^1.", OutlineNumFormat::Digit),
("^2.", OutlineNumFormat::HangulSyllable),
("^3)", OutlineNumFormat::Digit),
("^4)", OutlineNumFormat::HangulSyllable),
("(^5)", OutlineNumFormat::Digit),
("(^6)", OutlineNumFormat::HangulSyllable),
("^7", OutlineNumFormat::CircledDigit),
];
fn default_font() -> String {
"함초롬바탕".to_string()
}
fn default_page_size() -> PageSize {
PageSize {
width_mm: 210.0,
height_mm: 297.0,
}
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PageSize {
pub width_mm: f32,
pub height_mm: f32,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum CellAlign {
#[default]
Justify,
Left,
Center,
Right,
}
impl CellAlign {
pub fn to_alignment(self) -> crate::model::style::Alignment {
use crate::model::style::Alignment;
match self {
CellAlign::Justify => Alignment::Justify,
CellAlign::Left => Alignment::Left,
CellAlign::Center => Alignment::Center,
CellAlign::Right => Alignment::Right,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(untagged)]
pub enum CellAlignSpec {
All(CellAlign),
PerColumn(Vec<CellAlign>),
}
fn parse_cell_align(word: &str) -> Result<CellAlign, String> {
match word.trim() {
"justify" => Ok(CellAlign::Justify),
"left" => Ok(CellAlign::Left),
"center" => Ok(CellAlign::Center),
"right" => Ok(CellAlign::Right),
other => Err(format!(
"알 수 없는 cell_align 값 '{other}' (지원: justify|left|center|right)"
)),
}
}
impl<'de> Deserialize<'de> for CellAlignSpec {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
use serde::de::Error;
let value = serde_json::Value::deserialize(deserializer)?;
match value {
serde_json::Value::String(word) => parse_cell_align(&word)
.map(CellAlignSpec::All)
.map_err(D::Error::custom),
serde_json::Value::Array(items) => items
.iter()
.map(|item| {
item.as_str()
.ok_or_else(|| {
format!("cell_align 목록의 항목은 문자열이어야 합니다: {item}")
})
.and_then(parse_cell_align)
})
.collect::<Result<Vec<_>, String>>()
.map(CellAlignSpec::PerColumn)
.map_err(D::Error::custom),
other => Err(D::Error::custom(format!(
"cell_align 은 문자열(justify|left|center|right) 또는 그 목록이어야 합니다: {other}"
))),
}
}
}
impl CellAlignSpec {
pub fn for_column(&self, col: usize) -> CellAlign {
match self {
CellAlignSpec::All(a) => *a,
CellAlignSpec::PerColumn(list) => list.get(col).copied().unwrap_or_default(),
}
}
}
#[derive(Debug, Clone, Serialize)]
#[serde(tag = "type", rename_all = "lowercase")]
pub enum Block {
Heading {
level: u8,
text: String,
},
Paragraph {
text: String,
},
Table {
rows: Vec<Vec<String>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
cell_align: Option<CellAlignSpec>,
},
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct RawBlock {
#[serde(rename = "type")]
block_type: String,
#[serde(default)]
level: Option<u8>,
#[serde(default)]
text: Option<String>,
#[serde(default)]
rows: Option<Vec<Vec<String>>>,
#[serde(default)]
cell_align: Option<CellAlignSpec>,
}
impl<'de> Deserialize<'de> for Block {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
use serde::de::Error;
let raw = RawBlock::deserialize(deserializer)?;
let forbid =
|present: bool, block: &str, field: &str, hint: &str| -> Result<(), D::Error> {
if present {
Err(D::Error::custom(format!(
"{block} 블록에 허용되지 않는 필드 '{field}' — {hint}"
)))
} else {
Ok(())
}
};
match raw.block_type.as_str() {
"heading" => {
forbid(
raw.rows.is_some(),
"heading",
"rows",
"표는 type:\"table\" 블록을 쓰세요",
)?;
let text = raw
.text
.ok_or_else(|| D::Error::custom("heading 블록에 'text' 필드가 필요합니다"))?;
forbid(
raw.cell_align.is_some(),
"heading",
"cell_align",
"cell_align 은 table 블록 전용입니다",
)?;
let level = raw.level.ok_or_else(|| {
D::Error::custom("heading 블록에 'level' 필드가 필요합니다 (1~7)")
})?;
Ok(Block::Heading { level, text })
}
"paragraph" => {
forbid(
raw.level.is_some(),
"paragraph",
"level",
"level 은 heading 블록 전용입니다",
)?;
forbid(
raw.rows.is_some(),
"paragraph",
"rows",
"표는 type:\"table\" 블록을 쓰세요",
)?;
forbid(
raw.cell_align.is_some(),
"paragraph",
"cell_align",
"cell_align 은 table 블록 전용입니다",
)?;
let text = raw
.text
.ok_or_else(|| D::Error::custom("paragraph 블록에 'text' 필드가 필요합니다"))?;
Ok(Block::Paragraph { text })
}
"table" => {
forbid(
raw.level.is_some(),
"table",
"level",
"level 은 heading 블록 전용입니다",
)?;
forbid(
raw.text.is_some(),
"table",
"text",
"셀 내용은 'rows' 안에 넣으세요",
)?;
let rows = raw
.rows
.ok_or_else(|| D::Error::custom("table 블록에 'rows' 필드가 필요합니다"))?;
Ok(Block::Table {
rows,
cell_align: raw.cell_align,
})
}
other => Err(D::Error::custom(format!(
"알 수 없는 블록 type '{other}' (지원: heading|paragraph|table)"
))),
}
}
}