Skip to main content

logicaffeine_web/ui/
state.rs

1//! Global application state types.
2//!
3//! Defines state structures used across the application via Dioxus context.
4//! Includes registry authentication, chat state, and
5//! Studio mode types.
6//!
7//! # Key Types
8//!
9//! | Type | Purpose |
10//! |------|---------|
11//! | [`RegistryAuthState`] | GitHub OAuth for package registry |
12//! | [`AppState`] | Chat history for the REPL interface |
13//! | [`StudioMode`] | Active mode in the Studio playground |
14//! | [`FileNode`] | Virtual file system tree for Studio |
15//! | [`MathDocument`] | Math mode formula collection |
16//!
17
18use dioxus::prelude::*;
19use logicaffeine_language::{
20    compile_with_options, socratic_explanation, CompileOptions, Interner, OutputFormat,
21};
22
23/// A message in the REPL chat history.
24#[derive(Clone, PartialEq)]
25pub struct ChatMessage {
26    /// The sender of the message.
27    pub role: Role,
28    /// The message text (input or compiled output).
29    pub content: String,
30}
31
32/// Message sender role in the chat interface.
33#[derive(Clone, PartialEq)]
34pub enum Role {
35    /// User-entered input.
36    User,
37    /// Successful compilation result.
38    System,
39    /// Compilation error with Socratic guidance.
40    Error,
41}
42
43/// REPL chat state for the Landing page.
44///
45/// Maintains a history of user inputs and system responses.
46#[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
97// ============================================================
98// Package Registry Authentication
99// ============================================================
100
101/// Base URL for the package registry API.
102const REGISTRY_API_URL: &str = "https://registry.logicaffeine.com";
103
104/// GitHub user profile data from OAuth.
105#[derive(Clone, PartialEq, Debug, serde::Serialize, serde::Deserialize)]
106pub struct GitHubUser {
107    /// GitHub user ID (numeric string).
108    pub id: String,
109    /// GitHub username.
110    pub login: String,
111    /// Display name (may be empty).
112    pub name: Option<String>,
113    /// Profile picture URL.
114    pub avatar_url: Option<String>,
115}
116
117/// Authentication state for the package registry.
118///
119/// Manages GitHub OAuth tokens for publishing and starring packages.
120#[derive(Clone, PartialEq)]
121pub struct RegistryAuthState {
122    /// Currently authenticated GitHub user.
123    pub user: Signal<Option<GitHubUser>>,
124    /// OAuth access token for API calls.
125    pub token: Signal<Option<String>>,
126    /// True while authentication is in progress.
127    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// ============================================================
203// Package Registry Types
204// ============================================================
205
206/// Summary information for a package listing.
207#[derive(Clone, PartialEq, Debug, serde::Serialize, serde::Deserialize)]
208pub struct RegistryPackage {
209    /// Package name (unique identifier).
210    pub name: String,
211    /// Short description for search results.
212    pub description: Option<String>,
213    /// Most recent version number.
214    pub latest_version: Option<String>,
215    /// GitHub username of the package owner.
216    pub owner: String,
217    /// Owner's GitHub avatar URL.
218    pub owner_avatar: Option<String>,
219    /// Whether the package is officially verified.
220    pub verified: bool,
221    /// Total download count.
222    pub downloads: u64,
223    /// Searchable tags.
224    pub keywords: Vec<String>,
225}
226
227/// Metadata for a specific package version.
228#[derive(Clone, PartialEq, Debug, serde::Serialize, serde::Deserialize)]
229pub struct PackageVersion {
230    /// Semantic version string (e.g., "1.0.0").
231    pub version: String,
232    /// ISO 8601 publication timestamp.
233    pub published_at: String,
234    /// Package size in bytes.
235    pub size: u64,
236    /// Whether this version has been yanked.
237    pub yanked: bool,
238}
239
240/// Full package detail for the package page.
241#[derive(Clone, PartialEq, Debug, serde::Serialize, serde::Deserialize)]
242pub struct PackageDetails {
243    /// Package name.
244    pub name: String,
245    /// Full description.
246    pub description: Option<String>,
247    /// Package owner's GitHub username.
248    pub owner: String,
249    /// Owner's avatar URL.
250    pub owner_avatar: Option<String>,
251    /// Repository URL.
252    pub repository: Option<String>,
253    /// Documentation or homepage URL.
254    pub homepage: Option<String>,
255    /// SPDX license identifier.
256    pub license: Option<String>,
257    /// Searchable keywords.
258    pub keywords: Vec<String>,
259    /// Official verification status.
260    pub verified: bool,
261    /// Total downloads across all versions.
262    pub downloads: u64,
263    /// README content (markdown).
264    pub readme: Option<String>,
265    /// All published versions.
266    pub versions: Vec<PackageVersion>,
267}
268
269// ============================================================
270// Studio Mode State
271// ============================================================
272
273/// The active mode in the Studio playground.
274#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
275pub enum StudioMode {
276    /// English to First-Order Logic translation (default)
277    #[default]
278    Logic,
279    /// Vernacular REPL for proof development and .logos files
280    Code,
281    /// Visual formula builder with LaTeX preview
282    Math,
283    /// English hardware specs to SystemVerilog Assertions with in-browser,
284    /// kernel-certified proving (no Z3 in the bundle).
285    Hardware,
286    /// A LOGOS page (`## Page`) compiled to wasm in-browser and rendered LIVE in a
287    /// sandboxed iframe — edit the page's source and see it run.
288    Web,
289}
290
291impl StudioMode {
292    /// Every mode, in display order.
293    pub const ALL: [StudioMode; 5] = [
294        StudioMode::Logic,
295        StudioMode::Code,
296        StudioMode::Math,
297        StudioMode::Hardware,
298        StudioMode::Web,
299    ];
300
301    /// The mode a Studio file opens in. The Studio has no mode switch — opening a file is
302    /// choosing its mode — so this is the one place a path becomes a mode.
303    ///
304    /// The extension names the mode, except for `.logos`: it is the source language of
305    /// Code, Math and Web alike, so a `math/` or `web/` folder decides which. `None` is a
306    /// file with no LOGOS extension; the Studio keeps its current mode for it.
307    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    /// Returns the file extension for this mode.
325    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    /// Returns the display name for this mode.
336    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    /// The mode a `.logos` source opens in: a file that declares a `## Page` is a web page and
347    /// opens in the Web tab, where it runs live; any other program opens in Code. The header is read
348    /// by the real lexer, so a page is recognised exactly when the compiler would mount one.
349    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    /// The mode a file opens in once its text is known — the one rule the file browser and the
371    /// Studio's opening share. The path decides ([`Self::for_path`]); a `.logos` file the path
372    /// leaves to Code opens in Web when it declares a page ([`Self::for_logos_source`]). `None` is
373    /// a file with no LOGOS extension.
374    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    /// Infer mode from file extension.
382    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/// A node in the file tree representing a file or directory.
395#[derive(Clone, PartialEq, Debug)]
396pub struct FileNode {
397    /// Name of the file or directory (not full path).
398    pub name: String,
399    /// Full path from VFS root.
400    pub path: String,
401    /// True if this is a directory.
402    pub is_directory: bool,
403    /// Child nodes (empty for files).
404    pub children: Vec<FileNode>,
405    /// Whether this directory is expanded in the UI.
406    pub expanded: bool,
407}
408
409impl FileNode {
410    /// Create a new file node.
411    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    /// Create a new directory node.
422    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    /// Create the root node for the file tree.
433    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    /// The tree of the files at `paths` (VFS paths), each under its folders and every level in the
444    /// file browser's order: the tree the Studio loads from a file system that holds exactly these
445    /// files.
446    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    /// Put this directory's entries in the order the file browser shows them: directories first;
483    /// the Studio's code categories in learning order (basics first, projects last), everything
484    /// else alphabetically. Unknown directory names rank after the curated set, so a future
485    /// category still appears without touching this list.
486    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    /// This tree with each folder open or closed as `shown` has it, wherever `shown` has the same
521    /// folder: a tree loaded again keeps the reader's choices, and a folder new to it starts open.
522    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    /// The first file under the directory at `dir`, in the order the tree shows it.
546    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    /// Toggle the expanded state of a directory.
560    pub fn toggle_expanded(&mut self) {
561        if self.is_directory {
562            self.expanded = !self.expanded;
563        }
564    }
565
566    /// Find a node by path (mutable).
567    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/// A line in the REPL output history.
581#[derive(Clone, PartialEq, Debug)]
582pub struct ReplLine {
583    /// The input command.
584    pub input: String,
585    /// The output (result or error).
586    pub output: Result<String, String>,
587    /// Whether this was executed successfully.
588    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/// A formula entry for Math mode.
610#[derive(Clone, PartialEq, Debug, serde::Serialize, serde::Deserialize)]
611pub struct MathFormula {
612    /// The LaTeX source.
613    pub latex: String,
614    /// Optional label/name for the formula.
615    pub label: Option<String>,
616}
617
618/// Math mode file format.
619#[derive(Clone, PartialEq, Debug, serde::Serialize, serde::Deserialize)]
620pub struct MathDocument {
621    /// Document name.
622    pub name: String,
623    /// List of formulas.
624    pub formulas: Vec<MathFormula>,
625    /// Index of the currently active formula.
626    #[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;