craft-esign: add the e-sign contract and craft-ui's esign feature

This carries over crates/esign and craft-ui's esign dialog from the cut-down #160 branch, with minimal workspace wiring. The esign dialog speaks only craft_cloud::Contact and craft_esign types. This also brings crates/cloud along as a dependency until PR #160 lands on main.
This commit is contained in:
William Dunn committed 2026-11-07 08:26:29 -05:00
1 parent fd5e2feff6
commit 0a937efeac
16 files changed
+1904

No files matched your search

Generated
+20
View File
@@ -800,6 +800,14 @@ dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-cloud"
version = "0.1.0"
dependencies = [
"serde",
"thiserror 2.0.21",
]
[[package]]
name = "craft-cms"
version = "0.1.0"
@@ -860,6 +868,16 @@ dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-esign"
version = "0.1.0"
dependencies = [
"craft-cloud",
"serde",
"serde_json",
"thiserror 2.0.21",
]
[[package]]
name = "craft-font-catalog"
version = "0.1.0"
@@ -1131,6 +1149,8 @@ dependencies = [
name = "craft-ui"
version = "0.1.0"
dependencies = [
"craft-cloud",
"craft-esign",
"craft-fonts-build",
"craft-i18n",
"eframe",
+2
View File
@@ -24,12 +24,14 @@ bytemuck = "1"
kurbo = "0.13"
thiserror = "2"
craft-atomic = { path = "crates/atomic" }
craft-cloud = { path = "crates/cloud" }
craft-cms = { path = "crates/cms" }
craft-crw = { path = "crates/crw" }
craft-dialogs = { path = "crates/dialogs" }
craft-doc = { path = "crates/doc" }
craft-docpath = { path = "crates/docpath" }
craft-ecproj-format = { path = "crates/ecproj-format" }
craft-esign = { path = "crates/esign" }
craft-font-catalog = { path = "crates/font-catalog" }
craft-font-manager = { path = "crates/font-manager" }
craft-font-store = { path = "crates/font-store" }
+15
View File
@@ -0,0 +1,15 @@
[package]
name = "craft-cloud"
version.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
rust-version.workspace = true
description = "What a cloud provider offers the Craft apps: files, sharing, contacts, notifications and mail as contracts, with no vendor and no IO"
[lints]
workspace = true
[dependencies]
serde = { workspace = true }
thiserror = { workspace = true }
+68
View File
@@ -0,0 +1,68 @@
//! One error type for every contract.
//!
//! The cases are the ones a caller acts on differently. A UI shows a different
//! thing for "you may not" than for "the server is unreachable", and a save
//! retries on a conflict where it would not on a refusal.
use thiserror::Error;
#[derive(Debug, Error)]
pub enum Error {
/// The provider could not be reached. Worth retrying.
#[error("the provider could not be reached: {0}")]
Unreachable(String),
/// The credential was rejected. The user has to sign in again.
#[error("the provider rejected the credential")]
Unauthenticated,
/// Authenticated, and not allowed to do this. Signing in again will not
/// help, so a UI must not offer it.
#[error("not permitted: {0}")]
Forbidden(String),
/// No such document, folder or share.
#[error("{what} not found: {id}")]
NotFound { what: &'static str, id: String },
/// The document changed since the caller last read it. A save that would
/// have overwritten somebody else's work lands here.
#[error("{0} changed since you opened it")]
Conflict(String),
/// The provider does not offer this at all.
///
/// Distinct from [`Error::Forbidden`]: there is nothing to grant. A UI
/// hides the feature rather than explaining it.
#[error("this provider does not support {0}")]
Unsupported(&'static str),
/// The answer did not match the protocol.
#[error("malformed {what}: {detail}")]
Malformed { what: &'static str, detail: String },
/// A name or path could not be used safely. Carried, never panicked.
#[error("invalid {what}: {detail}")]
Invalid { what: &'static str, detail: String },
}
impl Error {
pub fn not_found(what: &'static str, id: impl Into<String>) -> Error {
Error::NotFound { what, id: id.into() }
}
pub fn malformed(what: &'static str, detail: impl Into<String>) -> Error {
Error::Malformed { what, detail: detail.into() }
}
pub fn invalid(what: &'static str, detail: impl Into<String>) -> Error {
Error::Invalid { what, detail: detail.into() }
}
/// Whether trying again could succeed without the user doing anything.
pub fn is_transient(&self) -> bool {
matches!(self, Error::Unreachable(_))
}
}
pub type Result<T> = std::result::Result<T, Error>;
+189
View File
@@ -0,0 +1,189 @@
//! What a cloud provider has to offer the Craft apps, and nothing about who
//! provides it.
//!
//! Every capability here is an RFC or an ordinary HTTP API that many systems
//! implement. Files are WebDAV. Contacts are CardDAV. Calendars are CalDAV.
//! Sharing and notification are the only genuinely vendor-shaped parts, and
//! they are small. So there is no reason for an app to know which server it is
//! talking to, and no reason to write the same logic again for the next one.
//!
//! Nothing in this crate opens a socket. Each trait is implemented by a
//! provider crate that brings its own transport, which keeps this testable
//! with no server and keeps the contracts honest about what they need.
//!
//! No type here names a vendor. If a field only makes sense for one product,
//! it belongs in that provider's crate.
//!
//! Nothing here says where an implementation runs. A local adapter may
//! implement these traits against a provider directly, and an application may
//! consume them that way. The contracts do not care.
//!
//! CollabCraft chooses otherwise for its own apps. They reach one service, and
//! that service is the single place a provider is configured, a credential is
//! held and a permission is decided. A desktop binary carrying a provider
//! credential leaks one the moment somebody copies the file, which is what
//! that arrangement exists to prevent. It is a deployment policy, and this
//! crate imposes it on nobody.
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
mod error;
mod types;
pub use error::{Error, Result};
pub use types::{
Capability, Contact, Conversation, Entry, EntryKind, Identity, MailMessage, Notification, Permission, Share, ShareOptions, ShareTarget,
};
/// Reading and writing documents.
///
/// `list` and `shared_with_me` are separate because they answer different
/// questions. One is a folder's contents, the other is everything another
/// person has given this user access to, which has no single parent folder.
pub trait Files {
/// One folder's contents. An empty path means the user's root.
fn list(&self, path: &str) -> Result<Vec<Entry>>;
/// Everything shared with this user, wherever it lives.
///
/// A provider with no concept of this returns an empty list rather than an
/// error, because "nobody has shared anything with you" and "this server
/// cannot tell you" look the same to a file picker.
fn shared_with_me(&self) -> Result<Vec<Entry>>;
/// One document's bytes.
fn read(&self, id: &str) -> Result<Vec<u8>>;
/// A byte range of one document.
///
/// Defaulted to a full [`read`] and a slice, so providers that have no
/// ranged GET still satisfy the trait. A provider with real range support
/// overrides this.
fn read_range(&self, id: &str, offset: u64, length: u64) -> Result<Vec<u8>> {
let bytes = self.read(id)?;
let start = usize::try_from(offset).unwrap_or(usize::MAX);
if start >= bytes.len() {
return Ok(Vec::new());
}
let take = usize::try_from(length).unwrap_or(usize::MAX);
let end = start.saturating_add(take).min(bytes.len());
Ok(bytes[start..end].to_vec())
}
/// Replace one document's bytes.
///
/// `if_match` carries the etag the caller last saw. A provider that
/// supports conditional writes uses it to refuse a save that would
/// overwrite somebody else's, returning [`Error::Conflict`]. Passing
/// `None` means "write regardless", which is what a Save As does.
fn write(&self, id: &str, bytes: &[u8], if_match: Option<&str>) -> Result<Entry>;
/// Create a document and return it.
fn create(&self, folder: &str, name: &str, bytes: &[u8]) -> Result<Entry>;
/// One document's metadata, without its bytes.
fn stat(&self, id: &str) -> Result<Entry>;
}
/// Giving other people access to a document.
///
/// Persisting a share through the provider matters more than it looks. A share
/// recorded only by the caller would be invisible in the provider's own file
/// manager, so the two would disagree about who can open what. The provider
/// stays the authority.
pub trait Sharing {
/// Share a document.
///
/// A link share has no recipient, so [`ShareTarget::Link`] is how a caller
/// asks for one. The returned [`Share::url`] is what to hand out.
fn share(&self, id: &str, with: &ShareTarget, permission: Permission, options: &ShareOptions) -> Result<Share>;
/// Who currently has access.
fn shares(&self, id: &str) -> Result<Vec<Share>>;
/// Withdraw one share.
fn unshare(&self, share_id: &str) -> Result<()>;
}
/// Looking people up, for a share dialog's autocomplete.
///
/// This is the only thing the share dialog needs, so it is the only thing the
/// contract exposes. A full address book API would be a bigger surface for no
/// gain.
pub trait Contacts {
/// People matching a partial name or address.
///
/// `limit` exists because this runs on every keystroke. A provider is free
/// to return fewer.
fn search(&self, query: &str, limit: usize) -> Result<Vec<Contact>>;
}
/// Telling somebody something happened.
///
/// Separate from [`Mail`] on purpose. An in-app notification is cheap, arrives
/// instantly and is read in context. An email is none of those and is the
/// right choice for somebody who is not currently in the app. A share usually
/// wants both.
pub trait Notifications {
fn notify(&self, user: &str, notification: &Notification) -> Result<()>;
}
/// Sending mail as the provider.
pub trait Mail {
fn send(&self, message: &MailMessage) -> Result<()>;
}
/// Who the caller is, according to the provider.
pub trait Accounts {
/// Resolve the signed-in user.
fn me(&self) -> Result<Identity>;
}
/// Working together on a document, through whatever the provider calls it.
///
/// Defaulted throughout. A provider without the feature writes an empty
/// `impl` and reports [`Capability::Conversation`] as absent. The caller
/// then draws no control at all.
pub trait Conversations {
/// What this provider calls the feature. `None` where it has none.
///
/// Separate from the capability on purpose. The name is a property of
/// the provider. Whether it is available is a property of the
/// instance, and an administrator decides that one.
fn conversation_name(&self) -> Option<String> {
None
}
/// Start a conversation about a document, or join the one already there.
///
/// Two people pressing the same control have to arrive in the same
/// place, so this is expected to be idempotent for a given document.
///
/// `id` is the provider's own handle and means nothing outside the
/// account it came from. A conversation is therefore keyed on the
/// provider, the account and the document together, and `self` carries
/// the first two. A document copied into another account is a different
/// document to its provider, so it gets a conversation of its own.
/// Nothing here can attach one account's thread to another's.
fn conversation(&self, _id: &str, _title: &str) -> Result<Conversation> {
Err(Error::Unsupported("conversations"))
}
}
/// Everything one provider can do.
///
/// A provider implements the capabilities it has and reports the rest as
/// absent, so a caller can hide a share button on a server with no sharing
/// rather than offering a feature that will fail.
pub trait Provider: Files + Sharing + Contacts + Notifications + Mail + Accounts + Conversations {
/// A stable identifier, such as `nextcloud`. Used in configuration and
/// logs, never shown to a user.
fn id(&self) -> &str;
/// What this provider actually supports.
fn capabilities(&self) -> Vec<Capability>;
fn supports(&self, capability: Capability) -> bool {
self.capabilities().contains(&capability)
}
}
+216
View File
@@ -0,0 +1,216 @@
//! The data the contracts pass around.
//!
//! Every type here is plain and vendor-neutral. A field that only means
//! something to one product belongs in that provider's crate.
use serde::{Deserialize, Serialize};
/// What a provider can do.
///
/// Reported rather than assumed, so a caller hides a share button on a
/// server without sharing instead of offering a feature that fails on use.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Capability {
Files,
SharedWithMe,
Sharing,
Contacts,
Notifications,
Mail,
/// Conditional writes, so a save can refuse to clobber a newer version.
Etags,
/// Public links. Absent on a server that forbids them, and the dialog then
/// offers no Copy link rather than a button that fails.
LinkShares,
/// A key on a public link. This is what most places mean when they talk
/// about sharing with somebody who has no account.
LinkPassword,
/// The server requires that key, so a link cannot be made without one.
LinkPasswordRequired,
/// An expiry date on a share.
ShareExpiry,
/// The provider can tell a recipient that something was shared with them.
///
/// Distinct from [`Capability::Mail`], which is about sending arbitrary
/// mail. A provider commonly has this and not that: it will notify the
/// person a share names without offering any way to send mail in general.
ShareNotify,
/// A conversation about a document, such as a call or a chat room.
///
/// Every provider that has this calls it something else, so the name
/// comes from [`crate::Conversations::conversation_name`]. Reported
/// separately from that name: a provider knows what it would call the
/// feature whether or not an administrator installed it.
Conversation,
}
/// A file or folder.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Entry {
/// An opaque handle for reading, writing and sharing this entry.
///
/// Only the provider that issued it may interpret it. A caller passes it
/// back and never parses it.
pub id: String,
/// The stable identity used for a collaboration room.
///
/// Separate from `id` on purpose. A provider's read and write handle is
/// often a path, and a path changes when somebody renames or moves the
/// file. A room keyed on that would silently split in two mid-session,
/// with each half seeing only its own edits. This one survives a rename.
pub room: String,
/// What to show the user.
pub name: String,
/// Where it sits, for a breadcrumb. Never a handle.
pub path: String,
pub kind: EntryKind,
/// Bytes, absent for a folder.
pub size: Option<u64>,
/// RFC 3339. Absent when the provider does not say.
pub modified: Option<String>,
/// For matching a document to the app that opens it.
pub mime: Option<String>,
/// The version the caller last saw, for a conditional write.
pub etag: Option<String>,
/// Whether this user may change it. A read-only share still lists.
pub writable: bool,
/// Who shared it, when it came from somebody else.
pub shared_by: Option<String>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum EntryKind {
File,
Folder,
}
/// A person, as a share dialog needs them.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Contact {
/// What the provider wants back when sharing with this person.
pub id: String,
/// How to share with them, decided by the provider and never guessed.
///
/// The distinction is not cosmetic. A contact with an account is a user
/// share. One known only by address is an email share. Sharing an address
/// as though it were a user id fails with "not found", because no such
/// user exists, and nothing in `id` alone says which case this is.
pub target: ShareTarget,
/// What to show. A display name where there is one.
pub name: String,
pub email: Option<String>,
/// An avatar, as a URL the client may fetch. Never image bytes: a search
/// returning ten people would otherwise carry ten pictures nobody asked
/// for yet.
pub avatar: Option<String>,
/// A group rather than a person. Shown differently and shared differently.
pub is_group: bool,
}
/// Who to share with.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "kind", content = "id")]
pub enum ShareTarget {
User(String),
Group(String),
/// Somebody with no account, reached by address.
Email(String),
/// Anybody holding the link.
Link,
}
/// What a share allows.
///
/// Deliberately coarse. Providers disagree on the fine detail, and a dialog
/// offering a distinction the server cannot keep is worse than one that does
/// not.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Permission {
/// Open and read. No edits reach the document.
View,
/// Open and edit.
Edit,
}
/// Everything optional about a share.
///
/// A struct rather than more positional arguments. The list grew past the
/// point where a call site reads correctly, and a provider that cannot honour
/// one of these needs to see which it was given.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ShareOptions {
/// Shown to the recipient.
pub note: Option<String>,
/// Send mail where the provider can.
pub notify: bool,
/// A key the recipient must present. Only meaningful for a link, and
/// refused by a server that does not allow one.
pub password: Option<String>,
/// `YYYY-MM-DD`. After this the share stops working.
pub expires: Option<String>,
}
/// Where to go to work together on a document.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Conversation {
/// Where to join. Handed to a browser, or to the provider's own app.
pub url: String,
/// What the provider calls the feature, for the control's wording. A
/// menu item reading "Work together in Talk" is built from this.
pub name: String,
}
/// A share that exists.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Share {
pub id: String,
pub target: ShareTarget,
/// What to call the recipient, where the provider says.
///
/// A share carries the handle the server wants back, which for a user is
/// an account id. People are not known to each other by account id. A
/// provider that knows the difference says so here.
pub display: Option<String>,
pub permission: Permission,
/// Present for a link share, absent otherwise.
pub url: Option<String>,
pub note: Option<String>,
/// RFC 3339.
pub created: Option<String>,
}
/// Something worth telling a user about, in the app.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Notification {
/// A short machine-readable kind, such as `document_shared`. Lets a client
/// decide how to render without parsing prose.
pub kind: String,
pub subject: String,
pub body: Option<String>,
/// Where to go when it is clicked.
pub link: Option<String>,
}
/// An email to send.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct MailMessage {
pub to: Vec<String>,
pub subject: String,
pub body: String,
/// Whether `body` is HTML. Plain text otherwise.
pub html: bool,
}
/// The signed-in user, as the provider sees them.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Identity {
/// The provider's identifier for this account.
pub id: String,
/// What to show. Never an identity: two people can share a display name.
pub display: String,
pub email: Option<String>,
pub avatar: Option<String>,
}
+19
View File
@@ -0,0 +1,19 @@
[package]
name = "craft-esign"
version.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
rust-version.workspace = true
description = "What an e-sign service offers the Craft apps: envelopes, recipients and events as contracts, with no vendor and no IO"
[lints]
workspace = true
[dependencies]
craft-cloud = { workspace = true }
serde = { workspace = true }
thiserror = { workspace = true }
[dev-dependencies]
serde_json = { workspace = true }
+63
View File
@@ -0,0 +1,63 @@
//! One error type for every e-sign contract.
//!
//! Cloud failures are wrapped so a host can surface sign-in and reachability
//! the same way it already does for files. The e-sign-only cases are the ones
//! a UI acts on differently: declined, voided, expired, identity check.
use thiserror::Error;
#[derive(Debug, Error)]
pub enum Error {
/// Something the cloud contracts already classify.
#[error(transparent)]
Cloud(#[from] craft_cloud::Error),
/// A recipient refused to sign.
#[error("declined: {0}")]
Declined(String),
/// The sender voided the envelope.
#[error("voided: {0}")]
Voided(String),
/// The envelope passed its deadline without completing.
#[error("expired: {0}")]
Expired(String),
/// The provider rejected the signer's identity check.
#[error("identity check failed: {0}")]
IdentityCheck(String),
/// The chosen provider refuses this request under its policy.
#[error("provider policy: {0}")]
ProviderPolicy(String),
/// The service does not offer this at all.
#[error("this signing service does not support {0}")]
Unsupported(&'static str),
/// The answer did not match the protocol.
#[error("malformed {what}: {detail}")]
Malformed { what: &'static str, detail: String },
/// A field the caller supplied could not be used safely.
#[error("invalid {what}: {detail}")]
Invalid { what: &'static str, detail: String },
}
impl Error {
pub fn malformed(what: &'static str, detail: impl Into<String>) -> Error {
Error::Malformed { what, detail: detail.into() }
}
pub fn invalid(what: &'static str, detail: impl Into<String>) -> Error {
Error::Invalid { what, detail: detail.into() }
}
/// Whether trying again could succeed without the user doing anything.
pub fn is_transient(&self) -> bool {
matches!(self, Error::Cloud(e) if e.is_transient())
}
}
pub type Result<T> = std::result::Result<T, Error>;
+195
View File
@@ -0,0 +1,195 @@
//! What an e-sign service has to offer the Craft apps, and nothing about who
//! provides it.
//!
//! An envelope is a ceremony: a document snapshot, a set of recipients, field
//! placements, and a status. The legal audit trail, identity checks and
//! invitation mail belong to the signing service. This crate only names the
//! contracts an app needs to create, send, watch and finish that ceremony.
//!
//! Nothing in this crate opens a socket. Each trait is implemented by a host
//! (CollabCraft, a desktop adapter, a test double) that brings its own
//! transport. No type here names a vendor. No type here knows about PDF
//! structure: a document is opaque bytes plus a content hash.
//!
//! This crate sits beside `craft-cloud`. It reuses [`craft_cloud::Identity`]
//! and the idea of a contact for autocomplete, but it does not extend
//! [`craft_cloud::Provider`] or [`craft_cloud::Capability`]. Signing is not
//! file access, and a signer role is not a share permission.
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
mod error;
mod types;
pub use error::{Error, Result};
pub use types::{
CompletedDocument, Envelope, EnvelopeDraft, EnvelopeEvent, EnvelopeStatus, EsignCapability, FieldPlacement, Recipient, RecipientStatus,
};
/// Creating and driving envelopes.
///
/// Methods that a minimal service may omit are defaulted to
/// [`Error::Unsupported`], the same pattern [`craft_cloud::Conversations`]
/// uses for optional cloud features.
pub trait Envelopes {
/// Create a draft from a document snapshot.
///
/// `document` is the exact byte sequence the ceremony seals. The
/// implementation hashes it and stores `content_sha256` on the envelope.
/// `idempotency_key` makes a retried create return the same envelope.
fn create(&self, draft: &EnvelopeDraft, document: &[u8], idempotency_key: &str) -> Result<Envelope>;
/// Send invitations and move the envelope to [`EnvelopeStatus::Sent`].
fn send(&self, envelope: &str) -> Result<Envelope>;
/// Current status, including per-recipient progress.
fn status(&self, envelope: &str) -> Result<Envelope>;
/// The finished document and provider evidence.
///
/// Fails unless status is [`EnvelopeStatus::Completed`].
fn completed(&self, envelope: &str) -> Result<CompletedDocument>;
/// Cancel an in-flight envelope.
fn void(&self, _envelope: &str, _reason: &str) -> Result<()> {
Err(Error::Unsupported("void"))
}
/// Nudge one recipient who has not signed yet.
fn remind(&self, _envelope: &str, _recipient: &str) -> Result<()> {
Err(Error::Unsupported("reminders"))
}
/// A URL the recipient opens to sign inside the provider's UI.
fn signing_url(&self, _envelope: &str, _recipient: &str, _return_to: &str) -> Result<String> {
Err(Error::Unsupported("embedded signing"))
}
}
/// Turning provider webhooks into [`EnvelopeEvent`]s.
///
/// Server-side only. A desktop host that implements [`Envelopes`] never needs
/// a webhook secret and need not implement this beyond refusing.
pub trait EventIntake {
/// Verify authenticity and parse zero or more events from one HTTP body.
fn verify_event(&self, headers: &[(String, String)], body: &[u8]) -> Result<Vec<EnvelopeEvent>>;
}
/// Everything one signing service can do.
///
/// A service implements the capabilities it has and reports the rest as
/// absent, so a caller can hide void on a stub that only supports the happy
/// path rather than offering a control that fails on use.
pub trait SigningService: Envelopes + EventIntake {
/// A stable identifier, such as `stub` or `documenso`. Used in
/// configuration and logs, never shown to a user.
fn id(&self) -> &str;
/// What this service actually supports.
fn capabilities(&self) -> Vec<EsignCapability>;
fn supports(&self, capability: EsignCapability) -> bool {
self.capabilities().contains(&capability)
}
/// The party that holds legal and compliance responsibility for the
/// ceremony. Shown to senders before they send (upstream #2315).
fn responsible_party(&self) -> String;
}
#[cfg(test)]
mod tests {
use super::*;
use craft_cloud::Identity;
struct RefuseAll;
impl Envelopes for RefuseAll {
fn create(&self, _: &EnvelopeDraft, _: &[u8], _: &str) -> Result<Envelope> {
Err(Error::Unsupported("create"))
}
fn send(&self, _: &str) -> Result<Envelope> {
Err(Error::Unsupported("send"))
}
fn status(&self, _: &str) -> Result<Envelope> {
Err(Error::Unsupported("status"))
}
fn completed(&self, _: &str) -> Result<CompletedDocument> {
Err(Error::Unsupported("completed"))
}
}
impl EventIntake for RefuseAll {
fn verify_event(&self, _: &[(String, String)], _: &[u8]) -> Result<Vec<EnvelopeEvent>> {
Err(Error::Unsupported("webhooks"))
}
}
impl SigningService for RefuseAll {
fn id(&self) -> &str {
"refuse"
}
fn capabilities(&self) -> Vec<EsignCapability> {
Vec::new()
}
fn responsible_party(&self) -> String {
"nobody".into()
}
}
#[test]
fn defaulted_methods_are_unsupported() {
let s = RefuseAll;
assert!(matches!(s.void("e", "x"), Err(Error::Unsupported("void"))));
assert!(matches!(s.remind("e", "r"), Err(Error::Unsupported("reminders"))));
assert!(matches!(s.signing_url("e", "r", "https://example"), Err(Error::Unsupported("embedded signing"))));
assert!(!s.supports(EsignCapability::Envelopes));
assert_eq!(s.responsible_party(), "nobody");
}
#[test]
fn draft_round_trips_json() {
let draft = EnvelopeDraft {
title: "NDA".into(),
message: Some("please sign".into()),
sender: Identity { id: "u1".into(), display: "Ada".into(), email: Some("ada@example.com".into()), avatar: None },
document_id: Some("doc-1".into()),
document_etag: Some("\"abc\"".into()),
recipients: vec![Recipient {
id: "r1".into(),
name: "Bob".into(),
email: "bob@example.com".into(),
role: "Signer".into(),
required: true,
status: RecipientStatus::Pending,
}],
placements: vec![FieldPlacement {
role: "Signer".into(),
page: 0,
x: 0.1,
y: 0.2,
w: 0.3,
h: 0.05,
kind: "signature".into(),
required: true,
}],
expires: Some("2026-12-31".into()),
};
let json = serde_json::to_string(&draft).expect("serialize");
let back: EnvelopeDraft = serde_json::from_str(&json).expect("deserialize");
assert_eq!(back, draft);
}
#[test]
fn cloud_errors_wrap_and_report_transient() {
let err = Error::from(craft_cloud::Error::Unreachable("down".into()));
assert!(err.is_transient());
let err = Error::Declined("no".into());
assert!(!err.is_transient());
}
}
+172
View File
@@ -0,0 +1,172 @@
//! The data the e-sign contracts pass around.
//!
//! Every type here is plain and vendor-neutral. A field that only means
//! something to one product belongs in that provider's crate. Nothing here
//! knows about PDF structure; a document is opaque bytes plus a content hash.
use craft_cloud::Identity;
use serde::{Deserialize, Serialize};
/// What a signing service can do.
///
/// Reported rather than assumed, so a caller hides void or remind on a service
/// that only supports create/send/status/completed.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum EsignCapability {
/// Create, send, poll status, and fetch the completed document.
Envelopes,
/// Cancel an in-flight envelope.
Void,
/// Nudge a recipient who has not signed yet.
Reminders,
/// Return a URL the recipient opens to sign in the provider's UI.
EmbeddedSigning,
/// Accept provider webhooks and turn them into [`EnvelopeEvent`]s.
Webhooks,
}
/// Where an envelope is in its life.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum EnvelopeStatus {
/// Created but not yet sent to recipients.
Draft,
/// At least one recipient still owes a signature.
Sent,
/// Every required recipient has signed.
Completed,
/// The sender cancelled it.
Voided,
/// A recipient declined.
Declined,
/// The deadline passed without completion.
Expired,
}
/// What one recipient still owes, or has done.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RecipientStatus {
Pending,
Viewed,
Signed,
Declined,
}
/// Who must sign, as the dialog and the service agree.
///
/// Built from a [`craft_cloud::Contact`] by an explicit conversion at the host
/// boundary. Never a [`craft_cloud::ShareTarget`]: signing is not access.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Recipient {
/// Opaque handle the service wants back.
pub id: String,
/// What to show. A display name where there is one.
pub name: String,
/// Delivery address. Required for invitation mail.
pub email: String,
/// Signer role label, such as "Client" or "Countersign". Colours and
/// field placement key off this string within one envelope.
pub role: String,
/// Whether the envelope cannot complete without this person.
pub required: bool,
pub status: RecipientStatus,
}
/// One signature (or initials / date) placement on the document.
///
/// Coordinates are normalised page space: origin top-left, `x`/`y`/`w`/`h` in
/// `[0.0, 1.0]` of the page. The document implementation maps these onto its
/// own field model; this crate never sees PDF objects.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct FieldPlacement {
/// Recipient role this field belongs to.
pub role: String,
/// Zero-based page index.
pub page: u32,
pub x: f32,
pub y: f32,
pub w: f32,
pub h: f32,
/// Machine-readable kind: `signature`, `initials`, `date`, `text`.
pub kind: String,
pub required: bool,
}
impl PartialEq for FieldPlacement {
fn eq(&self, other: &Self) -> bool {
self.role == other.role
&& self.page == other.page
&& self.kind == other.kind
&& self.required == other.required
&& self.x.to_bits() == other.x.to_bits()
&& self.y.to_bits() == other.y.to_bits()
&& self.w.to_bits() == other.w.to_bits()
&& self.h.to_bits() == other.h.to_bits()
}
}
impl Eq for FieldPlacement {}
/// What the caller wants to send, before the service assigns an id.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct EnvelopeDraft {
/// Human title for the ceremony.
pub title: String,
/// Optional note shown to recipients.
pub message: Option<String>,
/// Who is asking for signatures. Bound to the active account at send time.
pub sender: Identity,
/// Cloud document identity at the moment of the snapshot, when known.
pub document_id: Option<String>,
pub document_etag: Option<String>,
pub recipients: Vec<Recipient>,
pub placements: Vec<FieldPlacement>,
/// `YYYY-MM-DD`. After this the envelope expires if still open.
pub expires: Option<String>,
}
/// An envelope the service knows about.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Envelope {
pub id: String,
pub title: String,
pub message: Option<String>,
pub sender: Identity,
pub document_id: Option<String>,
pub document_etag: Option<String>,
/// SHA-256 of the document bytes at create time, lowercase hex.
pub content_sha256: String,
pub recipients: Vec<Recipient>,
pub placements: Vec<FieldPlacement>,
pub status: EnvelopeStatus,
pub expires: Option<String>,
/// RFC 3339.
pub created: Option<String>,
/// RFC 3339 when status became [`EnvelopeStatus::Completed`].
pub completed_at: Option<String>,
}
/// The finished document plus whatever evidence the provider returns.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct CompletedDocument {
pub envelope_id: String,
/// Signed document bytes. Opaque to this crate.
pub bytes: Vec<u8>,
/// Provider evidence (certificate of completion, audit export, …).
pub evidence: Vec<u8>,
}
/// Something that happened to an envelope.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct EnvelopeEvent {
pub envelope_id: String,
/// Machine-readable kind: `sent`, `viewed`, `signed`, `declined`, `voided`, `completed`.
pub kind: String,
/// Recipient id when the event is about one person.
pub recipient_id: Option<String>,
/// RFC 3339.
pub at: Option<String>,
pub detail: Option<String>,
}
+6
View File
@@ -19,6 +19,10 @@ log = "0.4"
serde = { version = "1", features = ["derive"], optional = true }
# Same version as epaint's, for reading a face's character map.
skrifa = { version = "0.44", default-features = false, features = ["std"] }
# The vendor-neutral vocabulary the e-sign dialog speaks. No IO and no
# vendor, so this stays buildable for the web.
craft-cloud = { workspace = true, optional = true }
craft-esign = { workspace = true, optional = true }
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
# Screenshot and input tests of an app's screens (the screen-testing feature).
@@ -54,6 +58,8 @@ testing = []
# craft_ui::testing: per-language screenshot tests and IME smoke tests with egui_kittest
# (desktop only).
screen-testing = ["dep:egui_kittest"]
# Request-signatures dialog.
esign = ["dep:craft-cloud", "dep:craft-esign"]
[dev-dependencies]
# serde: the IME tests read events that only the suite's egui fork has from JSON.
+15
View File
@@ -120,3 +120,18 @@ fn bounded_stroke(stroke: Stroke, rect: Rect) -> Stroke {
#[cfg(test)]
mod tests;
/// A downward triangle at the right-hand end of a control.
///
/// Painted rather than typed. The chevron character is absent from the default
/// font set, where it renders as a missing-glyph box. A caller leaves room for
/// it by padding the label, then paints it over the response.
pub fn chevron(ui: &Ui, rect: egui::Rect, colour: egui::Color32) {
let middle = rect.right_center() - egui::vec2(9.0, 0.0);
let half = 3.5;
ui.painter().add(egui::Shape::convex_polygon(
vec![middle + egui::vec2(-half, -half * 0.6), middle + egui::vec2(half, -half * 0.6), middle + egui::vec2(0.0, half * 0.9)],
colour,
egui::Stroke::NONE,
));
}
+92
View File
@@ -0,0 +1,92 @@
//! Where the e-sign dialog's work happens, which is never on the frame.
//!
//! Same shape as [`crate::share::ShareBackend`]: the dialog states what it
//! wants, something behind this trait does the waiting, and answers arrive on
//! a channel keyed by sequence number.
use craft_cloud::Contact;
use craft_esign::{CompletedDocument, Envelope, EnvelopeDraft, EsignCapability};
/// One thing the dialog needs done.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Request {
/// What the signing service can actually do, and who is legally responsible.
Capabilities,
/// People matching what has been typed so far (cloud contacts).
Lookup { query: String, limit: usize },
/// Create a draft from a document snapshot, then optionally send it.
Create { draft: Box<EnvelopeDraft>, document: Vec<u8>, idempotency_key: String, send: bool },
/// Current status of one envelope.
Status { envelope: String },
/// Finished document bytes.
Completed { envelope: String },
/// Cancel an in-flight envelope.
Void { envelope: String, reason: String },
/// Nudge one recipient.
Remind { envelope: String, recipient: String },
}
/// What came back.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Answer {
Capabilities {
capabilities: Vec<EsignCapability>,
responsible_party: String,
/// Whether a cloud account is attached so invitations can leave.
linked: bool,
},
Lookup(Vec<Contact>),
Created(Envelope),
Status(Envelope),
Completed(CompletedDocument),
Voided {
envelope: String,
},
Reminded {
envelope: String,
recipient: String,
},
}
/// Where one answer goes.
pub struct Replier {
seq: u64,
tx: std::sync::mpsc::Sender<(u64, Result<Answer, String>)>,
}
impl Replier {
pub(crate) fn new(seq: u64, tx: std::sync::mpsc::Sender<(u64, Result<Answer, String>)>) -> Replier {
Replier { seq, tx }
}
pub fn seq(&self) -> u64 {
self.seq
}
pub fn dup(&self) -> Replier {
Replier { seq: self.seq, tx: self.tx.clone() }
}
pub fn answer(self, answer: Answer) {
self.deliver(Ok(answer));
}
pub fn refuse(self, reason: impl Into<String>) {
self.deliver(Err(reason.into()));
}
fn deliver(self, result: Result<Answer, String>) {
let _ = self.tx.send((self.seq, result));
}
}
impl std::fmt::Debug for Replier {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Replier").field("seq", &self.seq).finish()
}
}
/// Somewhere a [`Request`] can run without blocking a frame.
pub trait EsignBackend {
fn submit(&self, request: Request, reply: Replier);
}
+607
View File
@@ -0,0 +1,607 @@
//! Request-signatures dialog, the same one in every Craft app that sends PDFs.
//!
//! Nothing here opens a socket. Every call goes through [`EsignBackend`].
//! Nothing here blocks: answers arrive on a channel and are read once per
//! frame. Signing is not sharing: recipients are never [`craft_cloud::ShareTarget`]s.
use std::sync::mpsc::{Receiver, Sender};
use std::time::Duration;
use craft_cloud::{Contact, Identity};
use craft_esign::{Envelope, EnvelopeDraft, EnvelopeStatus, EsignCapability, FieldPlacement, Recipient, RecipientStatus};
use egui::{Context, RichText, Ui};
mod backend;
pub use backend::{Answer, EsignBackend, Replier, Request};
/// How long after the last keystroke the dialog asks for matches.
pub const DEBOUNCE: Duration = Duration::from_millis(200);
const MATCHES: usize = 8;
const MIN_QUERY: usize = 2;
const RETRY: f64 = 20.0;
type Inbox = (u64, Result<Answer, String>);
/// Every string the dialog shows.
#[derive(Clone, Debug)]
pub struct EsignLabels {
pub title: String,
pub recipients: String,
pub recipient_hint: String,
pub searching: String,
pub no_matches: String,
pub add_address: String,
pub role: String,
pub message: String,
pub send: String,
pub sending: String,
pub close: String,
pub loading: String,
pub responsible: String,
pub no_service: String,
pub sign_in_first: String,
pub need_recipient: String,
pub status: String,
pub void: String,
pub remind: String,
pub download: String,
pub request: String,
}
impl Default for EsignLabels {
fn default() -> EsignLabels {
EsignLabels {
title: "Request signatures".into(),
recipients: "Signers".into(),
recipient_hint: "Name or email".into(),
searching: "Searching…".into(),
no_matches: "No matches".into(),
add_address: "Add email address".into(),
role: "Role".into(),
message: "Message".into(),
send: "Send".into(),
sending: "Sending…".into(),
close: "Close".into(),
loading: "Loading…".into(),
responsible: "Signing is provided by {party}. That party holds legal and compliance responsibility for the ceremony.".into(),
no_service: "Signatures cannot be requested here.".into(),
sign_in_first: "Sign in to request signatures.".into(),
need_recipient: "Add at least one signer.".into(),
status: "Status".into(),
void: "Void".into(),
remind: "Remind".into(),
download: "Download completed".into(),
request: "Request signatures".into(),
}
}
}
/// What the application must supply when the user presses Send.
///
/// The dialog holds recipients and copy; the application owns the document
/// bytes and encodes them, then submits [`Request::Create`] through the backend.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SendRequest {
pub draft: EnvelopeDraft,
pub idempotency_key: String,
}
/// One Request signatures dialog.
pub struct EsignDialog {
open: bool,
labels: EsignLabels,
backend: Option<Box<dyn EsignBackend>>,
capabilities: Option<Vec<EsignCapability>>,
responsible: Option<String>,
linked: bool,
asked_caps_at: Option<f64>,
caps_seq: Option<u64>,
draft_idempotency_key: Option<String>,
seq: u64,
tx: Sender<Inbox>,
rx: Receiver<Inbox>,
newest: u64,
document_id: String,
document_etag: Option<String>,
document_title: String,
sender: Option<Identity>,
query: String,
query_changed_at: f64,
lookup_seq: u64,
last_lookup_query: String,
matches: Vec<Contact>,
looking: bool,
recipients: Vec<Recipient>,
message: String,
placements: Vec<FieldPlacement>,
busy: bool,
error: Option<String>,
envelope: Option<Envelope>,
send_out: Option<SendRequest>,
completed_bytes: Option<Vec<u8>>,
account_fingerprint: Option<String>,
}
impl Default for EsignDialog {
fn default() -> EsignDialog {
let (tx, rx) = std::sync::mpsc::channel();
EsignDialog {
open: false,
labels: EsignLabels::default(),
backend: None,
capabilities: None,
responsible: None,
linked: false,
asked_caps_at: None,
caps_seq: None,
draft_idempotency_key: None,
seq: 0,
tx,
rx,
newest: 0,
document_id: String::new(),
document_etag: None,
document_title: String::new(),
sender: None,
query: String::new(),
query_changed_at: 0.0,
lookup_seq: 0,
last_lookup_query: String::new(),
matches: Vec::new(),
looking: false,
recipients: Vec::new(),
message: String::new(),
placements: Vec::new(),
busy: false,
error: None,
envelope: None,
send_out: None,
completed_bytes: None,
account_fingerprint: None,
}
}
}
impl EsignDialog {
pub fn new() -> EsignDialog {
EsignDialog::default()
}
pub fn labels(mut self, labels: EsignLabels) -> EsignDialog {
self.labels = labels;
self
}
pub fn set_backend(&mut self, backend: impl EsignBackend + 'static) {
self.backend = Some(Box::new(backend));
self.capabilities = None;
self.asked_caps_at = None;
self.caps_seq = None;
}
/// False until the service reports [`EsignCapability::Envelopes`].
pub fn available(&self) -> bool {
self.capabilities.as_ref().is_some_and(|c| c.contains(&EsignCapability::Envelopes))
}
pub fn is_open(&self) -> bool {
self.open
}
/// Open for a document. `sender` is the active account identity.
pub fn open(&mut self, document_id: String, document_title: String, document_etag: Option<String>, sender: Identity) {
let fingerprint = format!("{}@{}", sender.id, sender.email.as_deref().unwrap_or(""));
let account_changed = self.account_fingerprint.as_deref() != Some(fingerprint.as_str());
let document_changed = self.document_id != document_id;
if account_changed || document_changed {
self.recipients.clear();
self.message.clear();
self.envelope = None;
self.completed_bytes = None;
self.error = None;
self.draft_idempotency_key = None;
}
self.account_fingerprint = Some(fingerprint);
self.document_id = document_id;
self.document_title = document_title;
self.document_etag = document_etag;
self.sender = Some(sender);
self.open = true;
self.query.clear();
self.matches.clear();
}
pub fn close(&mut self) {
self.open = false;
}
/// Field placements the app prepared (page-normalised). Replaces any prior set.
pub fn set_placements(&mut self, placements: Vec<FieldPlacement>) {
self.placements = placements;
}
/// What Send asked the application to encode and submit, if anything.
pub fn take_send_request(&mut self) -> Option<SendRequest> {
self.send_out.take()
}
/// Submit a request through the host backend (for example after the app
/// encoded document bytes for a [`SendRequest`]).
pub fn submit_request(&mut self, request: Request) {
let _ = self.submit(request);
}
/// Completed document bytes after a successful download request.
pub fn take_completed_bytes(&mut self) -> Option<Vec<u8>> {
self.completed_bytes.take()
}
/// Tell the dialog create/send finished (or failed) after the app submitted.
pub fn note_create_result(&mut self, result: Result<Envelope, String>) {
self.busy = false;
match result {
Ok(env) => {
self.envelope = Some(env);
self.error = None;
}
Err(reason) => self.error = Some(reason),
}
}
fn submit(&mut self, request: Request) -> u64 {
self.seq = self.seq.saturating_add(1);
let seq = self.seq;
self.newest = seq;
if let Some(backend) = self.backend.as_ref() {
backend.submit(request, Replier::new(seq, self.tx.clone()));
} else {
let _ = self.tx.send((seq, Err("no e-sign backend".into())));
}
seq
}
fn pump(&mut self, now: f64) {
while let Ok((seq, result)) = self.rx.try_recv() {
if self.caps_seq == Some(seq) {
self.caps_seq = None;
}
if seq < self.newest && !matches!(result, Ok(Answer::Capabilities { .. })) {
// Stale lookup or status; keep capabilities even if older.
if !matches!(&result, Ok(Answer::Lookup(_))) {
continue;
}
if seq != self.lookup_seq {
continue;
}
}
match result {
Ok(Answer::Capabilities { capabilities, responsible_party, linked }) => {
self.capabilities = Some(capabilities);
self.responsible = Some(responsible_party);
self.linked = linked;
}
Ok(Answer::Lookup(contacts)) if seq == self.lookup_seq => {
self.matches = contacts;
self.looking = false;
}
Ok(Answer::Created(env)) | Ok(Answer::Status(env)) => {
self.busy = false;
self.envelope = Some(env);
self.error = None;
}
Ok(Answer::Completed(doc)) => {
self.busy = false;
self.completed_bytes = Some(doc.bytes);
self.error = None;
}
Ok(Answer::Voided { .. }) => {
self.busy = false;
if let Some(env) = self.envelope.as_mut() {
env.status = EnvelopeStatus::Voided;
}
}
Ok(Answer::Reminded { .. }) => {
self.busy = false;
}
Err(reason) => {
self.busy = false;
self.looking = false;
self.error = Some(reason);
}
_ => {}
}
}
if self.backend.is_some() && self.caps_seq.is_none() {
let first = self.capabilities.is_none() && self.asked_caps_at.is_none();
let retry = self.asked_caps_at.is_some_and(|asked| !self.available() && now - asked >= RETRY);
if first || retry {
self.asked_caps_at = Some(now);
self.caps_seq = Some(self.submit(Request::Capabilities));
}
}
}
fn maybe_lookup(&mut self, now: f64) {
if !self.open || self.query.len() < MIN_QUERY {
return;
}
if (now - self.query_changed_at) < DEBOUNCE.as_secs_f64() {
return;
}
if self.looking || self.last_lookup_query == self.query {
return;
}
self.looking = true;
self.last_lookup_query = self.query.clone();
self.lookup_seq = self.submit(Request::Lookup { query: self.query.clone(), limit: MATCHES });
}
fn add_contact(&mut self, contact: Contact) {
let email = contact.email.clone().unwrap_or_else(|| contact.id.clone());
if self.recipients.iter().any(|r| r.email.eq_ignore_ascii_case(&email)) {
return;
}
let role = format!("Signer {}", self.recipients.len() + 1);
self.recipients.push(Recipient { id: contact.id, name: contact.name, email, role, required: true, status: RecipientStatus::Pending });
self.draft_idempotency_key = None;
self.query.clear();
self.matches.clear();
}
fn add_email(&mut self, email: String) {
let email = email.trim().to_string();
if email.is_empty() || !email.contains('@') {
return;
}
if self.recipients.iter().any(|r| r.email.eq_ignore_ascii_case(&email)) {
return;
}
let role = format!("Signer {}", self.recipients.len() + 1);
self.recipients.push(Recipient { id: email.clone(), name: email.clone(), email, role, required: true, status: RecipientStatus::Pending });
self.draft_idempotency_key = None;
self.query.clear();
self.matches.clear();
}
fn queue_send(&mut self) {
let Some(sender) = self.sender.clone() else {
self.error = Some(self.labels.sign_in_first.clone());
return;
};
if self.recipients.is_empty() {
self.error = Some(self.labels.need_recipient.clone());
return;
}
if !self.linked {
self.error = Some(self.labels.sign_in_first.clone());
return;
}
let draft = EnvelopeDraft {
title: if self.document_title.is_empty() { "Document".into() } else { self.document_title.clone() },
message: if self.message.trim().is_empty() { None } else { Some(self.message.clone()) },
sender,
document_id: if self.document_id.is_empty() { None } else { Some(self.document_id.clone()) },
document_etag: self.document_etag.clone(),
recipients: self.recipients.clone(),
placements: self.placements.clone(),
expires: None,
};
if self.draft_idempotency_key.is_none() {
self.draft_idempotency_key = Some(format!("esign-{}-{}", self.document_id, self.seq.saturating_add(1)));
}
let idempotency_key = self.draft_idempotency_key.clone().unwrap_or_default();
self.busy = true;
self.error = None;
self.send_out = Some(SendRequest { draft, idempotency_key });
}
/// Draw the dialog when open. Call every frame (even when closed) so
/// capability probes and inbox pumping continue.
pub fn show(&mut self, ctx: &Context) {
let now = ctx.input(|i| i.time);
self.pump(now);
if self.open {
self.maybe_lookup(now);
}
if !self.open {
return;
}
let mut open = self.open;
let labels = self.labels.clone();
egui::Window::new(&labels.title).open(&mut open).resizable(true).default_width(420.0).show(ctx, |ui| {
self.ui(ui);
});
self.open = open;
}
fn ui(&mut self, ui: &mut Ui) {
if let Some(err) = &self.error {
ui.colored_label(ui.visuals().error_fg_color, err);
ui.add_space(4.0);
}
if !self.available() {
ui.label(if self.capabilities.is_none() { self.labels.loading.as_str() } else { self.labels.no_service.as_str() });
return;
}
if let Some(party) = &self.responsible {
ui.label(RichText::new(self.labels.responsible.replace("{party}", party)).small());
ui.add_space(6.0);
}
if let Some(env) = self.envelope.clone() {
self.status_panel(ui, &env);
return;
}
ui.label(RichText::new(&self.document_title).strong());
ui.add_space(4.0);
ui.label(&self.labels.recipients);
let response = ui.add(egui::TextEdit::singleline(&mut self.query).hint_text(&self.labels.recipient_hint));
if response.changed() {
self.query_changed_at = ui.input(|i| i.time);
self.matches.clear();
self.looking = false;
self.lookup_seq = 0;
self.last_lookup_query.clear();
}
if self.looking {
ui.spinner();
ui.label(&self.labels.searching);
} else if self.query.len() >= MIN_QUERY && self.matches.is_empty() {
ui.horizontal(|ui| {
ui.label(&self.labels.no_matches);
if ui.button(&self.labels.add_address).clicked() {
self.add_email(self.query.clone());
}
});
}
for contact in self.matches.clone() {
let label = match &contact.email {
Some(email) => format!("{} <{}>", contact.name, email),
None => contact.name.clone(),
};
if ui.selectable_label(false, label).clicked() {
self.add_contact(contact);
}
}
ui.add_space(4.0);
let mut remove: Option<usize> = None;
for (i, recipient) in self.recipients.iter().enumerate() {
ui.horizontal(|ui| {
ui.label(format!("{} — {}", recipient.name, recipient.email));
ui.label(RichText::new(&recipient.role).small());
if ui.small_button("×").clicked() {
remove = Some(i);
}
});
}
if let Some(i) = remove {
self.recipients.remove(i);
self.draft_idempotency_key = None;
}
ui.add_space(6.0);
ui.label(&self.labels.message);
let message = ui.add(egui::TextEdit::multiline(&mut self.message).desired_rows(3));
if message.changed() {
self.draft_idempotency_key = None;
}
ui.add_space(8.0);
ui.horizontal(|ui| {
let can_send = !self.busy && self.linked && !self.recipients.is_empty();
if ui.add_enabled(can_send, egui::Button::new(if self.busy { &self.labels.sending } else { &self.labels.send })).clicked() {
self.queue_send();
}
if ui.button(&self.labels.close).clicked() {
self.open = false;
}
});
}
fn status_panel(&mut self, ui: &mut Ui, env: &Envelope) {
ui.label(RichText::new(&env.title).strong());
ui.label(format!("{}: {:?}", self.labels.status, env.status));
for r in &env.recipients {
ui.label(format!("{} — {:?} ({})", r.name, r.status, r.role));
}
ui.add_space(8.0);
ui.horizontal(|ui| {
let caps = self.capabilities.clone().unwrap_or_default();
if caps.contains(&EsignCapability::Reminders)
&& ui.add_enabled(!self.busy, egui::Button::new(&self.labels.remind)).clicked()
&& let Some(r) = env.recipients.iter().find(|r| r.status == RecipientStatus::Pending)
{
self.busy = true;
let _ = self.submit(Request::Remind { envelope: env.id.clone(), recipient: r.id.clone() });
}
if caps.contains(&EsignCapability::Void)
&& env.status == EnvelopeStatus::Sent
&& ui.add_enabled(!self.busy, egui::Button::new(&self.labels.void)).clicked()
{
self.busy = true;
let _ = self.submit(Request::Void { envelope: env.id.clone(), reason: "voided by sender".into() });
}
if env.status == EnvelopeStatus::Completed && ui.add_enabled(!self.busy, egui::Button::new(&self.labels.download)).clicked() {
self.busy = true;
let _ = self.submit(Request::Completed { envelope: env.id.clone() });
}
if ui.button(&self.labels.close).clicked() {
self.open = false;
}
});
if ui.button("Refresh status").clicked() {
self.busy = true;
let _ = self.submit(Request::Status { envelope: env.id.clone() });
}
}
}
/// Split button that opens the request-signatures dialog.
///
/// `open` is called when the primary action is chosen. The chevron offers
/// status refresh when an envelope id is known.
pub fn request_button(ui: &mut Ui, labels: &EsignLabels, available: bool, menu: &[crate::menu::MenuItem]) -> Option<crate::menu::SplitHit> {
if !available {
return None;
}
let menu_labels = crate::menu::MenuLabels::default();
crate::menu::split(ui, &labels.request, menu, &menu_labels)
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::{Arc, Mutex};
struct Capture {
last: Mutex<Option<Request>>,
}
impl EsignBackend for Arc<Capture> {
fn submit(&self, request: Request, reply: Replier) {
*self.last.lock().expect("lock") = Some(request);
reply.answer(Answer::Capabilities {
capabilities: vec![EsignCapability::Envelopes, EsignCapability::Void],
responsible_party: "Stub Signing".into(),
linked: true,
});
}
}
#[test]
fn available_after_capabilities() {
let capture = Arc::new(Capture { last: Mutex::new(None) });
let mut dialog = EsignDialog::default();
dialog.set_backend(capture);
let ctx = Context::default();
dialog.show(&ctx);
dialog.show(&ctx);
assert!(dialog.available());
assert_eq!(dialog.responsible.as_deref(), Some("Stub Signing"));
}
#[test]
fn send_request_needs_recipient_and_sender() {
let mut dialog = EsignDialog {
linked: true,
sender: Some(Identity { id: "u".into(), display: "Ada".into(), email: Some("ada@example.com".into()), avatar: None }),
..Default::default()
};
dialog.queue_send();
assert!(dialog.take_send_request().is_none());
dialog.add_email("bob@example.com".into());
dialog.queue_send();
let req = dialog.take_send_request().expect("send");
assert_eq!(req.draft.recipients.len(), 1);
assert_eq!(req.draft.recipients[0].email, "bob@example.com");
}
}
+3
View File
@@ -10,12 +10,15 @@ pub mod capture;
pub mod combo;
pub mod direction;
pub mod docking;
#[cfg(feature = "esign")]
pub mod esign;
mod focus;
pub mod fonts;
pub mod icons;
pub mod ime;
pub mod layout;
pub mod localized;
pub mod menu;
pub mod panes;
pub mod printing;
pub mod tabs;
+222
View File
@@ -0,0 +1,222 @@
//! The two controls that offer more than one action.
//!
//! An overflow menu is the `…` that holds what did not earn a place on the
//! toolbar. A split button is a primary action with a chevron beside it, where
//! the chevron offers the variations. Share is the usual example. Most of the
//! time a person wants to share, and once in a while they want to copy a link
//! or start a call about the document instead.
//!
//! They are one module because they are the same control underneath. Building
//! them twice would mean getting the accessible naming right twice, and an
//! icon-only button that announces itself as an ellipsis character is useless
//! to anybody reading the screen rather than looking at it.
//!
//! Neither control knows what any item does. Each answers with the identifier
//! of the item a person chose. The application holds the meaning.
use egui::{Response, RichText, Ui};
/// One line in a menu.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct MenuItem {
/// What the caller recognises this by. Never shown.
pub id: String,
pub label: String,
/// A second line, smaller. Worth having where the label alone leaves a
/// person guessing what the action will do to their document.
pub detail: Option<String>,
/// A leading glyph. Decoration only, so it is never the accessible name.
pub icon: Option<String>,
pub enabled: bool,
/// Draw a rule above this item. A group of related actions reads as a
/// group only when something separates it from the last one.
pub separator_before: bool,
}
impl MenuItem {
pub fn new(id: impl Into<String>, label: impl Into<String>) -> MenuItem {
MenuItem { id: id.into(), label: label.into(), enabled: true, ..MenuItem::default() }
}
pub fn detail(mut self, detail: impl Into<String>) -> MenuItem {
self.detail = Some(detail.into());
self
}
pub fn icon(mut self, icon: impl Into<String>) -> MenuItem {
self.icon = Some(icon.into());
self
}
/// Present but unavailable, with a reason on hover.
///
/// Greying an item out says the action exists and is not possible now.
/// Removing it says the action does not exist. They are different facts and
/// a person reads them differently.
pub fn disabled(mut self, why: impl Into<String>) -> MenuItem {
self.enabled = false;
self.detail = Some(why.into());
self
}
pub fn separated(mut self) -> MenuItem {
self.separator_before = true;
self
}
}
/// What a person did to a split button.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum SplitHit {
/// They pressed the button itself.
Primary,
/// They chose something from the chevron's menu.
Item(String),
}
/// The accessible name of the chevron, and of the overflow button.
///
/// Public so an application can translate them. A glyph is not a name, and
/// these two are the only strings in this module that are not supplied by the
/// caller.
#[derive(Clone, Debug)]
pub struct MenuLabels {
/// The `…` button.
pub more: String,
/// The chevron on a split button. `{action}` is replaced with the primary
/// action's own label, so a screen reader says "more share options" rather
/// than "more options" on a toolbar holding four of them.
pub more_for: String,
}
impl Default for MenuLabels {
fn default() -> MenuLabels {
MenuLabels { more: "More options".into(), more_for: "More {action} options".into() }
}
}
/// The `…` button and its menu.
///
/// Answers with the identifier of the item chosen, if any.
pub fn overflow(ui: &mut Ui, items: &[MenuItem], labels: &MenuLabels) -> Option<String> {
// A horizontal ellipsis, not three periods. Three periods are three
// characters to anything reading the screen aloud.
let button = egui::Button::new(RichText::new("\u{2026}").size(15.0)).frame(false);
let hit = ui.add(button);
let name = labels.more.clone();
hit.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, name.as_str()));
let hit = hit.on_hover_text(labels.more.as_str());
items_of(&hit, items)
}
/// A primary action with a chevron beside it.
///
/// The two halves are two controls. Pressing the label does the thing. Pressing
/// the chevron offers the variations. One control that did both would leave a
/// person guessing which half they had hit.
pub fn split(ui: &mut Ui, primary: &str, items: &[MenuItem], labels: &MenuLabels) -> Option<SplitHit> {
let mut hit = None;
ui.horizontal(|ui| {
// The halves touch, so they read as one control with two parts. Square
// off the inside corners as well. Two default radii leave a pair of
// notches at the seam, which reads as two buttons that happen to abut.
ui.spacing_mut().item_spacing.x = 0.0;
let radius = ui.visuals().widgets.inactive.corner_radius;
// A toolbar that fills from its right edge hands this control a
// right-to-left layout, and whatever is added first lands furthest
// right. The label still belongs before the chevron, so the halves are
// added in the order that puts them there.
let backwards = ui.layout().main_dir() == egui::Direction::RightToLeft;
let (outer, inner) = if backwards {
(egui::CornerRadius { nw: 0, sw: 0, ..radius }, egui::CornerRadius { ne: 0, se: 0, ..radius })
} else {
(egui::CornerRadius { ne: 0, se: 0, ..radius }, egui::CornerRadius { nw: 0, sw: 0, ..radius })
};
let label = |ui: &mut Ui, hit: &mut Option<SplitHit>| {
if ui.add(egui::Button::new(primary).corner_radius(if backwards { inner } else { outer })).clicked() {
*hit = Some(SplitHit::Primary);
}
};
let chevron = |ui: &mut Ui, hit: &mut Option<SplitHit>| {
// Room for the triangle, which is painted rather than typed.
let more = ui.add(egui::Button::new(" ").corner_radius(if backwards { outer } else { inner }));
crate::buttons::chevron(ui, more.rect, ui.visuals().text_color());
let name = labels.more_for.replace("{action}", &primary.to_lowercase());
more.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, name.as_str()));
let more = more.on_hover_text(name.as_str());
if let Some(id) = items_of(&more, items) {
*hit = Some(SplitHit::Item(id));
}
};
if backwards {
chevron(ui, &mut hit);
label(ui, &mut hit);
} else {
label(ui, &mut hit);
chevron(ui, &mut hit);
}
});
hit
}
/// The menu both controls open.
fn items_of(anchor: &Response, items: &[MenuItem]) -> Option<String> {
let mut chosen = None;
egui::Popup::menu(anchor).show(|ui| {
ui.set_min_width(210.0);
let weak = ui.visuals().weak_text_color();
for item in items {
if item.separator_before {
ui.separator();
}
let label = match &item.icon {
Some(icon) => format!("{icon} {}", item.label),
None => item.label.clone(),
};
let row = ui.add_enabled(item.enabled, egui::Button::new(label).frame(false));
// The icon is decoration. The name is the label alone.
let name = item.label.clone();
let enabled = item.enabled;
row.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, enabled, name.as_str()));
if row.clicked() {
chosen = Some(item.id.clone());
ui.close();
}
if let Some(detail) = &item.detail {
ui.label(RichText::new(detail.as_str()).small().color(weak));
ui.add_space(2.0);
}
}
});
chosen
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn an_item_is_enabled_until_it_is_not() {
assert!(MenuItem::new("copy", "Copy link").enabled);
let off = MenuItem::new("copy", "Copy link").disabled("this server forbids public links");
assert!(!off.enabled);
assert_eq!(off.detail.as_deref(), Some("this server forbids public links"));
}
#[test]
fn the_chevrons_name_says_which_action_it_belongs_to() {
let labels = MenuLabels::default();
assert_eq!(labels.more_for.replace("{action}", "share"), "More share options");
}
#[test]
fn a_builder_keeps_what_it_was_given() {
let item = MenuItem::new("talk", "Work together").icon("\u{1f4de}").detail("Start a call").separated();
assert_eq!(item.id, "talk");
assert_eq!(item.label, "Work together");
assert_eq!(item.icon.as_deref(), Some("\u{1f4de}"));
assert_eq!(item.detail.as_deref(), Some("Start a call"));
assert!(item.separator_before);
assert!(item.enabled);
}
}