use std::collections::BTreeSet;
use std::error::Error;
use std::fmt;
use serde::{Deserialize, Serialize};
use crate::{Catalog, ControlKind, StoryKind};
pub const MANIFEST_VERSION_V1: u16 = 1;
pub const FRAME_VERSION_V1: u16 = 1;
pub const DEFAULT_MANIFEST_PATH: &str = "/__coatcheck/manifest.json";
pub const DEFAULT_FRAME_PATH: &str = "/__coatcheck/frame";
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ManifestV1 {
pub version: u16,
pub name: String,
pub frame: FrameContractV1,
#[serde(default)]
pub scenes: Vec<SceneV1>,
#[serde(default)]
pub stories: Vec<StoryV1>,
}
impl ManifestV1 {
#[must_use]
pub fn from_catalog(catalog: Catalog, frame: FrameContractV1) -> Self {
let stories = catalog.stories().iter().map(StoryV1::from_static).collect();
Self {
version: MANIFEST_VERSION_V1,
name: catalog.name().to_owned(),
frame,
scenes: vec![SceneV1::default()],
stories,
}
}
pub fn validate(&self) -> Result<(), ManifestError> {
if self.version != MANIFEST_VERSION_V1 {
return Err(ManifestError::UnsupportedManifestVersion(self.version));
}
if self.name.trim().is_empty() {
return Err(ManifestError::MissingName);
}
self.frame.validate()?;
let mut scene_ids = BTreeSet::new();
for scene in &self.scenes {
if scene.id.trim().is_empty() {
return Err(ManifestError::MissingSceneId);
}
if !scene_ids.insert(scene.id.as_str()) {
return Err(ManifestError::DuplicateSceneId(scene.id.clone()));
}
if scene.viewport.width == 0 || scene.viewport.height == 0 {
return Err(ManifestError::InvalidViewport(scene.id.clone()));
}
}
let mut story_ids = BTreeSet::new();
for story in &self.stories {
if story.id.trim().is_empty() {
return Err(ManifestError::MissingStoryId);
}
if !story_ids.insert(story.id.as_str()) {
return Err(ManifestError::DuplicateStoryId(story.id.clone()));
}
if story.title.trim().is_empty() {
return Err(ManifestError::MissingStoryTitle(story.id.clone()));
}
if story.source.trim().is_empty() {
return Err(ManifestError::MissingStorySource(story.id.clone()));
}
let mut arg_names = BTreeSet::new();
for arg in &story.args {
if !arg_names.insert(arg.name.as_str()) {
return Err(ManifestError::DuplicateArg {
story: story.id.clone(),
arg: arg.name.clone(),
});
}
}
for scene in &story.scenes {
if !scene_ids.contains(scene.as_str()) {
return Err(ManifestError::UnknownScene {
story: story.id.clone(),
scene: scene.clone(),
});
}
}
}
Ok(())
}
#[must_use]
pub fn cases(&self) -> Vec<CaseV1<'_>> {
self.stories
.iter()
.flat_map(|story| {
let scene_ids: Vec<&str> = if story.scenes.is_empty() {
self.scenes.iter().map(|scene| scene.id.as_str()).collect()
} else {
story.scenes.iter().map(String::as_str).collect()
};
scene_ids.into_iter().map(move |scene_id| CaseV1 {
story,
scene: self.scenes.iter().find(|scene| scene.id == scene_id),
})
})
.collect()
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct FrameContractV1 {
pub version: u16,
pub path: String,
pub story_query: String,
pub scene_query: String,
pub root_selector: String,
pub ready_selector: String,
pub error_selector: String,
}
impl Default for FrameContractV1 {
fn default() -> Self {
Self {
version: FRAME_VERSION_V1,
path: DEFAULT_FRAME_PATH.to_owned(),
story_query: "story".to_owned(),
scene_query: "scene".to_owned(),
root_selector: "[data-coatcheck-frame]".to_owned(),
ready_selector: "[data-coatcheck-ready]".to_owned(),
error_selector: "[data-coatcheck-error]".to_owned(),
}
}
}
impl FrameContractV1 {
fn validate(&self) -> Result<(), ManifestError> {
if self.version != FRAME_VERSION_V1 {
return Err(ManifestError::UnsupportedFrameVersion(self.version));
}
for (field, value) in [
("path", self.path.as_str()),
("story_query", self.story_query.as_str()),
("scene_query", self.scene_query.as_str()),
("root_selector", self.root_selector.as_str()),
("ready_selector", self.ready_selector.as_str()),
("error_selector", self.error_selector.as_str()),
] {
if value.trim().is_empty() {
return Err(ManifestError::MissingFrameField(field));
}
}
Ok(())
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct StoryV1 {
pub id: String,
pub title: String,
pub tier: String,
pub kind: String,
#[serde(default)]
pub description: String,
pub source: String,
#[serde(default)]
pub args: Vec<ArgV1>,
#[serde(default)]
pub scenes: Vec<String>,
}
impl StoryV1 {
fn from_static(story: &crate::Story) -> Self {
Self {
id: story.id.to_owned(),
title: story.title.to_owned(),
tier: story.tier.to_owned(),
kind: story.kind.label().to_owned(),
description: story.description.to_owned(),
source: story.source.to_owned(),
args: story
.args
.iter()
.map(|arg| ArgV1 {
name: arg.name.to_owned(),
type_name: arg.type_name.to_owned(),
control: arg.control.label().to_owned(),
default_value: arg.default_value.to_owned(),
description: arg.description.to_owned(),
options: arg.options.iter().map(ToString::to_string).collect(),
})
.collect(),
scenes: Vec::new(),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ArgV1 {
pub name: String,
pub type_name: String,
pub control: String,
pub default_value: String,
#[serde(default)]
pub description: String,
#[serde(default)]
pub options: Vec<String>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SceneV1 {
pub id: String,
pub label: String,
pub viewport: ViewportV1,
pub surface: String,
}
impl Default for SceneV1 {
fn default() -> Self {
Self {
id: "default".to_owned(),
label: "Default".to_owned(),
viewport: ViewportV1 {
width: 1280,
height: 900,
},
surface: "canvas".to_owned(),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ViewportV1 {
pub width: u16,
pub height: u16,
}
#[derive(Clone, Copy, Debug)]
pub struct CaseV1<'a> {
pub story: &'a StoryV1,
pub scene: Option<&'a SceneV1>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ManifestError {
UnsupportedManifestVersion(u16),
UnsupportedFrameVersion(u16),
MissingName,
MissingFrameField(&'static str),
MissingSceneId,
DuplicateSceneId(String),
InvalidViewport(String),
MissingStoryId,
DuplicateStoryId(String),
MissingStoryTitle(String),
MissingStorySource(String),
DuplicateArg {
story: String,
arg: String,
},
UnknownScene {
story: String,
scene: String,
},
}
impl fmt::Display for ManifestError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::UnsupportedManifestVersion(version) => {
write!(formatter, "unsupported manifest version: {version}")
}
Self::UnsupportedFrameVersion(version) => {
write!(formatter, "unsupported frame version: {version}")
}
Self::MissingName => formatter.write_str("manifest name cannot be empty"),
Self::MissingFrameField(field) => write!(formatter, "frame field {field} is empty"),
Self::MissingSceneId => formatter.write_str("scene ID cannot be empty"),
Self::DuplicateSceneId(id) => write!(formatter, "duplicate scene ID: {id}"),
Self::InvalidViewport(id) => write!(formatter, "scene {id} has an invalid viewport"),
Self::MissingStoryId => formatter.write_str("story ID cannot be empty"),
Self::DuplicateStoryId(id) => write!(formatter, "duplicate story ID: {id}"),
Self::MissingStoryTitle(id) => write!(formatter, "story {id} has no title"),
Self::MissingStorySource(id) => write!(formatter, "story {id} has no source"),
Self::DuplicateArg { story, arg } => {
write!(formatter, "duplicate argument {arg} in story {story}")
}
Self::UnknownScene { story, scene } => {
write!(formatter, "story {story} references unknown scene {scene}")
}
}
}
}
impl Error for ManifestError {}
const _: fn(StoryKind) -> &'static str = StoryKind::label;
const _: fn(ControlKind) -> &'static str = ControlKind::label;
#[cfg(test)]
mod tests {
use super::{FrameContractV1, ManifestError, ManifestV1, SceneV1, StoryV1, ViewportV1};
fn manifest() -> ManifestV1 {
ManifestV1 {
version: 1,
name: "Example".to_owned(),
frame: FrameContractV1::default(),
scenes: vec![SceneV1 {
id: "mobile".to_owned(),
label: "Mobile".to_owned(),
viewport: ViewportV1 {
width: 393,
height: 852,
},
surface: "canvas".to_owned(),
}],
stories: vec![StoryV1 {
id: "button".to_owned(),
title: "Button".to_owned(),
tier: "Atoms".to_owned(),
kind: "playground".to_owned(),
description: String::new(),
source: "src/button.rs".to_owned(),
args: Vec::new(),
scenes: vec!["mobile".to_owned()],
}],
}
}
#[test]
fn round_trips_json_and_expands_cases() {
let json = serde_json::to_string(&manifest()).unwrap();
let decoded: ManifestV1 = serde_json::from_str(&json).unwrap();
assert_eq!(decoded.validate(), Ok(()));
let cases = decoded.cases();
assert_eq!(cases.len(), 1);
assert_eq!(cases[0].story.id, "button");
assert_eq!(
cases[0].scene.map(|scene| scene.id.as_str()),
Some("mobile")
);
}
#[test]
fn rejects_unknown_scenes() {
let mut invalid = manifest();
invalid.stories[0].scenes = vec!["desktop".to_owned()];
assert_eq!(
invalid.validate(),
Err(ManifestError::UnknownScene {
story: "button".to_owned(),
scene: "desktop".to_owned(),
})
);
}
}