storybook.rs

  1mod actions;
  2mod app_menus;
  3mod assets;
  4mod stories;
  5mod story_selector;
  6
  7use std::sync::Arc;
  8
  9use clap::Parser;
 10use dialoguer::FuzzySelect;
 11use gpui::{
 12    AnyView, App, Bounds, Context, Render, Window, WindowBounds, WindowOptions,
 13    colors::{Colors, GlobalColors},
 14    div, px, size,
 15};
 16use log::LevelFilter;
 17use reqwest_client::ReqwestClient;
 18use settings::{KeymapFile, Settings};
 19use simplelog::SimpleLogger;
 20use strum::IntoEnumIterator;
 21use theme::ThemeSettings;
 22use ui::prelude::*;
 23
 24use crate::app_menus::app_menus;
 25use crate::assets::Assets;
 26use crate::story_selector::{ComponentStory, StorySelector};
 27use actions::Quit;
 28pub use indoc::indoc;
 29
 30#[derive(Parser)]
 31#[command(author, version, about, long_about = None)]
 32struct Args {
 33    #[arg(value_enum)]
 34    story: Option<StorySelector>,
 35
 36    /// The name of the theme to use in the storybook.
 37    ///
 38    /// If not provided, the default theme will be used.
 39    #[arg(long)]
 40    theme: Option<String>,
 41}
 42
 43fn main() {
 44    SimpleLogger::init(LevelFilter::Info, Default::default()).expect("could not initialize logger");
 45
 46    menu::init();
 47    let args = Args::parse();
 48
 49    let story_selector = args.story.unwrap_or_else(|| {
 50        let stories = ComponentStory::iter().collect::<Vec<_>>();
 51
 52        ctrlc::set_handler(move || {}).unwrap();
 53
 54        let result = FuzzySelect::new()
 55            .with_prompt("Choose a story to run:")
 56            .items(&stories)
 57            .interact();
 58
 59        let Ok(selection) = result else {
 60            dialoguer::console::Term::stderr().show_cursor().unwrap();
 61            std::process::exit(0);
 62        };
 63
 64        StorySelector::Component(stories[selection])
 65    });
 66    let theme_name = args.theme.unwrap_or("One Dark".to_string());
 67
 68    gpui_platform::application()
 69        .with_assets(Assets)
 70        .run(move |cx| {
 71            load_embedded_fonts(cx).unwrap();
 72
 73            cx.set_global(GlobalColors(Arc::new(Colors::default())));
 74
 75            let http_client = ReqwestClient::user_agent("zed_storybook").unwrap();
 76            cx.set_http_client(Arc::new(http_client));
 77
 78            settings::init(cx);
 79            theme::init(theme::LoadThemes::All(Box::new(Assets)), cx);
 80
 81            let selector = story_selector;
 82
 83            let mut theme_settings = ThemeSettings::get_global(cx).clone();
 84            theme_settings.theme =
 85                theme::ThemeSelection::Static(settings::ThemeName(theme_name.into()));
 86            ThemeSettings::override_global(theme_settings, cx);
 87
 88            editor::init(cx);
 89            init(cx);
 90            load_storybook_keymap(cx);
 91            cx.set_menus(app_menus());
 92
 93            let size = size(px(1500.), px(780.));
 94            let bounds = Bounds::centered(None, size, cx);
 95            let _window = cx.open_window(
 96                WindowOptions {
 97                    window_bounds: Some(WindowBounds::Windowed(bounds)),
 98                    ..Default::default()
 99                },
100                move |window, cx| {
101                    theme::setup_ui_font(window, cx);
102
103                    cx.new(|cx| StoryWrapper::new(selector.story(window, cx)))
104                },
105            );
106
107            cx.activate(true);
108        });
109}
110
111#[derive(Clone)]
112pub struct StoryWrapper {
113    story: AnyView,
114}
115
116impl StoryWrapper {
117    pub(crate) fn new(story: AnyView) -> Self {
118        Self { story }
119    }
120}
121
122impl Render for StoryWrapper {
123    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
124        div()
125            .flex()
126            .flex_col()
127            .size_full()
128            .font_family(".ZedMono")
129            .child(self.story.clone())
130    }
131}
132
133fn load_embedded_fonts(cx: &App) -> anyhow::Result<()> {
134    let font_paths = cx.asset_source().list("fonts")?;
135    let mut embedded_fonts = Vec::new();
136    for font_path in font_paths {
137        if font_path.ends_with(".ttf") {
138            let font_bytes = cx
139                .asset_source()
140                .load(&font_path)?
141                .expect("Should never be None in the storybook");
142            embedded_fonts.push(font_bytes);
143        }
144    }
145
146    cx.text_system().add_fonts(embedded_fonts)
147}
148
149fn load_storybook_keymap(cx: &mut App) {
150    cx.bind_keys(KeymapFile::load_asset("keymaps/storybook.json", None, cx).unwrap());
151}
152
153pub fn init(cx: &mut App) {
154    cx.on_action(quit);
155}
156
157fn quit(_: &Quit, cx: &mut App) {
158    cx.spawn(async move |cx| {
159        cx.update(|cx| cx.quit());
160    })
161    .detach();
162}