# Sharing

> Invite people and set who can view or edit.

Page: https://uicontext.com/docs/components/sharing

Group: Documents.

## When to use

Invite people and set who can view or edit. Use [Members](https://uicontext.com/docs/components/members.md) instead when you manage a workspace's people, not one item's access.

## Usage

```ts
import type { Outcome } from "./ui/uicontext/components/domain/Outcome.ts"
import { Share, type ShareCandidate, type ShareEntry } from "./ui/uicontext/components/Share.ts"

const Message = UiSchema.TaggedEnum({
	RequestedShareAdd: { id: Schema.String, role: Schema.String },
	RequestedShareInvite: { request: Schema.String, emails: Schema.Array(Schema.String), role: Schema.String },
	RequestedShareRole: { id: Schema.String, role: Schema.String },
	RequestedShareRemove: { id: Schema.String },
})

// every change is a request; the app answers through `outcomes` and sends the new entries back
export const PageSharing = (
	h: Html.H<typeof Message.Type>,
	page: { readonly title: string; readonly entries: ReadonlyArray<ShareEntry>; readonly members: ReadonlyArray<ShareCandidate>; readonly outcomes: ReadonlyArray<Outcome> },
) =>
	Share(h, {
		props: {
			objectName: page.title,
			roles: [{ value: "view", label: "Can view" }, { value: "edit", label: "Can edit" }],
			entries: page.entries,
			candidates: page.members,
			inviteEmails: true,
			can: ["manage"],
			outcomes: page.outcomes,
		},
		onEmit: (e) =>
			e._tag === "RequestedAdd" ? Message.RequestedShareAdd({ id: e.id, role: e.role })
			: e._tag === "RequestedInvite" ? Message.RequestedShareInvite({ request: e.request, emails: e.emails, role: e.role })
			: e._tag === "RequestedRole" ? Message.RequestedShareRole({ id: e.id, role: e.role })
			: e._tag === "RequestedRemove" ? Message.RequestedShareRemove({ id: e.id })
			: undefined,
	})
```

## Examples

Each example is a complete file. Its imports point where the CLI installs the source.

### Share a page

The example the page opens with: Sharing in “Share a page”.

```ts title="src/demo.ts" source="www/src/examples/sharing/demo.ts"
import { Command, UiSchema } from "effect/ui"
import { Html } from "effect/ui/html"
import * as stylex from "@stylexjs/stylex"
import { Effect, Schema } from "effect"
import { Outcome } from "./ui/uicontext/components/domain/Outcome.ts"
import { Share, ShareEntry } from "./ui/uicontext/components/Share.ts"
import { sx } from "./ui/uicontext/components/Sx.ts"
import { candidates, entries, generalOptions, link, roles } from "./people.ts"

// Sharing a spec. Type a name or paste a list of addresses; a pretend server takes a moment and
// refuses addresses outside northwind.example, as a workspace that only invites its own domain would.

const styles = stylex.create({ frame: { inlineSize: "min(100%, 34rem)" } })

const Change = Schema.Struct({
	request: Schema.String,
	kind: Schema.Literals(["add", "invite", "role", "remove", "general"]),
	id: Schema.String,
	role: Schema.String,
	emails: Schema.Array(Schema.String),
})
type Change = typeof Change.Type

const Message = UiSchema.TaggedEnum({ Requested: { change: Change }, Answered: { change: Change } })

// stands in for the server
const Send = Command.make("SendShareChange", { args: { change: Change } }, ({ change }) =>
	Effect.sleep("700 millis").pipe(Effect.as(Message.Answered({ change }))),
)

const outside = (email: string) => !email.toLowerCase().endsWith("@northwind.example")
const nameOf = (email: string) => email.split("@")[0]!.replace(/^./u, (c) => c.toUpperCase())

export const ShareSpec = Html.component({
	name: "ShareSpec",
	model: Schema.Struct({
		entries: Schema.Array(ShareEntry),
		general: Schema.String,
		generalRole: Schema.String,
		outcomes: Schema.Array(Outcome),
	}),
	message: Message,
}).make({
	init: () => ({ entries, general: "invited", generalRole: "view", outcomes: [] }),
	update: {
		Requested: ($, { change }) =>
			$.evolve({ outcomes: (o) => [...o.filter((x) => x.request !== change.request).slice(-20), { _tag: "Pending" as const, request: change.request }] }).run(
				Send.make({ change }),
			),
		Answered: ($, { change }) => {
			const settle = (outcome: Outcome) => (o: ReadonlyArray<Outcome>) => [...o.filter((x) => x.request !== change.request), outcome]
			const refusedEmails = change.emails.filter(outside)
			if (change.kind === "invite" && refusedEmails.length > 0) {
				return $.evolve({
					outcomes: settle({ _tag: "Refused", request: change.request, reason: `Northwind Freight only invites northwind.example addresses (${refusedEmails.join(", ")}).` }),
				})
			}
			const accepted = settle({ _tag: "Accepted", request: change.request })
			switch (change.kind) {
				case "add": {
					const who = candidates.find((c) => c.id === change.id)!
					return $.evolve({ outcomes: accepted, entries: (all) => [...all, { ...who, role: change.role }] })
				}
				case "invite":
					return $.evolve({
						outcomes: accepted,
						entries: (all) => [
							...all,
							...change.emails.map((email) => ({ id: email, name: nameOf(email), detail: `${email} · Invited`, kind: "person" as const, role: change.role })),
						],
					})
				case "role":
					return $.evolve({ outcomes: accepted, entries: (all) => all.map((e) => (e.id === change.id ? { ...e, role: change.role } : e)) })
				case "remove":
					return $.evolve({ outcomes: accepted, entries: (all) => all.filter((e) => e.id !== change.id) })
				case "general":
					return $.evolve({ outcomes: accepted, general: change.id, generalRole: change.role })
			}
		},
	},
	view: (h, model) => {
		const change = (c: Omit<Change, "emails" | "role"> & Partial<Pick<Change, "emails" | "role">>) =>
			Message.Requested({ change: { emails: [], role: "", ...c } })
		return h.div.attrs(sx(styles.frame)).children(
			Share(h, {
				props: {
					agentId: "share-demo",
					objectName: "Checkout retries",
					roles,
					maxRole: "full",
					defaultRole: "edit",
					entries: model.entries,
					candidates: candidates.filter((c) => !model.entries.some((e) => e.id === c.id)),
					inviteEmails: true,
					general: { value: model.general, role: model.generalRole, options: generalOptions },
					can: ["manage"],
					keepOne: { role: "full", message: "A page needs someone with full access." },
					outcomes: model.outcomes,
					link,
				},
				onEmit: {
					RequestedAdd: ({ id, role }) => change({ request: id, kind: "add", id, role }),
					RequestedInvite: ({ request, emails, role }) => change({ request, kind: "invite", id: request, role, emails }),
					RequestedRole: ({ id, role }) => change({ request: id, kind: "role", id, role }),
					RequestedRemove: ({ id }) => change({ request: id, kind: "remove", id }),
					RequestedGeneral: ({ value, role }) => change({ request: "general", kind: "general", id: value, role: role ?? model.generalRole }),
					RequestedInviteLink: () => undefined,
					RequestedClose: () => undefined,
				},
			}),
		)
	},
})
```

### In a dialog

`layout: "dialog"` with `open`; Escape, a press outside and Done all ask to close with `RequestedClose`.

```ts title="src/dialog.ts" source="www/src/examples/sharing/dialog.ts"
import { UiSchema } from "effect/ui"
import { Html } from "effect/ui/html"
import { Schema } from "effect"
import { Button } from "./ui/uicontext/components/Button.ts"
import { Share, ShareEntry } from "./ui/uicontext/components/Share.ts"
import { candidates, entries, generalOptions, link, roles } from "./people.ts"

// The usual place for sharing: a Share button in the page header opens it as a dialog.

const Message = UiSchema.TaggedEnum({
	ToggledShare: { open: Schema.Boolean },
	Added: { id: Schema.String, role: Schema.String },
	Changed: { id: Schema.String, role: Schema.String },
	Removed: { id: Schema.String },
})

export const ShareDialog = Html.component({
	name: "ShareDialog",
	model: Schema.Struct({ open: Schema.Boolean, entries: Schema.Array(ShareEntry) }),
	message: Message,
}).make({
	init: () => ({ open: false, entries }),
	update: {
		ToggledShare: ($, { open }) => $.evolve({ open }),
		// accepted at once here; a real app sends each change and passes `outcomes`
		Added: ($, { id, role }) => {
			const who = candidates.find((c) => c.id === id)
			return who === undefined ? $.model : $.evolve({ entries: (all) => [...all, { ...who, role }] })
		},
		Changed: ($, { id, role }) => $.evolve({ entries: (all) => all.map((e) => (e.id === id ? { ...e, role } : e)) }),
		Removed: ($, { id }) => $.evolve({ entries: (all) => all.filter((e) => e.id !== id) }),
	},
	view: (h, model) =>
		h.div.children(
			Button(h, { tone: "primary" }).on("click", Message.ToggledShare({ open: true })).children("Share"),
			Share(h, {
				props: {
					agentId: "share-dialog",
					objectName: "Checkout retries",
					roles,
					defaultRole: "comment",
					entries: model.entries,
					candidates: candidates.filter((c) => !model.entries.some((e) => e.id === c.id)),
					general: { value: "invited", role: "view", options: generalOptions },
					can: ["manage"],
					keepOne: { role: "full", message: "A page needs someone with full access." },
					link,
					layout: "dialog",
					open: model.open,
				},
				onEmit: {
					RequestedAdd: ({ id, role }) => Message.Added({ id, role }),
					RequestedInvite: () => undefined,
					RequestedRole: ({ id, role }) => Message.Changed({ id, role }),
					RequestedRemove: ({ id }) => Message.Removed({ id }),
					RequestedGeneral: () => undefined,
					RequestedInviteLink: () => undefined,
					RequestedClose: () => Message.ToggledShare({ open: false }),
				},
			}),
		),
})
```

### Read-only

Without `manage` in `can`, roles show as badges and `readOnlyReason` says who can change them.

```ts title="src/read-only.ts" source="www/src/examples/sharing/read-only.ts"
import type { Html } from "effect/ui/html"
import * as stylex from "@stylexjs/stylex"
import { Share } from "./ui/uicontext/components/Share.ts"
import { sx } from "./ui/uicontext/components/Sx.ts"
import { entries, generalOptions, link, roles } from "./people.ts"

// What someone with "Can view" sees: who has access and how wide it goes, with nothing to change.

const styles = stylex.create({ frame: { inlineSize: "min(100%, 34rem)" } })

export const SharedWithMe = <M>(h: Html.H<M>) =>
	h.div.attrs(sx(styles.frame)).children(
		Share(h, {
			props: {
				agentId: "share-read-only",
				objectName: "Checkout retries",
				title: "Who can see this page",
				roles,
				entries: entries.map((e) => ({ ...e, you: e.id === "scout" })),
				general: { value: "workspace", role: "comment", options: generalOptions },
				can: [],
				readOnlyReason: "Only people with full access can change sharing. Ask Ada Lovelace.",
				link,
			},
			onEmit: {
				RequestedAdd: () => undefined,
				RequestedInvite: () => undefined,
				RequestedRole: () => undefined,
				RequestedRemove: () => undefined,
				RequestedGeneral: () => undefined,
				RequestedInviteLink: () => undefined,
				RequestedClose: () => undefined,
			},
		}),
	)
```

### Sample data

The examples above import these files.

```ts title="src/people.ts" source="www/src/examples/sharing/people.ts"
import type { ShareCandidate, ShareEntry, ShareProps } from "./ui/uicontext/components/Share.ts"

// Who can open the "Checkout retries" spec at Northwind Freight, and who else is in the workspace.

export const roles: ShareProps["roles"] = [
	{ value: "view", label: "Can view", description: "Read and copy" },
	{ value: "comment", label: "Can comment", description: "Read and discuss" },
	{ value: "edit", label: "Can edit", description: "Change the page" },
	{ value: "full", label: "Full access", description: "Edit and share" },
]

export const entries: ReadonlyArray<ShareEntry> = [
	{ id: "ada", name: "Ada Lovelace", detail: "ada@northwind.example", kind: "person", role: "full", lockedReason: "Owner", you: true },
	{ id: "ben", name: "Ben Okafor", detail: "ben@northwind.example", kind: "person", role: "edit" },
	{
		id: "payments",
		name: "Payments team",
		detail: "6 members",
		kind: "group",
		role: "comment",
		source: "Inherited from Engineering",
		lockedReason: "Change it on Engineering",
	},
	{ id: "scout", name: "Scout", detail: "Agent · acts with this access", kind: "agent", role: "view" },
]

export const candidates: ReadonlyArray<ShareCandidate> = [
	{ id: "mira", name: "Mira Patel", detail: "mira@northwind.example", kind: "person" },
	{ id: "theo", name: "Theo Robinson", detail: "theo@northwind.example", kind: "person" },
	{ id: "maya", name: "Maya Chen", detail: "maya@northwind.example", kind: "person" },
	{ id: "support", name: "Support", detail: "23 members", kind: "group" },
	{ id: "relay", name: "Relay", detail: "Agent", kind: "agent" },
]

export const generalOptions: NonNullable<ShareProps["general"]>["options"] = [
	{ value: "invited", label: "Only people invited", description: "Only the people above can open it." },
	{ value: "workspace", label: "Everyone at Northwind Freight", description: "Anyone in the workspace can find and open it." },
	{ value: "link", label: "Anyone with the link", description: "Anyone who has the link can open it, no sign-in needed." },
]

export const link = "https://docs.northwind.example/p/checkout-retries"
```

## API reference

### Share (component)

**Props**

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `agentId` | `string` | — | This share control's id for agents, unique on the page: "share-page-q3" |
| `objectName` (required) | `string` | — | What is shared: "Q3 plan" |
| `title` | `string` | `Share "<objectName>"` | "Share", "Share this agent"; `Share "<objectName>"` by default |
| `roles` (required) | `RoleOption[]` | — | The roles that can be given, from least to most access: "Can view", "Can edit" |
| `maxRole` | `string` | — | The most the person may grant, by value; roles above it are disabled |
| `entries` (required) | `ShareEntry[]` | — | The people, groups and domains that have access now, each with a role |
| `candidates` | `ShareCandidate[]` | — | Who can be added; empty or left out hides the add row unless `inviteEmails` is on |
| `inviteEmails` | `boolean` | — | People outside `candidates` can be invited by typing or pasting their email addresses |
| `defaultRole` | `string` | — | The role a new entry gets unless the person picks another |
| `general` | `{ value, options, role }` | — | Who else can open it, from narrowest to widest |
| `can` (required) | `Can(["manage"])` | — | What the person may do: "manage" changes sharing; without it everything is read-only with `readOnlyReason` |
| `readOnlyReason` | `string` | — | Why sharing can't be changed here, shown when `can` leaves out "manage" |
| `keepOne` | `{ role, message }` | — | At least one entry must keep this role: { role: "owner", message: "A workspace needs at least one owner." } |
| `note` | `string` | — | A line about what sharing means here: "People who run the agent get its access, not their own." |
| `applying` | `string` | — | A change is still being applied: "Applying to 12 subfolders…" |
| `outcomes` | `Outcome[]` | — | The app's answers to requests, one per request. The request id is the entry's (or candidate's) id for `RequestedAdd`, `RequestedRole` and `RequestedRemove`, "general" for `RequestedGeneral` and "invite-link" for `RequestedInviteLink`. A pending entry is busy, a pending "invite-link" says the link is being made, and the newest refusal shows its reason. |
| `link` | `string` | — | A link to the object, to copy |
| `invite` | `{ label, url, note }` | — | An invitation link: anyone who opens it can join. "Create invite link" asks the app (`RequestedInviteLink`); once the app has made one it passes `url` and the person copies it. |
| `layout` | `"dialog" \| "inline"` | — | A native modal dialog (with `open`) or inline on the page |
| `open` | `boolean` | — | Whether the dialog is showing, with the `dialog` layout; closing it comes back as `RequestedClose` |

**Events**

| Event | Payload | Description |
| --- | --- | --- |
| `RequestedAdd` | `{ id: string; role: string }` | Give this person or group access with this role |
| `RequestedRole` | `{ id: string; role: string }` | Change the role of someone who already has access |
| `RequestedRemove` | `{ id: string }` | Take away this person's or group's access |
| `RequestedGeneral` | `{ value: string; role?: string }` | Change who else can open it, to this general access option; `role` when its role changes |
| `RequestedInvite` | `{ request: string; emails: string[]; role: string }` | Invite people by email at this role; answer through `outcomes` with the same request |
| `RequestedInviteLink` | `{}` | Make an invitation link; send it back as `invite.url` |
| `RequestedClose` | `{}` | The person closed the dialog |

**Agent actions**

| Action | Description |
| --- | --- |
| `AddedEntry` (asks first) | Share with a candidate (id from page_query) at a role. Target: { id, role: null }. |
| `ChangedRole` (asks first) | Change an entry's role. Target: { id, role } as in the snapshot. |
| `ConfirmedRemove` (asks first) | Remove an entry's access. Target: { id, role } as in the snapshot. |
| `InvitedByEmail` (asks first) | Invite people by email address at a role. Target: { emails }. |
| `ClickedInviteLink` (asks first) | Make an invitation link that lets anyone who has it join. The person copies it; you don't see it. |
| `ConfirmedGeneral` | Set general access (a value from generalOptions). Widening is consequential: target { general }. |

### RoleBadge (view function)

**Options**

| Name | Type | Description |
| --- | --- | --- |
| `label` (required) | `string` | The role's name: "Owner" |

## Keyboard and accessibility

- Opens as a modal dialog or sits inline, titled either way. Adding someone is a form with labelled selects for the person and the role.
- Each person has a role select and a Remove button named for them; roles above your own access are disabled, and locked entries say why.
- Removing someone and widening general access ask first, inline. Copying a link, a pending change and a refusal are announced.
- Agents read who has which role; adding, changing, removing and widening access are consequential and name the entry they change.

## Installation

```sh
pnpm dlx shadcn@latest add checkfu/uicontext/sharing
```

With npm: `npx shadcn@latest add checkfu/uicontext/sharing`. With yarn: `yarn dlx shadcn@latest add checkfu/uicontext/sharing`. With bun: `bunx --bun shadcn@latest add checkfu/uicontext/sharing`.

It writes these files:

- `src/ui/uicontext/components/Button.ts`
- `src/ui/uicontext/components/Dialog.ts`
- `src/ui/uicontext/components/FormControls.ts`
- `src/ui/uicontext/components/Glyph.ts`
- `src/ui/uicontext/components/IconStroke.ts`
- `src/ui/uicontext/components/InlineNotice.ts`
- `src/ui/uicontext/components/Share.ts`
- `src/ui/uicontext/components/ShowText.ts`
- `src/ui/uicontext/components/Sx.ts`
- `src/ui/uicontext/components/agent/Agent.ts`
- `src/ui/uicontext/components/button.stylex.ts`
- `src/ui/uicontext/components/domain/Format.ts`
- `src/ui/uicontext/components/domain/Glyph.ts`
- `src/ui/uicontext/components/domain/Outcome.ts`
- `src/ui/uicontext/components/domain/Permission.ts`
- `src/ui/uicontext/components/safeArea.stylex.ts`
- `src/ui/uicontext/components/tokens.stylex.ts`
- `src/ui/uicontext/components/touch.stylex.ts`
- `src/ui/uicontext/components/variants.ts`

And installs the npm packages `@stylexjs/stylex`, `effect`.

## Source

- [src/Share.ts](https://github.com/checkfu/uicontext/blob/main/src/Share.ts)

## Used in

- [Company brain](https://uicontext.com/blocks/doc-workspace.md)

## Related

- [Editor](https://uicontext.com/docs/components/editor.md) (`editor`): A block editor with a slash menu for headings, lists, to-dos and more.
- [Document Blocks](https://uicontext.com/docs/components/document-blocks.md) (`document-blocks`): Read-only rendering of a document's blocks.
- [Markdown](https://uicontext.com/docs/components/markdown.md) (`markdown`): Renders Markdown with readable type.
- [Code Block](https://uicontext.com/docs/components/code-block.md) (`code-block`): Code to read and copy, with highlighting, a file name and line numbers.
- [JSON Viewer](https://uicontext.com/docs/components/json-viewer.md) (`json-viewer`): A JSON value as a tree to open, search and walk with the arrow keys, such as a webhook's payload or a tool call's result.
- [Log Viewer](https://uicontext.com/docs/components/log-viewer.md) (`log-viewer`): A log that follows its newest line, with a filter, level buttons and Wrap, such as a deploy's or a server's.
