coatcheck 0.2.0

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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
#![doc = include_str!("../README.md")]
#![forbid(unsafe_code)]

pub mod config;
pub mod contract;
pub mod runner;

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

/// The editor used to change a story argument.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ControlKind {
    /// Single-line or multi-line text input.
    Text,
    /// Numeric input.
    Number,
    /// One value selected from a fixed option list.
    Choice,
    /// Boolean switch.
    Toggle,
    /// Color value input.
    Color,
    /// Metadata displayed without an editor.
    ReadOnly,
}

impl ControlKind {
    /// Returns a stable, human-readable control label.
    #[must_use]
    pub const fn label(self) -> &'static str {
        match self {
            Self::Text => "text",
            Self::Number => "number",
            Self::Choice => "choice",
            Self::Toggle => "toggle",
            Self::Color => "color",
            Self::ReadOnly => "read only",
        }
    }
}

/// Describes one editable or documented story argument.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ArgType {
    /// Rust-facing argument name.
    pub name: &'static str,
    /// Human-readable Rust type.
    pub type_name: &'static str,
    /// Editor displayed by the workbench.
    pub control: ControlKind,
    /// Serialized default value.
    pub default_value: &'static str,
    /// Short explanation of the argument's behavior.
    pub description: &'static str,
    /// Allowed values for [`ControlKind::Choice`].
    pub options: &'static [&'static str],
}

/// The intent of a story, modeled after useful Storybook story families.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum StoryKind {
    /// Interactive story whose arguments can be edited.
    #[default]
    Playground,
    /// One named component state.
    State,
    /// Multiple variants rendered together as a contract check.
    Matrix,
    /// A composed product scene.
    Scene,
    /// A design-token or usage reference.
    Documentation,
}

impl StoryKind {
    /// Returns a stable, human-readable story-kind label.
    #[must_use]
    pub const fn label(self) -> &'static str {
        match self {
            Self::Playground => "playground",
            Self::State => "state",
            Self::Matrix => "matrix",
            Self::Scene => "scene",
            Self::Documentation => "documentation",
        }
    }
}

/// A named production-component state in a Coatcheck catalog.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Story {
    /// Stable URL-safe identifier.
    pub id: &'static str,
    /// Display name.
    pub title: &'static str,
    /// Atomic or product hierarchy group.
    pub tier: &'static str,
    /// Story family.
    pub kind: StoryKind,
    /// Short explanation of what the story proves.
    pub description: &'static str,
    /// Source file containing the production component.
    pub source: &'static str,
    /// Editable and documented arguments.
    pub args: &'static [ArgType],
}

/// An allocation-free collection of registered stories.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Catalog {
    name: &'static str,
    stories: &'static [Story],
}

impl Catalog {
    /// Creates a catalog backed by a static story slice.
    #[must_use]
    pub const fn new(name: &'static str, stories: &'static [Story]) -> Self {
        Self { name, stories }
    }

    /// Returns the catalog name.
    #[must_use]
    pub const fn name(self) -> &'static str {
        self.name
    }

    /// Returns every registered story.
    #[must_use]
    pub const fn stories(self) -> &'static [Story] {
        self.stories
    }

    /// Returns the number of registered stories.
    #[must_use]
    pub const fn len(self) -> usize {
        self.stories.len()
    }

    /// Returns whether no stories are registered.
    #[must_use]
    pub const fn is_empty(self) -> bool {
        self.stories.is_empty()
    }

    /// Finds a story by stable ID without allocating.
    #[must_use]
    pub fn story(self, id: &str) -> Option<&'static Story> {
        self.stories.iter().find(|story| story.id == id)
    }

    /// Checks this catalog's structural guarantees.
    ///
    /// # Errors
    ///
    /// Returns a [`CatalogError`] when story IDs or argument names collide,
    /// required metadata is missing, or a choice control has no options.
    pub fn validate(self) -> Result<(), CatalogError> {
        validate(self.stories)
    }
}

