Skip to main content

rustafari_core/
spec.rs

1//! The UI-agnostic contract every tool implements.
2//!
3//! A tool declares *what* knobs it has; it never says how they are drawn. The
4//! frontend renders `OptionSpec`s generically, so adding a tool requires no UI
5//! code at all.
6
7use std::collections::HashMap;
8use std::fmt;
9
10#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
11pub enum Category {
12    Formatters,
13    Encoders,
14    Generators,
15    Text,
16}
17
18impl Category {
19    pub const ALL: &'static [Category] = &[
20        Category::Formatters,
21        Category::Encoders,
22        Category::Generators,
23        Category::Text,
24    ];
25
26    pub fn label(self) -> &'static str {
27        match self {
28            Category::Formatters => "Formatters",
29            Category::Encoders => "Encoders & Decoders",
30            Category::Generators => "Generators",
31            Category::Text => "Text",
32        }
33    }
34}
35
36/// Identity and search metadata for a tool.
37#[derive(Clone, Copy, Debug)]
38pub struct ToolMeta {
39    /// Stable id, used for persistence. Never change it once released.
40    pub id: &'static str,
41    pub name: &'static str,
42    pub category: Category,
43    pub description: &'static str,
44    /// Extra search terms that don't appear in the name.
45    pub keywords: &'static [&'static str],
46}
47
48/// Whether the tool transforms text or produces it from nothing.
49#[derive(Clone, Copy, PartialEq, Eq, Debug)]
50pub enum InputMode {
51    /// Runs continuously as the user types.
52    Text { placeholder: &'static str },
53    /// Two documents, for tools that compare rather than transform. The
54    /// frontend shows a pane per side; the labels name them.
55    TwoText {
56        left_label: &'static str,
57        right_label: &'static str,
58        placeholder: &'static str,
59    },
60    /// No input pane; runs when the user asks for it.
61    None,
62}
63
64/// What the user typed.
65///
66/// `right` is empty for every mode except [`InputMode::TwoText`], so a tool
67/// that only declared one input can read `left` and ignore the rest.
68#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
69pub struct Input<'a> {
70    pub left: &'a str,
71    pub right: &'a str,
72}
73
74impl<'a> Input<'a> {
75    pub fn pair(left: &'a str, right: &'a str) -> Self {
76        Input { left, right }
77    }
78}
79
80impl<'a> From<&'a str> for Input<'a> {
81    fn from(left: &'a str) -> Self {
82        Input { left, right: "" }
83    }
84}
85
86#[derive(Clone, Copy, Debug)]
87pub enum OptionSpec {
88    Toggle {
89        id: &'static str,
90        label: &'static str,
91        default: bool,
92    },
93    /// A one-of-N picker. Choices are `(value, label)` pairs.
94    Choice {
95        id: &'static str,
96        label: &'static str,
97        choices: &'static [(&'static str, &'static str)],
98        default: &'static str,
99    },
100    Number {
101        id: &'static str,
102        label: &'static str,
103        min: i64,
104        max: i64,
105        default: i64,
106    },
107    /// A short free-text field, for values no picker can enumerate — a cron
108    /// field, a delimiter, a format string. Rendered inline with the other
109    /// options, so keep it genuinely short.
110    Text {
111        id: &'static str,
112        label: &'static str,
113        placeholder: &'static str,
114        default: &'static str,
115    },
116}
117
118impl OptionSpec {
119    pub fn id(&self) -> &'static str {
120        match self {
121            OptionSpec::Toggle { id, .. }
122            | OptionSpec::Choice { id, .. }
123            | OptionSpec::Number { id, .. }
124            | OptionSpec::Text { id, .. } => id,
125        }
126    }
127
128    pub fn label(&self) -> &'static str {
129        match self {
130            OptionSpec::Toggle { label, .. }
131            | OptionSpec::Choice { label, .. }
132            | OptionSpec::Number { label, .. }
133            | OptionSpec::Text { label, .. } => label,
134        }
135    }
136
137    fn default_value(&self) -> OptionValue {
138        match self {
139            OptionSpec::Toggle { default, .. } => OptionValue::Bool(*default),
140            OptionSpec::Choice { default, .. } => OptionValue::Choice((*default).to_string()),
141            OptionSpec::Number { default, .. } => OptionValue::Number(*default),
142            OptionSpec::Text { default, .. } => OptionValue::Text((*default).to_string()),
143        }
144    }
145}
146
147#[derive(Clone, PartialEq, Debug)]
148pub enum OptionValue {
149    Bool(bool),
150    Choice(String),
151    Number(i64),
152    Text(String),
153}
154
155/// The current setting of every knob a tool declared.
156///
157/// Built from the specs, so every lookup has a default and the getters cannot
158/// fail — tool implementations never deal with missing options.
159#[derive(Clone, PartialEq, Debug, Default)]
160pub struct Options {
161    values: HashMap<&'static str, OptionValue>,
162}
163
164impl Options {
165    pub fn from_specs(specs: &[OptionSpec]) -> Self {
166        Options {
167            values: specs.iter().map(|s| (s.id(), s.default_value())).collect(),
168        }
169    }
170
171    pub fn get(&self, id: &str) -> Option<&OptionValue> {
172        self.values.get(id)
173    }
174
175    pub fn set(&mut self, id: &'static str, value: OptionValue) {
176        self.values.insert(id, value);
177    }
178
179    pub fn bool(&self, id: &str) -> bool {
180        matches!(self.values.get(id), Some(OptionValue::Bool(true)))
181    }
182
183    pub fn choice(&self, id: &str) -> &str {
184        match self.values.get(id) {
185            Some(OptionValue::Choice(v)) => v,
186            _ => "",
187        }
188    }
189
190    pub fn number(&self, id: &str) -> i64 {
191        match self.values.get(id) {
192            Some(OptionValue::Number(v)) => *v,
193            _ => 0,
194        }
195    }
196
197    pub fn text(&self, id: &str) -> &str {
198        match self.values.get(id) {
199            Some(OptionValue::Text(v)) => v,
200            _ => "",
201        }
202    }
203}
204
205/// A human-readable failure. Tools surface these to the output pane, so the
206/// message is user-facing copy, not a debug dump.
207#[derive(Clone, PartialEq, Debug)]
208pub struct ToolError(pub String);
209
210impl ToolError {
211    pub fn new(msg: impl Into<String>) -> Self {
212        ToolError(msg.into())
213    }
214}
215
216impl fmt::Display for ToolError {
217    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
218        f.write_str(&self.0)
219    }
220}
221
222impl std::error::Error for ToolError {}
223
224pub type ToolResult = Result<String, ToolError>;
225
226pub trait Tool: Send + Sync {
227    fn meta(&self) -> ToolMeta;
228
229    fn input_mode(&self) -> InputMode {
230        InputMode::Text {
231            placeholder: "Paste your input here",
232        }
233    }
234
235    fn options(&self) -> &'static [OptionSpec] {
236        &[]
237    }
238
239    fn run(&self, input: Input<'_>, opts: &Options) -> ToolResult;
240}