1use ferrokit_core::kept::{UiCell, UiLocal};
5use std::path::PathBuf;
6use std::rc::{Rc, Weak};
7
8use ferrokit_core::table::{ColumnState, Sort, TableEvent, TableModel};
9use ferrokit_core::text::{TextEvent, TextModel, TextStyle};
10use objc2::rc::Retained;
11
12use crate::signal::{Effect, Signal, batch, untrack};
13use crate::view::{Cx, Node, Size, View};
14
15type Drain = Rc<dyn Fn()>;
16
17thread_local! {
18 static DRAINS: UiCell<Vec<Weak<dyn Fn()>>> = const { UiCell::new(Vec::new()) };
20}
21
22pub(crate) fn flush() {
29 if !DRAINS.with_borrow(Vec::is_empty) {
30 drain_all();
31 }
32}
33
34pub(crate) fn drain_all() {
35 ferrokit_core::begin_frame();
36 let live: Vec<Drain> = DRAINS.with_borrow_mut(|d| {
37 d.retain(|w| w.strong_count() > 0);
38 d.iter().filter_map(Weak::upgrade).collect()
39 });
40 batch(|| live.iter().for_each(|f| f()));
41}
42
43fn register(drain: &Drain) {
44 DRAINS.with_borrow_mut(|d| d.push(Rc::downgrade(drain)));
45}
46
47type Callback<A> = Option<Box<dyn Fn(A)>>;
48type RowAction = (String, Box<dyn Fn(usize)>);
50
51pub struct Table<T: 'static> {
54 model: Rc<TableModel<T>>,
55 on_select: Callback<Vec<usize>>,
56 on_activate: Callback<usize>,
57 on_sort: Callback<Sort>,
58 on_toggle: Callback<(usize, String, bool)>,
59 on_edit: Callback<(usize, String, String)>,
60 on_columns: Callback<Vec<ColumnState>>,
61 on_move: Callback<(Vec<usize>, Option<usize>)>,
62 on_files: Callback<(Vec<PathBuf>, Option<usize>)>,
63 file_types: Vec<String>,
64 on_paste: Callback<String>,
65 row_drag: bool,
66 row_menu: Vec<RowAction>,
67}
68
69impl<T: 'static> Table<T> {
70 pub fn row_menu(mut self, title: &str, action: impl Fn(usize) + 'static) -> Self {
73 self.row_menu.push((title.into(), Box::new(action)));
74 self
75 }
76
77 pub fn on_select(mut self, f: impl Fn(Vec<usize>) + 'static) -> Self {
79 self.on_select = Some(Box::new(f));
80 self
81 }
82
83 pub fn on_activate(mut self, f: impl Fn(usize) + 'static) -> Self {
85 self.on_activate = Some(Box::new(f));
86 self
87 }
88
89 pub fn on_sort(mut self, f: impl Fn(Sort) + 'static) -> Self {
91 self.on_sort = Some(Box::new(f));
92 self
93 }
94
95 pub fn on_toggle(mut self, f: impl Fn(usize, String, bool) + 'static) -> Self {
97 self.on_toggle = Some(Box::new(move |(r, c, v)| f(r, c, v)));
98 self
99 }
100
101 pub fn on_edit(mut self, f: impl Fn(usize, String, String) + 'static) -> Self {
104 self.on_edit = Some(Box::new(move |(r, c, v)| f(r, c, v)));
105 self
106 }
107
108 pub fn row_drag(mut self) -> Self {
111 self.row_drag = true;
112 self
113 }
114
115 pub fn reorderable(mut self, f: impl Fn(Vec<usize>, Option<usize>) + 'static) -> Self {
119 self.on_move = Some(Box::new(move |(rows, before)| f(rows, before)));
120 self
121 }
122
123 pub fn on_files_dropped(mut self, extensions: &[&str], f: impl Fn(Vec<PathBuf>, Option<usize>) + 'static) -> Self {
126 self.file_types = extensions.iter().map(|e| e.to_string()).collect();
127 self.on_files = Some(Box::new(move |(paths, before)| f(paths, before)));
128 self
129 }
130
131 pub fn on_paste(mut self, f: impl Fn(String) + 'static) -> Self {
134 self.on_paste = Some(Box::new(f));
135 self
136 }
137
138 pub fn on_columns_changed(mut self, f: impl Fn(Vec<ColumnState>) + 'static) -> Self {
140 self.on_columns = Some(Box::new(f));
141 self
142 }
143}
144
145impl<T: 'static> View for Table<T> {
146 fn build(mut self, cx: &mut Cx) -> Node {
147 let scroll = self.model.scroll_view();
148 let (mut node, _) = Node::leaf(cx, Retained::into_super(scroll), (true, true), Size { w: 200.0, h: 120.0 });
149 if let crate::view::Kind::Leaf(l) = &node.kind {
150 l.content.set(Some(Size { w: 200.0, h: 120.0 }));
152 }
153 if !self.row_menu.is_empty() {
154 let tv = self.model.table_view();
155 let items = std::mem::take(&mut self.row_menu)
156 .into_iter()
157 .map(|(title, action)| {
158 let (tv, model) = (tv.clone(), self.model.clone());
159 crate::chrome::menu_item(&title, move || {
160 let clicked = tv.clickedRow();
161 let view_row = if clicked >= 0 { clicked } else { tv.selectedRow() };
162 if let Some(row) = usize::try_from(view_row).ok().and_then(|r| model.row_at(r)) {
163 action(row);
164 }
165 })
166 })
167 .collect();
168 let (menu, targets) = crate::chrome::build_menu(cx.mtm, items);
169 unsafe { tv.setMenu(Some(&menu)) };
171 targets.into_iter().for_each(|t| node.keep(t));
172 }
173 if self.row_drag {
174 self.model.set_row_drag(true);
175 }
176 if self.on_move.is_some() {
177 self.model.set_reorderable(true);
178 }
179 if self.on_files.is_some() {
180 let types: Vec<&str> = self.file_types.iter().map(String::as_str).collect();
181 self.model.set_file_drop(Some(&types));
182 }
183 if self.on_paste.is_some() {
184 self.model.set_pastes(true);
185 }
186 let model = self.model.clone();
187 let Table { on_select, on_activate, on_sort, on_toggle, on_edit, on_columns, on_move, on_files, on_paste, .. } = self;
188 let drain: Drain = Rc::new(move || {
189 for event in model.drain_events() {
190 match event {
191 TableEvent::Selection(rows) => on_select.iter().for_each(|f| f(rows.clone())),
192 TableEvent::Activate(row) => on_activate.iter().for_each(|f| f(row)),
193 TableEvent::Sort(sort) => on_sort.iter().for_each(|f| f(sort.clone())),
194 TableEvent::Toggle { row, column, value } => on_toggle.iter().for_each(|f| f((row, column.clone(), value))),
195 TableEvent::Edit { row, column, value } => on_edit.iter().for_each(|f| f((row, column.clone(), value.clone()))),
196 TableEvent::ColumnsChanged => on_columns.iter().for_each(|f| f(model.column_state())),
197 TableEvent::RowsMoved { rows, before } => on_move.iter().for_each(|f| f((rows.clone(), before))),
198 TableEvent::FilesDropped { paths, before } => on_files.iter().for_each(|f| f((paths.clone(), before))),
199 TableEvent::Paste(text) => on_paste.iter().for_each(|f| f(text.clone())),
200 _ => {}
201 }
202 }
203 });
204 register(&drain);
205 node.hold(drain);
206 node
207 }
208}
209
210pub fn table<T: 'static>(model: &Rc<TableModel<T>>) -> Table<T> {
212 Table {
213 model: model.clone(),
214 on_select: None,
215 on_activate: None,
216 on_sort: None,
217 on_toggle: None,
218 on_edit: None,
219 on_columns: None,
220 on_move: None,
221 on_files: None,
222 file_types: Vec::new(),
223 on_paste: None,
224 row_drag: false,
225 row_menu: Vec::new(),
226 }
227}
228
229pub struct TextEditor {
233 model: TextModel,
234 bound: Option<Signal<String>>,
235 on_change: Callback<String>,
236 on_selection: Callback<std::ops::Range<usize>>,
237 on_composition: Callback<Option<String>>,
238 shared_undo: bool,
239 highlight: Option<Rc<Highlight>>,
240 code: bool,
241 rich: Option<Rich>,
242}
243
244#[derive(Default)]
246struct Rich {
247 ruler: bool,
248 format_bar: bool,
249 rtf: Option<Signal<Vec<u8>>>,
250}
251
252type Highlight = dyn Fn(&str) -> Vec<(std::ops::Range<usize>, TextStyle)>;
253
254impl TextEditor {
255 pub fn shared_undo(mut self) -> Self {
260 self.shared_undo = true;
261 self
262 }
263
264 pub fn bind(mut self, text: &Signal<String>) -> Self {
268 self.bound = Some(*text);
269 self
270 }
271
272 pub fn on_change(mut self, f: impl Fn(String) + 'static) -> Self {
274 self.on_change = Some(Box::new(f));
275 self
276 }
277
278 pub fn on_selection(mut self, f: impl Fn(std::ops::Range<usize>) + 'static) -> Self {
280 self.on_selection = Some(Box::new(f));
281 self
282 }
283
284 pub fn on_composition(mut self, f: impl Fn(Option<String>) + 'static) -> Self {
286 self.on_composition = Some(Box::new(f));
287 self
288 }
289
290 pub fn highlight(mut self, f: impl Fn(&str) -> Vec<(std::ops::Range<usize>, TextStyle)> + 'static) -> Self {
295 self.highlight = Some(Rc::new(f));
296 self
297 }
298
299 pub fn syntax(self, syntax: crate::Syntax) -> Self {
302 self.code().highlight(move |text| syntax.highlight(text))
303 }
304
305 pub fn rich(mut self) -> Self {
311 self.rich.get_or_insert_with(Rich::default);
312 self
313 }
314
315 pub fn ruler(mut self) -> Self {
317 self.rich.get_or_insert_with(Rich::default).ruler = true;
318 self
319 }
320
321 pub fn format_bar(mut self) -> Self {
324 self.rich.get_or_insert_with(Rich::default).format_bar = true;
325 self
326 }
327
328 pub fn bind_rtf(mut self, rtf: &Signal<Vec<u8>>) -> Self {
332 self.rich.get_or_insert_with(Rich::default).rtf = Some(*rtf);
333 self
334 }
335
336 pub fn code(mut self) -> Self {
340 self.code = true;
341 self
342 }
343}
344
345impl View for TextEditor {
346 fn build(self, cx: &mut Cx) -> Node {
347 let scroll = self.model.scroll_view();
348 let (mut node, _) = Node::leaf(cx, Retained::into_super(scroll), (true, true), Size { w: 200.0, h: 80.0 });
349 if let crate::view::Kind::Leaf(l) = &node.kind {
350 l.content.set(Some(Size { w: 200.0, h: 80.0 }));
351 }
352 if self.shared_undo {
353 self.model.share_undo(crate::undo::manager_for(&cx.container).as_deref());
354 }
355 if self.code {
356 self.model.set_code_input(true);
357 }
358 let rtf = self.rich.as_ref().and_then(|r| r.rtf);
359 if let Some(rich) = &self.rich {
360 self.model.set_rich(true);
361 self.model.set_ruler_visible(rich.ruler);
362 self.model.set_format_bar(rich.format_bar);
363 }
364 if let Some(rtf) = rtf {
365 let model = self.model.clone();
367 node.own(Effect::new(move || {
368 let want = rtf.get();
369 untrack(|| {
370 if model.rtf() != want && !model.set_rtf(&want) && want.is_empty() {
371 model.set_text("");
372 }
373 });
374 }));
375 }
376 if let Some(f) = self.highlight.clone() {
377 let g = f.clone();
378 self.model.set_highlighter(Some(move |text: &str| g(text)));
379 let model = self.model.clone();
381 node.own(Effect::new(move || {
382 let _ = f(&untrack(|| model.text()));
383 untrack(|| model.restyle());
384 }));
385 }
386 if let Some(bound) = &self.bound {
387 let (bound, model) = (*bound, self.model.clone());
389 node.own(Effect::new(move || {
390 let want = bound.get();
391 untrack(|| {
392 if model.text() != want {
393 model.set_text(&want);
394 }
395 });
396 }));
397 }
398 let model = self.model.clone();
399 let TextEditor { bound, on_change, on_selection, on_composition, .. } = self;
400 let drain: Drain = Rc::new(move || {
401 for event in model.drain_events() {
402 match event {
403 TextEvent::Changed => {
404 if let Some(r) = &rtf {
405 r.set_if_changed(model.rtf());
406 }
407 let text = model.text();
408 if let Some(b) = &bound {
409 b.set_if_changed(text.clone());
410 }
411 on_change.iter().for_each(|f| f(text.clone()));
412 }
413 TextEvent::Selection(r) => on_selection.iter().for_each(|f| f(r.clone())),
414 TextEvent::Composition(c) => on_composition.iter().for_each(|f| f(c.clone())),
415 }
416 }
417 });
418 register(&drain);
419 node.hold(drain);
420 node
421 }
422}
423
424pub fn text_editor(model: &TextModel) -> TextEditor {
426 TextEditor { model: model.clone(), bound: None, on_change: None, on_selection: None, on_composition: None, shared_undo: false, highlight: None, code: false, rich: None }
427}