/// A named canvas size in CSS pixels.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Viewport {
    /// Stable identifier.
    pub id: &'static str,
    /// Display name.
    pub label: &'static str,
    /// Canvas width in CSS pixels.
    pub width: u16,
    /// Canvas height in CSS pixels.
    pub height: u16,
}

/// A named canvas background or surface.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Surface {
    /// Stable identifier.
    pub id: &'static str,
    /// Display name.
    pub label: &'static str,
    /// Consumer-defined CSS token or color value.
    pub value: &'static str,
}

/// A reusable pairing of viewport and surface.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Scene {
    /// Stable identifier.
    pub id: &'static str,
    /// Display name.
    pub label: &'static str,
    /// Referenced [`Viewport::id`].
    pub viewport: &'static str,
    /// Referenced [`Surface::id`].
    pub surface: &'static str,
}

/// Mobile-first viewports adapted from the first Coatcheck reference application.
pub const DEFAULT_VIEWPORTS: &[Viewport] = &[
    Viewport {
        id: "mobile393",
        label: "Mobile 393",
        width: 393,
        height: 852,
    },
    Viewport {
        id: "tablet768",
        label: "Tablet 768",
        width: 768,
        height: 1024,
    },
    Viewport {
        id: "desktop1280",
        label: "Desktop 1280",
        width: 1280,
        height: 900,
    },
];

/// Neutral surface contracts that applications can map to their own tokens.
pub const DEFAULT_SURFACES: &[Surface] = &[
    Surface {
        id: "canvas",
        label: "Canvas",
        value: "canvas",
    },
    Surface {
        id: "inverse",
        label: "Inverse",
        value: "inverse",
    },
    Surface {
        id: "grid",
        label: "Grid",
        value: "grid",
    },
];

/// Useful default viewport and surface pairings.
pub const DEFAULT_SCENES: &[Scene] = &[
    Scene {
        id: "mobile",
        label: "Mobile",
        viewport: "mobile393",
        surface: "canvas",
    },
    Scene {
        id: "desktop",
        label: "Desktop",
        viewport: "desktop1280",
        surface: "canvas",
    },
    Scene {
        id: "mobile-inverse",
        label: "Mobile inverse",
        viewport: "mobile393",
        surface: "inverse",
    },
    Scene {
        id: "desktop-grid",
        label: "Desktop grid",
        viewport: "desktop1280",
        surface: "grid",
    },
];

/// Structural errors in a story catalog.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum CatalogError {
    /// Two stories use the same ID.
    DuplicateId(&'static str),
    /// Two arguments in one story use the same name.
    DuplicateArg {
        /// Story containing the duplicate.
        story: &'static str,
        /// Duplicate argument name.
        arg: &'static str,
    },
    /// A story has no stable ID.
    MissingId,
    /// A story has no title.
    MissingTitle(&'static str),
    /// A story has no hierarchy tier.
    MissingTier(&'static str),
    /// A story has no production source path.
    MissingSource(&'static str),
    /// A choice control declares no options.
    ChoiceWithoutOptions {
        /// Story containing the invalid control.
        story: &'static str,
        /// Invalid argument name.
        arg: &'static str,
    },
}

impl fmt::Display for CatalogError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::DuplicateId(id) => write!(formatter, "duplicate story ID: {id}"),
            Self::DuplicateArg { story, arg } => {
                write!(formatter, "duplicate argument {arg} in story {story}")
            }
            Self::MissingId => formatter.write_str("story ID cannot be empty"),
            Self::MissingTitle(id) => write!(formatter, "story {id} has no title"),
            Self::MissingTier(id) => write!(formatter, "story {id} has no tier"),
            Self::MissingSource(id) => write!(formatter, "story {id} has no source"),
            Self::ChoiceWithoutOptions { story, arg } => {
                write!(
                    formatter,
                    "choice argument {arg} in story {story} has no options"
                )
            }
        }
    }
}

impl Error for CatalogError {}

