Skip to main content

tilo_resource/
share.rs

1//! `share-link` and `share-invite-link`: what a person, a bot or an agent
2//! asks for to get "a link to this".
3//!
4//! Every resource that declares a view publishes both. A resource without a
5//! view has nothing a link could open, so it has no link, except a record's
6//! root: the record itself opens in its app, so its root always offers
7//! `share-link` ([`offer_resource`]). The specs are bound here, where the views
8//! are attached, so every way a resource is published (the resource itself, an
9//! item, a live row) offers them the same way; the framework's root answers
10//! them.
11
12use std::sync::Arc;
13
14use serde::{Deserialize, Serialize};
15use tilo_actions::{
16    ActionKind, ActionParam, ActionSpec, ActionType, EncodedAction, ExecutionMode, OperationKind,
17    ParamType, ResultSpec, Target,
18};
19
20/// The link to the resource as a URL.
21pub const SHARE_LINK: &str = tilo_actions::remote::SHARE_LINK_ACTION;
22/// The link with an invitation for someone not yet in the workspace.
23pub const SHARE_INVITE_LINK: &str = "share-invite-link";
24
25/// Whether `action` is one of the framework's own share verbs, offered beside
26/// every resource's own: a resource's other actions are what the app declared.
27#[must_use]
28pub fn is_share_verb(action: &str) -> bool {
29    action == SHARE_LINK || action == SHARE_INVITE_LINK
30}
31
32/// Whether `type_id` is one of the framework's share operations (`SHARE_TYPE` or
33/// `SHARE_INVITE_TYPE`): what a host answers for itself rather than through the app.
34#[must_use]
35pub fn handles(type_id: &str) -> bool {
36    type_id == SHARE_TYPE || type_id == SHARE_INVITE_TYPE
37}
38/// `share-link` on `resource`, which `provider` publishes: how one app asks
39/// another app's resource for its link without knowing its views.
40#[must_use]
41pub fn share_link_target(
42    provider: impl Into<String>,
43    resource: impl Into<String>,
44) -> tilo_actions::remote::RemoteActionTarget {
45    tilo_actions::remote::RemoteActionTarget {
46        provider: provider.into(),
47        address: tilo_actions::ActionAddress::new(resource, SHARE_LINK),
48    }
49}
50
51/// `share-link` as the published resource `resource` offers it: what a
52/// caller holding the resource's id invokes for its link.
53#[must_use]
54pub fn share_link_address(resource: impl Into<String>) -> tilo_actions::ActionAddress {
55    tilo_actions::ActionAddress::new(resource, SHARE_LINK)
56}
57
58/// The operation type the framework answers `share-link` with.
59pub const SHARE_TYPE: &str = "tilo.resource.share-link";
60/// The operation type the framework answers `share-invite-link` with.
61pub const SHARE_INVITE_TYPE: &str = "tilo.resource.share-invite-link";
62
63/// One declared view, as the link names it.
64#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
65pub struct SharedView {
66    pub id: String,
67    pub primary: bool,
68    /// Whether the view opens at a range of the resource's text.
69    pub range: bool,
70    /// Whether the view opens on the whole desktop rather than its app
71    /// alone full tab: its link is a desktop link unless asked otherwise.
72    #[serde(default)]
73    pub desktop: bool,
74}
75
76/// What a `share-link` invocation asks for: the resource it was published
77/// on, its views as they were published, and the caller's arguments.
78#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
79pub struct ShareRequest {
80    pub resource: String,
81    pub kind: String,
82    pub views: Vec<SharedView>,
83    pub invite: bool,
84    pub args: serde_json::Map<String, serde_json::Value>,
85}
86
87/// Offer `share-link` and `share-invite-link` on `resource` when it
88/// declares a view and does not offer them already.
89pub fn offer(resource: &mut tilo_actions::ResourceSpec) {
90    if resource.views.is_empty() || resource.actions.iter().any(|spec| is_share_verb(&spec.id)) {
91        return;
92    }
93    let views = shared_views(resource);
94    let target = Target::new(resource.id.as_str().to_owned());
95    for invite in [false, true] {
96        let ty = share_type(invite, &resource.kind, &views);
97        resource.actions.push(ty.bind(target.clone()));
98    }
99}
100
101/// Offer `share-link` on `root`, a record's root resource, even when it
102/// declares no view: the link then names the record, which opens in its app.
103/// A root with views offers both links as any resource does ([`offer`]).
104pub fn offer_resource(root: &mut tilo_actions::ResourceSpec) {
105    offer(root);
106    if root.actions.iter().any(|spec| spec.id == SHARE_LINK) {
107        return;
108    }
109    let target = Target::new(root.id.as_str().to_owned());
110    root.actions
111        .push(share_type(false, &root.kind, &[]).bind(target));
112}
113
114/// Offer `share-link` alone on `resource`, when it declares a view and does not
115/// offer it already: for a resource whose host mints a link but cannot hand out
116/// an invitation, which is the shell's own act ([`SHARE_INVITE_LINK`]).
117pub fn offer_link(resource: &mut tilo_actions::ResourceSpec) {
118    if resource.views.is_empty() || resource.actions.iter().any(|spec| spec.id == SHARE_LINK) {
119        return;
120    }
121    let views = shared_views(resource);
122    let target = Target::new(resource.id.as_str().to_owned());
123    resource
124        .actions
125        .push(share_type(false, &resource.kind, &views).bind(target));
126}
127
128/// [`offer_link`] on `root`, a record's root resource, even when it declares no
129/// view: the link then names the record, which opens in its app.
130pub fn offer_resource_link(root: &mut tilo_actions::ResourceSpec) {
131    offer_link(root);
132    if root.actions.iter().any(|spec| spec.id == SHARE_LINK) {
133        return;
134    }
135    let target = Target::new(root.id.as_str().to_owned());
136    root.actions
137        .push(share_type(false, &root.kind, &[]).bind(target));
138}
139
140/// The views of `resource` as a link names them.
141fn shared_views(resource: &tilo_actions::ResourceSpec) -> Vec<SharedView> {
142    resource
143        .views
144        .iter()
145        .map(|view| SharedView {
146            id: view.id.clone(),
147            primary: view.primary,
148            range: view.range.is_some(),
149            desktop: view.desktop,
150        })
151        .collect()
152}
153
154/// Which link type: whether it invites, the kind of resource, its views.
155type ShareKey = (bool, String, Vec<SharedView>);
156
157/// The type of the link to resources of kind `kind` with `views`, kept once
158/// for every resource that offers it; its target is the resource's id.
159fn share_type(invite: bool, kind: &str, views: &[SharedView]) -> Arc<ActionType> {
160    thread_local! {
161        static KEPT: std::cell::RefCell<crate::kept::KeptTypes<ShareKey>> =
162            std::cell::RefCell::default();
163    }
164    let key = (invite, kind.to_owned(), views.to_vec());
165    crate::kept::kept_type(&KEPT, key, || {
166        Arc::clone(spec(invite, kind.to_owned(), views.to_vec()).action_type())
167    })
168}
169
170/// [`offer`] on `resource` and everything nested in it.
171pub fn offer_tree(resource: &mut tilo_actions::ResourceSpec) {
172    offer(resource);
173    for child in &mut resource.children {
174        offer_tree(child);
175    }
176}
177
178/// Offer the link actions again after `resource` gained views.
179pub fn reoffer(resource: &mut tilo_actions::ResourceSpec) {
180    resource.actions.retain(|spec| !is_share_verb(&spec.id));
181    offer(resource);
182}
183
184/// The parameters of the link to a resource with `views`; an invitation's
185/// also say what it admits.
186fn params(invite: bool, views: &[SharedView]) -> Vec<ActionParam> {
187    let ranged = views.iter().any(|view| view.range);
188    let mut params = vec![
189        ActionParam::optional(
190            "view",
191            ParamType::Text,
192            "Which declared view the link opens (default: the primary view)",
193        )
194        .with_choices(views.iter().map(|view| view.id.clone()))
195        .nullable(),
196    ];
197    if ranged {
198        params.extend([
199            ActionParam::optional(
200                "start",
201                ParamType::Integer,
202                "Where the linked range of the text starts",
203            )
204            .nullable(),
205            ActionParam::optional(
206                "end",
207                ParamType::Integer,
208                "Where the linked range of the text ends",
209            )
210            .nullable(),
211            ActionParam::optional(
212                "unit",
213                ParamType::Text,
214                "What start and end count (default: chars)",
215            )
216            .with_choices(["chars", "bytes"])
217            .nullable(),
218        ]);
219    }
220    params.push(
221        ActionParam::optional(
222            "mode",
223            ParamType::Text,
224            "app opens it alone in a full browser tab, desktop on the workspace's desktop (default: app)",
225        )
226        .with_choices(["app", "desktop"])
227        .nullable(),
228    );
229    if invite {
230        params.extend([
231            ActionParam::optional(
232                "role",
233                ParamType::Text,
234                "The role the invitation carries (default: viewer)",
235            )
236            .with_choices(["viewer", "commenter", "editor"])
237            .nullable(),
238            ActionParam::optional(
239                "expires_in",
240                ParamType::Integer,
241                "Seconds until the invitation can no longer be redeemed",
242            )
243            .nullable(),
244        ]);
245    }
246    params
247}
248
249/// The link spec of resources of kind `kind` with `views`, whose target is
250/// the resource's id.
251fn spec(invite: bool, kind: String, views: Vec<SharedView>) -> ActionSpec {
252    let params = params(invite, &views);
253    let (id, label, type_id, action_kind, description) = if invite {
254        (
255            SHARE_INVITE_LINK,
256            "Share invite link",
257            SHARE_INVITE_TYPE,
258            ActionKind::Outside,
259            "A link to this that also invites someone who is not yet in the workspace. The invitation is a capability: send it only to the person it is for.",
260        )
261    } else {
262        (
263            SHARE_LINK,
264            "Copy link",
265            SHARE_TYPE,
266            ActionKind::Read,
267            "A link to this, as a URL that opens it in a browser or an installed Tilo. Anyone opening it still needs access to the workspace.",
268        )
269    };
270    let mut spec = ActionSpec::typed_operation_on(
271        id,
272        label,
273        label,
274        OperationKind::Effect,
275        type_id,
276        params,
277        Arc::new(move |target, args| {
278            let request = ShareRequest {
279                resource: target.get::<String>().cloned().unwrap_or_default(),
280                kind: kind.clone(),
281                views: views.clone(),
282                invite,
283                args: args.to_json(),
284            };
285            EncodedAction::encode_operation(type_id, &request).unwrap_or_else(|_| EncodedAction {
286                type_id: type_id.into(),
287                payload: Vec::new(),
288            })
289        }),
290    )
291    .of_kind(action_kind)
292    .with_description(description);
293    // Minting waits on the workspace's host for a fresh locator, which only
294    // answers in-process at once; over the session it arrives later.
295    let contract = &mut spec.type_mut().contract;
296    contract.execution = ExecutionMode::Background { cancellable: true };
297    contract.result = ResultSpec::Json {
298        schema: serde_json::json!({
299            "type": "object",
300            "properties": {"url": {"type": "string"}},
301            "required": ["url"],
302        }),
303    };
304    spec
305}
306
307pub use tilo_actions::outside_document::{
308    admits_outside_document, outside_document, resolved_outside_document,
309};
310
311#[cfg(test)]
312mod tests {
313    use super::*;
314
315    fn params(spec: &ActionSpec) -> Vec<String> {
316        spec.params()
317            .iter()
318            .map(|param| param.name.to_string())
319            .collect()
320    }
321
322    tilo_test_env::scenario! {
323        fn a_resource_offers_its_link_and_its_views;
324
325        phase a_record_root_offers_its_link_without_a_view;
326        {
327            let mut root = tilo_actions::ResourceSpec::new("pdf", "pdf.document", "PDF");
328            offer(&mut root);
329            assert!(
330                root.actions.is_empty(),
331                "a resource without a view has no link"
332            );
333            offer_resource(&mut root);
334            let ids: Vec<_> = root.actions.iter().map(|spec| spec.id.as_str()).collect();
335            assert_eq!(
336                ids,
337                [SHARE_LINK],
338                "the record opens in its app; it invites no one"
339            );
340            assert_eq!(params(&root.actions[0]), ["view", "mode"]);
341            offer_resource(&mut root);
342            assert_eq!(root.actions.len(), 1, "offered once");
343
344            let mut viewed = tilo_actions::ResourceSpec::new("notes", "notes.page", "Page").with_view(
345                tilo_actions::ResourceViewSpec::new("page", "Page", "open-page"),
346            );
347            offer_resource(&mut viewed);
348            let ids: Vec<_> = viewed.actions.iter().map(|spec| spec.id.as_str()).collect();
349            assert_eq!(ids, [SHARE_LINK, SHARE_INVITE_LINK]);
350        }
351
352        phase a_resource_with_a_view_offers_both_and_range_params_only_with_a_range;
353        {
354            let mut plain =
355                tilo_actions::ResourceSpec::new("notes.page:1", "notes.page", "Page").with_view(
356                    tilo_actions::ResourceViewSpec::new("page", "Page", "open-page"),
357                );
358            offer(&mut plain);
359            let ids: Vec<_> = plain.actions.iter().map(|spec| spec.id.as_str()).collect();
360            assert_eq!(ids, [SHARE_LINK, SHARE_INVITE_LINK]);
361            assert_eq!(params(&plain.actions[0]), ["view", "mode"]);
362            assert_eq!(
363                params(&plain.actions[1]),
364                ["view", "mode", "role", "expires_in"]
365            );
366
367            let mut ranged = tilo_actions::ResourceSpec::new("notes.page:2", "notes.page", "Page")
368                .with_view(
369                    tilo_actions::ResourceViewSpec::new("page", "Page", "open-page")
370                        .with_range(tilo_actions::ResourceViewRangeSpec::new("open-page-range")),
371                );
372            offer(&mut ranged);
373            assert_eq!(
374                params(&ranged.actions[0]),
375                ["view", "start", "end", "unit", "mode"]
376            );
377            offer(&mut ranged);
378            assert_eq!(ranged.actions.len(), 2, "offered once");
379
380            let mut viewless = tilo_actions::ResourceSpec::new("notes.tag:1", "notes.tag", "Tag");
381            offer(&mut viewless);
382            assert!(viewless.actions.is_empty());
383        }
384    }
385}