story: Add open file to Markdown and Editor example. (#1363)

Close #1352
This commit is contained in:
Jason Lee 2025-10-13 11:52:16 +08:00 committed by GitHub
parent 97df4efd46
commit 2574e7f812
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 200 additions and 110 deletions

View file

@ -24,7 +24,7 @@ use lsp_types::{
CodeAction, CodeActionKind, CompletionContext, CompletionItem, CompletionResponse, CodeAction, CodeActionKind, CompletionContext, CompletionItem, CompletionResponse,
CompletionTextEdit, InsertReplaceEdit, TextEdit, WorkspaceEdit, CompletionTextEdit, InsertReplaceEdit, TextEdit, WorkspaceEdit,
}; };
use story::Assets; use story::{Assets, Open};
fn init() { fn init() {
LanguageRegistry::singleton().register( LanguageRegistry::singleton().register(
@ -865,6 +865,45 @@ impl Example {
lsp_store.update_diagnostics(diagnostics.clone()); lsp_store.update_diagnostics(diagnostics.clone());
}); });
} }
fn on_action_open(&mut self, _: &Open, window: &mut Window, cx: &mut Context<Self>) {
let path = cx.prompt_for_paths(PathPromptOptions {
files: true,
directories: true,
multiple: false,
prompt: Some("Select a source file".into()),
});
let view = cx.entity();
let editor = self.editor.clone();
cx.spawn_in(window, async move |_, window| {
let path = path.await.ok()?.ok()??.iter().next()?.clone();
let language = path
.extension()
.and_then(|ext| ext.to_str())
.unwrap_or_default();
let language = Language::from_str(&language);
let lang = Lang::BuiltIn(language.clone());
let content = std::fs::read_to_string(&path).ok()?;
window
.update(|window, cx| {
_ = editor.update(cx, |this, cx| {
this.set_highlighter(language.name(), cx);
this.set_value(content, window, cx);
});
view.update(cx, |this, cx| {
this.language = lang;
cx.notify();
})
})
.ok();
Some(())
})
.detach();
}
} }
impl Render for Example { impl Render for Example {
@ -883,78 +922,88 @@ impl Render for Example {
}); });
} }
v_flex().size_full().child( v_flex()
v_flex() .id("app")
.id("source") .size_full()
.w_full() .on_action(cx.listener(Self::on_action_open))
.flex_1() .child(
.child( v_flex()
TextInput::new(&self.editor) .id("source")
.bordered(false) .w_full()
.p_0() .flex_1()
.h_full() .child(
.font_family("Monaco") TextInput::new(&self.editor)
.text_size(px(12.)) .bordered(false)
.focus_bordered(false), .p_0()
) .h_full()
.child( .font_family("Monaco")
h_flex() .text_size(px(12.))
.justify_between() .focus_bordered(false),
.text_sm() )
.bg(cx.theme().background) .child(
.py_1p5() h_flex()
.px_4() .justify_between()
.border_t_1() .text_sm()
.border_color(cx.theme().border) .bg(cx.theme().background)
.text_color(cx.theme().muted_foreground) .py_1p5()
.child( .px_4()
h_flex() .border_t_1()
.gap_3() .border_color(cx.theme().border)
.child( .text_color(cx.theme().muted_foreground)
Dropdown::new(&self.language_state) .child(
.menu_width(px(160.)) h_flex()
.xsmall(), .gap_3()
) .child(
.child( Dropdown::new(&self.language_state)
Button::new("line-number") .menu_width(px(160.))
.ghost() .xsmall(),
.when(self.line_number, |this| this.icon(IconName::Check)) )
.label("Line Number") .child(
.xsmall() Button::new("line-number")
.on_click(cx.listener(|this, _, window, cx| { .ghost()
this.line_number = !this.line_number; .when(self.line_number, |this| {
this.editor.update(cx, |state, cx| { this.icon(IconName::Check)
state.set_line_number(this.line_number, window, cx); })
}); .label("Line Number")
cx.notify(); .xsmall()
})), .on_click(cx.listener(|this, _, window, cx| {
) this.line_number = !this.line_number;
.child({ this.editor.update(cx, |state, cx| {
Button::new("soft-wrap") state.set_line_number(
.ghost() this.line_number,
.xsmall() window,
.label("Soft Wrap") cx,
.selected(self.soft_wrap) );
.on_click(cx.listener(Self::toggle_soft_wrap)) });
}), cx.notify();
) })),
.child({ )
let position = self.editor.read(cx).cursor_position(); .child({
let cursor = self.editor.read(cx).cursor(); Button::new("soft-wrap")
.ghost()
.xsmall()
.label("Soft Wrap")
.selected(self.soft_wrap)
.on_click(cx.listener(Self::toggle_soft_wrap))
}),
)
.child({
let position = self.editor.read(cx).cursor_position();
let cursor = self.editor.read(cx).cursor();
Button::new("line-column") Button::new("line-column")
.ghost() .ghost()
.xsmall() .xsmall()
.label(format!( .label(format!(
"{}:{} ({} byte)", "{}:{} ({} byte)",
position.line + 1, position.line + 1,
position.character + 1, position.character + 1,
cursor cursor
)) ))
.on_click(cx.listener(Self::go_to_line)) .on_click(cx.listener(Self::go_to_line))
}), }),
), ),
) )
} }
} }

View file

