Skip to main content

tilo_actions/
step.rs

1//! What an actor's step is, as data: which kind of work it does, and on what.
2//!
3//! One vocabulary for every surface that says what a step is at — the line
4//! beside an actor's face, the people list, the card drawn in the window the
5//! step happens in, the words a reviewer reads on a run. A surface asks here
6//! which kind of work the step is, and says it in the reader's own language:
7//! a line is a catalogue message per kind, with the record or item it acts in
8//! as its argument ("Writing in Trip plan", "Schreibt in Trip plan"), so a
9//! language whose word order differs reads its own sentence rather than words
10//! assembled in English.
11//!
12//! The kind is the action's own declaration: what its app says it does
13//! ([`StepKind`] on its action), else the part of the record the invocation
14//! names ([`StepKind::of_anchor`]), else the declared operation of the change
15//! itself ([`StepKind::of_edit`]). Nothing here reads an English verb out of a
16//! label: an action whose declaration names no kind is [`StepKind::Work`],
17//! which says the record it works in and never invents a verb.
18
19use serde::{Deserialize, Serialize};
20
21use crate::entry::{Did, EditOp};
22use crate::interaction::{InteractionAnchor, SemanticInteraction};
23use crate::key::CREATE_ACTION;
24
25/// The kind of work a step does, as its action declares it.
26#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
27#[serde(rename_all = "kebab-case")]
28pub enum StepKind {
29    /// It makes something new in the record.
30    Create,
31    /// It writes words into the record, at a place in it.
32    Write,
33    /// It changes what the record or one of its items says.
34    Edit,
35    /// It takes something away.
36    Delete,
37    /// It moves something elsewhere.
38    Move,
39    /// It only reads.
40    Read,
41    /// It runs something: a command, a program, a job.
42    Run,
43    /// Its declaration names no kind of work of its own.
44    #[default]
45    Work,
46}
47
48impl StepKind {
49    /// The word a declaration names it by (`#[action(step = "create")]`).
50    #[must_use]
51    pub const fn word(self) -> &'static str {
52        match self {
53            Self::Create => "create",
54            Self::Write => "write",
55            Self::Edit => "edit",
56            Self::Delete => "delete",
57            Self::Move => "move",
58            Self::Read => "read",
59            Self::Run => "run",
60            Self::Work => "work",
61        }
62    }
63
64    /// What a step of this kind did, in the past tense, as a catalogue
65    /// message: the word beside the characters a write left says what the
66    /// person saw happen where the action declares no past-tense form of its
67    /// own ([`ActionType::did`](crate::ActionType::did)).
68    #[must_use]
69    pub const fn did_message(self) -> &'static str {
70        match self {
71            Self::Create => DID_CREATED,
72            Self::Write => DID_WROTE,
73            Self::Edit => DID_EDITED,
74            Self::Delete => DID_DELETED,
75            Self::Move => DID_MOVED,
76            Self::Read => DID_READ,
77            Self::Run => DID_RAN,
78            Self::Work => DID_WORKED,
79        }
80    }
81
82    /// The kind `word` names.
83    #[must_use]
84    pub fn of_word(word: &str) -> Option<Self> {
85        [
86            Self::Create,
87            Self::Write,
88            Self::Edit,
89            Self::Delete,
90            Self::Move,
91            Self::Read,
92            Self::Run,
93            Self::Work,
94        ]
95        .into_iter()
96        .find(|kind| kind.word() == word)
97    }
98
99    /// The kind of step the change `op` is, as the change itself declares it:
100    /// words written, an item added, something removed or moved.
101    #[must_use]
102    pub const fn of_edit(op: EditOp) -> Self {
103        match op {
104            EditOp::Splice | EditOp::Replace | EditOp::Mark => Self::Write,
105            EditOp::Add
106            | EditOp::Insert
107            | EditOp::InsertRow
108            | EditOp::InsertColumn
109            | EditOp::React => Self::Create,
110            EditOp::Remove
111            | EditOp::RemoveRow
112            | EditOp::RemoveColumn
113            | EditOp::Unreact
114            | EditOp::Forget => Self::Delete,
115            EditOp::MoveTo => Self::Move,
116            EditOp::Set | EditOp::SetCell => Self::Edit,
117            EditOp::Settle => Self::Work,
118        }
119    }
120
121    /// The kind of step an invocation is, from the part of the record it says
122    /// it acts on: the characters of a text are words written into it, one of
123    /// its items is that item changed, and the record as a whole names no kind
124    /// of its own.
125    #[must_use]
126    pub const fn of_anchor(anchor: &InteractionAnchor) -> Option<Self> {
127        match anchor {
128            InteractionAnchor::Text { .. } | InteractionAnchor::Grid { .. } => Some(Self::Write),
129            InteractionAnchor::ListItems { .. }
130            | InteractionAnchor::Objects { .. }
131            | InteractionAnchor::SemanticControl { .. } => Some(Self::Edit),
132            // A timeline interval is a range of the record changed as a whole,
133            // and a step on the record itself names no part to read a kind
134            // from.
135            InteractionAnchor::Timeline { .. } | InteractionAnchor::Resource => None,
136        }
137    }
138
139    /// The kind of step a committed change is, from what it declares: a field
140    /// edit's operation, a verb's own declaration ([`CREATE_ACTION`] makes
141    /// something, a command parameter runs something), or a group naming what
142    /// its members share. `None` for a step whose declaration names no kind of
143    /// its own.
144    #[must_use]
145    pub fn of_did(what: &Did) -> Option<Self> {
146        match what {
147            Did::Edit(edit) => Some(Self::of_edit(edit.op)),
148            Did::Verb(verb) => {
149                if verb.action.action == CREATE_ACTION {
150                    return Some(Self::Create);
151                }
152                // A parameter named for the command it runs: what the action
153                // declared its input to be.
154                verb.args
155                    .keys()
156                    .any(|name| COMMAND_PARAMS.contains(&name.as_str()))
157                    .then_some(Self::Run)
158            }
159            Did::Group(group) => group.shared().and_then(Self::of_did),
160            Did::History(_) => None,
161        }
162    }
163}
164
165/// The kind of step an invocation is: the kind its action declared, else the
166/// part of the record it names ([`StepKind::of_anchor`]), else
167/// [`StepKind::Work`].
168#[must_use]
169pub fn kind(declared: Option<StepKind>, anchor: &InteractionAnchor) -> StepKind {
170    declared
171        .or_else(|| StepKind::of_anchor(anchor))
172        .unwrap_or(StepKind::Work)
173}
174
175/// One step, as every surface says it: which kind of work it is, and the one
176/// name the line carries.
177#[derive(Clone, Debug, PartialEq, Eq)]
178pub struct Step<'a> {
179    pub kind: StepKind,
180    /// The item's title where the step names one, else the record's name as
181    /// its app shows it ("Trip plan").
182    pub record: Option<&'a str>,
183    /// The app the record belongs to, said where a step makes something new
184    /// in it and no title names what yet ("Tasks").
185    pub app: Option<&'a str>,
186    /// What a run runs, as the caller passed it.
187    pub command: Option<&'a str>,
188    /// What a create makes: the kind of the record it makes it in, and the
189    /// collection of that record it adds to as its declaration names it
190    /// (`tasks.tracker`, `issues`). A surface says one of them by the
191    /// collection's own noun ("an issue", "eine Aufgabe") where the app's
192    /// catalogue holds one, and only says where the step works otherwise.
193    pub makes: Option<(&'a str, &'a str)>,
194}
195
196impl<'a> Step<'a> {
197    /// A step of `kind` on `record`.
198    #[must_use]
199    pub fn new(kind: StepKind, record: Option<&'a str>) -> Self {
200        Self {
201            kind,
202            record: nonempty(record),
203            app: None,
204            command: None,
205            makes: None,
206        }
207    }
208
209    /// The same step, said in `app` where no record names it.
210    #[must_use]
211    pub fn in_app(mut self, app: Option<&'a str>) -> Self {
212        self.app = nonempty(app);
213        self
214    }
215
216    /// The same step, running `command`.
217    #[must_use]
218    pub fn running(mut self, command: Option<&'a str>) -> Self {
219        self.command = nonempty(command);
220        self
221    }
222
223    /// The same step, making something in the collection `field` of the record
224    /// of `kind`: what a surface names by that collection's own noun.
225    #[must_use]
226    pub fn making(mut self, kind: &'a str, field: &'a str) -> Self {
227        self.makes = Some((kind, field));
228        self
229    }
230
231    /// The step `interaction` is: its action's declared kind, else the part of
232    /// its record the invocation names, on the item's title or the record's
233    /// name.
234    #[must_use]
235    pub fn of_interaction(interaction: &'a SemanticInteraction) -> Step<'a> {
236        Self {
237            kind: kind(interaction.action.step, &interaction.anchor),
238            record: nonempty(Some(interaction.resource.label.as_str())),
239            app: nonempty(
240                interaction
241                    .action
242                    .app
243                    .as_ref()
244                    .map(|app| app.label.as_str()),
245            ),
246            command: None,
247            makes: interaction
248                .action
249                .creates
250                .as_deref()
251                .and_then(|field| nonempty(Some(field)))
252                .map(|field| (interaction.resource.kind.as_str(), field)),
253        }
254    }
255
256    /// The catalogue message this step is said in, and its one argument: the
257    /// name the line carries, and whether it is the record or what a run runs.
258    /// A kind whose argument the step does not know says
259    /// [`WORKING_ALONE`](self) instead of a sentence with a hole in it.
260    #[must_use]
261    pub fn message(&self) -> (&'static str, Option<(&'static str, &'a str)>) {
262        fn named<'n>(
263            key: &'static str,
264            name: &'n str,
265        ) -> (&'static str, Option<(&'static str, &'n str)>) {
266            (key, Some(("record", name)))
267        }
268        match self.kind {
269            StepKind::Create => match (self.record, self.app) {
270                (Some(record), _) => named(CREATING, record),
271                (None, Some(app)) => named(CREATING, app),
272                (None, None) => (WORKING_ALONE, None),
273            },
274            StepKind::Write => self
275                .record
276                .map_or((WORKING_ALONE, None), |record| named(WRITING, record)),
277            StepKind::Edit => self
278                .record
279                .map_or((WORKING_ALONE, None), |record| named(EDITING, record)),
280            StepKind::Delete => self
281                .record
282                .map_or((WORKING_ALONE, None), |record| named(DELETING, record)),
283            StepKind::Move => self
284                .record
285                .map_or((WORKING_ALONE, None), |record| named(MOVING, record)),
286            StepKind::Read => self
287                .record
288                .map_or((WORKING_ALONE, None), |record| named(READING, record)),
289            StepKind::Run => match (self.command, self.record) {
290                (Some(command), _) => (RUNNING, Some(("command", command))),
291                (None, Some(record)) => named(RUNNING_IN, record),
292                (None, None) => (WORKING_ALONE, None),
293            },
294            StepKind::Work => self
295                .record
296                .map_or((WORKING_ALONE, None), |record| named(WORKING, record)),
297        }
298    }
299}
300
301/// The parameter names a verb declares for the command it runs: a verb
302/// taking one is a step of [`StepKind::Run`], and the command is what a
303/// person reads.
304pub const COMMAND_PARAMS: &[&str] = &["command", "command_line", "cmd"];
305
306/// A step that makes something new in the record or the app it names.
307pub const CREATING: &str = "step-creating";
308/// A step that makes one of a collection, named by that collection's noun.
309pub const CREATING_ONE: &str = "step-creating-one";
310/// A step that writes words into the record.
311pub const WRITING: &str = "step-writing";
312/// A step that changes what the record or one of its items says.
313pub const EDITING: &str = "step-editing";
314/// A step that takes something away.
315pub const DELETING: &str = "step-deleting";
316/// A step that moves something elsewhere.
317pub const MOVING: &str = "step-moving";
318/// A step that only reads.
319pub const READING: &str = "step-reading";
320/// A step that runs a command.
321pub const RUNNING: &str = "step-running";
322/// A step that runs something in the record it names.
323pub const RUNNING_IN: &str = "step-running-in";
324/// A step of work its declaration names no kind of.
325pub const WORKING: &str = "step-working";
326/// The same where the step names nothing at all.
327pub const WORKING_ALONE: &str = "step-working-alone";
328
329/// What a step of each kind did, in the past tense ([`StepKind::did_message`]).
330pub const DID_CREATED: &str = "step-did-created";
331pub const DID_WROTE: &str = "step-did-wrote";
332pub const DID_EDITED: &str = "step-did-edited";
333pub const DID_DELETED: &str = "step-did-deleted";
334pub const DID_MOVED: &str = "step-did-moved";
335pub const DID_READ: &str = "step-did-read";
336pub const DID_RAN: &str = "step-did-ran";
337pub const DID_WORKED: &str = "step-did-worked";
338
339/// `name` trimmed, unless that leaves nothing to say.
340fn nonempty(name: Option<&str>) -> Option<&str> {
341    name.map(str::trim).filter(|name| !name.is_empty())
342}
343
344#[cfg(test)]
345mod tests {
346    #![allow(
347        clippy::unwrap_used,
348        clippy::expect_used,
349        reason = "in a test the unwrap is the assertion"
350    )]
351
352    use super::*;
353    use crate::interaction::{InteractionAction, InteractionTextRange};
354    use crate::{ActionApp, ActionResource, InteractionPhase, InvocationId};
355
356    fn interaction(
357        step: Option<StepKind>,
358        anchor: InteractionAnchor,
359        record: &str,
360    ) -> SemanticInteraction {
361        SemanticInteraction {
362            version: crate::INTERACTION_VERSION,
363            invocation: InvocationId(uuid::Uuid::from_u128(1)),
364            sequence: 1,
365            actor: crate::Acting::agent("quill", "ada"),
366            phase: InteractionPhase::Applying,
367            action: InteractionAction {
368                id: "create".into(),
369                label: "Create an issue".into(),
370                app: Some(ActionApp {
371                    id: "so.tilo.tasks".into(),
372                    label: "Tasks".into(),
373                }),
374                step,
375                creates: None,
376                did: None,
377            },
378            resource: ActionResource {
379                id: "tasks.tracker".into(),
380                kind: "tasks.tracker".into(),
381                label: record.into(),
382            },
383            anchor,
384            group: None,
385        }
386    }
387
388    tilo_test_env::scenario! {
389        fn a_step_names_its_kind_and_record;
390
391        phase a_steps_kind_is_declared_else_read_from_the_part_it_acts_on;
392        // A step's kind is its action's own declaration where it names one, and
393        // the part of the record it acts on where it does not.
394        {
395            let text = InteractionAnchor::Text {
396                region: "text".into(),
397                ranges: vec![InteractionTextRange {
398                    block: "note".into(),
399                    start: 0,
400                    end: 0,
401                }],
402            };
403            let created = interaction(Some(StepKind::Create), InteractionAnchor::Resource, "Tasks");
404            assert_eq!(Step::of_interaction(&created).kind, StepKind::Create);
405            let written = interaction(None, text, "Trip plan");
406            let writing = Step::of_interaction(&written);
407            assert_eq!(writing.kind, StepKind::Write);
408            assert_eq!(writing.message(), (WRITING, Some(("record", "Trip plan"))));
409            let items = InteractionAnchor::ListItems {
410                ids: vec!["issue-1".into()],
411            };
412            assert_eq!(
413                Step::of_interaction(&interaction(None, items, "Book the ferry")).kind,
414                StepKind::Edit,
415                "an item's own step changes that item"
416            );
417            assert_eq!(
418                Step::of_interaction(&interaction(None, InteractionAnchor::Resource, "Issues")).kind,
419                StepKind::Work
420            );
421        }
422
423        phase a_step_names_its_record_or_says_only_what_it_is;
424        // A declared kind says the record, and the app where nothing is named
425        // yet; a kind with no name says only what it is.
426        {
427            let made = interaction(
428                Some(StepKind::Create),
429                InteractionAnchor::Resource,
430                "Issues",
431            );
432            let created = Step::of_interaction(&made).in_app(Some(" Tasks "));
433            assert_eq!(created.message(), (CREATING, Some(("record", "Issues"))));
434            // A create whose declaration names the collection it adds to says what
435            // it makes: the record's kind and that collection.
436            let mut declaring = made.clone();
437            declaring.action.creates = Some(" issues ".into());
438            assert_eq!(
439                Step::of_interaction(&declaring).makes,
440                Some(("tasks.tracker", "issues")),
441                "what it makes, named by the record's kind and its collection"
442            );
443            assert_eq!(created.makes, None, "a create that names none makes none");
444            assert_eq!(
445                Step::new(StepKind::Create, None)
446                    .in_app(Some("Tasks"))
447                    .message(),
448                (CREATING, Some(("record", "Tasks")))
449            );
450            assert_eq!(
451                Step::new(StepKind::Delete, None).message(),
452                (WORKING_ALONE, None)
453            );
454            assert_eq!(
455                Step::new(StepKind::Run, Some("Terminal")).running(Some("cargo build")),
456                Step {
457                    kind: StepKind::Run,
458                    record: Some("Terminal"),
459                    app: None,
460                    command: Some("cargo build"),
461                    makes: None,
462                }
463            );
464            assert_eq!(
465                Step::new(StepKind::Run, Some("Terminal")).message(),
466                (RUNNING_IN, Some(("record", "Terminal")))
467            );
468        }
469
470        phase a_committed_change_names_its_kind_as_it_declared_it;
471        // A committed change names its kind by what it declared: the operation of
472        // a field edit, the platform's make, the command a verb runs.
473        {
474            for (op, kind) in [
475                (EditOp::Splice, StepKind::Write),
476                (EditOp::Replace, StepKind::Write),
477                (EditOp::Insert, StepKind::Create),
478                (EditOp::Remove, StepKind::Delete),
479                (EditOp::MoveTo, StepKind::Move),
480                (EditOp::Set, StepKind::Edit),
481            ] {
482                assert_eq!(StepKind::of_edit(op), kind, "{op:?}");
483            }
484            let made = Did::verb(
485                crate::ActionKey::new("so.tilo.notes", "notes.note", CREATE_ACTION),
486                std::iter::empty::<(String, crate::Scalar)>(),
487            );
488            assert_eq!(StepKind::of_did(&made), Some(StepKind::Create));
489            let command = Did::verb(
490                crate::ActionKey::new("so.tilo.terminal", "tl.so.tilo.terminal.Session", "run"),
491                [(
492                    "command".to_owned(),
493                    crate::Scalar::from_json(&serde_json::json!("cargo build")).unwrap(),
494                )],
495            );
496            assert_eq!(StepKind::of_did(&command), Some(StepKind::Run));
497            let renamed = Did::verb(
498                crate::ActionKey::new("so.tilo.notes", "notes.note", "rename"),
499                std::iter::empty::<(String, crate::Scalar)>(),
500            );
501            assert_eq!(StepKind::of_did(&renamed), None);
502        }
503
504        phase a_kind_reads_back_from_its_word;
505        {
506            for kind in [
507                StepKind::Create,
508                StepKind::Write,
509                StepKind::Edit,
510                StepKind::Delete,
511                StepKind::Move,
512                StepKind::Read,
513                StepKind::Run,
514                StepKind::Work,
515            ] {
516                assert_eq!(StepKind::of_word(kind.word()), Some(kind));
517            }
518            assert_eq!(StepKind::of_word("writing"), None);
519        }
520    }
521}