use std::sync::Arc;
use serde::{Deserialize, Serialize};
use tilo_actions::{
ActionKind, ActionParam, ActionSpec, ActionType, EncodedAction, ExecutionMode, OperationKind,
ParamType, ResultSpec, Target,
};
pub const SHARE_LINK: &str = tilo_actions::remote::SHARE_LINK_ACTION;
pub const SHARE_INVITE_LINK: &str = "share-invite-link";
#[must_use]
pub fn is_share_verb(action: &str) -> bool {
action == SHARE_LINK || action == SHARE_INVITE_LINK
}
#[must_use]
pub fn handles(type_id: &str) -> bool {
type_id == SHARE_TYPE || type_id == SHARE_INVITE_TYPE
}
#[must_use]
pub fn share_link_target(
provider: impl Into<String>,
resource: impl Into<String>,
) -> tilo_actions::remote::RemoteActionTarget {
tilo_actions::remote::RemoteActionTarget {
provider: provider.into(),
address: tilo_actions::ActionAddress::new(resource, SHARE_LINK),
}
}
#[must_use]
pub fn share_link_address(resource: impl Into<String>) -> tilo_actions::ActionAddress {
tilo_actions::ActionAddress::new(resource, SHARE_LINK)
}
pub const SHARE_TYPE: &str = "tilo.resource.share-link";
pub const SHARE_INVITE_TYPE: &str = "tilo.resource.share-invite-link";
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct SharedView {
pub id: String,
pub primary: bool,
pub range: bool,
#[serde(default)]
pub desktop: bool,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ShareRequest {
pub resource: String,
pub kind: String,
pub views: Vec<SharedView>,
pub invite: bool,
pub args: serde_json::Map<String, serde_json::Value>,
}
pub fn offer(resource: &mut tilo_actions::ResourceSpec) {
if resource.views.is_empty() || resource.actions.iter().any(|spec| is_share_verb(&spec.id)) {
return;
}
let views = shared_views(resource);
let target = Target::new(resource.id.as_str().to_owned());
for invite in [false, true] {
let ty = share_type(invite, &resource.kind, &views);
resource.actions.push(ty.bind(target.clone()));
}
}
pub fn offer_resource(root: &mut tilo_actions::ResourceSpec) {
offer(root);
if root.actions.iter().any(|spec| spec.id == SHARE_LINK) {
return;
}
let target = Target::new(root.id.as_str().to_owned());
root.actions
.push(share_type(false, &root.kind, &[]).bind(target));
}
pub fn offer_link(resource: &mut tilo_actions::ResourceSpec) {
if resource.views.is_empty() || resource.actions.iter().any(|spec| spec.id == SHARE_LINK) {
return;
}
let views = shared_views(resource);
let target = Target::new(resource.id.as_str().to_owned());
resource
.actions
.push(share_type(false, &resource.kind, &views).bind(target));
}
pub fn offer_resource_link(root: &mut tilo_actions::ResourceSpec) {
offer_link(root);
if root.actions.iter().any(|spec| spec.id == SHARE_LINK) {
return;
}
let target = Target::new(root.id.as_str().to_owned());
root.actions
.push(share_type(false, &root.kind, &[]).bind(target));
}
fn shared_views(resource: &tilo_actions::ResourceSpec) -> Vec<SharedView> {
resource
.views
.iter()
.map(|view| SharedView {
id: view.id.clone(),
primary: view.primary,
range: view.range.is_some(),
desktop: view.desktop,
})
.collect()
}
type ShareKey = (bool, String, Vec<SharedView>);
fn share_type(invite: bool, kind: &str, views: &[SharedView]) -> Arc<ActionType> {
thread_local! {
static KEPT: std::cell::RefCell<crate::kept::KeptTypes<ShareKey>> =
std::cell::RefCell::default();
}
let key = (invite, kind.to_owned(), views.to_vec());
crate::kept::kept_type(&KEPT, key, || {
Arc::clone(spec(invite, kind.to_owned(), views.to_vec()).action_type())
})
}
pub fn offer_tree(resource: &mut tilo_actions::ResourceSpec) {
offer(resource);
for child in &mut resource.children {
offer_tree(child);
}
}
pub fn reoffer(resource: &mut tilo_actions::ResourceSpec) {
resource.actions.retain(|spec| !is_share_verb(&spec.id));
offer(resource);
}
fn params(invite: bool, views: &[SharedView]) -> Vec<ActionParam> {
let ranged = views.iter().any(|view| view.range);
let mut params = vec![
ActionParam::optional(
"view",
ParamType::Text,
"Which declared view the link opens (default: the primary view)",
)
.with_choices(views.iter().map(|view| view.id.clone()))
.nullable(),
];
if ranged {
params.extend([
ActionParam::optional(
"start",
ParamType::Integer,
"Where the linked range of the text starts",
)
.nullable(),
ActionParam::optional(
"end",
ParamType::Integer,
"Where the linked range of the text ends",
)
.nullable(),
ActionParam::optional(
"unit",
ParamType::Text,
"What start and end count (default: chars)",
)
.with_choices(["chars", "bytes"])
.nullable(),
]);
}
params.push(
ActionParam::optional(
"mode",
ParamType::Text,
"app opens it alone in a full browser tab, desktop on the workspace's desktop (default: app)",
)
.with_choices(["app", "desktop"])
.nullable(),
);
if invite {
params.extend([
ActionParam::optional(
"role",
ParamType::Text,
"The role the invitation carries (default: viewer)",
)
.with_choices(["viewer", "commenter", "editor"])
.nullable(),
ActionParam::optional(
"expires_in",
ParamType::Integer,
"Seconds until the invitation can no longer be redeemed",
)
.nullable(),
]);
}
params
}
fn spec(invite: bool, kind: String, views: Vec<SharedView>) -> ActionSpec {
let params = params(invite, &views);
let (id, label, type_id, action_kind, description) = if invite {
(
SHARE_INVITE_LINK,
"Share invite link",
SHARE_INVITE_TYPE,
ActionKind::Outside,
"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.",
)
} else {
(
SHARE_LINK,
"Copy link",
SHARE_TYPE,
ActionKind::Read,
"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.",
)
};
let mut spec = ActionSpec::typed_operation_on(
id,
label,
label,
OperationKind::Effect,
type_id,
params,
Arc::new(move |target, args| {
let request = ShareRequest {
resource: target.get::<String>().cloned().unwrap_or_default(),
kind: kind.clone(),
views: views.clone(),
invite,
args: args.to_json(),
};
EncodedAction::encode_operation(type_id, &request).unwrap_or_else(|_| EncodedAction {
type_id: type_id.into(),
payload: Vec::new(),
})
}),
)
.of_kind(action_kind)
.with_description(description);
let contract = &mut spec.type_mut().contract;
contract.execution = ExecutionMode::Background { cancellable: true };
contract.result = ResultSpec::Json {
schema: serde_json::json!({
"type": "object",
"properties": {"url": {"type": "string"}},
"required": ["url"],
}),
};
spec
}
pub use tilo_actions::outside_document::{
admits_outside_document, outside_document, resolved_outside_document,
};
#[cfg(test)]
mod tests {
use super::*;
fn params(spec: &ActionSpec) -> Vec<String> {
spec.params()
.iter()
.map(|param| param.name.to_string())
.collect()
}
tilo_test_env::scenario! {
fn a_resource_offers_its_link_and_its_views;
phase a_record_root_offers_its_link_without_a_view;
{
let mut root = tilo_actions::ResourceSpec::new("pdf", "pdf.document", "PDF");
offer(&mut root);
assert!(
root.actions.is_empty(),
"a resource without a view has no link"
);
offer_resource(&mut root);
let ids: Vec<_> = root.actions.iter().map(|spec| spec.id.as_str()).collect();
assert_eq!(
ids,
[SHARE_LINK],
"the record opens in its app; it invites no one"
);
assert_eq!(params(&root.actions[0]), ["view", "mode"]);
offer_resource(&mut root);
assert_eq!(root.actions.len(), 1, "offered once");
let mut viewed = tilo_actions::ResourceSpec::new("notes", "notes.page", "Page").with_view(
tilo_actions::ResourceViewSpec::new("page", "Page", "open-page"),
);
offer_resource(&mut viewed);
let ids: Vec<_> = viewed.actions.iter().map(|spec| spec.id.as_str()).collect();
assert_eq!(ids, [SHARE_LINK, SHARE_INVITE_LINK]);
}
phase a_resource_with_a_view_offers_both_and_range_params_only_with_a_range;
{
let mut plain =
tilo_actions::ResourceSpec::new("notes.page:1", "notes.page", "Page").with_view(
tilo_actions::ResourceViewSpec::new("page", "Page", "open-page"),
);
offer(&mut plain);
let ids: Vec<_> = plain.actions.iter().map(|spec| spec.id.as_str()).collect();
assert_eq!(ids, [SHARE_LINK, SHARE_INVITE_LINK]);
assert_eq!(params(&plain.actions[0]), ["view", "mode"]);
assert_eq!(
params(&plain.actions[1]),
["view", "mode", "role", "expires_in"]
);
let mut ranged = tilo_actions::ResourceSpec::new("notes.page:2", "notes.page", "Page")
.with_view(
tilo_actions::ResourceViewSpec::new("page", "Page", "open-page")
.with_range(tilo_actions::ResourceViewRangeSpec::new("open-page-range")),
);
offer(&mut ranged);
assert_eq!(
params(&ranged.actions[0]),
["view", "start", "end", "unit", "mode"]
);
offer(&mut ranged);
assert_eq!(ranged.actions.len(), 2, "offered once");
let mut viewless = tilo_actions::ResourceSpec::new("notes.tag:1", "notes.tag", "Tag");
offer(&mut viewless);
assert!(viewless.actions.is_empty());
}
}
}