@ -2,10 +2,10 @@ use gpui::*;
use gpui_component::{ use gpui_component::{
highlighter::Language, highlighter::Language,
input::{InputEvent, InputState, TabSize, TextInput}, input::{InputEvent, InputState, TabSize, TextInput},
resizable::{h_resizable, resizable_panel, ResizableState}, resizable::{ResizableState, h_resizable, resizable_panel},
text::TextView, text::TextView,
}; };
use story::Assets; use story::{Assets, Open};
pub struct Example { pub struct Example {
input_state: Entity<InputState>, input_state: Entity<InputState>,
@ -40,6 +40,33 @@ impl Example {
} }
} }
fn on_action_open(&mut self, _: &Open, window: &mut Window, cx: &mut Context<Self>) {
let path = cx.prompt_for_paths(PathPromptOptions {
files: true,
directories: true,
multiple: false,
prompt: Some("Select a Markdown file".into()),
});
let input_state = self.input_state.clone();
cx.spawn_in(window, async move |_, window| {
let path = path.await.ok()?.ok()??.iter().next()?.clone();
let content = std::fs::read_to_string(&path).ok()?;
window
.update(|window, cx| {
_ = input_state.update(cx, |this, cx| {
this.set_value(content, window, cx);
});
})
.ok();
Some(())
})
.detach();
}
fn view(window: &mut Window, cx: &mut App) -> Entity<Self> { fn view(window: &mut Window, cx: &mut App) -> Entity<Self> {
cx.new(|cx| Self::new(window, cx)) cx.new(|cx| Self::new(window, cx))
} }
@ -47,40 +74,46 @@ impl Example {
impl Render for Example { impl Render for Example {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
h_resizable("container", self.resizable_state.clone()) div()
.id("editor")
.size_full()
.on_action(cx.listener(Self::on_action_open))
.child( .child(
resizable_panel().child( h_resizable("container", self.resizable_state.clone())
div() .child(
.id("source") resizable_panel().child(
.size_full() div()
.font_family("Monaco") .id("source")
.text_size(px(12.)) .size_full()
.child( .font_family("Monaco")
TextInput::new(&self.input_state) .text_size(px(12.))
.h_full() .child(
.p_0() TextInput::new(&self.input_state)
.border_0() .h_full()
.focus_bordered(false), .p_0()
.border_0()
.focus_bordered(false),
),
), ),
), )
) .child(
.child( resizable_panel().child(
resizable_panel().child( div()
div() .id("preview")
.id("preview") .size_full()
.size_full() .p_5()
.p_5() .overflow_y_scroll()
.overflow_y_scroll() .child(
.child( TextView::markdown(
TextView::markdown( "preview",
"preview", self.input_state.read(cx).value().clone(),
self.input_state.read(cx).value().clone(), window,
window, cx,
cx, )
) .selectable(),
.selectable(), ),
), ),
), ),
) )
} }
} }

View file

@ -1,13 +1,11 @@
use gpui::{App, Menu, MenuItem, SharedString, actions}; use gpui::{App, Menu, MenuItem, SharedString};
use gpui_component::{ThemeMode, ThemeRegistry}; use gpui_component::{ThemeMode, ThemeRegistry};
use crate::{ use crate::{
CloseWindow, Open, Quit, SelectLocale, ToggleSearch, About, CloseWindow, Open, Quit, SelectLocale, ToggleSearch,
themes::{SwitchTheme, SwitchThemeMode}, themes::{SwitchTheme, SwitchThemeMode},
}; };
actions!(story, [About]);
pub fn init(title: impl Into<SharedString>, cx: &mut App) { pub fn init(title: impl Into<SharedString>, cx: &mut App) {
cx.set_menus(vec![ cx.set_menus(vec![
Menu { Menu {
@ -15,6 +13,8 @@ pub fn init(title: impl Into<SharedString>, cx: &mut App) {
items: vec![ items: vec![
MenuItem::action("About", About), MenuItem::action("About", About),
MenuItem::Separator, MenuItem::Separator,
MenuItem::action("Open...", Open),
MenuItem::Separator,
MenuItem::Submenu(Menu { MenuItem::Submenu(Menu {
name: "Appearance".into(), name: "Appearance".into(),
items: vec![ items: vec![

View file

@ -140,8 +140,9 @@ pub struct SelectRadius(usize);
actions!( actions!(
story, story,
[ [
Quit, About,
Open, Open,
Quit,
CloseWindow, CloseWindow,
ToggleSearch, ToggleSearch,
TestAction, TestAction,
@ -307,7 +308,14 @@ pub fn init(cx: &mut App) {
cx.bind_keys([ cx.bind_keys([
KeyBinding::new("/", ToggleSearch, None), KeyBinding::new("/", ToggleSearch, None),
#[cfg(target_os = "macos")]
KeyBinding::new("cmd-o", Open, None),
#[cfg(not(target_os = "macos"))]
KeyBinding::new("ctrl-o", Open, None),
#[cfg(target_os = "macos")]
KeyBinding::new("cmd-q", Quit, None), KeyBinding::new("cmd-q", Quit, None),
#[cfg(not(target_os = "macos"))]
KeyBinding::new("alt-f4", Quit, None),
]); ]);
cx.on_action(|_: &Quit, cx: &mut App| { cx.on_action(|_: &Quit, cx: &mut App| {