1use serde::{Deserialize, Serialize};
18use serde_json::{Map, Value};
19
20use crate::{ActionDescriptor, ParamType};
21
22pub const AWAITING_CONFIRMATION: &str = "action_awaiting_confirmation";
26
27pub const AWAITING_CAUSE: &str = "action_awaiting_cause";
31
32pub const DECLINED: &str = "action_declined";
35
36pub const MESSAGE_PREVIEW_TAG: &str = "draft:message";
39
40pub const MAX_FIELD_CHARS: usize = 64 * 1024;
43
44pub const SUMMARY_CHARS: usize = 48;
46
47const MAX_LISTED: usize = 12;
49
50#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
52#[serde(rename_all = "snake_case")]
53pub enum DraftLayout {
54 #[default]
56 Fields,
57 Message,
59}
60
61#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
63#[serde(rename_all = "snake_case")]
64pub enum MessageRole {
65 To,
66 Cc,
67 Bcc,
68 Subject,
69 Body,
70 Attachments,
71}
72
73impl MessageRole {
74 fn of(name: &str) -> Option<Self> {
75 Some(match name {
76 "to" | "recipients" => Self::To,
77 "cc" => Self::Cc,
78 "bcc" => Self::Bcc,
79 "subject" | "title" => Self::Subject,
80 "body" | "text" | "message" => Self::Body,
81 "attachments" | "files" => Self::Attachments,
82 _ => return None,
83 })
84 }
85}
86
87#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
89#[serde(remote = "Self", rename_all = "snake_case")]
90pub enum DraftValue {
91 Text {
92 text: String,
93 },
94 Number {
95 text: String,
96 },
97 Flag {
98 on: bool,
99 },
100 List {
102 count: usize,
103 labels: Vec<String>,
104 },
105 Resource {
107 label: String,
108 },
109 Withheld,
111}
112
113crate::tagged_through_json_value!(DraftValue, "type");
114
115impl DraftValue {
116 #[must_use]
120 pub fn line(&self) -> String {
121 match self {
122 Self::Text { text } | Self::Number { text } => text.clone(),
123 Self::Flag { on } => if *on { "yes" } else { "no" }.to_owned(),
124 Self::List { count, labels } => {
125 let line = labels.join(", ");
126 match count.checked_sub(labels.len()) {
127 Some(more) if more > 0 => format!("{line} +{more}"),
128 _ => line,
129 }
130 }
131 Self::Resource { label } => label.clone(),
132 Self::Withheld => "•••".to_owned(),
133 }
134 }
135}
136
137#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
138pub struct DraftField {
139 pub path: Vec<String>,
142 pub label: String,
143 pub value: DraftValue,
144 #[serde(default)]
146 pub editable: bool,
147 #[serde(default)]
149 pub multiline: bool,
150 #[serde(default, skip_serializing_if = "Option::is_none")]
154 pub shows: Option<String>,
155 #[serde(default, skip_serializing_if = "Option::is_none")]
157 pub role: Option<MessageRole>,
158}
159
160#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
162pub struct Draft {
163 pub action_label: String,
164 pub resource_label: String,
165 #[serde(default, skip_serializing_if = "Option::is_none")]
166 pub description: Option<String>,
167 #[serde(default)]
168 pub layout: DraftLayout,
169 pub fields: Vec<DraftField>,
170 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
175 pub undoable: bool,
176}
177
178#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
180pub struct DraftEdit {
181 pub path: Vec<String>,
182 pub text: String,
183}
184
185impl Draft {
186 #[must_use]
187 pub fn render(descriptor: &ActionDescriptor, arguments: &Map<String, Value>) -> Self {
188 let mut fields = Vec::new();
189 for param in &descriptor.params {
190 let Some(value) = arguments.get(param.name.as_ref()) else {
191 continue;
192 };
193 let path = vec![param.name.to_string()];
194 match (param.ty, value) {
195 (ParamType::Secret, _) => {
196 fields.push(field(path, ¶m.name, DraftValue::Withheld));
197 }
198 (ParamType::Resource, _) if crate::remote::takes_item(param) => {
201 fields.push(field(path, ¶m.name, DraftValue::Withheld));
202 }
203 (ParamType::Object, Value::Object(object)) => {
204 let properties = param
205 .schema
206 .as_deref()
207 .and_then(|schema| schema.get("properties"))
208 .and_then(Value::as_object);
209 for (name, inner) in object {
210 let schema = properties.and_then(|properties| properties.get(name));
211 let mut path = path.clone();
212 path.push(name.clone());
213 if let Some(field) = value_field(path, name, inner, schema) {
214 fields.push(field);
215 }
216 }
217 }
218 (ty, value) => {
219 let schema = param.schema.as_deref();
220 let mut made = value_field(path, ¶m.name, value, schema);
221 if let Some(made) = made.as_mut()
222 && ty == ParamType::Resource
223 {
224 made.value = DraftValue::Resource {
225 label: made.value.line(),
226 };
227 made.editable = false;
228 }
229 if let (Some(made), Some(raw)) = (made.as_mut(), value.as_str())
235 && !raw.is_empty()
236 && let Some(label) = param.choice_label(raw)
237 && !label.trim().is_empty()
238 {
239 made.shows = Some(label.to_owned());
240 }
241 fields.extend(made);
242 }
243 }
244 }
245 let message = descriptor
246 .contract
247 .tags
248 .iter()
249 .any(|tag| tag == MESSAGE_PREVIEW_TAG)
250 || (fields
251 .iter()
252 .any(|field| field.role == Some(MessageRole::To))
253 && fields
254 .iter()
255 .any(|field| field.role == Some(MessageRole::Body)));
256 if !message {
257 for field in &mut fields {
258 field.role = None;
259 }
260 }
261 Self {
262 action_label: descriptor.action_label.clone(),
263 resource_label: descriptor.resource_label.clone(),
264 description: descriptor.description.clone(),
265 layout: if message {
266 DraftLayout::Message
267 } else {
268 DraftLayout::Fields
269 },
270 fields,
271 undoable: descriptor.contract.can_be_undone(),
272 }
273 }
274
275 #[must_use]
276 pub fn role(&self, role: MessageRole) -> Option<&DraftField> {
277 self.fields.iter().find(|field| field.role == Some(role))
278 }
279
280 #[must_use]
283 pub fn shown_line(field: &DraftField) -> String {
284 field.shows.clone().unwrap_or_else(|| field.value.line())
285 }
286
287 #[must_use]
291 pub fn gist(&self) -> Option<String> {
292 if self.layout == DraftLayout::Message {
293 let parts: Vec<String> = [MessageRole::To, MessageRole::Subject]
294 .into_iter()
295 .filter_map(|role| self.role(role))
296 .map(Draft::shown_line)
297 .filter(|line| !line.is_empty())
298 .collect();
299 if !parts.is_empty() {
300 return Some(parts.join(" · "));
301 }
302 }
303 let parts: Vec<String> = self
304 .fields
305 .iter()
306 .filter(|field| !field.multiline && field.value != DraftValue::Withheld)
307 .map(Draft::shown_line)
308 .filter(|line| !line.is_empty())
309 .take(2)
310 .collect();
311 (!parts.is_empty()).then(|| parts.join(" · "))
312 }
313
314 #[must_use]
318 pub fn summary(&self) -> Vec<(String, String)> {
319 self.fields
320 .iter()
321 .map(|field| {
322 let line = field
323 .value
324 .line()
325 .split_whitespace()
326 .collect::<Vec<_>>()
327 .join(" ");
328 let cut = if line.chars().count() > SUMMARY_CHARS {
329 let kept: String = line.chars().take(SUMMARY_CHARS).collect();
330 format!("{}…", kept.trim_end())
331 } else {
332 line
333 };
334 (field.label.clone(), cut)
335 })
336 .collect()
337 }
338
339 pub fn apply_edits(
342 &self,
343 arguments: &Map<String, Value>,
344 edits: &[DraftEdit],
345 ) -> Result<Map<String, Value>, String> {
346 let mut edited = arguments.clone();
347 for edit in edits {
348 set_path(&mut edited, &edit.path, self.edit_value(edit)?)?;
349 }
350 Ok(edited)
351 }
352
353 pub fn check_edits(&self, edits: &[DraftEdit]) -> Result<(), String> {
356 edits
357 .iter()
358 .try_for_each(|edit| self.edit_value(edit).map(drop))
359 }
360
361 fn edit_value(&self, edit: &DraftEdit) -> Result<Value, String> {
362 let field = self
363 .fields
364 .iter()
365 .find(|field| field.path == edit.path && field.editable)
366 .ok_or_else(|| format!("{} cannot be changed here", edit.path.join(".")))?;
367 if edit.text.chars().count() > MAX_FIELD_CHARS {
368 return Err(format!("{} is too long", field.label));
369 }
370 Ok(match &field.value {
371 DraftValue::Text { .. } => Value::String(edit.text.clone()),
372 DraftValue::Number { .. } => {
373 let number: serde_json::Number = edit
374 .text
375 .trim()
376 .parse()
377 .map_err(|_| format!("{} needs a number", field.label))?;
378 Value::Number(number)
379 }
380 DraftValue::Flag { .. } => match edit.text.trim() {
381 "true" | "yes" => Value::Bool(true),
382 "false" | "no" => Value::Bool(false),
383 _ => return Err(format!("{} needs yes or no", field.label)),
384 },
385 _ => return Err(format!("{} cannot be changed here", field.label)),
386 })
387 }
388
389 #[must_use]
396 pub fn arguments(&self) -> Option<Map<String, Value>> {
397 let mut arguments = Map::new();
398 for field in &self.fields {
399 let value = match &field.value {
400 DraftValue::Text { text } => Value::String(text.clone()),
401 DraftValue::Number { text } => Value::Number(text.parse().ok()?),
402 DraftValue::Flag { on } => Value::Bool(*on),
403 DraftValue::List { .. } | DraftValue::Resource { .. } | DraftValue::Withheld => {
404 return None;
405 }
406 };
407 let (last, parents) = field.path.split_last()?;
408 let mut object = &mut arguments;
409 for parent in parents {
410 object = object
411 .entry(parent.clone())
412 .or_insert_with(|| Value::Object(Map::new()))
413 .as_object_mut()?;
414 }
415 object.insert(last.clone(), value);
416 }
417 Some(arguments)
418 }
419
420 #[must_use]
423 pub fn edited(&self, edits: &[DraftEdit]) -> Self {
424 let mut draft = self.clone();
425 for edit in edits {
426 let Ok(value) = self.edit_value(edit) else {
427 continue;
428 };
429 if let Some(field) = draft
430 .fields
431 .iter_mut()
432 .find(|field| field.path == edit.path)
433 {
434 field.value = match value {
435 Value::Bool(on) => DraftValue::Flag { on },
436 Value::Number(number) => DraftValue::Number {
437 text: number.to_string(),
438 },
439 _ => DraftValue::Text {
440 text: edit.text.clone(),
441 },
442 };
443 field.shows = None;
446 }
447 }
448 draft
449 }
450}
451
452#[must_use]
455pub fn arguments_digest(arguments: &Map<String, Value>) -> [u8; 32] {
456 let mut hasher = blake3::Hasher::new_derive_key("Tilo draft arguments v1");
457 tilo_canonical_json::write_object_bytes(arguments, |chunk| {
458 hasher.update(chunk);
459 });
460 *hasher.finalize().as_bytes()
461}
462
463fn set_path(
464 arguments: &mut Map<String, Value>,
465 path: &[String],
466 value: Value,
467) -> Result<(), String> {
468 let Some((last, parents)) = path.split_last() else {
469 return Err("an edit names no field".into());
470 };
471 let mut object = arguments;
472 for parent in parents {
473 object = object
474 .get_mut(parent)
475 .and_then(Value::as_object_mut)
476 .ok_or_else(|| format!("{} is not in the draft", path.join(".")))?;
477 }
478 object.insert(last.clone(), value);
479 Ok(())
480}
481
482fn field(path: Vec<String>, name: &str, value: DraftValue) -> DraftField {
483 let role = path.last().and_then(|last| MessageRole::of(last));
484 DraftField {
485 path,
486 label: humanize(name),
487 value,
488 editable: false,
489 multiline: false,
490 shows: None,
491 role,
492 }
493}
494
495fn value_field(
498 path: Vec<String>,
499 name: &str,
500 value: &Value,
501 schema: Option<&Value>,
502) -> Option<DraftField> {
503 let label = schema
504 .and_then(|schema| schema.get("title"))
505 .and_then(Value::as_str)
506 .map_or_else(|| humanize(name), str::to_owned);
507 let mut made = field(path, name, DraftValue::Withheld);
508 made.label = label;
509 if schema
510 .and_then(|schema| schema.get("format"))
511 .is_some_and(|format| format == "password")
512 {
513 return Some(made);
514 }
515 match value {
516 Value::Null => return None,
517 Value::String(text) if text.trim().is_empty() => return None,
518 Value::String(text) => {
519 let long = text.chars().count() > MAX_FIELD_CHARS;
520 let shown: String = text.chars().take(MAX_FIELD_CHARS).collect();
521 made.multiline = text.contains('\n')
522 || text.chars().count() > 120
523 || made.role == Some(MessageRole::Body);
524 made.editable = !long;
525 made.value = DraftValue::Text { text: shown };
526 }
527 Value::Number(number) => {
528 made.editable = true;
529 made.value = DraftValue::Number {
530 text: number.to_string(),
531 };
532 }
533 Value::Bool(on) => {
534 made.editable = true;
535 made.value = DraftValue::Flag { on: *on };
536 }
537 Value::Array(items) if items.is_empty() => return None,
538 Value::Array(items) => {
539 made.value = DraftValue::List {
540 count: items.len(),
541 labels: items.iter().take(MAX_LISTED).map(entry_label).collect(),
542 };
543 }
544 Value::Object(object) => {
545 made.value = DraftValue::Resource {
546 label: object_label(object).unwrap_or_else(|| humanize(name)),
547 };
548 }
549 }
550 Some(made)
551}
552
553const LABEL_KEYS: [&str; 8] = [
555 "label",
556 "name",
557 "title",
558 "filename",
559 "file_name",
560 "path",
561 "address",
562 "id",
563];
564
565fn object_label(object: &Map<String, Value>) -> Option<String> {
566 LABEL_KEYS.iter().find_map(|key| {
567 let text = object.get(*key)?.as_str()?;
568 let text = if *key == "path" {
569 text.rsplit('/').next().unwrap_or(text)
570 } else {
571 text
572 };
573 (!text.is_empty()).then(|| text.to_owned())
574 })
575}
576
577fn entry_label(value: &Value) -> String {
578 match value {
579 Value::String(text) => text.rsplit('/').next().unwrap_or(text).to_owned(),
580 Value::Object(object) => object_label(object).unwrap_or_else(|| "…".to_owned()),
581 other => other.to_string(),
582 }
583}
584
585fn humanize(name: &str) -> String {
587 let spaced = name.replace(['_', '-'], " ");
588 let mut chars = spaced.trim().chars();
589 chars.next().map_or_else(String::new, |first| {
590 first.to_uppercase().chain(chars).collect()
591 })
592}
593
594#[cfg(test)]
595#[path = "draft_tests.rs"]
596mod tests;