1use std::collections::BTreeMap;
5use std::path::Path;
6
7use serde_json::{Value, json};
8
9use crate::SheetError;
10use crate::book::{Book, Kind, file_format};
11use crate::refs::{MAX_COLS, MAX_ROWS, range_name};
12use crate::store::{Entry, Store, s, sheet_format, xlsx_name};
13use crate::tools::{MAX_WRITE_CELLS, errors};
14
15pub const DEFAULT_WIDTH: f64 = 90.0;
16const MAX_BLOCK_CELLS: i64 = 40_000;
17
18#[derive(Default)]
20pub struct ViewState {
21 sheet: Option<String>,
22 charts: bool,
24 win: BTreeMap<String, (i64, i64, i64, i64)>,
25 sel: BTreeMap<String, Value>,
26}
27
28fn int(v: Option<&Value>, default: i64, lo: i64, hi: i64) -> i64 {
30 let n = match v {
31 Some(Value::Bool(b)) => i64::from(*b),
32 Some(Value::Number(n)) => n.as_i64().or_else(|| n.as_f64().filter(|f| f.is_finite()).map(|f| f.trunc() as i64)).unwrap_or(default),
33 Some(Value::String(t)) => crate::refs::py_int(t).unwrap_or(default),
34 _ => default,
35 };
36 n.clamp(lo, hi.max(lo))
37}
38
39fn hex6(t: &str) -> bool {
40 let h = t.strip_prefix('#').unwrap_or(t);
41 h.len() == 6 && h.chars().all(|c| c.is_ascii_hexdigit())
42}
43
44pub enum Which {
46 Live(String),
47 Old(std::path::PathBuf, &'static str),
48}
49
50pub fn view_book(store: &mut Store, a: &Value) -> Result<(Which, bool, String), SheetError> {
52 let aid = s(a, "id").unwrap_or_default().to_owned();
53 let path = s(a, "path").unwrap_or_default().to_owned();
54 let name = s(a, "filename").filter(|f| !f.is_empty()).unwrap_or(&path).to_owned();
55 let fmt = sheet_format(s(a, "content_type"), &name).unwrap_or_else(|| file_format(&path));
56 let (version, latest) = (a.get("version").filter(|v| !v.is_null()), a.get("latest").filter(|v| !v.is_null()));
57 if let (Some(v), Some(l)) = (version, latest)
58 && v.as_f64() != l.as_f64()
59 {
60 store.version_book(Path::new(&path), fmt)?;
61 let note = format!("version {}, read-only (the latest is {})", crate::text::pystr(v), crate::text::pystr(l));
62 return Ok((Which::Old(path.into(), fmt), false, note));
63 }
64 store.artifact_entry(&aid, Path::new(&path), fmt, version.and_then(Value::as_i64))?;
65 Ok((Which::Live(aid), true, String::new()))
66}
67
68fn cell_json(book: &Book, sh: u32, r: i64, c: i64) -> Value {
69 let content = book.content(sh, r, c);
70 let st = book.style(sh, r, c);
71 let font = st.get("font").cloned().unwrap_or(Value::Null);
72 let mut extra = serde_json::Map::new();
73 if font.get("b").and_then(Value::as_bool).unwrap_or(false) {
74 extra.insert("b".into(), json!(true));
75 }
76 if font.get("i").and_then(Value::as_bool).unwrap_or(false) {
77 extra.insert("it".into(), json!(true));
78 }
79 if let Some(f) = st.get("fill").and_then(|f| f.get("color")).and_then(Value::as_str).filter(|f| hex6(f)) {
80 extra.insert("fill".into(), json!(format!("#{}", f.trim_start_matches('#').to_lowercase())));
81 }
82 if let Some(fc) = font.get("color").and_then(Value::as_str).filter(|f| hex6(f))
83 && fc.trim_start_matches('#').to_lowercase() != "000000"
84 {
85 extra.insert("color".into(), json!(format!("#{}", fc.trim_start_matches('#').to_lowercase())));
86 }
87 if let Some(al) = st.get("alignment").and_then(|a| a.get("horizontal")).and_then(Value::as_str).filter(|a| ["left", "center", "right"].contains(a)) {
88 extra.insert("align".into(), json!(al));
89 }
90 if content.is_empty() {
91 if !extra.is_empty() {
92 extra.insert("v".into(), json!(""));
93 return Value::Object(extra);
94 }
95 return Value::Null;
96 }
97 let k = book.kind(sh, r, c);
98 let text = book.text(sh, r, c);
99 if k == Kind::S && content == text && extra.is_empty() {
100 return Value::String(text);
101 }
102 let mut d = serde_json::Map::new();
103 d.insert("v".into(), json!(text));
104 if k != Kind::S {
105 d.insert(
106 "t".into(),
107 json!(match k {
108 Kind::N => "n",
109 Kind::B => "b",
110 Kind::E => "e",
111 Kind::S => "s",
112 }),
113 );
114 }
115 if content != text {
116 d.insert("i".into(), json!(content));
117 }
118 d.extend(extra);
119 Value::Object(d)
120}
121
122fn block(book: &Book, sh: u32, row: i64, col: i64, rows: i64, cols: i64) -> Value {
124 let cells: Vec<Value> = (row..row + rows).map(|r| Value::Array((col..col + cols).map(|c| cell_json(book, sh, r + 1, c + 1)).collect())).collect();
125 json!({"row": row, "col": col, "cells": cells})
126}
127
128fn round1(w: f64) -> f64 {
129 (w * 10.0).round() / 10.0
130}
131
132pub fn grid(book: &mut Book, sh: u32, state: &ViewState, editable: bool) -> Value {
133 let name = book.sheet_names().get(sh as usize).cloned().unwrap_or_default();
134 let used = book.used(sh);
135 let (ur2, uc2) = used.map_or((0, 0), |u| (u.1, u.3));
136 let total_rows = MAX_ROWS.min((ur2 + 50).max(100));
137 let total_cols = MAX_COLS.min((uc2 + 10).max(26));
138 let (row, col, rows, cols) = state.win.get(&name).copied().unwrap_or((0, 0, 100, 26));
139 let mut rows = rows.clamp(1, 500);
140 let cols = cols.clamp(1, 200);
141 while rows * cols > MAX_BLOCK_CELLS {
142 rows = (rows / 2).max(1);
143 }
144 let row = row.clamp(0, (total_rows - 1).max(0));
145 let col = col.clamp(0, (total_cols - 1).max(0));
146 let rows = rows.min(total_rows - row);
147 let cols = cols.min(total_cols - col);
148 let mut blocks = vec![block(book, sh, row, col, rows, cols)];
149 let (fr, fc) = book.frozen(sh);
150 let (top, left) = (fr.min(row), fc.min(col));
151 if top > 0 {
152 blocks.push(block(book, sh, 0, col, top, cols));
153 }
154 if left > 0 {
155 blocks.push(block(book, sh, row, 0, rows, left));
156 }
157 if top > 0 && left > 0 {
158 blocks.push(block(book, sh, 0, 0, top, left));
159 }
160 let mut widths = serde_json::Map::new();
161 for c in (0..left).chain(col..col + cols) {
162 let w = book.width(sh, c + 1);
163 if (w - DEFAULT_WIDTH).abs() > 0.01 {
164 widths.insert(c.to_string(), json!(round1(w)));
165 }
166 }
167 let mut node = json!({
168 "type": "grid", "key": "g", "name": "sheet", "rows": total_rows, "cols": total_cols,
169 "blocks": blocks, "frozen_rows": fr, "frozen_cols": fc, "widths": widths,
170 "default_width": DEFAULT_WIDTH, "editable": editable, "headers": true,
171 });
172 if let Some(sel) = state.sel.get(&name) {
173 node["selection"] = sel.clone();
174 }
175 node
176}
177
178fn current_sheet(book: &mut Book, state: &mut ViewState) -> u32 {
179 let names = book.sheet_names();
180 if let Some(i) = state.sheet.as_ref().and_then(|n| names.iter().position(|x| x == n)) {
181 return u32::try_from(i).unwrap_or(0);
182 }
183 state.sheet = names.first().cloned();
184 0
185}
186
187#[derive(Default)]
189pub struct Views {
190 states: BTreeMap<String, ViewState>,
191}
192
193fn book_of<'a>(store: &'a mut Store, which: &Which) -> Result<&'a mut Book, SheetError> {
194 match which {
195 Which::Live(aid) => store.entries.get_mut(aid).map(|e| &mut e.book).ok_or_else(|| SheetError::Msg(format!("Artifact {aid} isn't loaded."))),
196 Which::Old(p, fmt) => store.version_book(p, fmt),
197 }
198}
199
200impl Views {
201 pub fn draw(&mut self, store: &mut Store, a: Option<&Value>) -> Value {
203 let Some(a) = a.filter(|a| a.is_object()) else {
204 return json!({"type": "text", "text": "This spreadsheet isn't available.", "tone": "dim"});
205 };
206 let (which, editable, note) = match view_book(store, a) {
207 Ok(x) => x,
208 Err(e) => return json!({"type": "column", "children": [{"type": "text", "text": e.text(), "tone": "warning"}]}),
209 };
210 let book = match book_of(store, &which) {
211 Ok(b) => b,
212 Err(e) => return json!({"type": "column", "children": [{"type": "text", "text": e.text(), "tone": "warning"}]}),
213 };
214 let state = self.states.entry(s(a, "id").unwrap_or_default().to_owned()).or_default();
215 let sh = current_sheet(book, state);
216 let names = book.sheet_names();
217 let mut children = Vec::new();
218 if names.len() > 1 {
219 let tabs: Vec<Value> = names
220 .iter()
221 .enumerate()
222 .map(|(i, n)| json!({"type": "button", "label": n, "action": format!("tab:{n}"), "primary": i == sh as usize}))
223 .collect();
224 children.push(json!({"type": "row", "key": "tabs", "children": tabs}));
225 }
226 let mut status = vec![names.get(sh as usize).cloned().unwrap_or_default()];
227 match book.used(sh) {
228 Some(u) => status.push(format!("{} rows × {} columns", u.1, u.3)),
229 None => status.push("empty".into()),
230 }
231 let ne = errors(book).iter().filter(|e| e.0 == sh).count();
232 if ne > 0 {
233 status.push(format!("{ne} error{}", if ne != 1 { "s" } else { "" }));
234 }
235 if !note.is_empty() {
236 status.push(note);
237 }
238 let status = json!({"type": "text", "key": "status", "style": "small", "tone": "dim", "text": status.join(" · ")});
239 let charts = match (s(a, "workspace").filter(|w| !w.is_empty()), s(a, "id")) {
241 (Some(ws), Some(aid)) => crate::charts::linked(ws, s(a, "chat"), aid),
242 _ => Vec::new(),
243 };
244 let showing_charts = state.charts && !charts.is_empty();
245 let mut bar = vec![status];
246 if showing_charts {
247 bar.push(json!({"type": "button", "key": "show-grid", "label": "Grid", "action": "show_grid"}));
248 } else {
249 if editable && matches!(which, Which::Live(_)) {
250 bar.push(json!({"type": "button", "key": "chart-selection", "label": "Chart selection", "action": "chart_selection"}));
252 }
253 if !charts.is_empty() {
254 bar.push(json!({"type": "button", "key": "show-charts", "label": format!("Charts ({})", charts.len()), "action": "show_charts"}));
255 }
256 }
257 children.push(if bar.len() > 1 { json!({"type": "row", "key": "toolbar", "children": bar}) } else { bar.remove(0) });
258 if showing_charts {
259 children.push(json!({"type": "text", "key": "charts-note", "style": "small", "tone": "dim", "text": "Drawn from this sheet: they redraw whenever it changes."}));
260 for (id, spec) in charts {
261 children.push(json!({"type": "chart", "key": format!("chart-{id}"), "spec": spec}));
262 }
263 } else {
264 children.push(grid(book, sh, state, editable));
265 }
266 json!({"type": "column", "children": children})
267 }
268
269 pub fn event(&mut self, store: &mut Store, ev: &Value, a: &Value, out: &byob_plugins::native::Outbox) -> Result<(), SheetError> {
271 let state = self.states.entry(s(a, "id").unwrap_or_default().to_owned()).or_default();
272 let action = s(ev, "action").unwrap_or_default().to_owned();
273 if let Some(tab) = action.strip_prefix("tab:") {
274 state.sheet = Some(tab.to_owned());
275 return Ok(());
276 }
277 if action == "chart_selection" {
278 return chart_selection(store, &mut *state, a, ev, out);
279 }
280 if action == "show_charts" || action == "show_grid" {
281 state.charts = action == "show_charts";
282 return Ok(());
283 }
284 let g = ev.get("grid").filter(|g| g.is_object()).cloned().unwrap_or_else(|| json!({}));
285 let op = s(&g, "op").filter(|o| !o.is_empty()).map_or(action.clone(), str::to_owned);
286 let (which, editable, _) = match view_book(store, a) {
287 Ok(x) => x,
288 Err(e) => {
289 out.notice(&e.text(), "error");
290 return Ok(());
291 }
292 };
293 let book = book_of(store, &which)?;
294 let sh = current_sheet(book, state);
295 let name = book.sheet_names().get(sh as usize).cloned().unwrap_or_default();
296 let row = int(g.get("row"), 0, 0, MAX_ROWS - 1);
297 let col = int(g.get("col"), 0, 0, MAX_COLS - 1);
298 match op.as_str() {
299 "window" => {
300 state.win.insert(name, (row, col, int(g.get("rows"), 100, 1, 500), int(g.get("cols"), 26, 1, 200)));
301 return Ok(());
302 }
303 "select" => {
304 let sel =
305 json!({"row": row, "col": col, "to_row": int(g.get("to_row"), row, 0, MAX_ROWS - 1), "to_col": int(g.get("to_col"), col, 0, MAX_COLS - 1)});
306 state.sel.insert(name, sel);
307 return Ok(());
308 }
309 "edit" | "paste" | "clear" => {}
310 _ => return Ok(()),
311 }
312 let Which::Live(aid) = &which else {
313 out.notice("This version of the spreadsheet is read-only; open the latest one to edit it.", "info");
314 return Ok(());
315 };
316 if !editable {
317 out.notice("This version of the spreadsheet is read-only; open the latest one to edit it.", "info");
318 return Ok(());
319 }
320 let label = |book: &mut Book, r1: i64, c1: i64, r2: i64, c2: i64| {
321 let names = book.sheet_names();
322 let rf = range_name(r1, c1, r2, c2);
323 if names.len() > 1 { format!("{}!{rf}", crate::refs::quote_sheet(&names[sh as usize])) } else { rf }
324 };
325 let mut labels = Vec::new();
326 if op == "edit" {
327 let v = g.get("value").filter(|v| !v.is_null()).map(crate::text::pystr).unwrap_or_default();
328 book.put_text(sh, row + 1, col + 1, &v)?;
329 labels.push(label(book, row + 1, col + 1, row + 1, col + 1));
330 } else if op == "paste" {
331 let text = g.get("text").filter(|v| crate::store::truthy(Some(v))).map(crate::text::pystr).unwrap_or_default();
332 let text = text.replace("\r\n", "\n").replace('\r', "\n");
333 let mut lines: Vec<&str> = text.split('\n').collect();
334 if lines.last() == Some(&"") {
335 lines.pop();
336 }
337 let grid_rows: Vec<Vec<&str>> = lines.iter().map(|l| l.split('\t').collect()).collect();
338 let n: usize = grid_rows.iter().map(Vec::len).sum();
339 if n as i64 > MAX_WRITE_CELLS {
340 out.notice(&format!("That paste has {n} cells; at most {MAX_WRITE_CELLS} fit in one go."), "error");
341 return Ok(());
342 }
343 let mut width = 0;
344 for (i, cells) in grid_rows.iter().enumerate() {
345 width = width.max(cells.len());
346 for (j, v) in cells.iter().enumerate() {
347 let (r, c) = (row + i as i64 + 1, col + j as i64 + 1);
348 if r <= MAX_ROWS && c <= MAX_COLS {
349 book.put_text(sh, r, c, v)?;
350 }
351 }
352 }
353 if !grid_rows.is_empty() && width > 0 {
354 labels.push(label(book, row + 1, col + 1, row + grid_rows.len() as i64, col + width as i64));
355 }
356 } else {
357 let tr = int(g.get("to_row"), row, row, MAX_ROWS - 1);
358 let tc = int(g.get("to_col"), col, col, MAX_COLS - 1);
359 book.clear(sh, row + 1, col + 1, tr + 1, tc + 1)?;
360 labels.push(label(book, row + 1, col + 1, tr + 1, tc + 1));
361 }
362 book.evaluate();
363 let data = book.to_xlsx()?;
364 let aid = aid.clone();
365 let chat_of = s(a, "chat").filter(|c| !c.is_empty()).or_else(|| s(ev, "chat")).map(str::to_owned);
367 let redrawn = s(a, "workspace").map(|ws| crate::charts::refresh(ws, chat_of.as_deref(), &aid, book, &[])).unwrap_or_default();
368 let (redrawn, lost) = redrawn;
369 for line in lost {
370 out.notice(&line, "info");
371 }
372 let filename = s(a, "filename").unwrap_or_default().to_owned();
373 let fmt = sheet_format(s(a, "content_type"), if filename.is_empty() { s(a, "path").unwrap_or_default() } else { &filename });
374 let new_name = (fmt != Some("xlsx")).then(|| xlsx_name(&filename, s(a, "id").filter(|i| !i.is_empty()).unwrap_or("sheet")));
375 let path = store.save_tmp(&data, new_name.as_deref().unwrap_or(if filename.is_empty() { "sheet.xlsx" } else { &filename }))?;
376 if let Some(e) = store.entries.get_mut(&aid) {
377 for lb in labels {
378 e.user_edited(lb);
379 }
380 e.wrote(&data, a.get("version").and_then(Value::as_i64));
381 }
382 let chat = s(a, "chat").filter(|c| !c.is_empty()).or_else(|| s(ev, "chat"));
383 let mut m = json!({"type": "artifact", "chat": chat, "file": path, "note": "Edited in the grid", "draft": true, "id": s(a, "id")});
384 if let Some(n) = new_name {
385 m["filename"] = json!(n);
386 }
387 out.send(m);
388 for (r, file) in crate::charts::files(store, redrawn) {
389 out.send(json!({"type": "artifact", "chat": chat, "file": file, "note": "Drawn again from the sheet", "draft": true, "id": r.id}));
390 }
391 Ok(())
392 }
393}
394
395fn chart_selection(store: &mut Store, state: &mut ViewState, a: &Value, ev: &Value, out: &byob_plugins::native::Outbox) -> Result<(), SheetError> {
397 let (which, editable, _) = view_book(store, a)?;
398 let Which::Live(aid) = &which else {
399 out.notice("This version of the spreadsheet is read-only; open the latest one to chart it.", "info");
400 return Ok(());
401 };
402 let aid = aid.clone();
403 if !editable {
404 out.notice("This version of the spreadsheet is read-only; open the latest one to chart it.", "info");
405 return Ok(());
406 }
407 let book = book_of(store, &which)?;
408 let sh = current_sheet(book, state);
409 let name = book.sheet_names().get(sh as usize).cloned().unwrap_or_default();
410 let Some(sel) = state.sel.get(&name) else {
411 out.notice("Select the cells to chart first: the header row and the columns, the one along the bottom first.", "info");
412 return Ok(());
413 };
414 let at = |k: &str| sel.get(k).and_then(Value::as_i64).unwrap_or(0);
415 let (r1, r2) = (at("row").min(at("to_row")), at("row").max(at("to_row")));
416 let (c1, c2) = (at("col").min(at("to_col")), at("col").max(at("to_col")));
417 let (title, filename, spec) = match crate::charts::from_selection(book, &aid, sh, (r1, c1, r2, c2)) {
418 Ok(x) => x,
419 Err(e) => {
420 out.notice(&e.text(), "info");
421 return Ok(());
422 }
423 };
424 let file = store.save_tmp(spec.to_string().as_bytes(), &filename)?;
425 let chat = s(a, "chat").filter(|c| !c.is_empty()).or_else(|| s(ev, "chat"));
426 let sheet = s(a, "title").filter(|t| !t.is_empty()).unwrap_or(&aid).to_owned();
427 out.send(json!({"type": "artifact", "chat": chat, "file": file, "title": title, "filename": filename, "note": format!("From {sheet}")}));
428 Ok(())
429}
430
431#[allow(dead_code)]
432fn entry_of<'a>(store: &'a Store, aid: &str) -> Option<&'a Entry> {
433 store.entries.get(aid)
434}