1use dioxus::prelude::*;
19use logicaffeine_language::{
20 compile_with_options, socratic_explanation, CompileOptions, Interner, OutputFormat,
21};
22
23#[derive(Clone, PartialEq)]
25pub struct ChatMessage {
26 pub role: Role,
28 pub content: String,
30}
31
32#[derive(Clone, PartialEq)]
34pub enum Role {
35 User,
37 System,
39 Error,
41}
42
43#[derive(Clone, Copy)]
47pub struct AppState {
48 history: Signal<Vec<ChatMessage>>,
49}
50
51impl AppState {
52 pub fn new() -> Self {
53 Self {
54 history: Signal::new(vec![ChatMessage {
55 role: Role::System,
56 content: "The Council is assembled. State your premise.".to_string(),
57 }]),
58 }
59 }
60
61 pub fn add_user_message(&mut self, text: String) {
62 self.history.write().push(ChatMessage {
63 role: Role::User,
64 content: text.clone(),
65 });
66 self.process_logic(text);
67 }
68
69 fn process_logic(&mut self, input: String) {
70 let options = CompileOptions {
71 format: OutputFormat::Unicode,
72 pragmatic: false,
73 };
74
75 let response = match compile_with_options(&input, options) {
76 Ok(logic) => ChatMessage {
77 role: Role::System,
78 content: logic,
79 },
80 Err(e) => {
81 let interner = Interner::new();
82 let advice = socratic_explanation(&e, &interner);
83 ChatMessage {
84 role: Role::Error,
85 content: advice,
86 }
87 }
88 };
89 self.history.write().push(response);
90 }
91
92 pub fn get_history(&self) -> Vec<ChatMessage> {
93 self.history.read().clone()
94 }
95}
96
97const REGISTRY_API_URL: &str = "https://registry.logicaffeine.com";
103
104#[derive(Clone, PartialEq, Debug, serde::Serialize, serde::Deserialize)]
106pub struct GitHubUser {
107 pub id: String,
109 pub login: String,
111 pub name: Option<String>,
113 pub avatar_url: Option<String>,
115}
116
117#[derive(Clone, PartialEq)]
121pub struct RegistryAuthState {
122 pub user: Signal<Option<GitHubUser>>,
124 pub token: Signal<Option<String>>,
126 pub is_loading: Signal<bool>,
128}
129
130impl RegistryAuthState {
131 pub fn new() -> Self {
132 let (token, user) = load_registry_auth_from_storage();
133 Self {
134 user: Signal::new(user),
135 token: Signal::new(token),
136 is_loading: Signal::new(false),
137 }
138 }
139
140 pub fn is_authenticated(&self) -> bool {
141 self.token.read().is_some()
142 }
143
144 pub fn login(&mut self, token: String, user: GitHubUser) {
145 self.token.set(Some(token.clone()));
146 self.user.set(Some(user.clone()));
147 save_registry_auth_to_storage(&token, &user);
148 }
149
150 pub fn logout(&mut self) {
151 self.token.set(None);
152 self.user.set(None);
153 clear_registry_auth_from_storage();
154 }
155
156 pub fn get_auth_url() -> String {
157 format!("{}/auth/github", REGISTRY_API_URL)
158 }
159}
160
161fn load_registry_auth_from_storage() -> (Option<String>, Option<GitHubUser>) {
162 #[cfg(target_arch = "wasm32")]
163 {
164 if let Some(window) = web_sys::window() {
165 if let Ok(Some(storage)) = window.local_storage() {
166 let token = storage.get_item("logos_registry_token").ok().flatten();
167 let user_json = storage.get_item("logos_registry_user").ok().flatten();
168 let user = user_json.and_then(|j| serde_json::from_str(&j).ok());
169 return (token, user);
170 }
171 }
172 }
173 (None, None)
174}
175
176fn save_registry_auth_to_storage(token: &str, user: &GitHubUser) {
177 #[cfg(target_arch = "wasm32")]
178 {
179 if let Some(window) = web_sys::window() {
180 if let Ok(Some(storage)) = window.local_storage() {
181 let _ = storage.set_item("logos_registry_token", token);
182 if let Ok(json) = serde_json::to_string(user) {
183 let _ = storage.set_item("logos_registry_user", &json);
184 }
185 }
186 }
187 }
188}
189
190fn clear_registry_auth_from_storage() {
191 #[cfg(target_arch = "wasm32")]
192 {
193 if let Some(window) = web_sys::window() {
194 if let Ok(Some(storage)) = window.local_storage() {
195 let _ = storage.remove_item("logos_registry_token");
196 let _ = storage.remove_item("logos_registry_user");
197 }
198 }
199 }
200}
201
202#[derive(Clone, PartialEq, Debug, serde::Serialize, serde::Deserialize)]
208pub struct RegistryPackage {
209 pub name: String,
211 pub description: Option<String>,
213 pub latest_version: Option<String>,
215 pub owner: String,
217 pub owner_avatar: Option<String>,
219 pub verified: bool,
221 pub downloads: u64,
223 pub keywords: Vec<String>,
225}
226
227#[derive(Clone, PartialEq, Debug, serde::Serialize, serde::Deserialize)]
229pub struct PackageVersion {
230 pub version: String,
232 pub published_at: String,
234 pub size: u64,
236 pub yanked: bool,
238}
239
240#[derive(Clone, PartialEq, Debug, serde::Serialize, serde::Deserialize)]
242pub struct PackageDetails {
243 pub name: String,
245 pub description: Option<String>,
247 pub owner: String,
249 pub owner_avatar: Option<String>,
251 pub repository: Option<String>,
253 pub homepage: Option<String>,
255 pub license: Option<String>,
257 pub keywords: Vec<String>,
259 pub verified: bool,
261 pub downloads: u64,
263 pub readme: Option<String>,
265 pub versions: Vec<PackageVersion>,
267}
268
269#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
275pub enum StudioMode {
276 #[default]
278 Logic,
279 Code,
281 Math,
283 Hardware,
286 Web,
289}
290
291impl StudioMode {
292 pub const ALL: [StudioMode; 5] = [
294 StudioMode::Logic,
295 StudioMode::Code,
296 StudioMode::Math,
297 StudioMode::Hardware,
298 StudioMode::Web,
299 ];
300
301 pub fn for_path(path: &str) -> Option<Self> {
308 let (folders, file) = path.rsplit_once('/').unwrap_or(("", path));
309 let (stem, ext) = file.rsplit_once('.')?;
310 if stem.is_empty() {
311 return None;
312 }
313 let ext = ext.to_ascii_lowercase();
314 let in_folder = |name: &str| folders.split('/').any(|f| f == name);
315 match ext.as_str() {
316 "logos" if in_folder("math") => Some(StudioMode::Math),
317 "logos" if in_folder("web") => Some(StudioMode::Web),
318 "vernac" => Some(StudioMode::Math),
319 "v" => Some(StudioMode::Hardware),
320 other => Self::from_extension(other),
321 }
322 }
323
324 pub fn extension(&self) -> &'static str {
326 match self {
327 StudioMode::Logic => "logic",
328 StudioMode::Code => "logos",
329 StudioMode::Math => "math",
330 StudioMode::Hardware => "hw",
331 StudioMode::Web => "web",
332 }
333 }
334
335 pub fn display_name(&self) -> &'static str {
337 match self {
338 StudioMode::Logic => "Logic",
339 StudioMode::Code => "Code",
340 StudioMode::Math => "Math",
341 StudioMode::Hardware => "Hardware",
342 StudioMode::Web => "Web",
343 }
344 }
345
346 pub fn for_logos_source(source: &str) -> Self {
350 use logicaffeine_language::{BlockType, TokenType};
351 let mut interner = Interner::new();
352 let declares_page = logicaffeine_language::Lexer::new(source, &mut interner)
353 .tokenize()
354 .iter()
355 .any(|t| {
356 matches!(
357 t.kind,
358 TokenType::BlockHeader {
359 block_type: BlockType::Page { .. }
360 }
361 )
362 });
363 if declares_page {
364 StudioMode::Web
365 } else {
366 StudioMode::Code
367 }
368 }
369
370 pub fn for_file(path: &str, text: &str) -> Option<Self> {
375 match Self::for_path(path)? {
376 StudioMode::Code => Some(Self::for_logos_source(text)),
377 mode => Some(mode),
378 }
379 }
380
381 pub fn from_extension(ext: &str) -> Option<Self> {
383 match ext.to_lowercase().as_str() {
384 "logic" => Some(StudioMode::Logic),
385 "logos" => Some(StudioMode::Code),
386 "math" => Some(StudioMode::Math),
387 "hw" => Some(StudioMode::Hardware),
388 "web" => Some(StudioMode::Web),
389 _ => None,
390 }
391 }
392}
393
394#[derive(Clone, PartialEq, Debug)]
396pub struct FileNode {
397 pub name: String,
399 pub path: String,
401 pub is_directory: bool,
403 pub children: Vec<FileNode>,
405 pub expanded: bool,
407}
408
409impl FileNode {
410 pub fn file(name: String, path: String) -> Self {
412 Self {
413 name,
414 path,
415 is_directory: false,
416 children: Vec::new(),
417 expanded: false,
418 }
419 }
420
421 pub fn directory(name: String, path: String) -> Self {
423 Self {
424 name,
425 path,
426 is_directory: true,
427 children: Vec::new(),
428 expanded: true,
429 }
430 }
431
432 pub fn root() -> Self {
434 Self {
435 name: "workspace".to_string(),
436 path: "/".to_string(),
437 is_directory: true,
438 children: Vec::new(),
439 expanded: true,
440 }
441 }
442
443 pub fn from_paths<'a>(paths: impl IntoIterator<Item = &'a str>) -> Self {
447 let mut root = Self::root();
448 for path in paths {
449 let mut node = &mut root;
450 let mut at = String::new();
451 let mut names = path.trim_start_matches('/').split('/').peekable();
452 while let Some(name) = names.next() {
453 at = format!("{at}/{name}");
454 let is_directory = names.peek().is_some();
455 let i = match node
456 .children
457 .iter()
458 .position(|c| c.name == name && c.is_directory == is_directory)
459 {
460 Some(i) => i,
461 None => {
462 let child = if is_directory {
463 Self::directory(name.to_string(), at.clone())
464 } else {
465 Self::file(name.to_string(), at.clone())
466 };
467 node.children.push(child);
468 node.children.len() - 1
469 }
470 };
471 node = &mut node.children[i];
472 }
473 }
474 fn sort_all(node: &mut FileNode) {
475 node.sort_children();
476 node.children.iter_mut().for_each(sort_all);
477 }
478 sort_all(&mut root);
479 root
480 }
481
482 pub fn sort_children(&mut self) {
487 fn category_rank(name: &str) -> usize {
488 const LEARNING_ORDER: [&str; 15] = [
489 "basics",
490 "strings",
491 "collections",
492 "functions",
493 "types",
494 "algorithms",
495 "memory",
496 "time-and-money",
497 "concurrency",
498 "distributed",
499 "networking",
500 "security",
501 "crypto",
502 "verification",
503 "projects",
504 ];
505 LEARNING_ORDER
506 .iter()
507 .position(|c| *c == name)
508 .unwrap_or(LEARNING_ORDER.len())
509 }
510 self.children
511 .sort_by(|a, b| match (a.is_directory, b.is_directory) {
512 (true, false) => std::cmp::Ordering::Less,
513 (false, true) => std::cmp::Ordering::Greater,
514 _ => category_rank(&a.name)
515 .cmp(&category_rank(&b.name))
516 .then_with(|| a.name.to_lowercase().cmp(&b.name.to_lowercase())),
517 });
518 }
519
520 pub fn with_expansion_of(mut self, shown: &FileNode) -> Self {
523 fn collect(node: &FileNode, open: &mut std::collections::HashMap<String, bool>) {
524 if node.is_directory {
525 open.insert(node.path.clone(), node.expanded);
526 node.children.iter().for_each(|child| collect(child, open));
527 }
528 }
529 fn apply(node: &mut FileNode, open: &std::collections::HashMap<String, bool>) {
530 if node.is_directory {
531 if let Some(&expanded) = open.get(&node.path) {
532 node.expanded = expanded;
533 }
534 node.children
535 .iter_mut()
536 .for_each(|child| apply(child, open));
537 }
538 }
539 let mut open = std::collections::HashMap::new();
540 collect(shown, &mut open);
541 apply(&mut self, &open);
542 self
543 }
544
545 pub fn first_file_under(&self, dir: &str) -> Option<&str> {
547 let inside = |path: &str| {
548 path.strip_prefix(dir)
549 .is_some_and(|rest| rest.starts_with('/'))
550 };
551 if !self.is_directory {
552 return inside(&self.path).then_some(self.path.as_str());
553 }
554 self.children
555 .iter()
556 .find_map(|child| child.first_file_under(dir))
557 }
558
559 pub fn toggle_expanded(&mut self) {
561 if self.is_directory {
562 self.expanded = !self.expanded;
563 }
564 }
565
566 pub fn find_mut(&mut self, path: &str) -> Option<&mut FileNode> {
568 if self.path == path {
569 return Some(self);
570 }
571 for child in &mut self.children {
572 if let Some(found) = child.find_mut(path) {
573 return Some(found);
574 }
575 }
576 None
577 }
578}
579
580#[derive(Clone, PartialEq, Debug)]
582pub struct ReplLine {
583 pub input: String,
585 pub output: Result<String, String>,
587 pub success: bool,
589}
590
591impl ReplLine {
592 pub fn success(input: String, output: String) -> Self {
593 Self {
594 input,
595 output: Ok(output),
596 success: true,
597 }
598 }
599
600 pub fn error(input: String, error: String) -> Self {
601 Self {
602 input,
603 output: Err(error),
604 success: false,
605 }
606 }
607}
608
609#[derive(Clone, PartialEq, Debug, serde::Serialize, serde::Deserialize)]
611pub struct MathFormula {
612 pub latex: String,
614 pub label: Option<String>,
616}
617
618#[derive(Clone, PartialEq, Debug, serde::Serialize, serde::Deserialize)]
620pub struct MathDocument {
621 pub name: String,
623 pub formulas: Vec<MathFormula>,
625 #[serde(default)]
627 pub active_index: usize,
628}
629
630impl Default for MathDocument {
631 fn default() -> Self {
632 Self {
633 name: "Untitled".to_string(),
634 formulas: vec![MathFormula {
635 latex: String::new(),
636 label: None,
637 }],
638 active_index: 0,
639 }
640 }
641}
642
643#[cfg(test)]
644#[path = "../../../../crates/logicaffeine_tests/unit/logicaffeine_web/ui/state/first_file_tests.rs"]
645mod first_file_tests;
646
647#[cfg(test)]
648#[path = "../../../../crates/logicaffeine_tests/unit/logicaffeine_web/ui/state/tree_order_tests.rs"]
649mod tree_order_tests;
650
651#[cfg(test)]
652#[path = "../../../../crates/logicaffeine_tests/unit/logicaffeine_web/ui/state/file_mode_tests.rs"]
653mod file_mode_tests;
654
655#[cfg(test)]
656#[path = "../../../../crates/logicaffeine_tests/unit/logicaffeine_web/ui/state/tests.rs"]
657mod tests;