Skip to main content

dx_story/
lib.rs

1//! Dioxus component stories.
2//!
3//! ```
4//! use dioxus::prelude::*;
5//! use dx_story::{stories, story};
6//!
7//! #[story]
8//! fn default() -> Element {
9//!     rsx! { button { "Save" } }
10//! }
11//!
12//! #[stories(id = "button", name = "Button")]
13//! const BUTTON_STORIES: () = &[default];
14//! ```
15
16extern crate self as dx_story;
17
18use std::{collections::HashSet, error::Error, fmt, sync::OnceLock};
19
20use dioxus::prelude::Element;
21/// Registers a story set from a const array of [`story`] functions.
22///
23/// `id` and `name` are required. `thumbnail` selects the card story;
24/// `extra_docs` appends Markdown. The const must have type `()` and contain
25/// `&[story_name, ...]`.
26///
27/// ```
28/// use dioxus::prelude::*;
29/// use dx_story::{stories, story};
30///
31/// #[story]
32/// fn default() -> Element {
33///     rsx! { "Default" }
34/// }
35///
36/// #[stories(id = "example", name = "Example")]
37/// const EXAMPLE: () = &[default];
38/// ```
39pub use dx_story_macros::stories;
40/// Registers a zero-argument Dioxus render function.
41///
42/// The function must be non-generic and return `Element`. `id` and `name`
43/// default to values derived from the function name.
44///
45/// ```
46/// use dioxus::prelude::*;
47/// use dx_story::story;
48///
49/// #[story(id = "with_count", name = "With count")]
50/// fn stateful() -> Element {
51///     let count = use_signal(|| 0_u32);
52///     rsx! { output { "{count}" } }
53/// }
54/// ```
55pub use dx_story_macros::story;
56
57#[cfg(feature = "catalog")]
58pub mod catalog;
59
60#[doc(hidden)]
61pub mod __private {
62    pub use const_format::concatcp;
63    pub use dioxus;
64    pub use inventory::submit;
65
66    #[doc(hidden)]
67    #[must_use]
68    pub const fn story(
69        id: &'static str,
70        name: &'static str,
71        description: Option<&'static str>,
72        render: fn() -> dioxus::prelude::Element,
73        source: &'static str,
74    ) -> super::Story {
75        super::Story {
76            id,
77            name,
78            description,
79            render,
80            source,
81        }
82    }
83
84    #[doc(hidden)]
85    #[must_use]
86    pub const fn story_set(
87        id: &'static str,
88        name: &'static str,
89        description: Option<&'static str>,
90        thumbnail: Option<&'static super::Story>,
91        stories: &'static [&'static super::Story],
92    ) -> super::StorySet {
93        super::StorySet {
94            id,
95            name,
96            description,
97            thumbnail,
98            stories,
99        }
100    }
101
102    #[cfg(feature = "benchmark-support")]
103    #[doc(hidden)]
104    pub fn build_registry_for_benchmark(
105        registrations: impl IntoIterator<Item = &'static super::StorySet>,
106    ) -> Result<Box<[&'static super::StorySet]>, super::RegistryError> {
107        super::build_registry(registrations)
108    }
109}
110
111/// A renderable component state.
112#[derive(Clone, Copy, Debug)]
113pub struct Story {
114    id: &'static str,
115    name: &'static str,
116    description: Option<&'static str>,
117    render: fn() -> Element,
118    source: &'static str,
119}
120
121impl Story {
122    #[must_use]
123    pub const fn id(&self) -> &'static str {
124        self.id
125    }
126
127    #[must_use]
128    pub const fn name(&self) -> &'static str {
129        self.name
130    }
131
132    #[must_use]
133    pub const fn description(&self) -> Option<&'static str> {
134        self.description
135    }
136
137    #[must_use]
138    pub const fn render(&self) -> fn() -> Element {
139        self.render
140    }
141
142    #[must_use]
143    pub const fn source(&self) -> &'static str {
144        self.source
145    }
146}
147
148impl PartialEq for Story {
149    fn eq(&self, other: &Self) -> bool {
150        self.id == other.id
151            && self.name == other.name
152            && self.description == other.description
153            && std::ptr::fn_addr_eq(self.render, other.render)
154            && self.source == other.source
155    }
156}
157
158impl Eq for Story {}
159
160/// A component and its stories.
161#[derive(Clone, Copy, Debug)]
162pub struct StorySet {
163    id: &'static str,
164    name: &'static str,
165    description: Option<&'static str>,
166    thumbnail: Option<&'static Story>,
167    stories: &'static [&'static Story],
168}
169
170impl StorySet {
171    #[must_use]
172    pub const fn id(&self) -> &'static str {
173        self.id
174    }
175
176    #[must_use]
177    pub const fn name(&self) -> &'static str {
178        self.name
179    }
180
181    #[must_use]
182    pub const fn description(&self) -> Option<&'static str> {
183        self.description
184    }
185
186    #[must_use]
187    pub const fn stories(&self) -> &'static [&'static Story] {
188        self.stories
189    }
190
191    #[must_use]
192    pub fn first_story(&self) -> Option<&'static Story> {
193        self.stories.first().copied()
194    }
195
196    /// Falls back to the first story.
197    #[must_use]
198    pub fn thumbnail(&self) -> Option<&'static Story> {
199        self.thumbnail.or_else(|| self.first_story())
200    }
201}
202
203impl PartialEq for StorySet {
204    fn eq(&self, other: &Self) -> bool {
205        self.id == other.id
206            && self.name == other.name
207            && self.description == other.description
208            && self.thumbnail == other.thumbnail
209            && self.stories == other.stories
210    }
211}
212
213impl Eq for StorySet {}
214
215/// A registry validation failure.
216#[derive(Clone, Copy, Debug, Eq, PartialEq)]
217pub enum RegistryError {
218    DuplicateStorySetId {
219        id: &'static str,
220    },
221    DuplicateStoryId {
222        story_set_id: &'static str,
223        story_id: &'static str,
224    },
225    StorySetWithoutStories {
226        story_set_id: &'static str,
227    },
228}
229
230impl fmt::Display for RegistryError {
231    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
232        match self {
233            Self::DuplicateStorySetId { id } => {
234                write!(formatter, "duplicate story set ID `{id}`")
235            }
236            Self::DuplicateStoryId {
237                story_set_id,
238                story_id,
239            } => write!(
240                formatter,
241                "duplicate story ID `{story_id}` in story set `{story_set_id}`"
242            ),
243            Self::StorySetWithoutStories { story_set_id } => {
244                write!(
245                    formatter,
246                    "story set `{story_set_id}` has no routed stories"
247                )
248            }
249        }
250    }
251}
252
253impl Error for RegistryError {}
254
255inventory::collect!(&'static StorySet);
256
257static STORY_SET_REGISTRY: OnceLock<Result<Box<[&'static StorySet]>, RegistryError>> =
258    OnceLock::new();
259const STORY_SET_COUNT_LINEAR_VALIDATION_MAX: usize = 16;
260
261#[cfg(target_family = "wasm")]
262unsafe extern "C" {
263    fn __wasm_call_ctors();
264}
265
266/// Validates registered story sets.
267///
268/// # Errors
269///
270/// Returns the first [`RegistryError`].
271pub fn init_registry() -> Result<(), RegistryError> {
272    registry().map(|_| ())
273}
274
275/// Registered story sets in display-name order.
276///
277/// # Errors
278///
279/// Returns the first [`RegistryError`].
280pub fn story_sets() -> Result<&'static [&'static StorySet], RegistryError> {
281    registry()
282}
283
284/// Finds a story by story set and story ID.
285///
286/// # Errors
287///
288/// Returns the first [`RegistryError`].
289pub fn find(
290    story_set_id: &str,
291    story_id: &str,
292) -> Result<Option<(&'static StorySet, &'static Story)>, RegistryError> {
293    let story_set = story_sets()?
294        .iter()
295        .copied()
296        .find(|story_set| story_set.id() == story_set_id);
297    let Some(story_set) = story_set else {
298        return Ok(None);
299    };
300    let story = story_set
301        .stories()
302        .iter()
303        .copied()
304        .find(|story| story.id() == story_id);
305    Ok(story.map(|story| (story_set, story)))
306}
307
308/// Validates the registry, then launches `root`.
309///
310/// # Errors
311///
312/// Returns the first [`RegistryError`].
313#[cfg(feature = "csr")]
314pub fn launch(root: fn() -> Element) -> Result<(), RegistryError> {
315    init_registry()?;
316    dioxus::launch(root);
317    Ok(())
318}
319
320fn registry() -> Result<&'static [&'static StorySet], RegistryError> {
321    STORY_SET_REGISTRY
322        .get_or_init(|| {
323            initialize_distributed_registrations();
324            build_registry(inventory::iter::<&'static StorySet>.into_iter().copied())
325        })
326        .as_ref()
327        .map(Box::as_ref)
328        .map_err(|error| *error)
329}
330
331fn initialize_distributed_registrations() {
332    #[cfg(target_family = "wasm")]
333    // SAFETY: Wasm synthesizes this function for static constructors. OnceLock
334    // runs this initializer exactly once before inventory is read.
335    unsafe {
336        __wasm_call_ctors();
337    }
338}
339
340fn build_registry(
341    registrations: impl IntoIterator<Item = &'static StorySet>,
342) -> Result<Box<[&'static StorySet]>, RegistryError> {
343    let mut story_sets = registrations.into_iter().collect::<Vec<_>>();
344    story_sets.sort_unstable_by_key(|story_set| (story_set.name(), story_set.id()));
345    validate_unique_ids(&story_sets)?;
346    Ok(story_sets.into_boxed_slice())
347}
348
349fn validate_unique_ids(story_sets: &[&'static StorySet]) -> Result<(), RegistryError> {
350    if story_sets.len() > STORY_SET_COUNT_LINEAR_VALIDATION_MAX {
351        return validate_unique_ids_with_hash_set(story_sets);
352    }
353
354    validate_unique_ids_with_linear_scan(story_sets)
355}
356
357fn validate_unique_ids_with_linear_scan(
358    story_sets: &[&'static StorySet],
359) -> Result<(), RegistryError> {
360    for (index, story_set) in story_sets.iter().enumerate() {
361        if story_sets[..index]
362            .iter()
363            .any(|registered| registered.id() == story_set.id())
364        {
365            return Err(RegistryError::DuplicateStorySetId { id: story_set.id() });
366        }
367        if story_set.stories().is_empty() {
368            return Err(RegistryError::StorySetWithoutStories {
369                story_set_id: story_set.id(),
370            });
371        }
372        if let Some(story_id) = duplicate_story_id(story_set) {
373            return Err(RegistryError::DuplicateStoryId {
374                story_set_id: story_set.id(),
375                story_id,
376            });
377        }
378    }
379    Ok(())
380}
381
382fn validate_unique_ids_with_hash_set(
383    story_sets: &[&'static StorySet],
384) -> Result<(), RegistryError> {
385    let mut story_set_ids = HashSet::with_capacity(story_sets.len());
386    for story_set in story_sets {
387        if !story_set_ids.insert(story_set.id()) {
388            return Err(RegistryError::DuplicateStorySetId { id: story_set.id() });
389        }
390        if story_set.stories().is_empty() {
391            return Err(RegistryError::StorySetWithoutStories {
392                story_set_id: story_set.id(),
393            });
394        }
395        if let Some(story_id) = duplicate_story_id(story_set) {
396            return Err(RegistryError::DuplicateStoryId {
397                story_set_id: story_set.id(),
398                story_id,
399            });
400        }
401    }
402    Ok(())
403}
404
405fn duplicate_story_id(story_set: &StorySet) -> Option<&'static str> {
406    story_set
407        .stories()
408        .iter()
409        .enumerate()
410        .find_map(|(index, story)| {
411            story_set.stories()[..index]
412                .iter()
413                .any(|registered| registered.id() == story.id())
414                .then_some(story.id())
415        })
416}
417
418#[cfg(test)]
419mod tests {
420    use dioxus::prelude::VNode;
421
422    use super::{
423        RegistryError, STORY_SET_COUNT_LINEAR_VALIDATION_MAX, Story, StorySet, build_registry,
424    };
425
426    fn render_empty() -> dioxus::prelude::Element {
427        VNode::empty()
428    }
429
430    static FIRST_STORY: Story = Story {
431        id: "default",
432        name: "Default",
433        description: None,
434        render: render_empty,
435        source: "",
436    };
437    static DUPLICATE_STORY: Story = Story {
438        id: "default",
439        name: "Duplicate",
440        description: None,
441        render: render_empty,
442        source: "",
443    };
444    static DUPLICATE_STORY_SET: StorySet = StorySet {
445        id: "duplicate-story",
446        name: "Duplicate story",
447        description: None,
448        thumbnail: None,
449        stories: &[&FIRST_STORY, &DUPLICATE_STORY],
450    };
451    static FIRST_STORY_SET: StorySet = StorySet {
452        id: "duplicate-story-set",
453        name: "First",
454        description: None,
455        thumbnail: None,
456        stories: &[&FIRST_STORY],
457    };
458    static SECOND_STORY_SET: StorySet = StorySet {
459        id: "duplicate-story-set",
460        name: "Second",
461        description: None,
462        thumbnail: None,
463        stories: &[&FIRST_STORY],
464    };
465    static EMPTY_STORY_SET: StorySet = StorySet {
466        id: "empty-story-set",
467        name: "Empty story set",
468        description: None,
469        thumbnail: None,
470        stories: &[],
471    };
472
473    #[test]
474    fn registry_rejects_duplicate_story_set_ids() {
475        assert_eq!(
476            build_registry([&FIRST_STORY_SET, &SECOND_STORY_SET]),
477            Err(RegistryError::DuplicateStorySetId {
478                id: "duplicate-story-set"
479            })
480        );
481    }
482
483    #[test]
484    fn registry_rejects_duplicate_story_ids() {
485        assert_eq!(
486            build_registry([&DUPLICATE_STORY_SET]),
487            Err(RegistryError::DuplicateStoryId {
488                story_set_id: "duplicate-story",
489                story_id: "default",
490            })
491        );
492    }
493
494    #[test]
495    fn large_registry_preserves_first_error_in_display_order() {
496        let registrations = vec![&DUPLICATE_STORY_SET; STORY_SET_COUNT_LINEAR_VALIDATION_MAX + 1];
497        assert_eq!(
498            build_registry(registrations),
499            Err(RegistryError::DuplicateStoryId {
500                story_set_id: "duplicate-story",
501                story_id: "default",
502            })
503        );
504    }
505
506    #[test]
507    fn registry_rejects_story_sets_without_routed_stories() {
508        assert_eq!(
509            build_registry([&EMPTY_STORY_SET]),
510            Err(RegistryError::StorySetWithoutStories {
511                story_set_id: "empty-story-set",
512            })
513        );
514    }
515
516    #[test]
517    fn thumbnail_falls_back_to_the_first_routed_story() {
518        assert_eq!(FIRST_STORY_SET.first_story(), Some(&FIRST_STORY));
519        assert_eq!(FIRST_STORY_SET.thumbnail(), Some(&FIRST_STORY));
520    }
521}