desktop: Add an actor profile editor behind the actorRepos lab

Co-authored-by: Brandon Oxendine <brandon.oxendine@gmail.com>
This commit is contained in:
Ioannis T.
2026-11-20 17:33:55 +01:00
co-authored by Brandon Oxendine
parent 442e58780f
commit bc2914f06b
74 changed files with 15563 additions and 35 deletions
+3
View File
@@ -42,6 +42,7 @@
import Auth from "@app/views/auth/Auth.svelte";
import CreateIdentity from "@app/views/auth/CreateIdentity.svelte";
import InboxView from "@app/views/Inbox.svelte";
import ProfileView from "@app/views/profile/Profile.svelte";
import Board from "@app/views/repo/Board.svelte";
import Identity from "@app/views/repo/Identity.svelte";
import Issue from "@app/views/repo/Issue.svelte";
@@ -272,6 +273,8 @@
<GuideView {...$activeRouteStore.params} />
{:else if $activeRouteStore.resource === "repo.board"}
<Board {...$activeRouteStore.params} />
{:else if $activeRouteStore.resource === "profile"}
<ProfileView {...$activeRouteStore.params} />
{:else if $activeRouteStore.resource === "repo.home"}
<RepoHome {...$activeRouteStore.params} />
{:else if $activeRouteStore.resource === "repo.commits"}
+97
View File
@@ -0,0 +1,97 @@
<script lang="ts">
import type { ActorInfo } from "@bindings/actor/ActorInfo";
import UserAvatar from "@radicle-gui/ui/components/UserAvatar.svelte";
import { onDestroy } from "svelte";
import { RepoImages } from "@app/lib/repoImages";
interface Props {
// The profile whose picture is shown. Without a profile, or without a
// picture that can be shown, the pattern generated from an ID stands in:
// the profile's, or `fallbackId` when there is no profile.
actor: Pick<ActorInfo, "rid" | "head" | "profile"> | null;
fallbackId?: string;
styleWidth: string;
}
const { actor, fallbackId, styleWidth }: Props = $props();
const images = new RepoImages();
onDestroy(() => images.dispose());
const rid = $derived(actor?.rid);
const head = $derived(actor?.head);
// A value with a colon is a web address. It is not fetched: that would
// tell its host who is looking, each time the picture is shown.
const path = $derived.by(() => {
const named = actor?.profile?.avatar?.trim();
return named && !named.includes(":") ? named : undefined;
});
// The picture shown and the profile it belongs to. A save moves `head`
// whether or not it changed the picture, so the one shown stays until the
// next has loaded.
let src = $state<string>();
let shownOf: string | undefined;
let broken = $state(false);
// The profile names a picture, so the pattern stands in only once that
// picture has failed to load: it must not show for a moment before it.
const named = $derived(Boolean(rid && head && path));
let failed = $state(false);
function showPicture(url: string | undefined) {
src = url;
broken = false;
failed = url === undefined;
// Releases the pictures loaded before this one.
images.sweep();
}
$effect(() => {
if (rid !== shownOf) {
shownOf = rid;
src = undefined;
}
if (!rid || !head || !path) {
showPicture(undefined);
return;
}
let gone = false;
void images
.load(rid, head, path)
.then(image => {
if (!gone) showPicture(image?.url);
})
.catch((e: unknown) => {
console.warn("Could not load the profile's avatar", e);
if (!gone) showPicture(undefined);
});
return () => {
gone = true;
};
});
const patternId = $derived(actor?.rid ?? fallbackId);
</script>
<style>
img {
display: block;
object-fit: cover;
}
</style>
{#if src && !broken}
<img
style:width={styleWidth}
style:height={styleWidth}
{src}
alt="Avatar"
onerror={() => (broken = true)} />
{:else if patternId && (!named || failed || broken)}
<UserAvatar nodeId={patternId} {styleWidth} />
{/if}
+7 -6
View File
@@ -3,12 +3,11 @@
</script>
<script lang="ts">
import type { RepoSummary } from "@bindings/repo/RepoSummary";
import { z } from "zod";
import { nodeRunning } from "@app/lib/events";
import { invoke } from "@app/lib/invoke";
import { cachedListReposWithActors, invoke } from "@app/lib/invoke";
import { repoListScope } from "@app/lib/repoListScope";
import { seedTarget } from "@app/lib/seedRepo";
import useLocalStorage from "@app/lib/useLocalStorage.svelte";
import { twemoji } from "@app/lib/utils";
@@ -24,11 +23,10 @@
interface Props {
reload: () => Promise<void>;
repos: RepoSummary[];
seededNotReplicated: string[];
}
const { reload, repos, seededNotReplicated }: Props = $props();
const { reload, seededNotReplicated }: Props = $props();
let popoverExpanded: boolean = $state(false);
let rid = $state("");
@@ -61,10 +59,13 @@
return;
}
// The project list hides actor repositories, so this check uses the full
// list.
const stored = await cachedListReposWithActors(repoListScope.value);
const target = seedTarget(
rid,
seededNotReplicated,
repos.map(r => r.rid),
stored.map(r => r.rid),
);
if ("error" in target) {
validationMessage = target.error;
+3 -1
View File
@@ -634,7 +634,9 @@
<div class="body">
<div class="nav">
{#if !mini}
<IdentityButton config={sidebarData.config} />
<IdentityButton
config={sidebarData.config}
actor={sidebarData.actor} />
{/if}
<a
+7 -2
View File
@@ -210,8 +210,13 @@
<path
d="M7.89634 2.39647C9.0581 1.23471 10.9416 1.23471 12.1034 2.39647C13.2651 3.55823 13.2651 5.44174 12.1034 6.6035L7.35337 11.3535C6.60582 12.101 5.39388 12.101 4.64634 11.3535C3.89879 10.606 3.89879 9.39401 4.64634 8.64647L8.64634 4.64647L9.35337 5.3535L5.35337 9.3535C4.99634 9.71052 4.99634 10.2894 5.35337 10.6465C5.71039 11.0035 6.28931 11.0035 6.64634 10.6465L11.3963 5.89647C12.1676 5.12523 12.1676 3.87473 11.3963 3.1035C10.6251 2.33226 9.3746 2.33226 8.60337 3.1035L3.85337 7.8535C2.66792 9.03895 2.66792 10.961 3.85337 12.1465C5.03882 13.3319 6.96089 13.3319 8.14634 12.1465L12.6463 7.64647L13.3534 8.3535L8.85337 12.8535C7.27739 14.4295 4.72231 14.4295 3.14634 12.8535C1.57036 11.2775 1.57036 8.72244 3.14634 7.14647L7.89634 2.39647Z" />
{:else if name === "avatar-incognito"}
<path
d="M13.5 8C13.5 4.96243 11.0376 2.5 8 2.5C4.96243 2.5 2.5 4.96243 2.5 8C2.5 9.74051 3.3094 11.291 4.57129 12.2988C4.61586 12.0809 4.68106 11.8667 4.7666 11.6602C4.94249 11.2357 5.2005 10.8503 5.52539 10.5254C5.85028 10.2005 6.23569 9.94249 6.66016 9.7666C7.0848 9.59071 7.54037 9.5 8 9.5C8.45963 9.5 8.9152 9.59071 9.33984 9.7666C9.76431 9.94249 10.1497 10.2005 10.4746 10.5254C10.7995 10.8503 11.0575 11.2357 11.2334 11.6602C11.3189 11.8666 11.3832 12.081 11.4277 12.2988C12.69 11.291 13.5 9.74078 13.5 8ZM8 10.5C7.6717 10.5 7.34628 10.5648 7.04297 10.6904C6.73978 10.8161 6.46449 11.0004 6.23242 11.2324C6.00036 11.4645 5.81606 11.7398 5.69043 12.043C5.57752 12.3155 5.51565 12.6061 5.50391 12.9004C6.25321 13.2828 7.10103 13.5 8 13.5C8.89866 13.5 9.74601 13.2826 10.4951 12.9004C10.4834 12.6061 10.4225 12.3155 10.3096 12.043C10.1839 11.7398 9.99964 11.4645 9.76758 11.2324C9.53551 11.0004 9.26022 10.8161 8.95703 10.6904C8.65372 10.5648 8.32831 10.5 8 10.5ZM9 6.5C9 5.94772 8.55228 5.5 8 5.5C7.44772 5.5 7 5.94772 7 6.5C7 7.05228 7.44772 7.5 8 7.5C8.55228 7.5 9 7.05228 9 6.5ZM14.5 8C14.5 10.3005 13.3033 12.3194 11.5 13.4746V13.5H11.4619C10.4593 14.1324 9.27294 14.5 8 14.5C6.72706 14.5 5.54065 14.1324 4.53809 13.5H4.5V13.4746C2.69675 12.3194 1.5 10.3005 1.5 8C1.5 4.41015 4.41015 1.5 8 1.5C11.5899 1.5 14.5 4.41015 14.5 8ZM10 6.5C10 7.60457 9.10457 8.5 8 8.5C6.89543 8.5 6 7.60457 6 6.5C6 5.39543 6.89543 4.5 8 4.5C9.10457 4.5 10 5.39543 10 6.5Z" />
<g fill="none" stroke="currentColor">
<circle cx="8" cy="8" r="6" />
<circle cx="8" cy="6.5" r="1.5" />
<path
d="M5 13L5.87868 9.87868L10.1213 9.87868L11 13"
stroke-linecap="square" />
</g>
{:else if name === "badge"}
<path
d="M4.64602 8.34829L5.35313 7.64118L7.00488 9.29294L10.6613 5.63656L11.3684 6.34367L7.00488 10.7072L4.64602 8.34829Z" />
+22 -4
View File
@@ -1,13 +1,16 @@
<script lang="ts">
import type { ActorInfo } from "@bindings/actor/ActorInfo";
import type { Config } from "@bindings/config/Config";
import UserAvatar from "@radicle-gui/ui/components/UserAvatar.svelte";
import debounce from "lodash/debounce";
import { writeToClipboard } from "@app/lib/invoke";
import { labs } from "@app/lib/labs";
import { entityUrl } from "@app/lib/mentions";
import * as router from "@app/lib/router";
import { didFromPublicKey, explorerHost, truncateDid } from "@app/lib/utils";
import ActorAvatar from "@app/components/ActorAvatar.svelte";
import Button from "@app/components/Button.svelte";
import DropdownListItem from "@app/components/DropdownListItem.svelte";
import Icon from "@app/components/Icon.svelte";
@@ -16,9 +19,10 @@
interface Props {
config: Config;
actor: ActorInfo | null;
}
const { config }: Props = $props();
const { config, actor }: Props = $props();
let popoverExpanded: boolean = $state(false);
let copyIcon: "copy" | "checkmark" = $state("copy");
@@ -35,8 +39,9 @@
styleJustifyContent="flex-start"
active={popoverExpanded}
{onclick}>
<UserAvatar nodeId={config.publicKey} styleWidth="1rem" />
<span class="label">{config.alias}</span>
<!-- A profile looks the same on each of its devices. -->
<ActorAvatar {actor} fallbackId={config.publicKey} styleWidth="1rem" />
<span class="label">{actor?.profile?.displayName || config.alias}</span>
<span class="label" style:color="var(--color-text-tertiary)">
<Icon name={popoverExpanded ? "chevron-up" : "chevron-down"} />
</span>
@@ -48,6 +53,19 @@
style:border-radius="var(--border-radius-md)"
style:background-color="var(--color-surface-canvas)"
style:padding="0.25rem">
{#if labs.actorRepos}
<DropdownListItem
styleGap="0.5rem"
styleWidth="100%"
selected={false}
onclick={async () => {
closeFocused();
await router.push({ resource: "profile", tab: "profile" });
}}>
<Icon name="avatar-incognito" />
{actor ? "Profile" : "Set up profile"}
</DropdownListItem>
{/if}
<DropdownListItem
styleGap="0.5rem"
styleWidth="100%"
@@ -390,10 +390,12 @@
async function reloadRepos() {
invalidateReposSummary();
[repos, seededNotReplicated] = await Promise.all([
const [reloaded, fetching] = await Promise.all([
cachedListReposSummary(repoListScope.value),
invoke<string[]>("seeded_not_replicated"),
]);
repos = reloaded;
seededNotReplicated = fetching;
}
// The route loader already fetched the list for the scope in force, so the
@@ -1127,7 +1129,7 @@
data-flip
onclick={e => e.stopPropagation()}
role="none">
<AddRepoButton reload={reloadRepos} {repos} {seededNotReplicated} />
<AddRepoButton reload={reloadRepos} {seededNotReplicated} />
</span>
</div>
+6 -1
View File
@@ -4,7 +4,12 @@ import useLocalStorage from "@app/lib/useLocalStorage.svelte";
// One-off tips that can be dismissed permanently. Kept in a single list so
// settings can offer to bring all of them back.
export type HintId = "markdown" | "guide";
export type HintId =
| "markdown"
| "guide"
| "profile.permanence"
// One for each profile and number of its controllers.
| `profile.controllers:${string}`;
const storage = useLocalStorage("dismissedHints", z.array(z.string()), []);
+29 -2
View File
@@ -1,3 +1,4 @@
import type { ActorInfo } from "@bindings/actor/ActorInfo";
import type { AliasSuggestion } from "@bindings/cob/AliasSuggestion";
import type { DiffOptions } from "@bindings/cob/DiffOptions";
import type { Issue } from "@bindings/cob/issue/Issue";
@@ -17,6 +18,8 @@ import type { TreePath } from "@bindings/repo/TreePath";
import { cached } from "@radicle-gui/ui/lib/cached";
import * as tauri from "@tauri-apps/api/core";
import { labs } from "@app/lib/labs";
import { projectsOf } from "@app/lib/projects";
import type { RepoListScope } from "@app/lib/repoListScope";
export async function invoke<T = null>(
@@ -416,15 +419,39 @@ export const cachedGetCommitDiff = cached(
* is cached with a short TTL; mutations that change it (adding, seeding,
* unseeding) go through invalidateReposSummary().
*/
export const cachedListReposSummary = cached(
export const cachedListReposWithActors = cached(
(show: RepoListScope) =>
invoke<RepoSummary[]>("list_repos_summary", { show }),
show => `list_repos_summary:${show}`,
{ max: 2, ttl: 30_000 },
);
/**
* The repositories to list as projects, see `projectsOf`. Whatever lists
* repositories calls this; `cachedListReposWithActors` is for telling what is
* in storage.
*/
export async function cachedListReposSummary(
show: RepoListScope,
): Promise<RepoSummary[]> {
return projectsOf(await cachedListReposWithActors(show), labs.actorRepos);
}
/**
* Finding the local actor scans storage like the repo list does, and every
* route loads it while the lab is on, so it shares the list's caching and
* invalidation; a save or create clears it as well.
*/
export const cachedActor = cached(
() => invoke<ActorInfo | null>("actor"),
() => "actor",
{ max: 1, ttl: 30_000 },
);
// The sidebar loads the repositories and the actor together, so both go.
export function invalidateReposSummary(): void {
cachedListReposSummary.clear();
cachedListReposWithActors.clear();
cachedActor.clear();
}
export async function writeToClipboard(
+9
View File
@@ -3,6 +3,7 @@ import { z } from "zod";
import useLocalStorage from "@app/lib/useLocalStorage.svelte";
const boards = useLocalStorage("labs.boards", z.boolean(), false);
const actorRepos = useLocalStorage("labs.actorRepos", z.boolean(), false);
// Experimental features, off until turned on in Settings.
export const labs = {
@@ -13,4 +14,12 @@ export const labs = {
set boards(value: boolean) {
boards.value = value;
},
get actorRepos(): boolean {
return actorRepos.value;
},
set actorRepos(value: boolean) {
actorRepos.value = value;
},
};
+10
View File
@@ -0,0 +1,10 @@
import type { RepoSummary } from "@bindings/repo/RepoSummary";
// The repositories to show as projects: with the actor lab on, an actor
// repository is a profile and is never listed as one.
export function projectsOf(
repos: RepoSummary[],
actorLab: boolean,
): RepoSummary[] {
return actorLab ? repos.filter(repo => !repo.actor) : repos;
}
+24 -6
View File
@@ -130,12 +130,16 @@ async function navigate(
route: Route,
fragment?: string,
): Promise<void> {
// Boards are a Labs feature; while it's off a board link shows the
// repository instead, and the address says so.
const hidden = route.resource === "repo.board" && !labs.boards;
const newRoute: Route = hidden
? { resource: "repo.home", rid: route.rid }
: route;
// Boards and the profile are Labs features; while one is off its link
// shows the repository, or the inbox, instead, and the address says so.
const hidden =
(route.resource === "repo.board" && !labs.boards) ||
(route.resource === "profile" && !labs.actorRepos);
const newRoute: Route = !hidden
? route
: route.resource === "repo.board"
? { resource: "repo.home", rid: route.rid }
: { resource: "inbox" };
const historyNav = pendingHistoryNavigation;
pendingHistoryNavigation = false;
isLoading.set(true);
@@ -209,6 +213,13 @@ function guideUrlToRoute(url: URL): { resource: "guide" } | undefined {
}
}
function profileUrlToRoute(url: URL): Route | undefined {
if (url.pathname === "/profile") {
const tab = url.searchParams.get("tab");
return { resource: "profile", tab: tab === "keys" ? "keys" : "profile" };
}
}
function urlToRoute(url: URL): Route | null {
const segments = url.pathname.substring(1).split("/");
const resource = segments.shift();
@@ -227,6 +238,11 @@ function urlToRoute(url: URL): Route | null {
return guideRoute;
}
const profileRoute = profileUrlToRoute(url);
if (profileRoute) {
return profileRoute;
}
switch (resource) {
case "repos": {
return repoUrlToRoute(segments, url.searchParams);
@@ -242,6 +258,8 @@ export function routeToPath(route: Route): string {
return "/inbox";
} else if (route.resource === "guide") {
return "/guide";
} else if (route.resource === "profile") {
return `/profile?tab=${route.tab}`;
} else if (
route.resource === "repo.board" ||
route.resource === "repo.home" ||
+58 -5
View File
@@ -1,4 +1,5 @@
import type { LoadedRepoRoute, RepoRoute } from "@app/views/repo/router";
import type { ActorInfo } from "@bindings/actor/ActorInfo";
import type { NotificationsByRepo } from "@bindings/cob/inbox/NotificationsByRepo";
import type { Config } from "@bindings/config/Config";
import type { RepoSummary } from "@bindings/repo/RepoSummary";
@@ -17,7 +18,13 @@ import {
loadRepoHome,
} from "@app/views/repo/router";
import { cachedListReposSummary, invoke } from "@app/lib/invoke";
import {
cachedActor,
cachedListReposSummary,
invoke,
InvokeError,
} from "@app/lib/invoke";
import { labs } from "@app/lib/labs";
import { repoListScope } from "@app/lib/repoListScope";
interface BootingRoute {
@@ -32,11 +39,21 @@ interface GuideRoute {
resource: "guide";
}
export type ProfileTab = "profile" | "keys";
interface ProfileRoute {
resource: "profile";
tab: ProfileTab;
}
export interface SidebarData {
config: Config;
repos: RepoSummary[];
notificationCount: number;
seededNotReplicated: string[];
actor: ActorInfo | null;
/** Why the actor could not be loaded, with the backend's error code. */
actorError?: { code: string; message: string };
}
export interface LoadedInboxRoute {
@@ -52,9 +69,19 @@ export interface LoadedGuideRoute {
params: { sidebarData: SidebarData };
}
export type Route = BootingRoute | RepoRoute | InboxRoute | GuideRoute;
export interface LoadedProfileRoute {
resource: "profile";
params: { sidebarData: SidebarData; tab: ProfileTab };
}
export type Route =
BootingRoute | RepoRoute | InboxRoute | GuideRoute | ProfileRoute;
export type LoadedRoute =
BootingRoute | LoadedRepoRoute | LoadedInboxRoute | LoadedGuideRoute;
| BootingRoute
| LoadedRepoRoute
| LoadedInboxRoute
| LoadedGuideRoute
| LoadedProfileRoute;
export function isLoadedRepoRoute(
route: LoadedRoute,
@@ -75,14 +102,31 @@ export function isLoadedRepoRoute(
}
export async function loadSidebarData(): Promise<SidebarData> {
const [config, repos, notificationCount, seededNotReplicated] =
const [config, repos, notificationCount, seededNotReplicated, lookup] =
await Promise.all([
invoke<Config>("config"),
cachedListReposSummary(repoListScope.value),
invoke<number>("notification_count"),
invoke<string[]>("seeded_not_replicated"),
labs.actorRepos ? loadActor() : { actor: null },
]);
return { config, repos, notificationCount, seededNotReplicated };
return { config, repos, notificationCount, seededNotReplicated, ...lookup };
}
// Whatever goes wrong with the actor is shown on the profile page, never
// allowed to stop a route from loading.
async function loadActor(): Promise<Pick<SidebarData, "actor" | "actorError">> {
try {
return { actor: await cachedActor() };
} catch (error) {
if (error instanceof InvokeError) {
return {
actor: null,
actorError: { code: error.code, message: error.message },
};
}
throw error;
}
}
export async function loadGuide(): Promise<LoadedGuideRoute> {
@@ -90,6 +134,13 @@ export async function loadGuide(): Promise<LoadedGuideRoute> {
return { resource: "guide", params: { sidebarData } };
}
export async function loadProfile(
route: ProfileRoute,
): Promise<LoadedProfileRoute> {
const sidebarData = await loadSidebarData();
return { resource: "profile", params: { sidebarData, tab: route.tab } };
}
export async function loadInbox(): Promise<LoadedInboxRoute> {
const [sidebarData, notificationsByRepo] = await Promise.all([
loadSidebarData(),
@@ -113,6 +164,8 @@ export async function loadRoute(
return loadGuide();
} else if (route.resource === "repo.board") {
return loadBoard(route);
} else if (route.resource === "profile") {
return loadProfile(route);
} else if (route.resource === "repo.home") {
return loadRepoHome(route);
} else if (route.resource === "repo.commits") {
+9 -3
View File
@@ -9,7 +9,10 @@
interface Props {
title: string;
width: string;
icon: ComponentProps<typeof Icon>["name"];
icon?: ComponentProps<typeof Icon>["name"];
// The confirm button's style: ghost for a destructive step, secondary
// for the step the dialog is there to take.
variant?: "ghost" | "secondary";
label: string;
busyLabel: string;
failure?: string;
@@ -24,6 +27,7 @@
title,
width,
icon,
variant = "ghost",
label,
busyLabel,
failure = "Something went wrong.",
@@ -123,11 +127,13 @@
{#if canConfirm}
<Button variant="outline" onclick={hide}>Cancel</Button>
<Button
variant="ghost"
{variant}
disabled={working || disabled}
onclick={() => void run()}>
<span class="confirm-label">
<Icon name={icon} />
{#if icon}
<Icon name={icon} />
{/if}
{working ? busyLabel : label}
</span>
</Button>
+246
View File
@@ -0,0 +1,246 @@
<script lang="ts">
import type { ActorInfo } from "@bindings/actor/ActorInfo";
import type { ProfileEdit } from "@bindings/actor/ProfileEdit";
import type { PaginatedQuery } from "@bindings/cob/PaginatedQuery";
import {
ago,
describeActorError,
keyName,
PROFILE_PATH,
} from "@app/views/profile/actor";
import { invoke } from "@app/lib/invoke";
import { hide } from "@app/lib/modal";
import Button from "@app/components/Button.svelte";
import CopyableId from "@app/components/CopyableId.svelte";
import Icon from "@app/components/Icon.svelte";
import ScrollArea from "@app/components/ScrollArea.svelte";
interface Props {
// The profile whose versions are listed, for its ID and its keys' names.
actor: ActorInfo;
}
const { actor }: Props = $props();
const PAGE = 20;
// The profile's fields as the form labels them.
const LABELS: Record<string, string> = {
displayName: "display name",
fullName: "full name",
pronouns: "pronouns",
bio: "bio",
location: "location",
timezone: "time zone",
avatar: "avatar",
banner: "banner",
links: "links",
};
const edits = $state<ProfileEdit[]>([]);
// How many versions the pages so far covered, which is more than `edits`
// holds once a page has repeated some.
let fetched = 0;
let more = $state(false);
let loading = $state(true);
let error = $state<string>();
async function load() {
loading = true;
error = undefined;
try {
const page = await invoke<PaginatedQuery<ProfileEdit[]>>(
"actor_profile_history",
{ skip: fetched, take: PAGE },
);
// A profile that moved since the last page shifts the next one back
// over versions already here.
fetched += page.content.length;
const held = new Set(edits.map(edit => edit.commit));
edits.push(...page.content.filter(edit => !held.has(edit.commit)));
more = page.more;
} catch (e) {
error = describeActorError(e, "Could not load the history.");
} finally {
loading = false;
}
}
void load();
function list(fields: string[]): string {
const names = fields.map(field => LABELS[field] ?? field);
if (names.length === 1) return names[0];
return `${names.slice(0, -1).join(", ")} and ${names[names.length - 1]}`;
}
// What a version did, told against the one it was saved over. A version
// that changed no field shown here changed something else: another file,
// or a part of the profile this version of Desktop does not read.
function summary(edit: ProfileEdit): string {
if (edit.parents.length === 0) return "Created the profile";
const changed = edit.fields?.length ? list(edit.fields) : undefined;
if (edit.parents.length > 1) {
const joined = "Joined versions saved on different devices";
return changed ? `${joined} and changed ${changed}` : joined;
}
return changed
? `Changed ${changed}`
: "Changed in a way this version of Desktop cannot show";
}
</script>
<style>
.modal {
width: 36rem;
max-width: 92vw;
display: flex;
flex-direction: column;
border: 1px solid var(--color-border-subtle);
border-radius: var(--border-radius-lg);
background-color: var(--color-surface-canvas);
overflow: hidden;
}
.header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 0 1.25rem;
height: 3.25rem;
flex-shrink: 0;
border-bottom: 1px solid var(--color-border-subtle);
}
.title {
font: var(--txt-heading-s);
color: var(--color-text-primary);
}
.source {
display: flex;
align-items: center;
gap: 0.5rem;
padding: 0.625rem 1.25rem;
border-bottom: 1px solid var(--color-border-subtle);
background-color: var(--color-surface-subtle);
color: var(--color-text-secondary);
}
.path {
font: var(--txt-code-regular);
color: var(--color-text-tertiary);
}
.entries {
display: flex;
flex-direction: column;
}
.entry {
display: flex;
align-items: flex-start;
gap: 0.75rem;
padding: 0.875rem 1.25rem;
}
.entry + .entry {
border-top: 1px solid var(--color-border-subtle);
}
.entry-icon {
display: flex;
flex-shrink: 0;
padding-top: 0.125rem;
color: var(--color-text-tertiary);
}
.entry-text {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: 0.25rem;
}
.changed {
color: var(--color-text-primary);
}
.byline {
color: var(--color-text-tertiary);
}
.more {
display: flex;
justify-content: center;
padding: 0.75rem 1.25rem;
border-top: 1px solid var(--color-border-subtle);
}
.empty {
padding: 2.5rem 1.25rem;
text-align: center;
}
.error {
color: var(--color-feedback-error-text);
}
</style>
<div class="modal">
<div class="header">
<span class="title">Published history</span>
<Button variant="naked" onclick={hide}>
<span style:color="var(--color-text-tertiary)">
<Icon name="close" />
</span>
</Button>
</div>
<div class="source txt-body-m-regular">
<Icon name="repository" />
<CopyableId id={actor.rid} styleFont="var(--txt-body-m-regular)">
{actor.rid}
</CopyableId>
<span class="path">{PROFILE_PATH}</span>
</div>
{#if edits.length > 0}
<ScrollArea style="max-height: 24rem;">
<div class="entries">
{#each edits as edit (edit.commit)}
<div class="entry">
<span class="entry-icon"><Icon name="commit" /></span>
<div class="entry-text">
<span class="changed txt-body-m-regular">{summary(edit)}</span>
<span class="byline txt-body-m-regular">
{edit.author
? keyName(actor, edit.author)
: "A device that left no name"} · {ago(edit.savedAt)} ·
<span class="path">{edit.commit.slice(0, 7)}</span>
{#if !edit.live}
· Not the profile yet
{/if}
</span>
</div>
</div>
{/each}
{#if more}
<div class="more">
<Button
variant="outline"
bordered
disabled={loading}
onclick={load}>
Show more
</Button>
</div>
{/if}
</div>
</ScrollArea>
{:else if !loading && !error}
<div class="empty">
<span class="txt-missing txt-body-m-regular">Nothing published yet</span>
</div>
{/if}
{#if error}
<div class="empty">
<span class="error txt-body-m-regular">{error}</span>
</div>
{/if}
</div>
+136
View File
@@ -0,0 +1,136 @@
<script lang="ts">
import type { ActorProfile } from "@bindings/actor/ActorProfile";
import { PROFILE_PATH } from "@app/views/profile/actor";
import debounce from "lodash/debounce";
import { writeToClipboard } from "@app/lib/invoke";
import { hide } from "@app/lib/modal";
import Button from "@app/components/Button.svelte";
import Icon from "@app/components/Icon.svelte";
import PierreFile from "@app/components/PierreFile.svelte";
import PierreSnippet from "@app/components/PierreSnippet.svelte";
import ScrollArea from "@app/components/ScrollArea.svelte";
import SegmentedSwitch from "@app/components/SegmentedSwitch.svelte";
interface Props {
// Whose version this is, as the keys list names it.
name: string;
// The commit of the version.
head: string;
// Unset when the version holds no profile this Desktop can read.
profile?: ActorProfile;
// What the version changed since it split from the one shown here, as a
// unified diff. Unset when that cannot be told.
changes?: string;
}
const { name, head, profile, changes }: Props = $props();
let chosen = $state<"document" | "changes">("changes");
const view = $derived(changes === undefined ? "document" : chosen);
const raw = $derived(profile ? JSON.stringify(profile, null, 2) : undefined);
const copied = $derived(view === "changes" ? changes : raw);
let copyIcon: "copy" | "checkmark" = $state("copy");
const restoreIcon = debounce(() => (copyIcon = "copy"), 1000);
async function copy() {
if (copied === undefined) return;
await writeToClipboard(copied);
copyIcon = "checkmark";
restoreIcon();
}
</script>
<style>
.modal {
width: min(46rem, 92vw);
height: min(38rem, 85vh);
display: flex;
flex-direction: column;
border: 1px solid var(--color-border-subtle);
border-radius: var(--border-radius-lg);
background-color: var(--color-surface-canvas);
overflow: hidden;
}
.header {
display: flex;
align-items: center;
gap: 0.75rem;
padding: 0 0.75rem 0 1.5rem;
height: 3.25rem;
flex-shrink: 0;
border-bottom: 1px solid var(--color-border-subtle);
}
.title {
font: var(--txt-heading-s);
color: var(--color-text-primary);
}
.actions {
display: flex;
align-items: center;
gap: 0.25rem;
margin-left: auto;
}
.code {
padding: 0.75rem 0;
}
.note {
padding: 0 1.5rem;
color: var(--color-text-secondary);
}
</style>
<div class="modal">
<div class="header">
<span class="title">Profile on {name}</span>
<div class="actions">
{#if raw !== undefined && changes !== undefined}
<SegmentedSwitch
options={[
{ value: "document", label: "Document" },
{ value: "changes", label: "Changes" },
]}
value={view}
onchange={value => (chosen = value)} />
{/if}
{#if copied !== undefined}
<Button variant="outline" styleHeight="2rem" onclick={copy}>
<Icon name={copyIcon} />
{view === "changes" ? "Copy diff" : "Copy JSON"}
</Button>
{/if}
<Button variant="naked" onclick={hide}>
<span style:color="var(--color-text-tertiary)">
<Icon name="close" />
</span>
</Button>
</div>
</div>
<ScrollArea style="flex: 1; min-height: 0;">
<div class="code">
{#if raw === undefined}
<span class="note txt-body-m-regular">
That version holds no profile this Desktop can read.
</span>
{:else if view === "document" || changes === undefined}
<PierreFile
contents={raw}
path={PROFILE_PATH}
cacheKey={`profile-version:${head}`} />
{:else if changes.trim() === ""}
<span class="note txt-body-m-regular">
The profile was not changed there.
</span>
{:else}
<PierreSnippet
patch={changes}
path={PROFILE_PATH}
cacheKey={`profile-split:${head}:${changes.length}`} />
{/if}
</div>
</ScrollArea>
</div>
+21
View File
@@ -7,6 +7,7 @@
import { hints } from "@app/lib/hints";
import { invoke } from "@app/lib/invoke";
import { labs } from "@app/lib/labs";
import * as router from "@app/lib/router";
import { updateChecker } from "@app/lib/updateChecker.svelte";
import { pluralize } from "@app/lib/utils";
@@ -34,6 +35,7 @@
// Shown so that a user seeing the slower fallback can tell which git, if
// any, was picked.
const gitInfo = invoke<GitInfo>("git_info");
const activeRoute = router.activeUnloadedRouteStore;
const diffStyleOptions: Option<DiffOptions["diffStyle"]>[] = [
{ value: "unified", icon: "diff-unified", title: "Unified" },
@@ -302,6 +304,25 @@
value={labs.boards ? "on" : "off"}
onchange={value => (labs.boards = value === "on")} />
</div>
<div class="row">
<div class="row-label">
<span class="row-title">Rich profiles</span>
<span class="row-description">
Link the keys on your devices into one profile. Experimental: the
profile format may still change.
</span>
</div>
<SegmentedSwitch
options={labsOptions}
value={labs.actorRepos ? "on" : "off"}
onchange={value => {
labs.actorRepos = value === "on";
// The sidebar is loaded with the route, so the page loads again
// for it to follow; the router leaves a page that needs this
// experiment.
void router.replace($activeRoute);
}} />
</div>
</div>
<div class="footer">
{#if updateChecker.currentVersion}
@@ -0,0 +1,107 @@
<script lang="ts">
import type { ActorInfo } from "@bindings/actor/ActorInfo";
import type { ActorRevision } from "@bindings/actor/ActorRevision";
import Icon from "@app/components/Icon.svelte";
import { ago, keyName, revisionTitle } from "./actor";
interface Props {
actor: ActorInfo;
// A change to the keys that ended, or one that waits on another.
revision: ActorRevision;
localDid: string;
// The change the profile began with.
first?: boolean;
}
const { actor, revision, localDid, first = false }: Props = $props();
const STATES = {
accepted: "Applied",
rejected: "Rejected",
lapsed: "Lapsed",
open: "Waiting",
} as const;
const name = (did: string) =>
did === localDid ? "this device" : keyName(actor, did);
const list = (dids: string[]) =>
new Intl.ListFormat("en", { type: "conjunction" }).format(dids.map(name));
</script>
<style>
.change {
display: flex;
align-items: flex-start;
gap: 0.75rem;
padding: 0.75rem;
}
.change-icon {
display: flex;
align-items: center;
justify-content: center;
width: 2rem;
height: 2rem;
flex-shrink: 0;
border-radius: var(--border-radius-md);
background-color: var(--color-surface-subtle);
color: var(--color-text-secondary);
}
.text {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: 0.25rem;
color: var(--color-text-primary);
}
.byline {
color: var(--color-text-tertiary);
}
.state {
flex-shrink: 0;
padding: 0.125rem 0.5rem;
border-radius: var(--border-radius-sm);
background-color: var(--color-surface-subtle);
color: var(--color-text-secondary);
}
.state.accepted {
background-color: var(--color-feedback-success-bg);
color: var(--color-feedback-success-text);
}
.state.rejected {
background-color: var(--color-feedback-error-bg);
color: var(--color-feedback-error-text);
}
.state.open {
background-color: var(--color-feedback-warning-bg);
color: var(--color-feedback-warning-text);
}
</style>
<div class="change">
<span class="change-icon">
<Icon name={revision.removed.length > 0 ? "trash" : "key"} />
</span>
<div class="text">
<span class="txt-body-m-medium">
{first ? "Created the profile" : revisionTitle(actor, revision, true)}
</span>
<span class="byline txt-body-m-regular">
Proposed by {name(revision.author)}
{ago(revision.createdAt)}
{#if revision.accepted.length > 0}
· approved by {list(revision.accepted)}
{/if}
{#if revision.rejected.length > 0}
· rejected by {list(revision.rejected)}
{/if}
</span>
</div>
<span class="state {revision.state} txt-body-m-medium">
{STATES[revision.state]}
</span>
</div>
+235
View File
@@ -0,0 +1,235 @@
<script lang="ts">
import type { EnrollmentPreview } from "@bindings/actor/EnrollmentPreview";
import { invoke } from "@app/lib/invoke";
import { publicKeyFromDid } from "@app/lib/utils";
import Checkbox from "@app/components/Checkbox.svelte";
import CopyableId from "@app/components/CopyableId.svelte";
import Icon from "@app/components/Icon.svelte";
import TextInput from "@app/components/TextInput.svelte";
import ConfirmModal from "@app/modals/ConfirmModal.svelte";
import { describeActorError } from "./actor";
import KeyChunks from "./KeyChunks.svelte";
interface Props {
rid: string;
majority: number;
confirm: (code: string, controller: boolean) => Promise<void>;
}
const { rid, majority, confirm }: Props = $props();
// The joining key makes the code, so it consents before anything changes;
// this key only checks and signs it.
let code = $state("");
// Tooling defaults to enrolling a key as both, with an opt-out.
let controller = $state(true);
const ENROLL_PREFIX = "rad-enroll:";
const looksLikeCode = $derived(code.trim().startsWith(ENROLL_PREFIX));
// The code is checked as it is pasted, and the key it binds shown, so the
// user can tell it is the machine they are adding before anything is
// signed.
type Check =
| { status: "none" }
| { status: "checking" }
| { status: "ok"; preview: EnrollmentPreview }
| { status: "failed"; message: string };
let check = $state<Check>({ status: "none" });
// A key that already controls the actor keeps that role whatever the box
// says, so the box says so.
const controls = $derived(check.status === "ok" && check.preview.controller);
$effect(() => {
if (controls) controller = true;
});
// A check scans every repository, so it waits for the typing to stop.
const CHECK_DELAY_MS = 300;
$effect(() => {
const pasted = code.trim();
check = { status: "none" };
if (!looksLikeCode) return;
let current = true;
const timer = setTimeout(() => {
check = { status: "checking" };
invoke<EnrollmentPreview>("decode_enrollment", { code: pasted })
.then(preview => {
if (current) check = { status: "ok", preview };
})
.catch((error: unknown) => {
if (current) check = { status: "failed", message: describe(error) };
});
}, CHECK_DELAY_MS);
return () => {
current = false;
clearTimeout(timer);
};
});
function describe(error: unknown): string {
return describeActorError(error, "Could not add the key.", {
"ActorError.NotController":
"This device's key cannot add keys. Approve from a key that can.",
});
}
</script>
<style>
.step {
display: flex;
gap: 0.75rem;
}
.step-number {
display: inline-flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
width: 1.5rem;
height: 1.5rem;
border-radius: 50%;
background-color: var(--color-surface-subtle);
color: var(--color-text-secondary);
font: var(--txt-body-m-medium);
}
.step-body {
display: flex;
flex-direction: column;
gap: 0.5rem;
min-width: 0;
flex: 1;
}
.lead,
.step-text {
color: var(--color-text-secondary);
}
.check-label {
display: flex;
flex-direction: column;
gap: 0.25rem;
}
.hint {
color: var(--color-text-tertiary);
}
.error {
color: var(--color-feedback-error-text);
}
.verified {
display: flex;
gap: 0.5rem;
padding: 0.875rem;
border: 1px solid var(--color-border-subtle);
border-radius: var(--border-radius-md);
background-color: var(--color-surface-subtle);
}
.verified-rows {
display: flex;
flex-direction: column;
gap: 0.5rem;
min-width: 0;
}
.verified-row {
color: var(--color-text-secondary);
}
.verified .ok {
display: flex;
flex-shrink: 0;
padding-top: 0.125rem;
color: var(--color-feedback-success-text);
}
</style>
<ConfirmModal
title="Add a key"
width="34rem"
icon="key"
variant="secondary"
label={majority > 1 ? "Sign and propose" : "Add key"}
busyLabel="Signing…"
disabled={check.status !== "ok"}
confirm={() => confirm(code.trim(), controller)}
describeError={describe}>
{#snippet body()}
<span class="lead txt-body-m-regular">
Add another device's key so that your work on both devices appears under
the same profile. Start on that device, then approve it here.
</span>
<div class="step">
<span class="step-number">1</span>
<div class="step-body">
<span class="step-text txt-body-m-regular">
On the device you are adding, open Profile, choose Join existing
profile, and enter this Profile ID:
</span>
<CopyableId id={rid} styleFont="var(--txt-code-regular)">
{rid}
</CopyableId>
</div>
</div>
<div class="step">
<span class="step-number">2</span>
<div class="step-body">
<span class="step-text txt-body-m-regular">
Create a code there, then paste it here.
</span>
<TextInput bind:value={code} placeholder="{ENROLL_PREFIX}…" autofocus />
{#if code.trim() && !looksLikeCode}
<span class="hint txt-body-s-regular">
A code starts with {ENROLL_PREFIX}
</span>
{:else if check.status === "checking"}
<span class="hint txt-body-s-regular">Checking the code…</span>
{:else if check.status === "failed"}
<span class="error txt-body-s-regular">{check.message}</span>
{:else if check.status === "ok"}
<div class="verified">
<span class="ok"><Icon name="checkmark" /></span>
<div class="verified-rows txt-body-m-regular">
<div class="verified-row">
Valid code. It adds the key below. Make sure the device you are
adding shows the same key.
</div>
<!-- Whole, since a look-alike only has to match what is shown. -->
<KeyChunks
publicKey={publicKeyFromDid(check.preview.did)}
name={check.preview.alias} />
{#if check.preview.controller}
<div class="verified-row">
Already a controller, as a recovery key. Adding it makes it a
full key.
</div>
{/if}
</div>
</div>
{/if}
</div>
</div>
<Checkbox bind:checked={controller} disabled={controls}>
<span class="check-label">
<span class="txt-body-m-regular">Also make it a controller</span>
<span class="hint txt-body-s-regular">
Recommended. Controllers are the keys that can add and remove other
keys. Keep at least three, so losing one is not permanent. Turn this
off for a device you do not fully trust. Its work still appears under
your profile, but it cannot change which keys are yours or edit the
profile.
</span>
</span>
</Checkbox>
{/snippet}
</ConfirmModal>
@@ -0,0 +1,264 @@
<script lang="ts">
import type { Form } from "./form";
import UserAvatar from "@radicle-gui/ui/components/UserAvatar.svelte";
import { publicKeyFromDid, truncateId } from "@app/lib/utils";
import Icon from "@app/components/Icon.svelte";
interface Props {
form: Form;
avatar: string | undefined;
banner: string | undefined;
// What the generated avatar is drawn from when there is no picture.
avatarId: string;
// The keys whose work Explorer credits to the profile.
keys: { did: string; alias?: string }[];
url: string | undefined;
}
const { form, avatar, banner, avatarId, keys, url }: Props = $props();
let avatarBroken = $state(false);
let bannerBroken = $state(false);
$effect(() => {
void avatar;
avatarBroken = false;
});
$effect(() => {
void banner;
bannerBroken = false;
});
const facts = $derived(
[form.pronouns, form.location, form.timezone]
.map(fact => fact.trim())
.filter(Boolean),
);
const links = $derived(form.links.filter(link => link.url.trim()));
function linkLabel(link: { url: string; label?: string }): string {
if (link.label?.trim()) return link.label.trim();
const value = link.url.trim();
if (value.startsWith("mailto:")) return "Email";
try {
return new URL(value).host || value;
} catch {
return value;
}
}
function linkValue(url: string): string {
const value = url.trim();
return value.startsWith("mailto:") ? value.slice("mailto:".length) : value;
}
</script>
<style>
.browser {
border: 1px solid var(--color-border-subtle);
border-radius: var(--border-radius-md);
background-color: var(--color-surface-canvas);
overflow: hidden;
}
.chrome {
display: flex;
align-items: center;
gap: 0.5rem;
padding: 0.5rem 0.75rem;
border-bottom: 1px solid var(--color-border-subtle);
background-color: var(--color-surface-subtle);
color: var(--color-text-tertiary);
}
.url {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font: var(--txt-code-regular);
}
/* Across the top, as profile pages usually have one. */
.banner {
height: 5rem;
overflow: hidden;
background-color: var(--color-surface-subtle);
}
.banner img {
display: block;
width: 100%;
height: 100%;
object-fit: cover;
}
.head {
display: flex;
align-items: flex-end;
justify-content: space-between;
padding: 0.875rem 0.875rem 0;
}
/* With a banner, the avatar overlaps its bottom-left edge. */
.banner + .head {
margin-top: -2rem;
padding-top: 0;
}
.avatar {
width: 4rem;
height: 4rem;
overflow: hidden;
border: 3px solid var(--color-surface-canvas);
border-radius: var(--border-radius-md);
background-color: var(--color-surface-subtle);
}
.avatar :global(img) {
display: block;
width: 100%;
height: 100%;
object-fit: cover;
}
.body {
display: flex;
flex-direction: column;
gap: 0.625rem;
padding: 0.5rem 0.875rem 0.875rem;
}
.name {
font: var(--txt-heading-s);
color: var(--color-text-primary);
min-width: 0;
overflow-wrap: anywhere;
}
.name.empty {
color: var(--color-text-tertiary);
}
.follow {
display: inline-flex;
align-items: center;
gap: 0.25rem;
flex-shrink: 0;
padding: 0.25rem 0.5rem;
border: 1px solid var(--color-border-subtle);
border-radius: var(--border-radius-sm);
color: var(--color-text-secondary);
}
.full-name,
.facts {
color: var(--color-text-secondary);
}
.facts {
display: flex;
align-items: center;
gap: 0.375rem;
flex-wrap: wrap;
}
.separator {
color: var(--color-text-quaternary);
}
.bio {
color: var(--color-text-primary);
overflow-wrap: anywhere;
}
/* The page lists keys this way already, so links share the shape. */
.rows {
display: flex;
flex-direction: column;
gap: 0.375rem;
}
.row {
display: flex;
align-items: center;
gap: 0.5rem;
min-width: 0;
}
.chip {
display: inline-flex;
align-items: center;
gap: 0.25rem;
flex-shrink: 0;
padding: 0.125rem 0.375rem;
border: 1px solid var(--color-border-subtle);
border-radius: var(--border-radius-sm);
color: var(--color-text-secondary);
}
.value {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: var(--color-text-tertiary);
font: var(--txt-code-regular);
}
</style>
<div class="browser">
<div class="chrome">
<Icon name="globe" />
<span class="url">{url ?? "Explorer"}</span>
</div>
{#if banner && !bannerBroken}
<div class="banner">
<img src={banner} alt="" onerror={() => (bannerBroken = true)} />
</div>
{/if}
<div class="head">
<div class="avatar">
{#if avatar && !avatarBroken}
<img src={avatar} alt="" onerror={() => (avatarBroken = true)} />
{:else}
<UserAvatar nodeId={avatarId} styleWidth="100%" />
{/if}
</div>
<span class="follow txt-body-m-regular">
<Icon name="plus" />
Follow
</span>
</div>
<div class="body">
<span class="name" class:empty={!form.displayName.trim()}>
{form.displayName.trim() || "Display name"}
</span>
{#if form.fullName.trim()}
<span class="full-name txt-body-m-regular">{form.fullName}</span>
{/if}
{#if facts.length > 0}
<div class="facts txt-body-m-regular">
{#each facts as fact, index (index)}
{#if index > 0}
<span class="separator">·</span>
{/if}
<span>{fact}</span>
{/each}
</div>
{/if}
{#if form.bio.trim()}
<span class="bio txt-body-m-regular">{form.bio}</span>
{/if}
<div class="rows">
{#each links as link (link.id)}
<div class="row txt-body-m-regular">
<span class="chip">
<Icon name="link" />
{linkLabel(link)}
</span>
<span class="value">{linkValue(link.url)}</span>
</div>
{/each}
{#each keys as key (key.did)}
<div class="row txt-body-m-regular">
<span class="chip">
<Icon name="key" />
{key.alias ?? "Unnamed"}
</span>
<span class="value">{truncateId(publicKeyFromDid(key.did))}</span>
</div>
{/each}
</div>
</div>
</div>
+163
View File
@@ -0,0 +1,163 @@
<script lang="ts">
import type { Form } from "./form";
import UserAvatar from "@radicle-gui/ui/components/UserAvatar.svelte";
import { truncateId } from "@app/lib/utils";
import Icon from "@app/components/Icon.svelte";
interface Props {
form: Form;
avatar: string | undefined;
banner: string | undefined;
// What the generated avatar is drawn from when there is no picture.
avatarId: string;
// The Profile ID, or this device's key before there is a profile.
did: string;
}
const { form, avatar, banner, avatarId, did }: Props = $props();
let broken = $state(false);
let bannerBroken = $state(false);
$effect(() => {
void avatar;
broken = false;
});
$effect(() => {
void banner;
bannerBroken = false;
});
</script>
<style>
/* Inert: the shape of the card other people see, not a working one. */
.card {
display: flex;
flex-direction: column;
border: 1px solid var(--color-border-subtle);
border-radius: var(--border-radius-md);
background-color: var(--color-surface-canvas);
box-shadow: var(--elevation-low);
overflow: hidden;
}
.banner {
height: 3.5rem;
background-color: var(--color-surface-subtle);
}
.banner img {
display: block;
width: 100%;
height: 100%;
object-fit: cover;
}
.avatar {
width: 3rem;
height: 3rem;
margin: 0.875rem 0 0 0.875rem;
overflow: hidden;
border: 3px solid var(--color-surface-canvas);
border-radius: var(--border-radius-md);
background-color: var(--color-surface-subtle);
}
/* With a banner, the avatar overlaps its bottom-left edge. */
.banner + .avatar {
margin-top: -1.5rem;
}
.avatar :global(img) {
display: block;
width: 100%;
height: 100%;
object-fit: cover;
}
.body {
display: flex;
flex-direction: column;
gap: 0.75rem;
padding: 0.5rem 0.875rem 0.875rem;
}
.text {
min-width: 0;
display: flex;
flex-direction: column;
gap: 0.125rem;
}
.name,
.full-name {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.name {
color: var(--color-text-primary);
}
.name.empty {
color: var(--color-text-tertiary);
}
.full-name,
.bio {
color: var(--color-text-secondary);
}
.bio {
display: -webkit-box;
-webkit-line-clamp: 3;
line-clamp: 3;
-webkit-box-orient: vertical;
overflow: hidden;
}
.did {
color: var(--color-text-tertiary);
font: var(--txt-code-regular);
}
.action {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 0.375rem;
padding: 0.375rem 0.5rem;
border: 1px solid var(--color-border-subtle);
border-radius: var(--border-radius-sm);
color: var(--color-text-secondary);
}
</style>
<div class="card">
{#if banner && !bannerBroken}
<div class="banner">
<img src={banner} alt="" onerror={() => (bannerBroken = true)} />
</div>
{/if}
<span class="avatar">
{#if avatar && !broken}
<img src={avatar} alt="" onerror={() => (broken = true)} />
{:else}
<UserAvatar nodeId={avatarId} styleWidth="100%" />
{/if}
</span>
<div class="body">
<span class="text">
<span
class="name txt-body-m-medium"
class:empty={!form.displayName.trim()}>
{form.displayName.trim() || "Display name"}
</span>
{#if form.fullName.trim()}
<span class="full-name txt-body-m-regular">{form.fullName}</span>
{/if}
</span>
{#if form.bio.trim()}
<span class="bio txt-body-m-regular">{form.bio}</span>
{/if}
<span class="did">{truncateId(did)}</span>
<span class="action txt-body-m-medium">
View profile
<Icon name="open-external" />
</span>
</div>
</div>
@@ -0,0 +1,289 @@
<script lang="ts" module>
// A picture chosen for the profile and not saved yet. The backend names
// the file it is saved as, by what its content is.
export interface PickedImage {
base64: string;
// An object URL to show it by.
url: string;
}
</script>
<script lang="ts">
import UserAvatar from "@radicle-gui/ui/components/UserAvatar.svelte";
import Button from "@app/components/Button.svelte";
import Icon from "@app/components/Icon.svelte";
interface Props {
kind: "avatar" | "banner";
// What the profile field holds: a path in the repository, or a web URL
// that another tool wrote.
value: string;
// The picture to show for it, if there is one to show.
src: string | undefined;
picked: PickedImage | undefined;
// An empty avatar falls back to the pattern generated from this ID,
// since that is what people see.
fallbackId?: string;
disabled: boolean;
// What the backend would refuse in the field.
error: string | undefined;
onpick: (image: PickedImage | undefined) => void;
}
/* eslint-disable prefer-const */
let {
kind,
value = $bindable(""),
src,
picked,
fallbackId,
disabled,
error,
onpick,
}: Props = $props();
/* eslint-enable prefer-const */
// The backend's limits, checked here so the answer comes at once. Which
// kinds of picture it takes is the backend's to say.
const LIMIT_KIB = { avatar: 1024, banner: 2048 } as const;
const label = $derived(kind === "avatar" ? "Avatar" : "Banner");
let input = $state<HTMLInputElement>();
let pickError = $state<string>();
let broken = $state(false);
$effect(() => {
void src;
broken = false;
});
$effect(() => {
const url = picked?.url;
return () => {
if (url) URL.revokeObjectURL(url);
};
});
function base64(bytes: Uint8Array): string {
let binary = "";
const step = 0x8000;
for (let at = 0; at < bytes.length; at += step) {
binary += String.fromCharCode(...bytes.subarray(at, at + step));
}
return btoa(binary);
}
async function pick(file: File | undefined) {
pickError = undefined;
if (!file) return;
const kib = Math.ceil(file.size / 1024);
if (kib > LIMIT_KIB[kind]) {
pickError = `This picture is ${kib} KiB, and the limit is ${LIMIT_KIB[kind]} KiB.`;
return;
}
// A file that does not decode is no picture, whatever its name says.
try {
(await createImageBitmap(file)).close();
} catch {
pickError = "This file is not a picture that can be shown.";
return;
}
onpick({
base64: base64(new Uint8Array(await file.arrayBuffer())),
url: URL.createObjectURL(file),
});
}
// A picture picked and not saved goes back to what the field held;
// otherwise the field is emptied.
function remove() {
if (picked) onpick(undefined);
else value = "";
pickError = undefined;
}
</script>
<style>
.field {
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.label {
color: var(--color-text-primary);
}
.row {
display: flex;
align-items: center;
gap: 0.875rem;
}
.preview {
position: relative;
flex-shrink: 0;
padding: 0;
cursor: pointer;
overflow: hidden;
border: 1px solid var(--color-border-subtle);
border-radius: var(--border-radius-sm);
background-color: var(--color-surface-subtle);
}
.preview[disabled] {
cursor: not-allowed;
}
.preview.avatar {
width: 4rem;
height: 4rem;
}
.preview.banner {
width: 12rem;
height: 4rem;
}
.preview img,
.preview :global(img) {
display: block;
width: 100%;
height: 100%;
object-fit: cover;
}
.preview:hover:not([disabled]) {
border-color: var(--color-border-mid);
}
/* Sits on the picture, so the picker has no button of its own. */
.pick {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
display: flex;
align-items: center;
justify-content: center;
width: 1.75rem;
height: 1.75rem;
border-radius: var(--border-radius-sm);
background-color: var(--color-surface-canvas);
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
color: var(--color-text-primary);
}
.preview:hover .pick {
background-color: var(--color-surface-base);
}
.placeholder {
display: flex;
align-items: center;
justify-content: center;
width: 100%;
height: 100%;
color: var(--color-text-quaternary);
}
.details {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: 0.375rem;
}
.source {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: var(--color-text-primary);
font: var(--txt-code-regular);
}
.unsaved {
color: var(--color-text-secondary);
}
.actions {
display: flex;
align-items: center;
gap: 0.5rem;
}
.actions :global(.button.outline) {
color: var(--color-text-secondary);
}
.limits {
color: var(--color-text-tertiary);
}
.error {
display: flex;
align-items: center;
gap: 0.375rem;
color: var(--color-feedback-error-text);
}
input[type="file"] {
display: none;
}
</style>
<div class="field">
<span class="label txt-body-m-medium">{label}</span>
<input
bind:this={input}
type="file"
accept="image/png,image/jpeg,image/webp,image/gif"
aria-label="{kind} picture"
onchange={() => {
void pick(input?.files?.[0]);
if (input) input.value = "";
}} />
<div class="row">
<button
type="button"
class="preview {kind}"
title={disabled ? undefined : src ? `Replace ${kind}` : `Choose ${kind}`}
{disabled}
onclick={() => input?.click()}>
{#if src && !broken}
<img {src} alt="" onerror={() => (broken = true)} />
{:else if fallbackId}
<UserAvatar nodeId={fallbackId} styleWidth="100%" />
{:else}
<span class="placeholder"><Icon name="placeholder" /></span>
{/if}
{#if !disabled}
<span class="pick"><Icon name={src ? "edit" : "plus"} /></span>
{/if}
</button>
<div class="details">
{#if picked || value}
{#if picked}
<span class="unsaved txt-body-m-regular">
New picture, not saved yet
</span>
{:else}
<span class="source">{value}</span>
{#if value.includes(":")}
<span class="limits txt-body-s-regular">
A web address. Desktop does not load pictures from the web.
</span>
{/if}
{/if}
<!-- A picture that cannot be changed is only shown. -->
{#if !disabled}
<div class="actions">
<Button variant="outline" bordered onclick={remove}>Remove</Button>
</div>
{/if}
{:else if !disabled}
<span class="limits txt-body-s-regular">
Up to {LIMIT_KIB[kind] / 1024} MiB.
</span>
{/if}
</div>
</div>
{#if pickError ?? error}
<span class="error txt-body-m-regular">
<Icon name="warning" />
{pickError ?? error}
</span>
{/if}
</div>
+597
View File
@@ -0,0 +1,597 @@
<script lang="ts">
import type { ActorInfo } from "@bindings/actor/ActorInfo";
import { untrack } from "svelte";
import { nodeRunning } from "@app/lib/events";
import { poll } from "@app/lib/interval";
import { invoke, InvokeError } from "@app/lib/invoke";
import { fetchingRepos, seededRepos, seedRepo } from "@app/lib/seedRepo";
import { parseRepositoryId, publicKeyFromDid } from "@app/lib/utils";
import ActorAvatar from "@app/components/ActorAvatar.svelte";
import Button from "@app/components/Button.svelte";
import Clipboard from "@app/components/Clipboard.svelte";
import Icon from "@app/components/Icon.svelte";
import Spinner from "@app/components/Spinner.svelte";
import TextInput from "@app/components/TextInput.svelte";
import {
describeActorError,
keyKind,
profileName,
reload,
roleText,
} from "./actor";
import KeyChunks from "./KeyChunks.svelte";
import Notice from "./Notice.svelte";
interface Props {
// This device's key, which the approving device shows from the code.
publicKey: string;
// This device's name, shown with its key.
alias: string;
oncancel: () => void;
}
const { publicKey, alias, oncancel }: Props = $props();
let rid = $state("");
let working = $state(false);
let error = $state<string>();
let code = $state<string>();
const EXAMPLE_ID = "rad:z3gqcJUoA1n9HaHKufZs5FCSGazv5";
// The ID as the lists of repositories write it, however it was entered.
const target = $derived.by(() => {
const parsed = parseRepositoryId(rid.trim());
return parsed && `${parsed.prefix}${parsed.pubkey}`;
});
// The profile is looked up as its ID is entered and shown, so the user
// sees whose it is before this device's key consents to anything.
type Check =
| { status: "none" }
| { status: "checking" }
| { status: "ok"; actor: ActorInfo }
| { status: "missing"; rid: string }
// The copy here has no head, so the node fetches nothing more into it.
| { status: "stuck"; rid: string; message: string }
| { status: "failed"; message: string };
let check = $state<Check>({ status: "none" });
// Only the answer to the latest lookup counts.
let latest = 0;
async function lookup(id: string): Promise<void> {
const mine = ++latest;
check = { status: "checking" };
let found: Check;
try {
const actor = await invoke<ActorInfo>("joinable_actor", { rid: id });
found = { status: "ok", actor };
} catch (e) {
found = refusal(id, e);
}
if (mine === latest) check = found;
}
function refusal(id: string, e: unknown): Check {
if (e instanceof InvokeError && e.code === "ActorError.NotFetched") {
return { status: "missing", rid: id };
}
if (e instanceof InvokeError && e.code === "ActorError.CopyStuck") {
return { status: "stuck", rid: id, message: e.message };
}
return {
status: "failed",
message: describeActorError(e, "Could not look up the profile."),
};
}
// A lookup scans every repository, so it waits for the typing to stop.
const CHECK_DELAY_MS = 300;
$effect(() => {
const id = target;
latest += 1;
check = { status: "none" };
error = undefined;
if (id === undefined) return;
const timer = setTimeout(() => void lookup(id), CHECK_DELAY_MS);
return () => clearTimeout(timer);
});
const fetching = $derived(
check.status === "missing" && $fetchingRepos.includes(check.rid),
);
// A look at a profile that is still awaited: one at a time, and only an
// answer changes the page, so a lookup that fails leaves it waiting.
let lookingAgain = false;
async function lookAgain(id: string): Promise<void> {
if (lookingAgain) return;
lookingAgain = true;
const mine = latest;
let found: Check;
try {
const actor = await invoke<ActorInfo>("joinable_actor", { rid: id });
found = { status: "ok", actor };
} catch (e) {
found = refusal(id, e);
} finally {
lookingAgain = false;
}
if (
mine === latest &&
(found.status === "ok" || found.status === "stuck")
) {
check = found;
}
}
// The missing profile whose fetch was asked for or seen on its way.
let awaited: string | undefined;
$effect(() => {
if ($seededRepos === 0) return;
untrack(() => {
if (check.status === "missing") awaited = check.rid;
});
});
// The sidebar looks at what is being fetched once a repository is asked
// for, and every few seconds while any is on its way. An awaited profile
// that is not among them when it has looked may have arrived, however
// quickly the fetch went. One that stays among them is looked up at each
// look, since a copy the node cannot update never leaves them.
$effect(() => {
const underway = $fetchingRepos;
untrack(() => {
if (check.status !== "missing") return;
if (underway.includes(check.rid)) {
if (awaited === check.rid) void lookAgain(check.rid);
awaited = check.rid;
} else if (awaited === check.rid) {
awaited = undefined;
void lookup(check.rid);
}
});
});
// The user asked for this profile by its ID, so fetching it seeds it
// without asking again.
async function fetchProfile(target: string) {
working = true;
error = undefined;
try {
await seedRepo(target);
} catch (e) {
error = describeActorError(e, "Could not fetch the profile.");
} finally {
working = false;
}
}
async function join(target: string) {
working = true;
error = undefined;
try {
code = await invoke<string>("join_actor", { rid: target });
} catch (e) {
error = describeActorError(e, "Could not create a code.");
} finally {
working = false;
}
}
async function submit() {
if (check.status === "ok") {
await join(check.actor.rid);
} else if (check.status === "missing" && !fetching && $nodeRunning) {
// It may have arrived since the last look.
const id = check.rid;
await lookup(id);
if (check.status === "missing") await fetchProfile(id);
}
}
// Storage drops a copy this device never wrote to, so the fetch that
// follows starts from nothing. The user asked for this profile, so it is
// seeded again without asking.
async function fetchAgain(id: string) {
working = true;
error = undefined;
try {
await invoke<null>("clean", { rid: id });
await lookup(id);
if (check.status === "stuck") {
error = "Could not remove this device's copy of the profile.";
} else if (check.status === "missing" && $nodeRunning) {
await seedRepo(id);
}
} catch (e) {
error = describeActorError(e, "Could not fetch the profile again.");
} finally {
working = false;
}
}
function back() {
code = undefined;
if (target !== undefined) void lookup(target);
}
async function done() {
await reload("profile");
oncancel();
}
// While the code waits to be approved, the page looks every few seconds
// for this key in a profile and moves on once it is.
const APPROVAL_POLL_MS = 5000;
$effect(() => {
if (code === undefined) return;
return poll(async active => {
try {
const actor = await invoke<ActorInfo | null>("actor");
if (active() && actor) void reload("profile");
} catch (e) {
console.warn("Could not look for the approval", e);
}
}, APPROVAL_POLL_MS);
});
</script>
<style>
.join {
display: flex;
flex-direction: column;
gap: 1rem;
width: 100%;
max-width: 40rem;
}
.title {
font: var(--txt-body-l-medium);
color: var(--color-text-primary);
}
.text {
color: var(--color-text-secondary);
}
.hint {
color: var(--color-text-tertiary);
}
.error {
color: var(--color-feedback-error-text);
}
.status {
display: flex;
align-items: center;
gap: 0.5rem;
color: var(--color-text-secondary);
}
.step {
display: flex;
gap: 0.75rem;
}
.step-number {
display: inline-flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
width: 1.5rem;
height: 1.5rem;
border-radius: 50%;
background-color: var(--color-surface-subtle);
color: var(--color-text-secondary);
font: var(--txt-body-m-medium);
}
.step-body {
display: flex;
flex-direction: column;
gap: 0.5rem;
min-width: 0;
flex: 1;
}
.found {
display: flex;
flex-direction: column;
gap: 0.75rem;
margin-top: 0.5rem;
}
.found-title {
font: var(--txt-body-l-medium);
color: var(--color-text-primary);
}
.card {
display: flex;
flex-direction: column;
border: 1px solid var(--color-border-subtle);
border-radius: var(--border-radius-md);
background-color: var(--color-surface-canvas);
overflow: hidden;
}
.card-head {
display: flex;
align-items: center;
gap: 0.75rem;
padding: 1rem;
color: var(--color-text-primary);
}
.card-head :global(img) {
border-radius: var(--border-radius-md);
}
.card-name {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: 0.25rem;
}
.card-rid {
color: var(--color-text-tertiary);
word-break: break-all;
}
.devices {
display: flex;
flex-direction: column;
gap: 0.75rem;
padding: 1rem;
border-top: 1px solid var(--color-border-subtle);
}
.device {
display: flex;
align-items: center;
gap: 0.75rem;
}
.device-icon {
display: flex;
align-items: center;
justify-content: center;
width: 2rem;
height: 2rem;
flex-shrink: 0;
border-radius: var(--border-radius-md);
background-color: var(--color-surface-subtle);
color: var(--color-text-secondary);
}
.device-text {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: 0.125rem;
color: var(--color-text-primary);
}
.device-name {
display: flex;
align-items: center;
gap: 0.5rem;
}
.chip {
padding: 0.125rem 0.375rem;
border-radius: var(--border-radius-sm);
background-color: var(--color-surface-subtle);
color: var(--color-text-secondary);
}
.did {
font: var(--txt-code-small);
color: var(--color-text-tertiary);
word-break: break-all;
}
.code {
display: flex;
align-items: flex-start;
gap: 0.5rem;
padding: 0.75rem;
border-radius: var(--border-radius-sm);
background-color: var(--color-surface-subtle);
font: var(--txt-code-regular);
color: var(--color-text-primary);
word-break: break-all;
}
.actions {
display: flex;
align-items: center;
justify-content: flex-end;
gap: 0.5rem;
}
.waiting {
margin-right: auto;
}
</style>
{#snippet copyable(text: string)}
<div class="code">
<span style:flex="1">{text}</span>
<Clipboard {text} />
</div>
{/snippet}
{#snippet found(actor: ActorInfo)}
<div class="found">
<span class="found-title">Is this your profile?</span>
<div class="card">
<div class="card-head">
<ActorAvatar {actor} styleWidth="2.5rem" />
<div class="card-name">
{#if actor.profileUnreadable}
<span class="text txt-body-m-regular">
Its profile file is not one this version of Desktop can read.
</span>
{:else}
<span class="txt-heading-s">{profileName(actor)}</span>
{#if actor.profile?.fullName}
<span class="text txt-body-m-regular">
{actor.profile.fullName}
</span>
{/if}
{/if}
<span class="card-rid txt-body-s-regular">{actor.rid}</span>
</div>
{#if actor.kind === "agent"}
<span class="chip txt-body-s-regular">Automated agent</span>
{/if}
</div>
<div class="devices">
{#each actor.keys as key (key.did)}
{@const role = roleText[keyKind(key)]}
<div class="device">
<span class="device-icon"><Icon name="key" /></span>
<div class="device-text">
<div class="device-name">
<!-- Only a label: a look-alike can copy it. -->
<span class="txt-body-m-medium">{key.alias ?? "Unnamed"}</span>
{#if role}
<span class="chip txt-body-s-regular">{role}</span>
{/if}
</div>
<!-- Whole, since a look-alike only has to match what is shown. -->
<span class="did">{publicKeyFromDid(key.did)}</span>
</div>
</div>
{/each}
</div>
</div>
{#if actor.payloadNewer}
<Notice icon="warning" tone="warning">
<span class="txt-body-s-regular">
Written by a newer Desktop or another app. It may hold keys this
version does not show.
</span>
</Notice>
{/if}
<span class="hint txt-body-s-regular">
Nothing changes until your other devices approve this one.
</span>
</div>
{/snippet}
<div class="join">
<span class="title">Join existing profile</span>
{#if code}
<span class="text txt-body-m-regular">
Paste this code on a device that has your profile, under Keys → Add key.
</span>
{@render copyable(code)}
<span class="text txt-body-m-regular">
It will show this device's key. Check that it matches.
</span>
<KeyChunks {publicKey} name={alias} />
<div class="actions">
<span class="status waiting txt-body-m-regular">
<Spinner />
Waiting for approval…
</span>
<!-- Creating a code writes nothing, so the profile can be looked at again. -->
<Button variant="outline" bordered onclick={back}>Back</Button>
<Button variant="secondary" onclick={() => void done()}>Done</Button>
</div>
{:else}
<div class="step">
<span class="step-number">1</span>
<span class="text txt-body-m-regular">
On a device that already has your profile, open Profile and copy the
Profile ID.
</span>
</div>
<div class="step">
<span class="step-number">2</span>
<div class="step-body">
<span class="text txt-body-m-regular">Paste it here.</span>
<TextInput
bind:value={rid}
placeholder="Profile ID, e.g. {EXAMPLE_ID}"
disabled={working || fetching}
autofocus
onSubmit={() => void submit()} />
{#if rid.trim() && target === undefined}
<span class="hint txt-body-s-regular">
That is not a Profile ID. One looks like {EXAMPLE_ID}.
</span>
{:else if check.status === "missing" && !$nodeRunning}
<!-- The code signs the profile's current state, which only a copy
of it gives, and a stopped node fetches none. -->
<Notice icon="warning" tone="warning">
<span class="txt-body-m-regular">
Your node is offline. Start it to fetch this profile.
</span>
</Notice>
{:else if fetching}
<span class="status txt-body-m-regular">
<Spinner />
Fetching the profile from the network…
</span>
{:else if check.status === "checking"}
<span class="status txt-body-m-regular">Looking up the profile…</span>
{:else if check.status === "missing"}
<span class="status txt-body-m-regular">
This profile is not on this device yet. Fetch it to see whose it is.
</span>
{:else if check.status === "stuck"}
<Notice icon="warning" tone="warning">
<span class="txt-body-m-regular">{check.message}</span>
</Notice>
{:else if check.status === "failed"}
<span class="error txt-body-m-regular">{check.message}</span>
{:else if check.status === "ok"}
{@render found(check.actor)}
{/if}
{#if error}
<span class="error txt-body-m-regular">{error}</span>
{/if}
</div>
</div>
<div class="actions">
<Button variant="outline" bordered onclick={oncancel}>Cancel</Button>
{#if check.status === "missing"}
<Button
variant="secondary"
disabled={fetching || working || !$nodeRunning}
onclick={submit}>
Fetch the profile
</Button>
{:else if check.status === "stuck"}
{@const id = check.rid}
<Button
variant="secondary"
disabled={working}
onclick={() => fetchAgain(id)}>
Fetch again
</Button>
{:else}
<Button
variant="secondary"
disabled={check.status !== "ok" || working}
onclick={submit}>
Create code
</Button>
{/if}
</div>
{/if}
</div>
@@ -0,0 +1,56 @@
<script lang="ts">
interface Props {
// A public key, without the `did:key:` prefix.
publicKey: string;
// The device name the key's node goes by. It only labels the key: a
// look-alike can copy it.
name?: string;
}
const { publicKey, name }: Props = $props();
// Large and in two even lines, so two screens can be compared a line at a
// time.
const LINES = 2;
const lines = $derived.by(() => {
const length = Math.ceil(publicKey.length / LINES);
return Array.from({ length: LINES }, (_, i) =>
publicKey.slice(i * length, (i + 1) * length),
);
});
</script>
<style>
.key {
display: flex;
flex-direction: column;
align-items: center;
padding: 0.75rem 1rem;
border: 1px solid var(--color-border-subtle);
border-radius: var(--border-radius-md);
background-color: var(--color-surface-canvas);
color: var(--color-text-primary);
font: var(--txt-code-regular);
font-size: 1.125rem;
line-height: 1.75rem;
letter-spacing: 0.2em;
}
.name {
margin-top: 0.5rem;
padding: 0 0.375rem;
border-radius: var(--border-radius-sm);
background-color: var(--color-surface-brand-subtle);
color: var(--color-text-brand);
letter-spacing: normal;
}
</style>
<div class="key" aria-label={publicKey}>
{#each lines as line, index (index)}
<span>{line}</span>
{/each}
{#if name}
<span class="name txt-body-m-medium">{name}</span>
{/if}
</div>
+511
View File
@@ -0,0 +1,511 @@
<script lang="ts">
import type { ActorInfo } from "@bindings/actor/ActorInfo";
import type { ActorRevision } from "@bindings/actor/ActorRevision";
import type { HintId } from "@app/lib/hints";
import { hints } from "@app/lib/hints";
import { invoke } from "@app/lib/invoke";
import { show } from "@app/lib/modal";
import { publicKeyFromDid, truncateId } from "@app/lib/utils";
import Button from "@app/components/Button.svelte";
import CopyableId from "@app/components/CopyableId.svelte";
import Icon from "@app/components/Icon.svelte";
import {
type ActorWrite,
ago,
change,
controllersOf,
describeActorError,
keyKind,
keyName,
mayChangeKeys,
roleText,
votedRemoval,
} from "./actor";
import ClosedRevision from "./ClosedRevision.svelte";
import EnrollKey from "./EnrollKey.svelte";
import Notice from "./Notice.svelte";
import PendingRevision from "./PendingRevision.svelte";
interface Props {
actor: ActorInfo;
localDid: string;
}
const { actor, localDid }: Props = $props();
const controllers = $derived(controllersOf(actor));
// The warnings about too few controllers that the user has read and closed,
// by profile. Fewer controllers is a choice, so neither comes back for the
// same count.
const warning = $derived<HintId>(
`profile.controllers:${actor.rid}:${controllers.length}`,
);
const dismiss = () => hints.dismiss(warning);
const canChangeKeys = $derived(mayChangeKeys(actor, localDid));
// What an identity change shows in: the open changes and their votes, the
// keys and what each may do, and the two counts of approvals.
const moved = $derived(
JSON.stringify([
actor.rid,
actor.pending,
actor.keys,
actor.threshold,
actor.majority,
]),
);
// The changes to the keys that ended, newest first, loaded again whenever
// the identity moves.
let closed = $state<ActorRevision[]>([]);
$effect(() => {
void moved;
let gone = false;
invoke<ActorRevision[]>("closed_actor_revisions")
.then(revisions => {
if (!gone) closed = revisions;
})
.catch((e: unknown) =>
console.warn("Could not load the past changes to the keys", e),
);
return () => {
gone = true;
};
});
let acting = $state(false);
let actionError = $state<string>();
let confirmingRevoke = $state<string>();
let revokeError = $state<{ did: string; message: string }>();
// The error goes to the page's own place, or to `onerror` when the caller
// shows it next to what was clicked.
async function act(
write: ActorWrite,
onerror?: (error: unknown) => void,
): Promise<void> {
acting = true;
actionError = undefined;
revokeError = undefined;
try {
await change(write, "keys");
} catch (error) {
if (onerror) onerror(error);
else
actionError = describeActorError(error, "Could not make the change.");
} finally {
acting = false;
}
}
function revoke(did: string) {
confirmingRevoke = undefined;
void act({ command: "remove_actor_key", args: { did } }, error => {
revokeError = {
did,
message: describeActorError(error, "Could not revoke the key.", {
"ActorError.NotController":
"This device's key cannot revoke keys. Revoke from a key that can.",
}),
};
});
}
// A key whose removal has this machine's vote and waits for the others.
function revokePending(did: string): boolean {
return votedRemoval(actor, did, localDid) !== undefined;
}
// A confirmation for a key that left the list must not reopen when it
// comes back.
$effect(() => {
if (
confirmingRevoke &&
!actor.keys.some(key => key.did === confirmingRevoke)
)
confirmingRevoke = undefined;
});
function openEnroll() {
show({
component: EnrollKey,
props: {
rid: actor.rid,
majority: actor.majority,
confirm: (code: string, controller: boolean) =>
change(
{ command: "approve_enrollment", args: { code, controller } },
"keys",
),
},
});
}
</script>
<style>
.quorums {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 0.75rem;
}
.quorum {
display: flex;
flex-direction: column;
gap: 0.375rem;
padding: 0.875rem;
border: 1px solid var(--color-border-subtle);
border-radius: var(--border-radius-md);
background-color: var(--color-surface-canvas);
}
.quorum-title {
display: flex;
align-items: center;
gap: 0.375rem;
color: var(--color-text-secondary);
}
.quorum-value {
color: var(--color-text-primary);
}
.quorum-note {
color: var(--color-text-tertiary);
}
/* Past changes in one box, each below the last. */
.closed {
display: flex;
flex-direction: column;
border: 1px solid var(--color-border-subtle);
border-radius: var(--border-radius-md);
background-color: var(--color-surface-canvas);
}
.closed > :global(* + *) {
border-top: 1px solid var(--color-border-subtle);
}
.approvals {
display: flex;
flex-direction: column;
gap: 0.75rem;
}
.footer-note {
color: var(--color-text-tertiary);
}
.error {
color: var(--color-feedback-error-text);
}
.section-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 1rem;
margin-bottom: 0.625rem;
}
/* As tall as its title, so the taller button beside it does not push the
first line lower than on the Profile tab. */
.section-header.with-action {
height: 1.25rem;
margin-bottom: 1rem;
}
.section-title {
display: inline-flex;
align-items: center;
gap: 0.375rem;
color: var(--color-text-secondary);
}
.keys {
display: flex;
flex-direction: column;
border: 1px solid var(--color-border-subtle);
border-radius: var(--border-radius-md);
overflow: hidden;
}
.key {
display: flex;
align-items: center;
gap: 0.75rem;
padding: 0.75rem;
background-color: var(--color-surface-canvas);
}
.key + .key {
border-top: 1px solid var(--color-border-subtle);
}
.key-icon {
display: flex;
align-items: center;
justify-content: center;
width: 2rem;
height: 2rem;
flex-shrink: 0;
border-radius: var(--border-radius-md);
background-color: var(--color-surface-subtle);
color: var(--color-text-secondary);
}
.key-actions {
flex-shrink: 0;
}
.confirm {
display: flex;
align-items: center;
gap: 0.375rem;
}
.confirm-text {
color: var(--color-text-secondary);
}
.key-text {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: 0.25rem;
}
.key-name-row {
display: flex;
align-items: center;
gap: 0.5rem;
flex-wrap: wrap;
}
.key-name {
color: var(--color-text-primary);
}
.chip {
padding: 0.125rem 0.375rem;
border-radius: var(--border-radius-sm);
background-color: var(--color-surface-subtle);
color: var(--color-text-secondary);
}
.chip.brand {
background-color: var(--color-surface-brand-subtle);
color: var(--color-text-brand);
}
.key-facts {
display: flex;
align-items: center;
gap: 0.5rem;
flex-wrap: wrap;
color: var(--color-text-tertiary);
}
.separator {
color: var(--color-text-quaternary);
}
</style>
{#if actor.payloadNewer}
<Notice
icon="warning"
title="Written by a newer Desktop or another app"
tone="warning">
<span class="txt-body-m-regular">
This profile holds fields this version of Desktop does not know, so the
keys cannot be changed here. It may also hold keys this version does not
show.
</span>
</Notice>
{/if}
<div>
<div class="section-header with-action">
<span class="section-title txt-body-m-medium">
Keys
<span class="global-counter-badge">{actor.keys.length}</span>
</span>
{#if canChangeKeys}
<Button variant="secondary" onclick={openEnroll}>
<Icon name="plus" />
Add key
</Button>
{/if}
</div>
<div class="keys">
{#each actor.keys as key (key.did)}
{@const kind = keyKind(key)}
{@const role = roleText[kind]}
<div class="key">
<span class="key-icon">
<Icon name={kind === "recovery" ? "lock" : "key"} />
</span>
<div class="key-text">
<div class="key-name-row">
<span class="key-name txt-body-m-medium">
{keyName(actor, key.did)}
</span>
{#if key.did === localDid}
<span class="chip brand txt-body-m-medium">This device</span>
{/if}
{#if role}
<span class="chip txt-body-m-medium">{role}</span>
{/if}
</div>
<div class="key-facts txt-body-m-regular">
<CopyableId id={key.did} styleFont="var(--txt-body-m-regular)">
{truncateId(publicKeyFromDid(key.did))}
</CopyableId>
<span class="separator">·</span>
<span>added {ago(key.addedAt)}</span>
{#if key.did === localDid}
<span class="separator">·</span>
<span>active now</span>
{:else if !key.bound}
<span class="separator">·</span>
<span>kept offline</span>
{/if}
</div>
{#if revokeError?.did === key.did}
<span class="error txt-body-m-regular">{revokeError.message}</span>
{/if}
</div>
<!-- Revoking the key this machine signs with would lock it out. -->
{#if canChangeKeys && key.did !== localDid}
<div class="key-actions">
{#if confirmingRevoke === key.did}
<div class="confirm">
<span class="confirm-text txt-body-m-regular">
{#if key.controller && controllers.length - 1 < actor.majority}
This needs its own approval too. Propose anyway?
{:else}
{actor.majority > 1 ? "Propose revoking?" : "Revoke?"}
{/if}
</span>
<Button
variant="ghost"
styleHeight="1.75rem"
disabled={acting}
onclick={() => revoke(key.did)}>
Yes
</Button>
<Button
variant="outline"
styleHeight="1.75rem"
disabled={acting}
onclick={() => (confirmingRevoke = undefined)}>
Cancel
</Button>
</div>
{:else if revokePending(key.did)}
<span class="chip txt-body-m-medium">Revoke pending</span>
{:else}
<Button
variant="naked"
title="Revoke key"
disabled={acting}
onclick={() => (confirmingRevoke = key.did)}>
<Icon name="trash" />
</Button>
{/if}
</div>
{/if}
</div>
{/each}
</div>
<!-- The key the error is about can be gone after the reload. -->
{#if revokeError && !actor.keys.some(key => key.did === revokeError?.did)}
<span class="footer-note error txt-body-m-regular">
{revokeError.message}
</span>
{/if}
</div>
<!-- Below three controllers, losing one can freeze the keys for good. -->
{#if controllers.length === 2 && !hints.isDismissed(warning)}
<Notice
icon="warning"
title="Don't get locked out"
tone="warning"
ondismiss={dismiss}>
<span class="txt-body-m-regular">
With two controllers, both have to approve every change to your keys. If
you lose one, you can never remove it or add a replacement. With three
controllers, any two can approve, so losing one does not lock you out.
</span>
</Notice>
{:else if controllers.length === 1 && !hints.isDismissed(warning)}
<Notice
icon="warning"
title="Only one controller"
tone="warning"
ondismiss={dismiss}>
<span class="txt-body-m-regular">
Lose this key and you lose control of the profile, with no way to get it
back. Three controllers is the recommended minimum.
</span>
</Notice>
{/if}
<div>
<div class="section-header">
<span class="section-title txt-body-m-medium">Approvals needed</span>
</div>
<div class="quorums">
<div class="quorum">
<span class="quorum-title txt-body-m-medium">
<Icon name="key" />
Adding or removing a key
</span>
<span class="quorum-value txt-heading-s">
{actor.majority} of {controllers.length}
</span>
<span class="quorum-note txt-body-m-regular">
How many of your controllers have to approve. Always a majority, so it
rises as you add keys.
</span>
</div>
<div class="quorum">
<span class="quorum-title txt-body-m-medium">
<Icon name="edit" />
Editing your profile
</span>
<span class="quorum-value txt-heading-s">
{actor.threshold} of {controllers.length}
</span>
<span class="quorum-note txt-body-m-regular">
How many controllers have to agree on an edit. With one, your edits show
up straight away.
</span>
</div>
</div>
</div>
{#if actor.pending.length > 0 || closed.length > 0}
<div>
<div class="section-header">
<span class="section-title txt-body-m-medium">Changes</span>
</div>
<div class="approvals">
{#each actor.pending as revision (revision.id)}
<PendingRevision {actor} {revision} {localDid} {acting} {act} />
{/each}
{#if closed.length > 0}
<div class="closed">
{#each closed as revision, index (revision.id)}
<ClosedRevision
{actor}
{revision}
{localDid}
first={index === closed.length - 1} />
{/each}
</div>
{/if}
</div>
</div>
{/if}
{#if actionError}
<span class="footer-note error txt-body-m-regular">{actionError}</span>
{/if}
+132
View File
@@ -0,0 +1,132 @@
<script lang="ts">
import type { ComponentProps, Snippet } from "svelte";
import Icon from "@app/components/Icon.svelte";
interface Props {
icon: ComponentProps<typeof Icon>["name"];
// With a title, the icon heads the box and the children follow below;
// without one, the icon sits beside the text.
title?: string;
tone?: "error" | "warning";
// Ends the notice with a button the user acknowledges it with.
ondismiss?: () => void;
children: Snippet;
}
const { icon, title, tone, ondismiss, children }: Props = $props();
</script>
<style>
.notice {
display: flex;
flex-direction: column;
gap: 0.375rem;
padding: 0.75rem;
border: 1px solid var(--color-border-subtle);
border-radius: var(--border-radius-md);
background-color: var(--color-surface-subtle);
color: var(--color-text-secondary);
}
.notice.inline {
flex-direction: row;
gap: 0.5rem;
}
.notice.error {
border-color: var(--color-feedback-error-border);
background-color: var(--color-feedback-error-bg);
color: var(--color-feedback-error-text);
}
.notice.warning {
border-color: var(--color-feedback-warning-border);
background-color: var(--color-feedback-warning-bg);
color: var(--color-text-primary);
}
.heading {
display: flex;
align-items: center;
gap: 0.375rem;
color: var(--color-text-primary);
}
.content {
display: flex;
flex-direction: column;
gap: 0.375rem;
min-width: 0;
}
.dismiss {
display: flex;
margin-top: 0.375rem;
}
/* The app's filled primary button, in the notice's color. */
.acknowledge {
height: 1.75rem;
padding: 0 0.5rem;
border: 0;
border-radius: var(--border-radius-sm);
background-color: var(--tone-fill, var(--color-surface-brand-secondary));
color: var(--color-text-on-brand);
cursor: pointer;
}
.acknowledge:hover {
background-color: var(
--tone-fill-hover,
var(--color-surface-brand-primary)
);
}
.notice.warning {
--tone-fill: var(--color-feedback-warning-border);
--tone-fill-hover: color-mix(
in srgb,
var(--color-feedback-warning-border) 85%,
black
);
}
.notice.error {
--tone-fill: var(--color-feedback-error-fill);
--tone-fill-hover: var(--color-feedback-error-fill-hover);
}
.notice.error .heading {
color: inherit;
}
.icon {
display: flex;
flex-shrink: 0;
color: var(--color-text-tertiary);
padding-top: 0.0625rem;
}
.notice.warning .icon {
color: inherit;
}
</style>
<div
class="notice"
class:inline={!title}
class:error={tone === "error"}
class:warning={tone === "warning"}>
{#if title}
<div class="heading txt-body-m-medium">
<Icon name={icon} />
{title}
</div>
{:else}
<span class="icon">
<Icon name={icon} />
</span>
{/if}
<!-- Beside the icon in an inline notice, so the button goes under the
text rather than next to it. -->
<div class="content">
{@render children()}
{#if ondismiss}
<div class="dismiss">
<button class="acknowledge txt-body-m-medium" onclick={ondismiss}>
I understand
</button>
</div>
{/if}
</div>
</div>
@@ -0,0 +1,332 @@
<script lang="ts">
import type { ActorInfo } from "@bindings/actor/ActorInfo";
import type { ActorRevision } from "@bindings/actor/ActorRevision";
import { publicKeyFromDid } from "@app/lib/utils";
import Button from "@app/components/Button.svelte";
import Clipboard from "@app/components/Clipboard.svelte";
import Icon from "@app/components/Icon.svelte";
import {
type ActorWrite,
ago,
controllersOf,
describeActorError,
isController,
keyName,
mayChangeKeys,
revisionTitle,
type Vote,
votesText,
} from "./actor";
interface Props {
actor: ActorInfo;
revision: ActorRevision;
localDid: string;
acting: boolean;
act: (
write: ActorWrite,
onerror?: (error: unknown) => void,
) => Promise<void>;
}
const { actor, revision, localDid, acting, act }: Props = $props();
// A vote's error stays on the card it was cast from.
let error = $state<string>();
const vote = (command: Vote) => {
error = undefined;
void act({ command, args: { id: revision.id } }, e => {
error = describeActorError(e, "Could not make the change.");
});
};
const controllers = $derived(controllersOf(actor));
const controls = $derived(isController(actor, localDid));
const canChangeKeys = $derived(mayChangeKeys(actor, localDid));
const mine = $derived(revision.author === localDid);
const signed = $derived(revision.accepted.includes(localDid));
const rejected = $derived(revision.rejected.includes(localDid));
const removesMe = $derived(revision.removed.includes(localDid));
const hinted = $derived(revision.unreadable || removesMe);
const votes = $derived(mine || (controls && !signed && !rejected));
const title = $derived(revisionTitle(actor, revision));
</script>
<style>
.approval {
display: flex;
flex-direction: column;
gap: 0.875rem;
padding: 0.875rem;
border: 1px solid var(--color-border-subtle);
border-radius: var(--border-radius-md);
background-color: var(--color-surface-canvas);
}
.approval-head {
display: flex;
align-items: flex-start;
gap: 0.75rem;
}
.approval-icon {
display: flex;
align-items: center;
justify-content: center;
width: 2rem;
height: 2rem;
flex-shrink: 0;
border-radius: var(--border-radius-md);
background-color: var(--color-surface-subtle);
color: var(--color-text-secondary);
}
.approval-text {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: 0.25rem;
color: var(--color-text-primary);
}
.byline,
.actions-hint {
color: var(--color-text-tertiary);
}
/* The buttons line up with the bottom of a hint that holds a command. */
.actions.tall {
align-items: flex-end;
}
.status {
flex-shrink: 0;
padding: 0.125rem 0.5rem;
border-radius: var(--border-radius-sm);
background-color: var(--color-feedback-warning-bg);
color: var(--color-feedback-warning-text);
}
.status.rejected {
background-color: var(--color-feedback-error-bg);
color: var(--color-feedback-error-text);
}
.actions {
display: flex;
align-items: center;
gap: 0.5rem;
}
.actions-hint {
margin-right: auto;
}
.command {
display: flex;
align-items: flex-start;
gap: 0.5rem;
padding: 0.75rem;
border-radius: var(--border-radius-sm);
background-color: var(--color-surface-subtle);
font: var(--txt-code-regular);
color: var(--color-text-primary);
}
.unsupported {
display: flex;
flex-direction: column;
gap: 0.5rem;
min-width: 0;
word-break: break-all;
}
.signatures {
display: flex;
flex-direction: column;
gap: 0.5rem;
padding-top: 0.875rem;
border-top: 1px solid var(--color-border-subtle);
}
.progress-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.75rem;
color: var(--color-text-secondary);
}
.track {
display: flex;
gap: 0.1875rem;
flex: 1;
max-width: 12rem;
}
.segment {
flex: 1;
height: 0.25rem;
border-radius: var(--border-radius-sm);
background-color: var(--color-surface-mid);
}
.segment.filled {
background-color: var(--color-feedback-success-fill);
}
.signer {
display: flex;
align-items: center;
gap: 0.5rem;
color: var(--color-text-primary);
}
.signer-icon {
display: flex;
flex-shrink: 0;
color: var(--color-text-quaternary);
}
.signer-icon.signed {
color: var(--color-feedback-success-text);
}
.signer-icon.rejected {
color: var(--color-feedback-error-text);
}
.added-key {
display: flex;
flex-direction: column;
gap: 0.25rem;
padding: 0.5rem 0;
border-top: 1px solid var(--color-border-hint);
}
.mono {
font: var(--txt-code-regular);
color: var(--color-text-primary);
word-break: break-all;
}
.card-error {
color: var(--color-feedback-error-text);
}
.chip.brand {
padding: 0 0.375rem;
border-radius: var(--border-radius-sm);
background-color: var(--color-surface-brand-subtle);
color: var(--color-text-brand);
}
.signer-when {
margin-left: auto;
color: var(--color-text-tertiary);
}
</style>
<div class="approval">
<div class="approval-head">
<span class="approval-icon"><Icon name="key" /></span>
<div class="approval-text">
<span class="txt-body-m-medium">{title}</span>
<span class="byline txt-body-m-regular">
Proposed by {mine ? "this device" : keyName(actor, revision.author)}
{ago(revision.createdAt)}
</span>
</div>
{#if revision.rejected.length > 0}
<span class="status rejected txt-body-m-medium">Rejected</span>
{:else}
<span class="status txt-body-m-medium">Awaiting signatures</span>
{/if}
</div>
<!-- Approving is a decision about a key, so each key added is shown
whole; the alias only labels it. -->
{#each revision.added as key (key.did)}
<div class="added-key txt-body-m-regular">
{#if key.alias}
<span class="txt-body-m-medium">{key.alias}</span>
{/if}
<span class="mono">{publicKeyFromDid(key.did)}</span>
</div>
{/each}
<div class="signatures">
<div class="progress-row">
<span class="txt-body-m-medium">
{votesText(actor, revision)}
</span>
<div class="track">
{#each Array.from({ length: actor.majority }, (_, i) => i) as slot (slot)}
<span class="segment" class:filled={slot < revision.accepted.length}>
</span>
{/each}
</div>
</div>
{#each controllers as key (key.did)}
{@const verdict = revision.accepted.includes(key.did)
? "signed"
: revision.rejected.includes(key.did)
? "rejected"
: "waiting"}
<div class="signer txt-body-m-regular">
<span
class="signer-icon"
class:signed={verdict === "signed"}
class:rejected={verdict === "rejected"}>
<Icon
name={verdict === "signed"
? "checkmark"
: verdict === "rejected"
? "close"
: "clock"} />
</span>
<span>{keyName(actor, key.did)}</span>
{#if key.did === localDid}
<span class="chip brand txt-body-s-regular">This device</span>
{/if}
<span class="signer-when">{verdict}</span>
</div>
{/each}
</div>
{#if hinted || votes}
<div class="actions" class:tall={revision.unreadable}>
<span class="actions-hint txt-body-m-regular">
{#if revision.unreadable}
{@const command = `rad id show ${revision.id} --repo ${actor.rid}`}
<span class="unsupported">
This change edits more than this version of Desktop supports. Review
it with this command.
<span class="command">
<span style:flex="1">{command}</span>
<Clipboard text={command} />
</span>
</span>
{:else if removesMe}
Approving removes this device from your profile.
{/if}
</span>
{#if mine}
<Button
variant="outline"
bordered
disabled={acting}
onclick={() => vote("withdraw_actor_revision")}>
Withdraw
</Button>
{:else if controls && !signed && !rejected}
<Button
variant="outline"
bordered
disabled={acting}
onclick={() => vote("reject_actor_revision")}>
Reject
</Button>
{#if canChangeKeys && !revision.unreadable}
<Button
variant="secondary"
disabled={acting}
onclick={() => vote("approve_actor_revision")}>
Approve
</Button>
{/if}
{/if}
</div>
{/if}
{#if error}
<span class="card-error txt-body-m-regular">{error}</span>
{/if}
</div>
+272
View File
@@ -0,0 +1,272 @@
<script lang="ts">
import type { ComponentProps } from "svelte";
import * as router from "@app/lib/router";
import type { ProfileTab, SidebarData } from "@app/lib/router/definitions";
import { didFromPublicKey } from "@app/lib/utils";
import Button from "@app/components/Button.svelte";
import CopyableId from "@app/components/CopyableId.svelte";
import Icon from "@app/components/Icon.svelte";
import ScrollArea from "@app/components/ScrollArea.svelte";
import Topbar from "@app/components/Topbar.svelte";
import Layout from "@app/views/repo/Layout.svelte";
import JoinActor from "./JoinActor.svelte";
import Keys from "./Keys.svelte";
import Notice from "./Notice.svelte";
import ProfileForm from "./ProfileForm.svelte";
import SeveralProfiles from "./SeveralProfiles.svelte";
interface Props {
sidebarData: SidebarData;
tab: ProfileTab;
}
const { sidebarData, tab }: Props = $props();
const actor = $derived(sidebarData.actor);
const localDid = $derived(didFromPublicKey(sidebarData.config.publicKey));
const tabs = $derived<
{
value: ProfileTab;
label: string;
icon: ComponentProps<typeof Icon>["name"];
count?: number;
}[]
>([
{ value: "profile", label: "Profile", icon: "avatar-incognito" },
{ value: "keys", label: "Keys", icon: "key", count: actor?.keys.length },
]);
// The user may well have a profile on another device, so this speaks only
// of this one.
const NO_PROFILE = "This device has no profile yet.";
let editing = $state(false);
let joining = $state(false);
// A profile that arrives while the form is up, as after a create, ends the
// choice.
$effect(() => {
if (actor) {
editing = false;
joining = false;
}
});
</script>
<style>
.page {
display: flex;
flex-direction: column;
height: 100%;
}
.tabs {
display: flex;
align-items: center;
gap: 0.25rem;
}
.tab {
display: flex;
align-items: center;
gap: 0.25rem;
font: var(--txt-body-m-regular);
color: var(--color-text-secondary);
padding: 0.25rem 0.5rem;
border-radius: var(--border-radius-sm);
text-decoration: none;
cursor: pointer;
white-space: nowrap;
}
.tab:hover {
background-color: var(--color-surface-subtle);
color: var(--color-text-primary);
}
.tab.active {
background-color: var(--color-surface-subtle);
color: var(--color-text-primary);
}
.topbar-end {
margin-left: auto;
display: flex;
align-items: center;
gap: 0.5rem;
}
.actor-label {
color: var(--color-text-tertiary);
}
.chip {
padding: 0.125rem 0.375rem;
border-radius: var(--border-radius-sm);
background-color: var(--color-surface-subtle);
color: var(--color-text-secondary);
}
.body {
flex: 1;
min-height: 0;
}
.inner {
width: min(100%, 52rem);
margin: 0 auto;
padding: 1.5rem 1.5rem 7rem;
display: flex;
flex-direction: column;
gap: 1.5rem;
}
/* Room for the preview beside the form. */
.inner.wide {
width: min(100%, 68rem);
}
.missing {
display: flex;
flex-direction: column;
align-items: center;
gap: 0.5rem;
text-align: center;
color: var(--color-text-secondary);
}
.missing-icon {
display: flex;
margin-bottom: 0.5rem;
color: var(--color-text-tertiary);
}
.missing-title {
color: var(--color-text-primary);
}
.empty {
display: flex;
height: 100%;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 1rem;
}
</style>
{#snippet failed(error: { code: string; message: string })}
{#if error.code === "ActorError.Ambiguous"}
<ScrollArea style="height: 100%; min-width: 0;">
<div class="inner">
<SeveralProfiles {localDid} {tab} message={error.message} />
</div>
</ScrollArea>
{:else}
<div class="empty">
<div class="inner">
<Notice icon="warning" tone="error" title="Could not load the profile">
<span class="txt-body-m-regular">{error.message}</span>
</Notice>
</div>
</div>
{/if}
{/snippet}
{#snippet missing(text: string)}
<div class="missing">
<span class="missing-icon"><Icon name="avatar-incognito" size="32" /></span>
<span class="missing-title txt-body-l-medium">{text}</span>
<span class="txt-body-m-regular">
A profile ties your devices together under one name.
</span>
</div>
{/snippet}
<Layout selfScroll>
<div class="page">
<Topbar>
<div class="tabs">
{#each tabs as t (t.value)}
<a
class="tab"
class:active={tab === t.value}
href={router.routeToPath({ resource: "profile", tab: t.value })}>
<Icon name={t.icon} />
{t.label}
{#if t.count}
<span class="global-counter-badge">{t.count}</span>
{/if}
</a>
{/each}
</div>
{#if actor}
<div class="topbar-end">
{#if actor.kind === "agent"}
<span class="chip txt-body-m-regular">Automated agent</span>
{/if}
<span class="actor-label txt-body-m-regular">Profile ID</span>
<CopyableId id={actor.rid} styleFont="var(--txt-body-m-regular)">
{actor.rid}
</CopyableId>
<Button
variant="ghost"
title="The identity document of this profile"
onclick={() =>
router.push({ resource: "repo.identity", rid: actor.rid })}>
<Icon name="code" />
Identity
</Button>
</div>
{/if}
</Topbar>
<div class="body">
{#if sidebarData.actorError}
{@render failed(sidebarData.actorError)}
{:else if tab === "profile"}
{#if actor || editing}
<ScrollArea style="height: 100%; min-width: 0;">
<div class="inner wide">
<ProfileForm
{actor}
{localDid}
config={sidebarData.config}
oncancel={() => (editing = false)} />
</div>
</ScrollArea>
{:else if joining}
<div class="empty">
<JoinActor
publicKey={sidebarData.config.publicKey}
alias={sidebarData.config.alias}
oncancel={() => (joining = false)} />
</div>
{:else}
<div class="empty">
{@render missing(NO_PROFILE)}
<div
class="global-flex"
style:gap="0.5rem"
style:margin-top="0.5rem">
<Button
variant="outline"
bordered
onclick={() => (joining = true)}>
Join existing profile
</Button>
<Button variant="secondary" onclick={() => (editing = true)}>
Create a new profile
</Button>
</div>
</div>
{/if}
{:else if actor}
<ScrollArea style="height: 100%; min-width: 0;">
<div class="inner">
<Keys {actor} {localDid} />
</div>
</ScrollArea>
{:else}
<div class="empty">
{@render missing(NO_PROFILE)}
</div>
{/if}
</div>
</div>
</Layout>
@@ -0,0 +1,179 @@
<script lang="ts">
import type { ActorInfo } from "@bindings/actor/ActorInfo";
import { hide } from "@app/lib/modal";
import * as router from "@app/lib/router";
import ActorAvatar from "@app/components/ActorAvatar.svelte";
import Button from "@app/components/Button.svelte";
import Clipboard from "@app/components/Clipboard.svelte";
import Icon from "@app/components/Icon.svelte";
import { profileName } from "./actor";
interface Props {
actor: ActorInfo;
}
const { actor }: Props = $props();
const rid = $derived(actor.rid);
async function toKeys() {
hide();
await router.push({ resource: "profile", tab: "keys" });
}
</script>
<style>
.modal {
width: 30rem;
max-width: 92vw;
display: flex;
flex-direction: column;
border: 1px solid var(--color-border-subtle);
border-radius: var(--border-radius-lg);
background-color: var(--color-surface-canvas);
overflow: hidden;
}
.header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 0 1.5rem;
height: 3.25rem;
border-bottom: 1px solid var(--color-border-subtle);
}
.title {
font: var(--txt-heading-s);
color: var(--color-text-primary);
}
.body {
display: flex;
flex-direction: column;
gap: 1.25rem;
padding: 1.5rem;
}
.profile {
display: flex;
align-items: center;
gap: 0.75rem;
}
.avatar {
width: 2.5rem;
height: 2.5rem;
flex-shrink: 0;
overflow: hidden;
border-radius: var(--border-radius-md);
}
.name {
min-width: 0;
overflow-wrap: anywhere;
color: var(--color-text-primary);
}
.next {
display: flex;
flex-direction: column;
gap: 0.75rem;
padding-top: 1.25rem;
border-top: 1px solid var(--color-border-subtle);
}
.next-title {
color: var(--color-text-primary);
}
.step {
display: flex;
gap: 0.75rem;
color: var(--color-text-secondary);
}
.step-number {
display: inline-flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
width: 1.5rem;
height: 1.5rem;
border-radius: 50%;
background-color: var(--color-surface-subtle);
color: var(--color-text-secondary);
font: var(--txt-body-m-medium);
}
.step-body {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: 0.5rem;
padding-top: 0.125rem;
}
.id {
display: flex;
align-items: center;
gap: 0.5rem;
padding: 0.625rem 0.75rem;
border-radius: var(--border-radius-sm);
background-color: var(--color-surface-subtle);
font: var(--txt-code-regular);
color: var(--color-text-primary);
word-break: break-all;
}
.actions {
display: flex;
justify-content: flex-end;
gap: 0.5rem;
padding: 0 1.5rem 1.5rem;
}
</style>
<div class="modal">
<div class="header">
<span class="title">Profile created</span>
<Button variant="naked" onclick={hide}>
<span style:color="var(--color-text-tertiary)">
<Icon name="close" />
</span>
</Button>
</div>
<div class="body">
<div class="profile">
<span class="avatar">
<ActorAvatar {actor} styleWidth="100%" />
</span>
<span class="name txt-body-m-medium">{profileName(actor)}</span>
</div>
<div class="next">
<span class="next-title txt-body-m-medium">Add your other devices</span>
<div class="step txt-body-m-regular">
<span class="step-number">1</span>
<span class="step-body">
On another device, open Profile and choose Join existing profile.
</span>
</div>
<div class="step txt-body-m-regular">
<span class="step-number">2</span>
<div class="step-body">
Paste this Profile ID.
<div class="id">
<span style:flex="1">{rid}</span>
<Clipboard text={rid} />
</div>
</div>
</div>
<div class="step txt-body-m-regular">
<span class="step-number">3</span>
<span class="step-body">Approve the device here, under Keys.</span>
</div>
</div>
</div>
<div class="actions">
<Button variant="outline" bordered onclick={hide}>Done</Button>
<Button variant="secondary" onclick={() => void toKeys()}>
Go to Keys
</Button>
</div>
</div>
@@ -0,0 +1,965 @@
<script lang="ts">
import type { ActorFork } from "@bindings/actor/ActorFork";
import type { ActorInfo } from "@bindings/actor/ActorInfo";
import type { ActorProfile } from "@bindings/actor/ActorProfile";
import type { ProfileLink } from "@bindings/actor/ProfileLink";
import type { Config } from "@bindings/config/Config";
import { onDestroy, untrack } from "svelte";
import { hints } from "@app/lib/hints";
import { entityUrl } from "@app/lib/mentions";
import { show } from "@app/lib/modal";
import { RepoImages } from "@app/lib/repoImages";
import Button from "@app/components/Button.svelte";
import Icon from "@app/components/Icon.svelte";
import TextInput from "@app/components/TextInput.svelte";
import ProfileHistory from "@app/modals/ProfileHistory.svelte";
import { change, describeActorError, isController } from "./actor";
import ExplorerPreview from "./ExplorerPreview.svelte";
import {
compareVersions,
fieldValue,
type Form,
laidOver,
type MergeField,
TEXT_FIELDS,
type TextField,
} from "./form";
import HoverCard from "./HoverCard.svelte";
import ImagePicker, { type PickedImage } from "./ImagePicker.svelte";
import Notice from "./Notice.svelte";
import ProfileCreated from "./ProfileCreated.svelte";
import PronounsPicker from "./PronounsPicker.svelte";
import SplitNotice from "./SplitNotice.svelte";
import TimezonePicker from "./TimezonePicker.svelte";
interface Props {
actor: ActorInfo | null;
localDid: string;
config: Config;
// Leaves the form of a profile not created yet.
oncancel: () => void;
}
const { actor, localDid, config, oncancel }: Props = $props();
// The limits of the profile file, as the backend checks them.
const LIMITS = { string: 255, label: 64, links: 16 } as const;
const LINK_SCHEMES = ["https", "http", "mailto", "rad"];
const IMAGE_SCHEMES = ["https", "http"];
let nextLinkId = 0;
const linkRow = (link: ProfileLink) => ({ ...link, id: nextLinkId++ });
// What a text field shows besides its label: a description above the
// input, a hint below it.
type TextOptions = {
required?: boolean;
description?: string;
hint?: string;
placeholder?: string;
autofocus?: boolean;
};
function formFrom(profile: ActorProfile | undefined): Form {
return {
displayName: profile?.displayName ?? "",
fullName: profile?.fullName ?? "",
pronouns: profile?.pronouns ?? "",
bio: profile?.bio ?? "",
location: profile?.location ?? "",
timezone: profile?.timezone ?? "",
avatar: profile?.avatar ?? "",
banner: profile?.banner ?? "",
links: (profile?.links ?? []).map(linkRow),
};
}
function profileFrom(form: Form): ActorProfile {
const field = (value: string) => value.trim() || undefined;
return {
version: 1,
displayName: form.displayName.trim(),
fullName: field(form.fullName),
pronouns: field(form.pronouns),
bio: field(form.bio),
location: field(form.location),
timezone: field(form.timezone),
avatar: field(form.avatar),
banner: field(form.banner),
links: form.links
.filter(link => link.url.trim() !== "")
.map(({ url, label }) => ({
url: url.trim(),
label: field(label ?? ""),
})),
};
}
// An edit is the profile only once enough controllers carry it, and a
// save here is carried by this key alone. Where that is not enough, there
// is no step for the others to take it over, so the profile is only shown.
const cannotEdit = $derived.by(() => {
if (actor === null) return undefined;
if (!isController(actor, localDid)) {
return "Only a device that controls this profile can edit it. Keys lists which devices do.";
}
if (actor.threshold > 1) {
return `Edits to this profile need ${actor.threshold} controllers to agree, so it is shown here read-only.`;
}
return undefined;
});
const shown = $derived(actor?.profile);
const shownHead = $derived(actor?.head);
// The parent reuses this component across routes, so the form is rebuilt
// when the route brings a different profile, as after a save.
// svelte-ignore state_referenced_locally
let form = $state<Form>(formFrom(actor?.profile));
// svelte-ignore state_referenced_locally
let lastHead = actor?.head;
// The profile the form was built from, to tell edits from a clean form.
// svelte-ignore state_referenced_locally
let base = actor?.profile;
$effect(() => {
if (shownHead !== lastHead) {
lastHead = shownHead;
// A create form whose key turned out to have a profile, made elsewhere
// or just now: what was typed goes over it, so a save does not blank
// its other fields. Otherwise edits survive a head that moved under
// them; a save then extends the new head.
if (base === undefined && shown !== undefined) {
form = laidOver(form, formFrom(shown), formFrom(undefined));
} else if (same(form, formFrom(base)) && !anyPicked) {
form = formFrom(shown);
submitted = false;
}
base = shown;
}
});
// The pictures chosen since the last save. Each replaces what its field
// holds when the profile is saved.
type ImageField = "avatar" | "banner";
let picked = $state<Partial<Record<ImageField, PickedImage>>>({});
const anyPicked = $derived(
picked.avatar !== undefined || picked.banner !== undefined,
);
const images = new RepoImages();
onDestroy(() => images.dispose());
// The file in the profile's repository that the saved profile names and
// the form still does.
function savedImage(field: ImageField) {
const path = shown?.[field];
if (!actor?.head || !path || path.includes(":")) return undefined;
if (picked[field] || form[field].trim() !== path) return undefined;
return { rid: actor.rid, head: actor.head, path };
}
// The saved pictures the form still names, loaded to show them.
const savedUrls = $state<Partial<Record<ImageField, string>>>({});
for (const field of ["avatar", "banner"] as const) {
$effect(() => {
const ref = savedImage(field);
if (!ref) {
savedUrls[field] = undefined;
return;
}
let gone = false;
void images
.load(ref.rid, ref.head, ref.path)
.then(image => {
if (!gone) savedUrls[field] = image?.url;
})
.catch((e: unknown) => {
console.warn(`Could not load the ${field} picture`, e);
if (!gone) savedUrls[field] = undefined;
});
return () => {
gone = true;
};
});
}
// The picture a field shows: one picked and not saved, or the saved file.
// One kept at a web address is not fetched, since that would tell its host
// who is looking.
function imageSrc(field: ImageField): string | undefined {
return picked[field]?.url ?? savedUrls[field];
}
// The previews show the form as typed, where the profile is seen.
type Surface = "card" | "explorer";
let surface = $state<Surface>("card");
const avatarId = $derived(actor?.rid ?? config.publicKey);
const previewKeys = $derived(
actor
? actor.keys
.filter(key => key.bound)
.map(key => ({ did: key.did, alias: key.alias ?? undefined }))
: [{ did: localDid, alias: config.alias }],
);
const explorerUrl = $derived(
entityUrl({ type: "node", nid: config.publicKey }, config),
);
// Puts another version's value of a field into the form.
function pickFrom(field: MergeField, from: ActorProfile | undefined) {
const picked = formFrom(from);
if (field === "links") form.links = picked.links;
else form[field] = picked[field];
}
// Takes from another version each field only its device changed since
// the versions split, where the form still holds the profile's value.
function takeTheirs(fork: ActorFork) {
if (!actor) return;
const current = profileFrom(form);
for (const { field, changedOn } of compareVersions(
actor.profile,
fork.profile,
fork.base,
)) {
if (
changedOn === "theirs" &&
fieldValue(current, field) === fieldValue(actor.profile, field)
) {
pickFrom(field, fork.profile);
}
}
}
// A version is taken from once, when the split first shows; the user
// picks the rest.
const merged: string[] = [];
$effect(() => {
if (!actor) return;
for (const fork of actor.forks) {
if (merged.includes(fork.head) || fork.profileNewer) continue;
merged.push(fork.head);
untrack(() => takeTheirs(fork));
}
});
let submitting = $state(false);
let submitted = $state(false);
let submitError = $state<string>();
// What the last save did, shown briefly beside the button: a message that
// stays could outlast what it was said of.
let saved = $state(false);
// A profile just created is announced once it has loaded, with what to do
// next.
let created = $state(false);
$effect(() => {
if (!created || !actor) return;
created = false;
show({
component: ProfileCreated,
props: { actor },
});
});
const SAVED_MS = 4000;
let savedTimer: ReturnType<typeof setTimeout> | undefined;
// Nothing is saved from here when this device cannot edit the profile, or
// when a newer app wrote the file: it has fields this one would drop, here
// or on another controller's version that a save would replace.
const readOnly = $derived(
actor !== null &&
(cannotEdit !== undefined ||
actor.profileNewer ||
actor.forks.some(fork => fork.profileNewer)),
);
// A form that turns read-only under an edit goes back to the profile: the
// edit has nowhere to be saved from, and the notice says why.
$effect(() => {
if (!readOnly) return;
untrack(() => {
form = formFrom(shown);
picked = {};
confirmingRemove = undefined;
submitted = false;
});
});
const changed = $derived(
actor !== null && (!same(form, formFrom(shown)) || anyPicked),
);
$effect(() => {
if (changed) saved = false;
});
// Another controller's version makes the form as it is worth saving: the
// save is what replaces that version.
const dirty = $derived(
actor === null ||
actor.profile === undefined ||
changed ||
actor.forks.length > 0,
);
// Lengths count code points of the trimmed text in NFC, as the limits do.
const length = (value: string) =>
Array.from(value.trim().normalize("NFC")).length;
const tooLong = (value: string, limit: number) => {
const over = length(value) - limit;
return over > 0 ? `Too long by ${over} characters.` : undefined;
};
const hasScheme = (value: string, schemes: string[]) => {
const scheme = value.split(":", 1)[0];
return value.includes(":") && schemes.includes(scheme.toLowerCase());
};
// Other clients render these as links and images, so what the backend
// refuses is refused here too.
const isImageRef = (value: string) =>
value.includes(":")
? hasScheme(value, IMAGE_SCHEMES)
: !value.includes("\\") &&
!value.includes("%") &&
!value.startsWith("/") &&
!value.split("/").includes("..");
// What the backend would refuse, by field; a link's errors by its index.
const errors = $derived.by(() => {
const text: Partial<Record<TextField, string>> = {};
if (form.displayName.trim().length === 0) {
text.displayName = "Enter a display name.";
}
for (const field of TEXT_FIELDS) {
text[field] ??= tooLong(form[field], LIMITS.string);
}
for (const field of ["avatar", "banner"] as const) {
const image = form[field].trim();
if (image && !isImageRef(image)) {
text[field] ??=
"Desktop cannot save this picture. Remove it to save the profile.";
}
}
const links = form.links.map(link => {
const url = link.url.trim();
if (!url) return undefined;
return (
tooLong(url, LIMITS.string) ??
(hasScheme(url, LINK_SCHEMES)
? tooLong(link.label ?? "", LIMITS.label)
: "A web URL, a mailto: address or a rad: URI.")
);
});
const any = Object.values(text).some(Boolean) || links.some(error => error);
return { text, links, any };
});
const errorOf = (field: TextField) =>
submitted ? errors.text[field] : undefined;
const bioLeft = $derived(LIMITS.string - length(form.bio));
const canAddLink = $derived(form.links.length < LIMITS.links);
const canSubmit = $derived(
dirty && !readOnly && !submitting && !(submitted && errors.any),
);
async function submit() {
submitted = true;
if (errors.any) return;
submitting = true;
submitError = undefined;
saved = false;
const updating = actor !== null;
try {
await change(
{
command: updating ? "update_actor_profile" : "create_actor",
args: {
profile: profileFrom(form),
images: {
avatar: picked.avatar?.base64,
banner: picked.banner?.base64,
},
},
},
"profile",
);
} catch (error) {
submitError = describeActorError(
error,
updating
? "Could not save the profile."
: "Could not create the profile.",
{
"ActorError.Exists":
"This key already has a profile, made elsewhere. It is shown here with your edits over it; save again to apply them.",
},
);
return;
} finally {
submitting = false;
}
form = formFrom(shown);
base = shown;
picked = {};
submitted = false;
if (!updating) {
created = true;
return;
}
saved = true;
clearTimeout(savedTimer);
savedTimer = setTimeout(() => (saved = false), SAVED_MS);
}
function same(a: Form, b: Form): boolean {
return JSON.stringify(profileFrom(a)) === JSON.stringify(profileFrom(b));
}
// Back to the form as it opened, which holds what only another device
// changed: a save without it would undo that device's edit.
function discard() {
picked = {};
form = formFrom(shown);
for (const fork of actor?.forks ?? []) {
if (!fork.profileNewer) takeTheirs(fork);
}
submitted = false;
submitError = undefined;
}
// The row just added, whose URL takes the focus.
let focusedLink = $state<number>();
let confirmingRemove = $state<number>();
function addLink() {
if (!canAddLink) return;
const row = linkRow({ url: "", label: undefined });
focusedLink = row.id;
form.links.push(row);
}
// A row with nothing typed in it goes without asking.
function askRemoveLink(index: number) {
const link = form.links[index];
if (link.url.trim() || link.label?.trim()) confirmingRemove = link.id;
else removeLink(index);
}
function removeLink(index: number) {
confirmingRemove = undefined;
form.links.splice(index, 1);
}
// The bio grows with what is typed instead of scrolling.
let bioElement = $state<HTMLTextAreaElement>();
$effect(() => {
void form.bio;
if (bioElement) {
bioElement.style.height = "0px";
bioElement.style.height = `${bioElement.scrollHeight + 2}px`;
}
});
</script>
<style>
.columns {
display: flex;
align-items: flex-start;
gap: 2rem;
}
.preview-column {
position: sticky;
top: 0;
width: 19rem;
flex-shrink: 0;
display: flex;
flex-direction: column;
gap: 0.625rem;
}
/* Below this the preview stops earning its column. */
@media (max-width: 66rem) {
.columns {
flex-direction: column;
}
.preview-column {
position: static;
width: 100%;
max-width: 22rem;
}
}
.surface-switch {
display: flex;
align-items: center;
}
.surface-note {
color: var(--color-text-secondary);
}
.form {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: 1.25rem;
}
.field {
display: flex;
flex-direction: column;
gap: 0.375rem;
}
.picker {
min-width: 0;
}
.field-label {
display: flex;
align-items: baseline;
gap: 0.375rem;
color: var(--color-text-primary);
}
/* Drawn rather than marked up, so reformatting cannot put a space between
the asterisk and the word it marks. */
.required::after {
content: "*";
color: var(--color-text-quaternary);
}
.field-note {
color: var(--color-text-secondary);
}
.field-error {
display: flex;
align-items: center;
gap: 0.375rem;
color: var(--color-feedback-error-text);
}
.counter {
margin-left: auto;
color: var(--color-text-tertiary);
}
.counter.over {
color: var(--color-feedback-error-text);
}
.row {
display: flex;
gap: 0.75rem;
}
.row > :global(*) {
flex: 1;
min-width: 0;
}
.links {
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.link-row {
display: flex;
align-items: center;
gap: 0.5rem;
}
.link-url-field {
flex: 1;
min-width: 0;
}
.link-label-field {
width: 9rem;
flex-shrink: 0;
}
.confirm {
display: flex;
align-items: center;
gap: 0.375rem;
flex-shrink: 0;
}
.confirm-text {
color: var(--color-text-secondary);
}
/* Drawn as the app's text inputs are. */
.bio {
width: 100%;
min-height: 2rem;
padding: 0.25rem 0.75rem;
border: 1px solid var(--color-border-subtle);
border-radius: var(--border-radius-sm);
background-color: var(--color-surface-base);
color: var(--color-text-primary);
line-height: 1.6;
resize: none;
overflow: hidden;
outline: none;
}
.bio:focus {
border-color: var(--color-border-brand);
}
.bio.invalid {
border-color: var(--color-feedback-error-border);
}
.bio[disabled] {
cursor: not-allowed;
}
.footer {
display: flex;
align-items: center;
justify-content: flex-end;
gap: 0.5rem;
padding-top: 0.25rem;
}
.footer-note {
margin-right: auto;
color: var(--color-text-tertiary);
}
.error {
color: var(--color-feedback-error-text);
}
.success {
display: flex;
align-items: center;
gap: 0.25rem;
color: var(--color-foreground-success);
}
</style>
{#snippet fieldError(message: string | undefined)}
{#if message}
<span class="field-error txt-body-m-regular">
<Icon name="warning" />
{message}
</span>
{/if}
{/snippet}
{#snippet text(field: TextField, label: string, options: TextOptions = {})}
<div class="field">
<span class="field-label txt-body-m-medium">
{#if options.required}
<span class="required">{label}</span>
{:else}
{label}
{/if}
</span>
{#if options.description}
<span class="field-note txt-body-m-regular">{options.description}</span>
{/if}
<TextInput
bind:value={form[field]}
valid={errorOf(field) === undefined}
placeholder={options.placeholder}
autofocus={options.autofocus}
disabled={readOnly} />
{@render fieldError(errorOf(field))}
{#if options.hint}
<span class="field-note txt-body-s-regular">{options.hint}</span>
{/if}
</div>
{/snippet}
<div class="columns">
<aside class="preview-column">
<div class="surface-switch">
<Button
variant="ghost"
flatRight
active={surface === "card"}
onclick={() => (surface = "card")}>
Hover card
</Button>
<Button
variant="ghost"
flatLeft
active={surface === "explorer"}
onclick={() => (surface = "explorer")}>
Explorer
</Button>
</div>
{#if surface === "card"}
<span class="surface-note txt-body-m-regular">
Shown when someone hovers your name in the app.
</span>
<HoverCard
{form}
avatar={imageSrc("avatar")}
banner={imageSrc("banner")}
{avatarId}
did={actor?.rid ?? config.publicKey} />
{:else}
<span class="surface-note txt-body-m-regular">
Your profile on Explorer.
</span>
<ExplorerPreview
{form}
avatar={imageSrc("avatar")}
banner={imageSrc("banner")}
{avatarId}
keys={previewKeys}
url={explorerUrl} />
{/if}
</aside>
<div class="form">
{#if actor?.profileNewer}
<Notice icon="warning" title="Written by a newer Desktop" tone="warning">
<span class="txt-body-m-regular">
This profile was written by a newer version of Desktop. Editing it
here would drop the fields this version does not know, so it is shown
as is.
</span>
</Notice>
{:else if actor?.profileUnreadable}
<Notice icon="warning" title="Profile file not readable" tone="warning">
<span class="txt-body-m-regular">
The profile file in the repository is not one this version of Desktop
can read.
{#if !cannotEdit}Saving replaces it.{/if}
</span>
</Notice>
{/if}
{#if actor && actor.forks.length > 0}
<SplitNotice {actor} current={profileFrom(form)} onpick={pickFrom} />
{/if}
{#if cannotEdit}
<Notice icon="lock" title="Read-only">
<span class="txt-body-m-regular">{cannotEdit}</span>
</Notice>
{/if}
<ImagePicker
kind="avatar"
bind:value={form.avatar}
src={imageSrc("avatar")}
picked={picked.avatar}
fallbackId={avatarId}
disabled={readOnly}
error={errorOf("avatar")}
onpick={image => (picked.avatar = image)} />
<ImagePicker
kind="banner"
bind:value={form.banner}
src={imageSrc("banner")}
picked={picked.banner}
disabled={readOnly}
error={errorOf("banner")}
onpick={image => (picked.banner = image)} />
<div class="row">
{@render text("displayName", "Display name", {
required: true,
// The first thing to type on a new profile; a saved one is read first.
autofocus: actor === null,
hint: "This is not unique.",
})}
{@render text("fullName", "Full name")}
<div class="field">
<span class="field-label txt-body-m-medium">Pronouns</span>
<div class="picker">
<PronounsPicker bind:value={form.pronouns} disabled={readOnly} />
</div>
{@render fieldError(errorOf("pronouns"))}
</div>
</div>
<div class="row">
{@render text("location", "Location")}
<div class="field">
<span class="field-label txt-body-m-medium">Time zone</span>
<div class="picker">
<TimezonePicker bind:value={form.timezone} disabled={readOnly} />
</div>
{@render fieldError(errorOf("timezone"))}
</div>
</div>
<div class="field">
<span class="field-label txt-body-m-medium">
Bio
<span class="counter" class:over={bioLeft < 0}>
{bioLeft < 0 ? `${-bioLeft} over` : `${bioLeft} left`}
</span>
</span>
<textarea
class="bio txt-body-m-regular"
class:invalid={errorOf("bio") !== undefined}
rows="1"
bind:this={bioElement}
bind:value={form.bio}
disabled={readOnly}>
</textarea>
<span class="field-note txt-body-s-regular">
Saved as one paragraph. Line breaks become spaces.
</span>
{@render fieldError(errorOf("bio"))}
</div>
<div class="field">
<span class="field-label txt-body-m-medium">
Links
<span class="counter">
{form.links.length} of {LIMITS.links}
</span>
</span>
<span class="field-note txt-body-m-regular">
Web URLs, mailto: addresses and rad: URIs.
</span>
<div class="links">
{#each form.links as link, index (link.id)}
{@const linkError = submitted ? errors.links[index] : undefined}
<div class="link-row">
<div class="link-url-field">
<TextInput
bind:value={link.url}
valid={linkError === undefined}
placeholder="https://example.com"
autofocus={link.id === focusedLink}
disabled={readOnly}
onSubmit={addLink} />
</div>
<div class="link-label-field">
<TextInput
bind:value={link.label}
placeholder="Label"
disabled={readOnly}
onSubmit={addLink} />
</div>
{#if confirmingRemove === link.id && !readOnly}
<div class="confirm">
<span class="confirm-text txt-body-m-regular">Remove?</span>
<Button
variant="ghost"
styleHeight="1.75rem"
onclick={() => removeLink(index)}>
Yes
</Button>
<Button
variant="outline"
styleHeight="1.75rem"
onclick={() => (confirmingRemove = undefined)}>
Cancel
</Button>
</div>
{:else}
<Button
variant="naked"
title="Remove link"
disabled={readOnly}
onclick={() => askRemoveLink(index)}>
<Icon name="trash" />
</Button>
{/if}
</div>
{@render fieldError(linkError)}
{/each}
<div>
<Button
variant="outline"
bordered
disabled={!canAddLink || readOnly}
onclick={addLink}>
<Icon name="plus" />
Add link
</Button>
</div>
</div>
</div>
<!-- It says the same for every profile, so once read it stays closed. -->
{#if !hints.isDismissed("profile.permanence") && !readOnly}
<Notice
icon="warning"
tone="warning"
ondismiss={() => hints.dismiss("profile.permanence")}>
<span class="txt-body-m-regular">
Everything you save here is permanent. Every node that has your
profile copies it and keeps its earlier versions, even after you
change or remove something.
</span>
</Notice>
{/if}
<div class="footer">
{#if submitError}
<span class="footer-note error txt-body-m-regular">
{submitError}
</span>
{:else if saved}
<span class="footer-note success txt-body-m-regular">
<Icon name="checkmark" />
Saved.
</span>
{:else if changed}
<span class="footer-note txt-body-m-regular">Unsaved changes</span>
{/if}
{#if changed}
<Button variant="outline" bordered onclick={discard}>Discard</Button>
{:else if !actor}
<Button
variant="outline"
bordered
disabled={submitting}
onclick={oncancel}>
Cancel
</Button>
{/if}
{#if actor}
<Button
variant="ghost"
onclick={() => show({ component: ProfileHistory, props: { actor } })}>
View history
</Button>
{/if}
<Button variant="secondary" disabled={!canSubmit} onclick={submit}>
{#if !actor}
Create profile
{:else}
Save profile
{/if}
</Button>
</div>
</div>
</div>
@@ -0,0 +1,152 @@
<script lang="ts">
import Button from "@app/components/Button.svelte";
import DropdownListItem from "@app/components/DropdownListItem.svelte";
import Icon from "@app/components/Icon.svelte";
import Popover, { closeFocused } from "@app/components/Popover.svelte";
import TextInput from "@app/components/TextInput.svelte";
interface Props {
value: string;
disabled?: boolean;
}
/* eslint-disable prefer-const */
let { value = $bindable(""), disabled = false }: Props = $props();
/* eslint-enable prefer-const */
// The field is free text, so these are a shortcut past typing rather than
// the answers allowed.
const common = [
"he/him",
"she/her",
"they/them",
"he/they",
"she/they",
"any pronouns",
];
let expanded = $state(false);
let custom = $state("");
// A value typed before is offered for editing, not retyped.
$effect(() => {
if (expanded) custom = common.includes(value) ? "" : value;
});
function pick(pronouns: string) {
value = pronouns;
closeFocused();
}
</script>
<style>
.control {
display: flex;
align-items: center;
gap: 0.25rem;
min-width: 0;
}
.control > :global(:first-child) {
flex: 1;
min-width: 0;
}
.clear-icon {
display: flex;
color: var(--color-text-tertiary);
}
.trigger {
display: flex;
align-items: center;
gap: 0.5rem;
width: 100%;
min-width: 0;
}
.trigger-value {
flex: 1;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.placeholder {
flex: 1;
color: var(--color-text-tertiary);
}
.panel {
display: flex;
flex-direction: column;
width: 14rem;
padding-top: 0.25rem;
border: 1px solid var(--color-border-subtle);
border-radius: var(--border-radius-md);
background-color: var(--color-surface-canvas);
overflow: hidden;
}
.custom {
display: flex;
flex-direction: column;
gap: 0.375rem;
margin-top: 0.25rem;
padding: 0.5rem;
border-top: 1px solid var(--color-border-subtle);
}
.custom-label {
color: var(--color-text-tertiary);
}
</style>
<div class="control">
<Popover
popoverPadding="0"
placement="bottom-start"
styleDisplay="flex"
bind:expanded>
{#snippet toggle(onclick)}
<Button
variant="outline"
bordered
{onclick}
{disabled}
styleWidth="100%"
styleJustifyContent="flex-start">
<span class="trigger">
{#if value}
<span class="trigger-value">{value}</span>
{:else}
<span class="placeholder">Not set</span>
{/if}
<Icon name={expanded ? "chevron-up" : "chevron-down"} />
</span>
</Button>
{/snippet}
{#snippet popover()}
<div class="panel">
{#each common as pronouns (pronouns)}
<DropdownListItem
styleWidth="100%"
selected={value === pronouns}
onclick={() => pick(pronouns)}>
<span class="txt-body-m-regular">{pronouns}</span>
</DropdownListItem>
{/each}
<div class="custom">
<span class="custom-label txt-body-s-regular">Something else</span>
<TextInput
bind:value={custom}
placeholder="Write your own"
styleHeight="1.75rem"
onSubmit={() => {
if (custom.trim()) pick(custom.trim());
}} />
</div>
</div>
{/snippet}
</Popover>
{#if value && !disabled}
<Button variant="naked" title="Clear pronouns" onclick={() => (value = "")}>
<span class="clear-icon"><Icon name="close" /></span>
</Button>
{/if}
</div>
@@ -0,0 +1,88 @@
<script lang="ts">
import ConfirmModal from "@app/modals/ConfirmModal.svelte";
import { describeActorError } from "./actor";
import Notice from "./Notice.svelte";
interface Props {
name: string;
rid: string;
// The profiles shown that this device is in besides the one retired, by
// name; empty if none can be shown.
staysIn: string;
// The devices the profile has besides this one.
others: number;
confirm: () => Promise<void>;
}
const { name, rid, staysIn, others, confirm }: Props = $props();
</script>
<style>
.profile {
display: flex;
flex-direction: column;
gap: 0.25rem;
color: var(--color-text-primary);
}
.rid {
word-break: break-all;
}
.caution {
display: flex;
flex-direction: column;
gap: 0.5rem;
min-width: 0;
}
</style>
<ConfirmModal
title="Retire profile"
width="28rem"
label="Retire"
busyLabel="Retiring…"
describeError={e =>
describeActorError(e, "Could not retire the profile.", {
"ActorError.NotController":
"This device's key does not control this profile, so it cannot retire it.",
"ActorError.PayloadNewer":
"This profile holds fields this version of Desktop does not know, so it cannot retire it.",
})}
{confirm}>
{#snippet body()}
<div class="profile">
<span class="txt-body-m-medium">{name}</span>
<span class="rid">{rid}</span>
</div>
<span>
This ends the profile.
{#if staysIn}
This device stays in {staysIn}.
{/if}
</span>
<Notice icon="warning" tone="warning">
<div class="caution">
{#if others === 1}
<span>
This profile has 1 other device. It loses the profile too, without
being asked.
</span>
{:else if others > 1}
<span>
This profile has {others} other devices. They lose the profile too, without
being asked.
</span>
{/if}
<span>
Nothing is deleted. The profile stays on the network with everything
saved in it.
</span>
<span>This cannot be undone.</span>
</div>
</Notice>
{/snippet}
</ConfirmModal>
@@ -0,0 +1,308 @@
<script lang="ts">
import type { ActorInfo } from "@bindings/actor/ActorInfo";
import { invoke } from "@app/lib/invoke";
import { show } from "@app/lib/modal";
import type { ProfileTab } from "@app/lib/router/definitions";
import Button from "@app/components/Button.svelte";
import CopyableId from "@app/components/CopyableId.svelte";
import {
change,
controllersOf,
describeActorError,
isController,
mayChangeKeys,
profileName,
votedRemoval,
votesText,
} from "./actor";
import Notice from "./Notice.svelte";
import RetireProfile from "./RetireProfile.svelte";
interface Props {
localDid: string;
tab: ProfileTab;
// What the backend said when it found the key in several profiles.
message: string;
}
const { localDid, tab, message }: Props = $props();
let actors = $state<ActorInfo[]>();
let loadError = $state<string>();
let acting = $state(false);
let confirming = $state<string>();
let actionError = $state<{ rid: string; message: string }>();
// A load of the page builds this anew, so another device's vote shows
// then, as on every profile page.
async function load() {
try {
actors = await invoke<ActorInfo[]>("actors_of_key");
loadError = undefined;
} catch (e) {
loadError = describeActorError(e, message);
}
}
void load();
const nameOf = (actor: ActorInfo) =>
actor.profile?.displayName || "the profile with no name";
// The open change by which this device leaves `actor`, once it has voted.
// The backend also counts a change from another tool that unbinds the key
// without removing it; that one shows only as its refusal of a leave.
const leaveOf = (actor: ActorInfo) => votedRemoval(actor, localDid, localDid);
// One leave at a time: two that both went through would leave this device
// in no profile.
const leaving = $derived(actors?.find(actor => leaveOf(actor)));
const several = $derived(actors !== undefined && actors.length > 2);
function staysIn(left: ActorInfo): string {
return (actors ?? [])
.filter(actor => actor.rid !== left.rid)
.map(nameOf)
.join(" and ");
}
// Retiring is permanent and applies at once, so it is confirmed in a
// dialog, which shows a failure itself.
function openRetire(actor: ActorInfo) {
show({
component: RetireProfile,
props: {
name: profileName(actor),
rid: actor.rid,
staysIn: staysIn(actor),
others: actor.keys.length - 1,
confirm: async () => {
try {
await change(
{ command: "retire_actor", args: { rid: actor.rid } },
tab,
);
} finally {
// Not waited for: the page has reloaded by now, and this only
// refreshes the list where the device is still in several.
void load();
}
},
},
});
}
async function act(
command: "leave_actor" | "cancel_leave",
actor: ActorInfo,
fallback: string,
) {
confirming = undefined;
actionError = undefined;
acting = true;
try {
await change({ command, args: { rid: actor.rid } }, tab);
} catch (e) {
actionError = {
rid: actor.rid,
message: describeActorError(e, fallback),
};
} finally {
await load();
acting = false;
}
}
</script>
<style>
.profiles {
display: flex;
flex-direction: column;
border: 1px solid var(--color-border-subtle);
border-radius: var(--border-radius-md);
overflow: hidden;
}
.profile {
display: flex;
flex-direction: column;
gap: 0.5rem;
padding: 0.75rem;
background-color: var(--color-surface-canvas);
}
.profile + .profile {
border-top: 1px solid var(--color-border-subtle);
}
.head {
display: flex;
align-items: center;
gap: 0.75rem;
}
.name {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: 0.25rem;
color: var(--color-text-primary);
}
.text {
color: var(--color-text-secondary);
}
.confirm {
display: flex;
align-items: center;
gap: 0.375rem;
flex-wrap: wrap;
color: var(--color-text-secondary);
}
.did {
color: var(--color-text-primary);
word-break: break-all;
}
.error {
color: var(--color-feedback-error-text);
}
</style>
<Notice
icon="warning"
tone="error"
title={several
? "This device is in several profiles"
: "This device is in two profiles"}>
<span class="txt-body-m-regular">
{#if several}
A device belongs to one profile. Until this one is in one only, its work
is credited to none of them and it cannot change any.
{:else}
A device belongs to one profile. Until this one leaves the other, its work
is credited to neither and it cannot change either.
{/if}
</span>
</Notice>
{#if loadError}
<span class="error txt-body-m-regular">{loadError}</span>
{:else if actors}
<div class="profiles">
{#each actors as actor (actor.rid)}
{@const controllers = controllersOf(actor)}
{@const open = leaveOf(actor)}
<div class="profile txt-body-m-regular">
<div class="head">
<div class="name">
<span class="txt-body-m-medium">
{profileName(actor)}
</span>
<CopyableId id={actor.rid} styleFont="var(--txt-body-m-regular)">
{actor.rid}
</CopyableId>
</div>
{#if open?.author === localDid}
<Button
variant="outline"
bordered
disabled={acting}
onclick={() =>
act("cancel_leave", actor, "Could not cancel the leave.")}>
Cancel leave
</Button>
{:else if !leaving && mayChangeKeys(actor, localDid) && controllers.length > 1 && confirming !== actor.rid}
<Button
variant="outline"
bordered
disabled={acting}
onclick={() => (confirming = actor.rid)}>
Leave
</Button>
{:else if !leaving && mayChangeKeys(actor, localDid) && controllers.length === 1}
<Button
variant="outline"
bordered
disabled={acting}
onclick={() => openRetire(actor)}>
Retire
</Button>
{/if}
</div>
{#if open?.author === localDid}
<span class="text">
You asked to leave. Open Keys on a device that controls this profile
and approve the change. {votesText(actor, open)}.
</span>
{:else if open}
<!-- Only the key that proposed a change withdraws it. -->
<span class="text">
Another device proposed removing this one, and you approved.
{votesText(actor, open)}. Only that device can withdraw it.
</span>
{:else if leaving}
<span class="text">
You are already leaving {nameOf(leaving)}. Cancel that leave first,
or wait until it is approved or rejected.
</span>
{:else if !isController(actor, localDid)}
<span class="text">
Only a controller can remove this device. Open Keys on one of these
and revoke this device's key:
</span>
{#each controllers as key (key.did)}
<span class="txt-body-s-regular">
{#if key.alias}
<span class="txt-body-s-medium">{key.alias}</span>
{/if}
<span class="did">{key.did}</span>
</span>
{/each}
{:else if actor.payloadNewer}
<span class="text">
Written by a newer Desktop or another app, so this device cannot
leave it from here.
</span>
{:else if controllers.length === 1}
<span class="text">
This device is the only controller here, so it cannot leave. This
profile can only be retired.
</span>
{:else if confirming === actor.rid}
<div class="confirm">
<span>
Leave {nameOf(actor)}? This device stays in {staysIn(actor)} and cannot
be added to {nameOf(actor)} again while {staysIn(actor)} exists.
</span>
<Button
variant="ghost"
styleHeight="1.75rem"
disabled={acting}
onclick={() =>
act("leave_actor", actor, "Could not leave the profile.")}>
Yes
</Button>
<Button
variant="outline"
styleHeight="1.75rem"
disabled={acting}
onclick={() => (confirming = undefined)}>
Cancel
</Button>
</div>
{/if}
{#if actionError?.rid === actor.rid}
<span class="error">{actionError.message}</span>
{/if}
</div>
{/each}
</div>
{/if}
@@ -0,0 +1,214 @@
<script lang="ts">
import type { ActorInfo } from "@bindings/actor/ActorInfo";
import type { ActorProfile } from "@bindings/actor/ActorProfile";
import { show } from "@app/lib/modal";
import Button from "@app/components/Button.svelte";
import Icon from "@app/components/Icon.svelte";
import ProfileVersionModal from "@app/modals/ProfileVersion.svelte";
import { keyName } from "./actor";
import { compareVersions, fieldValue, type MergeField } from "./form";
import Notice from "./Notice.svelte";
interface Props {
// An actor with versions of the profile on other controllers' branches.
actor: ActorInfo;
// The profile as the form holds it now.
current: ActorProfile;
// Puts a version's value of a field into the form.
onpick: (field: MergeField, from: ActorProfile | undefined) => void;
}
const { actor, current, onpick }: Props = $props();
const LABELS: Record<MergeField, string> = {
displayName: "Display name",
fullName: "Full name",
pronouns: "Pronouns",
bio: "Bio",
location: "Location",
timezone: "Time zone",
avatar: "Avatar",
banner: "Banner",
links: "Links",
};
const forks = $derived(
actor.forks.map(fork => ({
...fork,
name: keyName(actor, fork.did),
differences: compareVersions(actor.profile, fork.profile, fork.base),
})),
);
const picked = (field: MergeField, from: ActorProfile | undefined) =>
fieldValue(current, field) === fieldValue(from, field);
</script>
<style>
.lead {
color: var(--color-text-primary);
}
.compare {
display: grid;
grid-template-columns: 7rem 1fr 1fr;
gap: 0.375rem 0.5rem;
margin-top: 0.375rem;
padding: 0.75rem;
border: 1px solid var(--color-border-subtle);
border-radius: var(--border-radius-md);
background-color: var(--color-surface-canvas);
}
.column {
color: var(--color-text-tertiary);
}
.field {
display: flex;
flex-direction: column;
gap: 0.125rem;
padding-top: 0.5rem;
color: var(--color-text-primary);
}
.note {
color: var(--color-text-tertiary);
}
.option {
align-self: start;
display: flex;
align-items: flex-start;
gap: 0.5rem;
padding: 0.5rem 0.625rem;
border: 1px solid var(--color-border-subtle);
border-radius: var(--border-radius-sm);
background-color: var(--color-surface-canvas);
color: var(--color-text-primary);
font: var(--txt-body-m-regular);
text-align: left;
cursor: pointer;
min-width: 0;
}
.option:hover {
border-color: var(--color-border-mid);
}
.option.picked {
border-color: var(--color-border-brand);
background-color: var(--color-surface-brand-subtle);
}
.value {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: 0.125rem;
overflow-wrap: anywhere;
}
.empty {
color: var(--color-text-tertiary);
}
.check {
display: flex;
flex-shrink: 0;
color: var(--color-text-brand);
visibility: hidden;
}
.picked .check {
visibility: visible;
}
.raw {
display: flex;
padding-top: 0.25rem;
}
</style>
{#snippet value(field: MergeField, from: ActorProfile | undefined)}
{#if field === "links"}
{#each from?.links ?? [] as link (link.url)}
<span>{link.label ? `${link.label}: ` : ""}{link.url}</span>
{:else}
<span class="empty">No links</span>
{/each}
{:else if fieldValue(from, field)}
<span>{fieldValue(from, field)}</span>
{:else}
<span class="empty">Empty</span>
{/if}
{/snippet}
{#snippet option(field: MergeField, from: ActorProfile | undefined)}
<button
type="button"
class="option"
class:picked={picked(field, from)}
onclick={() => onpick(field, from)}>
<span class="value">{@render value(field, from)}</span>
<span class="check"><Icon name="checkmark" /></span>
</button>
{/snippet}
{#each forks as fork (fork.did)}
<Notice icon="warning" title={`Also edited on ${fork.name}`} tone="warning">
{#if fork.profileNewer}
<span class="txt-body-m-regular">
The version on {fork.name} was written by a newer Desktop, so this one cannot
replace it. Save the profile from {fork.name}.
</span>
{:else}
<span class="lead txt-body-m-regular">
{#if fork.differences.some(d => d.changedOn === "both")}
Pick which version to keep where both devices changed something, then
save.
{:else}
Its changes are filled in below. Save to publish them.
{/if}
</span>
{#if fork.differences.length > 0}
<div class="compare txt-body-m-regular">
<span></span>
<span class="column txt-body-s-regular">This device</span>
<span class="column txt-body-s-regular">{fork.name}</span>
{#each fork.differences as { field, changedOn } (field)}
<span class="field txt-body-m-medium">
{LABELS[field]}
{#if changedOn === "theirs"}
<span class="note txt-body-s-regular">
Only changed on {fork.name}
</span>
{/if}
</span>
{@render option(field, actor.profile)}
{@render option(field, fork.profile)}
{/each}
</div>
{/if}
{#if fork.otherFiles}
<span class="txt-body-m-regular">
The version on {fork.name} also changed other files in the repository. Saving
here leaves them out; they stay in the history.
</span>
{/if}
{/if}
<div class="raw">
<Button
variant="naked"
styleHeight="1.75rem"
onclick={() =>
show({
component: ProfileVersionModal,
props: {
name: fork.name,
head: fork.head,
profile: fork.profile,
changes: fork.changes,
},
})}>
<Icon name="code" />View raw changes
</Button>
</div>
</Notice>
{/each}
@@ -0,0 +1,257 @@
<script lang="ts">
import fuzzysort from "fuzzysort";
import Button from "@app/components/Button.svelte";
import DropdownListItem from "@app/components/DropdownListItem.svelte";
import Icon from "@app/components/Icon.svelte";
import Popover, { closeFocused } from "@app/components/Popover.svelte";
import ScrollArea from "@app/components/ScrollArea.svelte";
import TextInput from "@app/components/TextInput.svelte";
interface Props {
value: string;
disabled?: boolean;
}
/* eslint-disable prefer-const */
let { value = $bindable(""), disabled = false }: Props = $props();
/* eslint-enable prefer-const */
const supported: string[] = (() => {
try {
return Intl.supportedValuesOf("timeZone");
} catch {
return ["UTC"];
}
})();
const detected: string | undefined = (() => {
try {
return Intl.DateTimeFormat().resolvedOptions().timeZone;
} catch {
return undefined;
}
})();
// Every IANA zone, so the answer is never "none of these six". The list
// leaves out UTC and aliases such as Asia/Calcutta, which the system or a
// stored profile can still name.
const zones = $derived([
...new Set(
[...supported, detected, value].filter(
(zone): zone is string => typeof zone === "string" && zone !== "",
),
),
]);
let filter = $state("");
let expanded = $state(false);
// The Etc/GMT zones are fixed offsets rather than places, so they sit after
// the real ones instead of interleaving with them.
function isOffset(zone: string): boolean {
return zone.startsWith("Etc/");
}
// Shown without the "Etc/" prefix, which means nothing to anyone.
function label(zone: string): string {
return isOffset(zone) ? zone.slice("Etc/".length) : zone;
}
function offsetsLast(list: string[]): string[] {
return [...list.filter(z => !isOffset(z)), ...list.filter(isOffset)];
}
// Every zone, with the detected one first so it is one click away.
const results = $derived.by(() => {
const matched = filter.trim()
? fuzzysort.go(filter, zones, { all: false }).map(r => r.target)
: [...zones].sort((a, b) => a.localeCompare(b));
const ordered = offsetsLast(matched);
return detected && ordered.includes(detected)
? [detected, ...ordered.filter(zone => zone !== detected)]
: ordered;
});
// The moment the picker opened, so every row shows the same minute.
const now = $derived.by(() => {
void expanded;
return new Date();
});
function localTime(zone: string): string | undefined {
try {
return new Intl.DateTimeFormat(undefined, {
timeStyle: "short",
timeZone: zone,
}).format(now);
} catch {
return undefined;
}
}
function pick(zone: string) {
value = zone;
filter = "";
closeFocused();
}
</script>
<style>
.control {
display: flex;
align-items: center;
gap: 0.25rem;
min-width: 0;
}
.control > :global(:first-child) {
flex: 1;
min-width: 0;
}
.clear-icon {
display: flex;
color: var(--color-text-tertiary);
}
.trigger {
display: flex;
align-items: center;
gap: 0.5rem;
width: 100%;
min-width: 0;
}
.trigger-value {
flex: 1;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.trigger-time {
flex-shrink: 0;
color: var(--color-text-tertiary);
}
.chip {
flex-shrink: 0;
padding: 0.125rem 0.375rem;
border-radius: var(--border-radius-sm);
background-color: var(--color-surface-subtle);
color: var(--color-text-secondary);
}
.placeholder {
flex: 1;
color: var(--color-text-tertiary);
}
.panel {
display: flex;
flex-direction: column;
width: 20rem;
border: 1px solid var(--color-border-subtle);
border-radius: var(--border-radius-md);
background-color: var(--color-surface-canvas);
overflow: hidden;
}
.search {
padding: 0.5rem;
border-bottom: 1px solid var(--color-border-subtle);
}
.list {
max-height: 16rem;
}
.row {
display: flex;
align-items: center;
gap: 0.5rem;
width: 100%;
min-width: 0;
}
.zone {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.time {
margin-left: auto;
flex-shrink: 0;
color: var(--color-text-tertiary);
}
.empty {
padding: 0.75rem;
color: var(--color-text-tertiary);
}
</style>
<div class="control">
<Popover
popoverPadding="0"
placement="bottom-start"
styleDisplay="flex"
bind:expanded>
{#snippet toggle(onclick)}
<Button
variant="outline"
bordered
{onclick}
{disabled}
styleWidth="100%"
styleJustifyContent="flex-start">
<span class="trigger">
<Icon name="clock" />
{#if value}
<span class="trigger-value">{label(value)}</span>
{#if localTime(value)}
<span class="trigger-time">{localTime(value)}</span>
{/if}
{:else}
<span class="placeholder">Not set</span>
{/if}
<Icon name={expanded ? "chevron-up" : "chevron-down"} />
</span>
</Button>
{/snippet}
{#snippet popover()}
<div class="panel">
<div class="search">
<TextInput
autofocus
bind:value={filter}
placeholder="Search time zones"
styleHeight="1.75rem" />
</div>
{#if results.length > 0}
<ScrollArea style="max-height: 16rem;">
<div class="list">
{#each results as zone (zone)}
<DropdownListItem
styleWidth="100%"
selected={value === zone}
onclick={() => pick(zone)}>
<span class="row txt-body-m-regular">
<span class="zone">{label(zone)}</span>
{#if zone === detected}
<span class="chip txt-body-m-medium">Detected</span>
{/if}
<span class="time">{localTime(zone)}</span>
</span>
</DropdownListItem>
{/each}
</div>
</ScrollArea>
{:else}
<div class="empty txt-body-m-regular">No matching time zones</div>
{/if}
</div>
{/snippet}
</Popover>
{#if value && !disabled}
<Button
variant="naked"
title="Clear time zone"
onclick={() => (value = "")}>
<span class="clear-icon"><Icon name="close" /></span>
</Button>
{/if}
</div>
+199
View File
@@ -0,0 +1,199 @@
import type { ActorInfo } from "@bindings/actor/ActorInfo";
import type { ActorKey } from "@bindings/actor/ActorKey";
import type { ActorProfile } from "@bindings/actor/ActorProfile";
import type { ActorRevision } from "@bindings/actor/ActorRevision";
import type { ProfileImages } from "@bindings/actor/ProfileImages";
import { get } from "svelte/store";
import { nodeRunning } from "@app/lib/events";
import { invalidateReposSummary, invoke, InvokeError } from "@app/lib/invoke";
import * as router from "@app/lib/router";
import type { ProfileTab } from "@app/lib/router/definitions";
import { formatTimestamp, publicKeyFromDid, truncateId } from "@app/lib/utils";
import { announce } from "@app/components/AnnounceSwitch.svelte";
// Where the profile is kept in the actor's repository.
export const PROFILE_PATH = ".radicle/profile.json";
// The text for `error`: `overrides` first, where a place needs other words
// than the backend's for a code, then the backend's own message, then
// `fallback`.
export function describeActorError(
error: unknown,
fallback: string,
overrides: Record<string, string> = {},
): string {
if (error instanceof InvokeError && error.code in overrides) {
return overrides[error.code];
}
return error instanceof Error ? error.message : fallback;
}
// Reloads the profile page on `tab` from storage, so it shows what was
// written.
export async function reload(tab: ProfileTab): Promise<void> {
invalidateReposSummary();
await router.replace({ resource: "profile", tab });
}
// The actor writes and what each takes; the options are added by `change`.
export type ActorWrite =
| {
command: "create_actor" | "update_actor_profile";
args: { profile: ActorProfile; images: ProfileImages };
}
| {
command: "approve_enrollment";
args: { code: string; controller: boolean };
}
| { command: "remove_actor_key"; args: { did: string } }
| { command: "leave_actor"; args: { rid: string } }
| { command: "cancel_leave"; args: { rid: string } }
| { command: "retire_actor"; args: { rid: string } }
| { command: "approve_actor_revision"; args: { id: string } }
| { command: "withdraw_actor_revision"; args: { id: string } }
| { command: "reject_actor_revision"; args: { id: string } };
// The votes on an open identity change.
export type Vote = Extract<ActorWrite, { args: { id: string } }>["command"];
// Runs an actor write, then reloads `tab` whether or not it went through: a
// failure may come from state the page has not seen, and a write that went
// through is not undone by a reload that did not. The write announces when
// the node runs and the user has not turned announcing off.
export async function change(
{ command, args }: ActorWrite,
tab: ProfileTab,
): Promise<void> {
const opts = { announce: get(nodeRunning) && get(announce) };
const reloadQuietly = () =>
reload(tab).catch((e: unknown) =>
console.warn("Could not reload the profile", e),
);
try {
await invoke<ActorInfo>(command, { ...args, opts });
} catch (error) {
await reloadQuietly();
throw error;
}
await reloadQuietly();
}
// The keys that govern the actor's identity.
export function controllersOf(actor: ActorInfo): ActorKey[] {
return actor.keys.filter(key => key.controller);
}
// Whether `did` governs the actor's identity. A rejection signs a verdict,
// not the document, so a controller rejects a change this version of the
// app cannot write back whole.
export function isController(actor: ActorInfo, did: string): boolean {
return actor.keys.some(key => key.did === did && key.controller);
}
// Whether `did` may change the actor's keys: it governs the identity, and
// the payload is one this version of Desktop can write back whole.
export function mayChangeKeys(actor: ActorInfo, did: string): boolean {
return isController(actor, did) && !actor.payloadNewer;
}
// The open change that removes `did` from `actor` and has `voter`'s vote.
export function votedRemoval(
actor: ActorInfo,
did: string,
voter: string,
): ActorRevision | undefined {
return actor.pending.find(
revision =>
revision.removed.includes(did) && revision.accepted.includes(voter),
);
}
// What a change to `actor`'s keys does, in a line. A change that ended is
// told in the past tense, and since the keys have moved on since, every key
// it lists is told as added.
export function revisionTitle(
actor: ActorInfo,
revision: ActorRevision,
past = false,
): string {
const parts = [
...revision.added.map(key => {
const known = !past && actor.keys.some(k => k.did === key.did);
const role = {
full: "",
recovery: " as a recovery key",
bound: " (not a controller)",
}[keyKind(key)];
const verb = past ? "Added" : known ? "Change" : "Add";
return `${verb} ${keyName(actor, key.did)}${role}`;
}),
...revision.removed.map(
did => `${past ? "Removed" : "Remove"} ${keyName(actor, did)}`,
),
];
// A lower quorum on profile edits is a change of its own; it must not
// pass unseen inside a removal or a role change.
if (revision.threshold !== undefined) {
const approvals = revision.threshold === 1 ? "approval" : "approvals";
const quorum = past
? `needed ${revision.threshold} ${approvals}`
: `need ${revision.threshold} ${approvals} instead of ${actor.threshold}`;
return parts.length > 0
? `${parts.join(", ")}; profile edits ${quorum}`
: `Profile edits ${quorum}`;
}
if (parts.length > 0) return parts.join(", ");
return past ? "Changed the identity" : "Change the identity";
}
// How the votes on an open change of `actor` stand.
export function votesText(actor: ActorInfo, revision: ActorRevision): string {
const approved = Math.min(revision.accepted.length, actor.majority);
const rejected =
revision.rejected.length > 0
? `, ${revision.rejected.length} rejected`
: "";
return `${approved} of ${actor.majority} approved${rejected}`;
}
// What a key does for the actor: a full key acts as it and approves
// changes, a recovery key only approves, a bound key only acts.
export function keyKind(key: ActorKey): "full" | "recovery" | "bound" {
if (key.bound && key.controller) return "full";
return key.controller ? "recovery" : "bound";
}
// The label of each kind of key. Both roles are the default, so a key that
// has them needs none.
export const roleText = {
full: undefined,
recovery: "Recovery key",
bound: "Not a controller",
};
// What a profile is called where its name is shown.
export function profileName(actor: ActorInfo): string {
return actor.profile?.displayName || "A profile with no name";
}
// The alias of a key of `actor`, or of one an open change adds, and the
// shortened key otherwise.
export function keyName(actor: ActorInfo, did: string): string {
const key =
actor.keys.find(key => key.did === did) ??
actor.pending.flatMap(r => r.added).find(key => key.did === did);
return key?.alias ?? truncateId(publicKeyFromDid(did));
}
export function ago(seconds: number): string {
const elapsed = formatTimestamp(seconds * 1000);
return elapsed === "now" ? "just now" : `${elapsed} ago`;
}
+88
View File
@@ -0,0 +1,88 @@
import type { ActorProfile } from "@bindings/actor/ActorProfile";
import type { ProfileLink } from "@bindings/actor/ProfileLink";
// The form holds every field as a string, so an empty one reads as unset
// when the profile is sent. A link row has an id of its own, so a removed
// row above it does not take its values and focus.
export interface Form {
displayName: string;
fullName: string;
pronouns: string;
bio: string;
location: string;
timezone: string;
avatar: string;
banner: string;
links: (ProfileLink & { id: number })[];
}
export type TextField = Exclude<keyof Form, "links">;
export const TEXT_FIELDS: TextField[] = [
"displayName",
"fullName",
"pronouns",
"bio",
"location",
"timezone",
"avatar",
"banner",
];
// `loaded` with the fields typed into `typed` over it, for a form that
// turned out to edit a profile made elsewhere. A field the user left as
// `empty` keeps the loaded value; so do the links while no link was typed.
export function laidOver(typed: Form, loaded: Form, empty: Form): Form {
const merged = { ...loaded };
for (const field of TEXT_FIELDS) {
if (typed[field] !== empty[field]) merged[field] = typed[field];
}
if (typed.links.length > 0) merged.links = typed.links;
return merged;
}
// What can differ between two versions of the profile, field by field.
export type MergeField = TextField | "links";
export const MERGE_FIELDS: MergeField[] = [...TEXT_FIELDS, "links"];
// A field as the profile file holds it, for comparing two versions.
export function fieldValue(
profile: ActorProfile | undefined,
field: MergeField,
): string {
if (field === "links") {
return JSON.stringify(
(profile?.links ?? []).map(({ url, label }) => ({ url, label })),
);
}
return (profile?.[field] ?? "").trim();
}
// A field that differs between this device's version and another's: one
// only the other device changed since the two split is taken from there;
// one both changed is for the user to pick. A field only this device
// changed keeps its value, so it is left out.
export interface FieldDifference {
field: MergeField;
changedOn: "theirs" | "both";
}
export function compareVersions(
mine: ActorProfile | undefined,
theirs: ActorProfile | undefined,
base: ActorProfile | undefined,
): FieldDifference[] {
return MERGE_FIELDS.flatMap(field => {
const ours = fieldValue(mine, field);
const other = fieldValue(theirs, field);
if (ours === other) return [];
// Without the version both started from, every difference is a choice.
if (base === undefined) return [{ field, changedOn: "both" as const }];
const before = fieldValue(base, field);
if (other === before) return [];
return [
{ field, changedOn: ours === before ? ("theirs" as const) : "both" },
];
});
}