story.rs

  1use gpui::{
  2    div, hsla, prelude::*, px, rems, AnyElement, Div, ElementId, Hsla, SharedString, WindowContext,
  3};
  4use itertools::Itertools;
  5use smallvec::SmallVec;
  6
  7use std::path::PathBuf;
  8use std::sync::atomic::{AtomicUsize, Ordering};
  9use std::time::{SystemTime, UNIX_EPOCH};
 10
 11static COUNTER: AtomicUsize = AtomicUsize::new(0);
 12
 13pub fn reasonably_unique_id() -> String {
 14    let now = SystemTime::now();
 15    let timestamp = now.duration_since(UNIX_EPOCH).unwrap();
 16
 17    let cnt = COUNTER.fetch_add(1, Ordering::Relaxed);
 18
 19    let id = format!("{}_{}", timestamp.as_nanos(), cnt);
 20
 21    id
 22}
 23
 24pub struct StoryColor {
 25    pub primary: Hsla,
 26    pub secondary: Hsla,
 27    pub border: Hsla,
 28    pub background: Hsla,
 29    pub card_background: Hsla,
 30    pub divider: Hsla,
 31    pub link: Hsla,
 32}
 33
 34impl StoryColor {
 35    pub fn new() -> Self {
 36        Self {
 37            primary: hsla(216. / 360., 11. / 100., 0. / 100., 1.),
 38            secondary: hsla(216. / 360., 11. / 100., 16. / 100., 1.),
 39            border: hsla(216. / 360., 11. / 100., 91. / 100., 1.),
 40            background: hsla(0. / 360., 0. / 100., 1., 1.),
 41            card_background: hsla(0. / 360., 0. / 100., 96. / 100., 1.),
 42            divider: hsla(216. / 360., 11. / 100., 86. / 100., 1.),
 43            link: hsla(206. / 360., 1., 50. / 100., 1.),
 44        }
 45    }
 46}
 47
 48pub fn story_color() -> StoryColor {
 49    StoryColor::new()
 50}
 51
 52#[derive(IntoElement)]
 53pub struct StoryContainer {
 54    title: SharedString,
 55    relative_path: &'static str,
 56    children: SmallVec<[AnyElement; 2]>,
 57}
 58
 59impl StoryContainer {
 60    pub fn new(title: impl Into<SharedString>, relative_path: &'static str) -> Self {
 61        Self {
 62            title: title.into(),
 63            relative_path,
 64            children: SmallVec::new(),
 65        }
 66    }
 67}
 68
 69impl ParentElement for StoryContainer {
 70    fn extend(&mut self, elements: impl Iterator<Item = AnyElement>) {
 71        self.children.extend(elements)
 72    }
 73}
 74
 75impl RenderOnce for StoryContainer {
 76    fn render(self, _cx: &mut WindowContext) -> impl IntoElement {
 77        div()
 78            .size_full()
 79            .flex()
 80            .flex_col()
 81            .id("story_container")
 82            .bg(story_color().background)
 83            .child(
 84                div()
 85                    .flex()
 86                    .flex_none()
 87                    .w_full()
 88                    .justify_between()
 89                    .p_2()
 90                    .bg(story_color().background)
 91                    .border_b()
 92                    .border_color(story_color().border)
 93                    .child(Story::title(self.title))
 94                    .child(
 95                        div()
 96                            .text_xs()
 97                            .text_color(story_color().primary)
 98                            .child(Story::open_story_link(self.relative_path)),
 99                    ),
100            )
101            .child(
102                div()
103                    .w_full()
104                    .h_px()
105                    .flex_1()
106                    .id("story_body")
107                    .overflow_x_hidden()
108                    .overflow_y_scroll()
109                    .flex()
110                    .flex_col()
111                    .pb_4()
112                    .children(self.children),
113            )
114    }
115}
116
117pub struct Story {}
118
119impl Story {
120    pub fn container() -> Div {
121        div().size_full().overflow_hidden().child(
122            div()
123                .id("story_container")
124                .overflow_y_scroll()
125                .w_full()
126                .min_h_full()
127                .flex()
128                .flex_col()
129                .bg(story_color().background),
130        )
131    }
132
133    // TODO: Move all stories to container2, then rename
134    pub fn container2<T>(relative_path: &'static str) -> Div {
135        div().size_full().child(
136            div()
137                .size_full()
138                .id("story_container")
139                .overflow_y_scroll()
140                .flex()
141                .flex_col()
142                .flex_none()
143                .child(
144                    div()
145                        .flex()
146                        .justify_between()
147                        .p_2()
148                        .border_b()
149                        .border_color(story_color().border)
150                        .child(Story::title_for::<T>())
151                        .child(
152                            div()
153                                .text_xs()
154                                .text_color(story_color().primary)
155                                .child(Story::open_story_link(relative_path)),
156                        ),
157                )
158                .child(
159                    div()
160                        .w_full()
161                        .min_h_full()
162                        .flex()
163                        .flex_col()
164                        .bg(story_color().background),
165                ),
166        )
167    }
168
169    pub fn open_story_link(relative_path: &'static str) -> impl Element {
170        let path = PathBuf::from_iter([relative_path]);
171
172        div()
173            .flex()
174            .gap_2()
175            .text_xs()
176            .text_color(story_color().primary)
177            .id(SharedString::from(format!("id_{}", relative_path)))
178            .on_click({
179                let path = path.clone();
180
181                move |_event, _cx| {
182                    let path = format!("{}:0:0", path.to_string_lossy());
183
184                    std::process::Command::new("zed").arg(path).spawn().ok();
185                }
186            })
187            .children(vec![div().child(Story::link("Open in Zed →"))])
188    }
189
190    pub fn title(title: impl Into<SharedString>) -> impl Element {
191        div()
192            .text_xs()
193            .text_color(story_color().primary)
194            .child(title.into())
195    }
196
197    pub fn title_for<T>() -> impl Element {
198        Self::title(std::any::type_name::<T>())
199    }
200
201    pub fn section() -> Div {
202        div()
203            .p_4()
204            .m_4()
205            .border()
206            .border_color(story_color().border)
207    }
208
209    pub fn section_title() -> Div {
210        div().text_lg().text_color(story_color().primary)
211    }
212
213    pub fn group() -> Div {
214        div().my_2().bg(story_color().background)
215    }
216
217    pub fn code_block(code: impl Into<SharedString>) -> Div {
218        div()
219            .size_full()
220            .p_2()
221            .max_w(rems(36.))
222            .bg(gpui::black())
223            .rounded_md()
224            .text_sm()
225            .text_color(gpui::white())
226            .overflow_hidden()
227            .child(code.into())
228    }
229
230    pub fn divider() -> Div {
231        div().my_2().h(px(1.)).bg(story_color().divider)
232    }
233
234    pub fn link(link: impl Into<SharedString>) -> impl Element {
235        div()
236            .id(ElementId::from(SharedString::from(reasonably_unique_id())))
237            .text_xs()
238            .text_color(story_color().link)
239            .cursor(gpui::CursorStyle::PointingHand)
240            .child(link.into())
241    }
242
243    pub fn description(description: impl Into<SharedString>) -> impl Element {
244        div()
245            .text_sm()
246            .text_color(story_color().secondary)
247            .min_w_96()
248            .child(description.into())
249    }
250
251    pub fn label(label: impl Into<SharedString>) -> impl Element {
252        div()
253            .text_xs()
254            .text_color(story_color().primary)
255            .child(label.into())
256    }
257
258    /// Note: Not `ui::v_flex` as the `story` crate doesn't depend on the `ui` crate.
259    pub fn v_flex() -> Div {
260        div().flex().flex_col().gap_1()
261    }
262}
263
264#[derive(IntoElement)]
265pub struct StoryItem {
266    label: SharedString,
267    item: AnyElement,
268    description: Option<SharedString>,
269    usage: Option<SharedString>,
270}
271
272impl StoryItem {
273    pub fn new(label: impl Into<SharedString>, item: impl IntoElement) -> Self {
274        Self {
275            label: label.into(),
276            item: item.into_any_element(),
277            description: None,
278            usage: None,
279        }
280    }
281
282    pub fn description(mut self, description: impl Into<SharedString>) -> Self {
283        self.description = Some(description.into());
284        self
285    }
286
287    pub fn usage(mut self, code: impl Into<SharedString>) -> Self {
288        self.usage = Some(code.into());
289        self
290    }
291}
292
293impl RenderOnce for StoryItem {
294    fn render(self, _cx: &mut WindowContext) -> impl IntoElement {
295        div()
296            .my_2()
297            .flex()
298            .gap_4()
299            .w_full()
300            .child(
301                Story::v_flex()
302                    .px_2()
303                    .w_1_2()
304                    .min_h_px()
305                    .child(Story::label(self.label))
306                    .child(
307                        div()
308                            .rounded_md()
309                            .bg(story_color().card_background)
310                            .border()
311                            .border_color(story_color().border)
312                            .py_1()
313                            .px_2()
314                            .overflow_hidden()
315                            .child(self.item),
316                    )
317                    .when_some(self.description, |this, description| {
318                        this.child(Story::description(description))
319                    }),
320            )
321            .child(
322                Story::v_flex()
323                    .px_2()
324                    .flex_none()
325                    .w_1_2()
326                    .min_h_px()
327                    .when_some(self.usage, |this, usage| {
328                        this.child(Story::label("Example Usage"))
329                            .child(Story::code_block(usage))
330                    }),
331            )
332    }
333}
334
335#[derive(IntoElement)]
336pub struct StorySection {
337    description: Option<SharedString>,
338    children: SmallVec<[AnyElement; 2]>,
339}
340
341impl StorySection {
342    pub fn new() -> Self {
343        Self {
344            description: None,
345            children: SmallVec::new(),
346        }
347    }
348
349    pub fn description(mut self, description: impl Into<SharedString>) -> Self {
350        self.description = Some(description.into());
351        self
352    }
353}
354
355impl RenderOnce for StorySection {
356    fn render(self, _cx: &mut WindowContext) -> impl IntoElement {
357        let children: SmallVec<[AnyElement; 2]> = SmallVec::from_iter(Itertools::intersperse_with(
358            self.children.into_iter(),
359            || Story::divider().into_any_element(),
360        ));
361
362        Story::section()
363            // Section title
364            .py_2()
365            // Section description
366            .when_some(self.description.clone(), |section, description| {
367                section.child(Story::description(description))
368            })
369            .child(div().flex().flex_col().gap_2().children(children))
370            .child(Story::divider())
371    }
372}
373
374impl ParentElement for StorySection {
375    fn extend(&mut self, elements: impl Iterator<Item = AnyElement>) {
376        self.children.extend(elements)
377    }
378}