/// Checks the structural guarantees every Coatcheck catalog relies on.
///
/// # Errors
///
/// Returns a [`CatalogError`] when story IDs or argument names collide,
/// required metadata is missing, or a choice control has no options.
pub fn validate(stories: &[Story]) -> Result<(), CatalogError> {
    let mut ids = BTreeSet::new();

    for story in stories {
        if story.id.trim().is_empty() {
            return Err(CatalogError::MissingId);
        }
        if !ids.insert(story.id) {
            return Err(CatalogError::DuplicateId(story.id));
        }
        if story.title.trim().is_empty() {
            return Err(CatalogError::MissingTitle(story.id));
        }
        if story.tier.trim().is_empty() {
            return Err(CatalogError::MissingTier(story.id));
        }
        if story.source.trim().is_empty() {
            return Err(CatalogError::MissingSource(story.id));
        }

        let mut arg_names = BTreeSet::new();
        for arg in story.args {
            if !arg_names.insert(arg.name) {
                return Err(CatalogError::DuplicateArg {
                    story: story.id,
                    arg: arg.name,
                });
            }
            if arg.control == ControlKind::Choice && arg.options.is_empty() {
                return Err(CatalogError::ChoiceWithoutOptions {
                    story: story.id,
                    arg: arg.name,
                });
            }
        }
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::{
        ArgType, Catalog, CatalogError, ControlKind, DEFAULT_SCENES, DEFAULT_SURFACES,
        DEFAULT_VIEWPORTS, Story, StoryKind, validate,
    };

    const LABEL: ArgType = ArgType {
        name: "label",
        type_name: "String",
        control: ControlKind::Text,
        default_value: "Enter briefing",
        description: "Visible action copy.",
        options: &[],
    };

    const STORIES: &[Story] = &[
        Story {
            id: "wordmark",
            title: "Wordmark",
            tier: "Atoms",
            kind: StoryKind::State,
            description: "Cold Front identity.",
            source: "atoms.rs",
            args: &[],
        },
        Story {
            id: "action-link",
            title: "Action link",
            tier: "Atoms",
            kind: StoryKind::Playground,
            description: "Navigational action.",
            source: "atoms.rs",
            args: &[LABEL],
        },
    ];
    const DUPLICATE_ARGS: &[ArgType] = &[LABEL, LABEL];

    #[test]
    fn accepts_a_valid_catalog() {
        assert_eq!(validate(STORIES), Ok(()));
    }

    #[test]
    fn catalog_lookup_is_allocation_free() {
        let catalog = Catalog::new("Cold Front", STORIES);

        assert_eq!(catalog.name(), "Cold Front");
        assert_eq!(catalog.len(), 2);
        assert!(!catalog.is_empty());
        assert_eq!(
            catalog.story("action-link").map(|story| story.title),
            Some("Action link")
        );
        assert!(catalog.story("unknown").is_none());
        assert_eq!(catalog.validate(), Ok(()));
    }

    #[test]
    fn defaults_reference_known_viewports_and_surfaces() {
        for scene in DEFAULT_SCENES {
            assert!(
                DEFAULT_VIEWPORTS
                    .iter()
                    .any(|viewport| viewport.id == scene.viewport)
            );
            assert!(
                DEFAULT_SURFACES
                    .iter()
                    .any(|surface| surface.id == scene.surface)
            );
        }
    }

    #[test]
    fn rejects_duplicate_story_ids() {
        let duplicate = [STORIES[0], STORIES[0]];
        assert_eq!(
            validate(&duplicate),
            Err(CatalogError::DuplicateId("wordmark"))
        );
    }

    #[test]
    fn rejects_duplicate_arg_names() {
        let stories = [Story {
            id: "action-link",
            title: "Action link",
            tier: "Atoms",
            kind: StoryKind::Playground,
            description: "Navigational action.",
            source: "atoms.rs",
            args: DUPLICATE_ARGS,
        }];

        assert_eq!(
            validate(&stories),
            Err(CatalogError::DuplicateArg {
                story: "action-link",
                arg: "label",
            })
        );
    }
}