coatcheck 0.2.1

Contracts and a Playwright accessibility runner for Topcoat component workbenches.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
//! Versioned wire contracts shared by a Coatcheck host and runner.

use std::collections::BTreeSet;
use std::error::Error;
use std::fmt;

use serde::{Deserialize, Serialize};

use crate::{Catalog, ControlKind, StoryKind};

/// Version 1 of the manifest contract.
pub const MANIFEST_VERSION_V1: u16 = 1;

/// Version 1 of the frame contract.
pub const FRAME_VERSION_V1: u16 = 1;

/// The default path at which a host serves its manifest.
pub const DEFAULT_MANIFEST_PATH: &str = "/__coatcheck/manifest.json";

/// The default path at which a host renders an isolated story frame.
pub const DEFAULT_FRAME_PATH: &str = "/__coatcheck/frame";

/// Version 1 of the JSON manifest returned by a Coatcheck host.
///
/// Unknown JSON fields are intentionally accepted so producers can add
/// metadata without breaking a version-1 consumer.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ManifestV1 {
    /// Must equal [`MANIFEST_VERSION_V1`].
    pub version: u16,
    /// Human-readable catalog name.
    pub name: String,
    /// Contract used to construct and inspect isolated frame URLs.
    pub frame: FrameContractV1,
    /// Named rendering scenes available to stories.
    #[serde(default)]
    pub scenes: Vec<SceneV1>,
    /// Stories available to the runner.
    #[serde(default)]
    pub stories: Vec<StoryV1>,
}

impl ManifestV1 {
    /// Creates a manifest from the allocation-free 0.1 catalog API.
    #[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,
        }
    }

    /// Validates cross-record and frame invariants.
    ///
    /// # Errors
    ///
    /// Returns a [`ManifestError`] for unsupported versions, duplicate or
    /// missing IDs, invalid dimensions, unknown scenes, or an invalid frame
    /// contract.
    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(())
    }

    /// Expands the catalog into deterministic story/scene cases.
    #[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()
    }
}

/// DOM and URL conventions for version-1 isolated frames.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct FrameContractV1 {
    /// Must equal [`FRAME_VERSION_V1`].
    pub version: u16,
    /// Path or absolute URL for the isolated frame.
    pub path: String,
    /// Query parameter containing the story ID.
    pub story_query: String,
    /// Query parameter containing the optional scene ID.
    pub scene_query: String,
    /// Selector for the isolated component root.
    pub root_selector: String,
    /// Selector that appears when rendering has settled.
    pub ready_selector: String,
    /// Selector that appears when the host reports a rendering error.
    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(())
    }
}

/// One story in a version-1 manifest.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct StoryV1 {
    /// Stable URL-safe story ID.
    pub id: String,
    /// Human-readable story title.
    pub title: String,
    /// Atomic or product hierarchy group.
    pub tier: String,
    /// Stable story kind label.
    pub kind: String,
    /// What the story proves.
    #[serde(default)]
    pub description: String,
    /// Human-maintained source path.
    pub source: String,
    /// Editable and documented arguments.
    #[serde(default)]
    pub args: Vec<ArgV1>,
    /// Scene IDs to test. Empty means every manifest scene.
    #[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(),
        }
    }
}

/// One owned argument record in a version-1 manifest.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ArgV1 {
    /// Stable argument name.
    pub name: String,
    /// Human-readable Rust type.
    pub type_name: String,
    /// Stable [`ControlKind::label`] value.
    pub control: String,
    /// Serialized default value.
    pub default_value: String,
    /// Short behavior description.
    #[serde(default)]
    pub description: String,
    /// Allowed choice values.
    #[serde(default)]
    pub options: Vec<String>,
}

/// One named viewport and surface combination.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SceneV1 {
    /// Stable scene ID.
    pub id: String,
    /// Human-readable scene label.
    pub label: String,
    /// Browser viewport for the case.
    pub viewport: ViewportV1,
    /// Consumer-defined surface token.
    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(),
        }
    }
}

/// A browser viewport in CSS pixels.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ViewportV1 {
    /// Width in CSS pixels.
    pub width: u16,
    /// Height in CSS pixels.
    pub height: u16,
}

/// One expanded manifest case.
#[derive(Clone, Copy, Debug)]
pub struct CaseV1<'a> {
    /// Story under test.
    pub story: &'a StoryV1,
    /// Scene under test, or `None` when the manifest declares no scenes.
    pub scene: Option<&'a SceneV1>,
}

/// Validation errors for a version-1 manifest.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ManifestError {
    /// The manifest version is not supported.
    UnsupportedManifestVersion(u16),
    /// The frame version is not supported.
    UnsupportedFrameVersion(u16),
    /// The catalog has no name.
    MissingName,
    /// A required frame field is empty.
    MissingFrameField(&'static str),
    /// A scene has no ID.
    MissingSceneId,
    /// Two scenes share an ID.
    DuplicateSceneId(String),
    /// A scene has a zero viewport dimension.
    InvalidViewport(String),
    /// A story has no ID.
    MissingStoryId,
    /// Two stories share an ID.
    DuplicateStoryId(String),
    /// A story has no title.
    MissingStoryTitle(String),
    /// A story has no source.
    MissingStorySource(String),
    /// Two arguments in one story share a name.
    DuplicateArg {
        /// Story containing the duplicate.
        story: String,
        /// Duplicate argument name.
        arg: String,
    },
    /// A story references an unknown scene.
    UnknownScene {
        /// Story containing the reference.
        story: String,
        /// Unknown scene ID.
        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(),
            })
        );
    }
}