Files
lune/web/src/Canvas.tsx
Adnan Zahir 4f6414b256 Leave a team, delete a vault; keep tests out of the real settings
- A hub test unset LUNE_HOME for the whole test run, so later tests saved
  into the real user's config. Tests now always keep their own settings
  folder.
- Leaving a team: `lunesync leave` and the app's Leave hand over and remove
  this device there; a hub that's gone can be forgotten (folders stay).
- Deleting a vault (owner): everyone is removed the usual way, the history
  is archived on the hub and the name is freed. Canvas asks first.
- Connect this Mac says what to do when Lune isn't installed.
- Update checks skip http hubs instead of failing for all of them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 14:36:46 +07:00

1049 lines
61 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// The team canvas (M5): vaults on the left, people on the right, ribbons for who can sync what.
// Grant = drag a vault onto a person; revoke = pull a ribbon's dot until it snaps (Undo for 8 s). Every gesture
// also has a button in the details panel (X3).
import { useEffect, useMemo, useRef, useState } from 'react';
import { MacSection } from './MacApp';
import { api, type CanvasData, type Comparison, type Health, type LogEntry, type Member, type Person, type Role, type Status, type Vault } from './api';
import {
HANDLE_T, W, boardHeight, circle, easeBack, lerp, personColor, positions, ribbon, roundRect, vaultColor,
type Layout, type Pt,
} from './geometry';
const UNDO_SECONDS = 8;
const ROLES: Role[] = ['read', 'edit', 'manage'];
const roleName = (r: Role) => r.charAt(0).toUpperCase() + r.slice(1);
const plural = (n: number, word: string, many = word + 's') => `${n} ${n === 1 ? word : many}`;
const keyOf = (m: { vault: string; person: string }) => `${m.vault}|${m.person}`;
/** Status colors are reserved for status (X6): green current, amber behind or needs a decision, grey offline,
* red only for a possible secret held back. */
const STATUS: Record<Status, string> = { current: '#2E8B5F', behind: '#E09A2B', offline: '#A9A5B6' };
const STATUS_WORDS: Record<Status, string> = { current: 'Current', behind: 'Behind', offline: 'Offline' };
const PILL: Record<Status, [string, string]> = { current: ['#E3F2EA', '#1F6B47'], behind: ['#FBEBD3', '#7A4500'], offline: ['#EEECF2', '#5C5770'] };
const SECRET_RED = '#C8323B';
/** A person's freshness is their worst device. */
function worst(p: Person): Status {
if (!p.devices.length) return 'offline';
if (p.devices.some((d) => d.health.status === 'behind')) return 'behind';
if (p.devices.some((d) => d.health.status === 'offline')) return 'offline';
return 'current';
}
function ago(unix: number | null): string {
if (!unix) return 'never';
const s = Math.max(0, Date.now() / 1000 - unix);
if (s < 90) return 'just now';
if (s < 3600) return `${Math.round(s / 60)} min ago`;
if (s < 86400) return `${Math.round(s / 3600)} h ago`;
return plural(Math.round(s / 86400), 'day') + ' ago';
}
function healthLine(h: Health): string {
const waiting = h.waiting > 0 ? `${plural(h.waiting, 'change')} not shared` : '';
if (h.status === 'offline') return `Offline · last seen ${ago(h.last_seen)}${waiting ? ' · ' + waiting : ''}`;
if (h.status === 'behind') return [waiting, h.last_synced ? `last synced ${ago(h.last_synced)}` : ''].filter(Boolean).join(' · ') || 'Something is held on this device';
return `Synced ${ago(h.last_synced)}`;
}
type Sel =
| { kind: 'overview'; back?: Sel }
| { kind: 'vault'; id: string; back?: Sel }
| { kind: 'person'; id: string; back?: Sel };
type Drag =
| { kind: 'grant'; v: string; start: Pt; p: Pt; moved: boolean }
| { kind: 'retract'; v: string; p: Pt }
| { kind: 'detach'; key: string; p: Pt }
| { kind: 'snap'; key: string; p: Pt };
type Toast = { text: string; undo?: () => void };
type Sheet =
| 'invite'
| 'vault'
| { kind: 'compare'; vault: Vault; copy: string }
| { kind: 'team'; p: Person }
| { kind: 'delete'; v: Vault }
| { kind: 'restored'; p: Person; link: string };
function store(key: string, value?: string): string | null {
try {
if (value !== undefined) localStorage.setItem(key, value);
return localStorage.getItem(key);
} catch {
return null;
}
}
const reducedMotion = () => window.matchMedia?.('(prefers-reduced-motion: reduce)').matches ?? false;
export function Canvas({ data, reload, onSignOut }: { data: CanvasData; reload: () => Promise<void>; onSignOut: () => void }) {
const [layout, setLayoutState] = useState<Layout>(store('lune.layout') === 'dock' ? 'dock' : 'float');
const [blend, setBlend] = useState<{ from: Layout; to: Layout; t: number } | null>(null);
const [sel, setSel] = useState<Sel | null>(null);
const [hover, setHover] = useState<{ kind: 'vault' | 'person'; id: string } | null>(null);
const [drag, setDrag] = useState<Drag | null>(null);
const [pinched, setPinched] = useState<{ key: string; p: Pt; t: number } | null>(null);
const [toast, setToast] = useState<Toast | null>(null);
const [sheet, setSheet] = useState<Sheet | null>(null);
const [onboarded, setOnboarded] = useState(store('lune.onboarded') === '1');
const [hidden, setHidden] = useState<Set<string>>(new Set());
const [extra, setExtra] = useState<Member[]>([]);
const [log, setLog] = useState<LogEntry[]>([]);
const svgRef = useRef<SVGSVGElement>(null);
const rafs = useRef<Record<string, number>>({});
const toastTimer = useRef<number>();
const hoverTimer = useRef<number>();
const lastFocus = useRef<{ kind: 'vault' | 'person'; id: string } | null>(null);
// Optimistic additions last until fresh data arrives; the hub stays the source of truth.
useEffect(() => setExtra([]), [data]);
useEffect(() => {
const t = window.setInterval(() => reload(), 10000);
return () => window.clearInterval(t);
}, [reload]);
useEffect(() => () => Object.values(rafs.current).forEach(cancelAnimationFrame), []);
// Float: every node bobs on one shared clock (X8).
useEffect(() => {
try {
document.getAnimations?.().forEach((a) => {
if ((a as CSSAnimation).animationName === 'bob' && a.startTime !== 0) a.startTime = 0;
});
} catch {
/* older browsers: unsynced bobbing is fine */
}
});
useEffect(() => {
if (sel?.kind === 'overview' && data.me.owner) api.log(8).then(setLog).catch(() => setLog([]));
}, [sel, data]);
const vaults = data.vaults;
const people = data.people;
const vault = (id: string) => vaults.find((v) => v.id === id)!;
const person = (id: string) => people.find((p) => p.id === id)!;
const pendingKeys = useMemo(() => new Set(data.pending.map(keyOf)), [data]);
const members = useMemo(
() =>
[...data.members, ...extra.filter((e) => !data.members.some((m) => keyOf(m) === keyOf(e)))].filter(
(m) => !hidden.has(keyOf(m)) && !pendingKeys.has(keyOf(m)),
),
[data, extra, hidden, pendingKeys],
);
const H = boardHeight(vaults.length, people.length);
const at = useMemo(
() => ({
float: positions(vaults.map((v) => v.id), people.map((p) => p.id), 'float', H),
dock: positions(vaults.map((v) => v.id), people.map((p) => p.id), 'dock', H),
}),
[vaults, people, H],
);
const pos = (id: string): Pt => {
if (!blend) return at[layout][id];
const a = at[blend.from][id], c = at[blend.to][id], t = easeBack(blend.t);
return { x: lerp(a.x, c.x, t), y: lerp(a.y, c.y, t) };
};
const ends = (m: { vault: string; person: string }) => {
const a = pos(m.vault), b = pos(m.person);
return { ax: a.x, ay: a.y, bx: b.x, by: b.y };
};
function anim(key: string, ms: number, step: (t: number) => void, done?: () => void) {
const t0 = performance.now();
cancelAnimationFrame(rafs.current[key]);
const tick = (now: number) => {
const t = Math.min(1, (now - t0) / ms);
step(t);
if (t < 1) rafs.current[key] = requestAnimationFrame(tick);
else done?.();
};
rafs.current[key] = requestAnimationFrame(tick);
}
function say(text: string, undo?: () => void) {
setToast({ text, undo });
window.clearTimeout(toastTimer.current);
toastTimer.current = window.setTimeout(() => setToast(null), undo ? UNDO_SECONDS * 1000 : 4200);
}
async function run(action: () => Promise<unknown>, ok?: string) {
try {
await action();
if (ok) say(ok);
} catch (e) {
say((e as Error).message);
} finally {
await reload();
}
}
// ---- What the gestures and buttons do ----
function grant(vId: string, pId: string) {
const v = vault(vId), p = person(pId);
if (members.some((m) => m.vault === vId && m.person === pId)) return say(`${p.name} already has ${v.name}.`);
setExtra((x) => [...x, { vault: vId, person: pId, role: 'edit' }]);
run(
() => (p.invited ? api.inviteGrant(p.name, v.name, 'edit') : api.grant(p.name, v.name, 'edit')),
p.invited ? `${v.name} is added to ${p.name}'s invite.` : `${p.name} can now sync ${v.name}. It arrives on their devices within a minute.`,
);
}
async function revoke(key: string) {
const [vId, pId] = key.split('|');
const v = vault(vId), p = person(pId);
setHidden((h) => new Set(h).add(key));
const unhide = () => setHidden((h) => { const n = new Set(h); n.delete(key); return n; });
if (p.invited) {
await run(() => api.inviteGrant(p.name, v.name, null, true), `${v.name} is off ${p.name}'s invite.`);
unhide();
return;
}
try {
const res = await api.remove(p.name, v.name, UNDO_SECONDS);
const copies = v.delete_from_devices ? 'then deleted from their devices' : 'then their copy stops updating';
say(`${p.name} removed from ${v.name}. Unshared work comes to you for review, ${copies}.`, async () => {
setToast(null);
await run(() => api.undoRemove(res.pending!), `${p.name} has ${v.name} again. Nothing changed on their devices.`);
unhide();
});
window.setTimeout(() => reload().then(unhide), (UNDO_SECONDS + 1.5) * 1000);
} catch (e) {
unhide();
say((e as Error).message);
}
}
function cycleRole(m: Member) {
const v = vault(m.vault), p = person(m.person);
const next = ROLES[(ROLES.indexOf(m.role) + 1) % ROLES.length];
run(() => (p.invited ? api.inviteGrant(p.name, v.name, next) : api.grant(p.name, v.name, next)), `${p.name} now has ${roleName(next)} on ${v.name}.`);
}
function setLayout(l: Layout) {
if (blend || l === layout) return;
store('lune.layout', l);
if (reducedMotion()) return setLayoutState(l);
const from = layout;
setBlend({ from, to: l, t: 0 });
anim('layout', 720, (t) => setBlend({ from, to: l, t }), () => { setLayoutState(l); setBlend(null); });
}
// ---- Pointer handling ----
const toSvg = (e: React.PointerEvent): Pt => {
const svg = svgRef.current;
if (!svg) return { x: 0, y: 0 };
const pt = svg.createSVGPoint();
pt.x = e.clientX;
pt.y = e.clientY;
const q = pt.matrixTransform(svg.getScreenCTM()!.inverse());
return { x: q.x, y: q.y };
};
const capture = (e: React.PointerEvent) => { try { svgRef.current?.setPointerCapture(e.pointerId); } catch { /* fine */ } };
const target = (p: Pt) => {
let best: string | null = null, bd = 1e9;
for (const pr of people) {
if (pr.removed) continue;
const q = pos(pr.id), d = Math.hypot(p.x - q.x, p.y - q.y);
if (d < bd) { bd = d; best = pr.id; }
}
return best && bd < 130 ? { id: best, dist: bd } : null;
};
function startGrant(vId: string, e: React.PointerEvent) {
if (sheet || drag || pinched) return;
e.preventDefault();
const p = toSvg(e);
capture(e);
setDrag({ kind: 'grant', v: vId, start: p, p, moved: false });
}
function startDetach(key: string, e: React.PointerEvent) {
if (sheet || drag || pinched) return;
e.preventDefault();
capture(e);
setDrag({ kind: 'detach', key, p: toSvg(e) });
}
function onMove(e: React.PointerEvent) {
if (!drag || (drag.kind !== 'grant' && drag.kind !== 'detach')) return;
const p = toSvg(e);
if (drag.kind === 'grant') setDrag({ ...drag, p, moved: drag.moved || Math.hypot(p.x - drag.start.x, p.y - drag.start.y) > 6 });
else setDrag({ ...drag, p });
}
function onUp() {
const d = drag;
if (!d) return;
if (d.kind === 'grant') {
if (!d.moved) { setDrag(null); setSel({ kind: 'vault', id: d.v }); return; }
const t = target(d.p);
if (t && t.dist < 75) { setDrag(null); grant(d.v, t.id); return; }
const a = pos(d.v), p0 = d.p;
setDrag({ kind: 'retract', v: d.v, p: p0 });
anim('drag', 260, (t) => { const k = 1 - Math.pow(1 - t, 3); setDrag({ kind: 'retract', v: d.v, p: { x: lerp(p0.x, a.x, k), y: lerp(p0.y, a.y, k) } }); }, () => setDrag(null));
} else if (d.kind === 'detach') {
const [vId, pId] = d.key.split('|');
const e = ends({ vault: vId, person: pId });
const h0 = { x: lerp(e.ax, e.bx, HANDLE_T), y: lerp(e.ay, e.by, HANDLE_T) };
if (Math.hypot(d.p.x - h0.x, d.p.y - h0.y) > 110) {
const key = d.key, P = d.p;
setDrag(null);
setPinched({ key, p: P, t: 0 });
anim('pinch', reducedMotion() ? 1 : 300, (t) => setPinched({ key, p: P, t }), () => { setPinched(null); revoke(key); });
} else {
const q0 = d.p;
setDrag({ kind: 'snap', key: d.key, p: q0 });
anim('drag', 240, (t) => { const k = 1 - Math.pow(1 - t, 3); setDrag({ kind: 'snap', key: d.key, p: { x: lerp(q0.x, h0.x, k), y: lerp(q0.y, h0.y, k) } }); }, () => setDrag(null));
}
}
}
// ---- Drawing ----
const bob = !blend && layout === 'float' && !reducedMotion() ? 'bob' : '';
const grantDrag = drag && drag.kind === 'grant' && drag.moved ? drag : null;
const tgt = grantDrag ? target(grantDrag.p) : null;
const hot = tgt && tgt.dist < 75 ? tgt.id : null;
const focus = !drag && hover ? hover : sel && (sel.kind === 'vault' || sel.kind === 'person') ? { kind: sel.kind, id: sel.id } : null;
if (focus) lastFocus.current = focus;
const relV = (vId: string) => !focus || (focus.kind === 'vault' ? focus.id === vId : members.some((m) => m.vault === vId && m.person === focus.id));
const relP = (pId: string) => !focus || (focus.kind === 'person' ? focus.id === pId : members.some((m) => m.person === pId && m.vault === focus.id));
const pct = (x: number, y: number): React.CSSProperties => ({ position: 'absolute', left: `${(x / W) * 100}%`, top: `${(y / H) * 100}%` });
const leave = () => { window.clearTimeout(hoverTimer.current); hoverTimer.current = window.setTimeout(() => setHover(null), 90); };
const enter = (kind: 'vault' | 'person', id: string) => { window.clearTimeout(hoverTimer.current); if (!drag) setHover({ kind, id }); };
const blobs: { d: string; fill: string; delay: string; op: number }[] = [];
const labels: { text: string; style: React.CSSProperties; inner: React.CSSProperties }[] = [];
const ribbons: { d: string; fill: string; op?: number; dim?: number }[] = [];
const handles: { key: string; x: number; y: number; dim: boolean }[] = [];
const grips: { x: number; y: number; r: number }[] = [];
const grads: { id: string; x1: number; y1: number; x2: number; y2: number; c1: string; c2: string }[] = [];
vaults.forEach((v, i) => {
const p = pos(v.id), delay = (i * 0.7).toFixed(1), vo = relV(v.id) ? 1 : 0.35;
// Amber means a decision is waiting (X6): notes to tidy, handovers to review.
const review = v.handovers.filter((h) => h.state === 'received').length, tidy = v.tidy.length;
const decide = review + tidy;
if (decide > 0) {
labels.push({
text: tidy && !review ? `${tidy} to tidy` : review && !tidy ? plural(review, 'handover') : `${decide} to decide`,
style: { ...pct(p.x + 34, p.y - 40), transform: 'translate(-50%,-50%)', opacity: vo },
inner: { display: 'inline-block', whiteSpace: 'nowrap', fontWeight: 700, fontSize: 'max(1.05cqw, 9px)', color: '#7A4500', background: '#FBEBD3', border: '1px solid #E09A2B', borderRadius: 999, padding: '0.15em 0.7em', animationDelay: `${delay}s` },
});
}
blobs.push({ d: roundRect(p.x, p.y, 138, 70, 26), fill: vaultColor(v.id).fill, delay, op: focus && relV(v.id) ? 1 : 0 });
labels.push({
text: v.name,
style: { ...pct(p.x - 20, p.y), transform: 'translateY(-50%)', opacity: vo, transition: 'opacity .2s' },
inner: { display: 'inline-block', whiteSpace: 'nowrap', fontWeight: 700, fontSize: 'max(1.4cqw, 10px)', animationDelay: `${delay}s`, maxWidth: '8.2cqw', overflow: 'hidden', textOverflow: 'ellipsis' },
});
});
people.forEach((pr, i) => {
const p = pos(pr.id), delay = (0.35 + i * 0.6).toFixed(1), po = pr.removed ? 0.45 : relP(pr.id) ? 1 : 0.35;
if (!pr.invited && !pr.removed) blobs.push({ d: circle(p.x, p.y, 38), fill: personColor(pr.id).fill, delay, op: focus && relP(pr.id) ? 1 : 0 });
labels.push({ text: pr.name.charAt(0).toUpperCase(), style: { ...pct(p.x, p.y), transform: 'translate(-50%,-50%)', opacity: po }, inner: { display: 'inline-block', fontWeight: 700, fontSize: 'max(2cqw, 12px)', animationDelay: `${delay}s` } });
labels.push({
text: pr.invited ? `${pr.name} · invited` : pr.removed ? `${pr.name} · removed` : pr.name,
style: { ...pct(p.x, p.y + 48), transform: 'translate(-50%,-50%)', opacity: po },
inner: { display: 'inline-block', whiteSpace: 'nowrap', fontSize: 'max(1.3cqw, 10px)', animationDelay: `${delay}s` },
});
});
for (const m of members) {
const key = keyOf(m), e = ends(m), gid = `g-${key.replace(/[^a-zA-Z0-9]/g, '-')}`, fill = `url(#${gid})`;
grads.push({ id: gid, x1: e.ax, y1: e.ay, x2: e.bx, y2: e.by, c1: vaultColor(m.vault).fill, c2: personColor(m.person).fill });
const dim = !!(focus && ((focus.kind === 'vault' && focus.id !== m.vault) || (focus.kind === 'person' && focus.id !== m.person)));
const h0 = { x: lerp(e.ax, e.bx, HANDLE_T), y: lerp(e.ay, e.by, HANDLE_T) };
if (pinched?.key === key) {
const P = pinched.p, shrink = 1 - pinched.t;
ribbons.push({ d: ribbon(e.ax, e.ay, lerp(e.ax, P.x, 0.45 * shrink), lerp(e.ay, P.y, 0.45 * shrink), 14, 3, 0.6), fill });
ribbons.push({ d: ribbon(e.bx, e.by, lerp(e.bx, P.x, 0.3 * shrink), lerp(e.by, P.y, 0.3 * shrink), 11, 4, 0.6), fill });
continue;
}
const active = drag && (drag.kind === 'detach' || drag.kind === 'snap') && drag.key === key ? drag.p : null;
if (active) {
const P = active, dist = Math.hypot(P.x - h0.x, P.y - h0.y), neck = dist < 110 ? 4 + 4 * (1 - dist / 110) : 0;
if (neck > 0.5) {
ribbons.push({ d: ribbon(e.ax, e.ay, P.x, P.y, 16, Math.max(4, neck * 0.8), neck), fill });
ribbons.push({ d: ribbon(P.x, P.y, e.bx, e.by, neck, Math.max(4, neck * 0.8), 11), fill });
grips.push({ x: P.x, y: P.y, r: 7 });
} else {
ribbons.push({ d: ribbon(e.ax, e.ay, lerp(e.ax, P.x, 0.45), lerp(e.ay, P.y, 0.45), 14, 3, 0.6), fill });
ribbons.push({ d: ribbon(e.bx, e.by, lerp(e.bx, P.x, 0.3), lerp(e.by, P.y, 0.3), 9, 3, 0.6), fill });
grips.push({ x: P.x, y: P.y, r: 5 });
}
} else {
ribbons.push({ d: ribbon(e.ax, e.ay, e.bx, e.by, 16, 4.5, 11), fill, dim: focus && !dim ? 1 : 0 });
const pr = person(m.person);
// You can't pull your own ribbon, nor the team owner's (they always keep access).
if (vault(m.vault).can_manage && !pr.owner && pr.id !== data.me.id) handles.push({ key, x: h0.x, y: h0.y, dim });
}
}
let ghost: { d: string; cx: number; cy: number; c2: string } | null = null;
if (drag && ((drag.kind === 'grant' && drag.moved) || drag.kind === 'retract')) {
const a = pos(drag.v);
let E = drag.p;
if (tgt) { const q = pos(tgt.id), k = Math.max(0, Math.min(1, 1 - tgt.dist / 130)) * 0.55; E = { x: lerp(E.x, q.x, k), y: lerp(E.y, q.y, k) }; }
const c2 = tgt ? personColor(tgt.id).fill : vaultColor(drag.v).fill;
grads.push({ id: 'g-ghost', x1: a.x, y1: a.y, x2: E.x, y2: E.y, c1: vaultColor(drag.v).fill, c2 });
ghost = { d: ribbon(a.x, a.y, E.x, E.y, 16, 4.5, 9), cx: E.x, cy: E.y, c2 };
}
let hint = '', hintHot = false;
if (grantDrag) {
hint = hot ? `Release to give ${person(hot).name} access to ${vault(grantDrag.v).name}.` : 'Drop on a person to give access.';
hintHot = !!hot;
}
if (drag?.kind === 'detach') {
const [vId, pId] = drag.key.split('|'), e = ends({ vault: vId, person: pId });
const far = Math.hypot(drag.p.x - lerp(e.ax, e.bx, HANDLE_T), drag.p.y - lerp(e.ay, e.by, HANDLE_T)) > 110;
hint = far ? `Release to remove ${person(pId).name} from ${vault(vId).name}.` : 'Pull further to remove access.';
hintHot = far;
}
const manages = vaults.some((v) => v.can_manage);
const back = sel?.back;
const backLabel = !back ? '' : back.kind === 'overview' ? 'Vaults & people' : back.kind === 'vault' ? vault(back.id)?.name : person(back.id)?.name;
const open = (s: Sel) => setSel({ ...s, back: sel ?? undefined });
const boardStyle: React.CSSProperties = { width: `min(100%, calc((100dvh - 160px) * ${W / H}))`, aspectRatio: `${W} / ${H}` };
return (
<div className={`root${sel ? ' open' : ''}`}>
<header className="topbar">
<div className="float-card" style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 16px 10px 12px' }}>
<svg width="34" height="34" viewBox="0 0 34 34" aria-hidden="true"><circle cx="9" cy="17" r="7" fill="#6A4BD0" /><circle cx="27" cy="17" r="5" fill="#BBA8F2" /><path d="M9 12 C16 15 20 15 27 13 L27 21 C20 19 16 19 9 22 Z" fill="#BBA8F2" /></svg>
<div style={{ display: 'flex', flexDirection: 'column' }}>
<span className="disp" style={{ fontSize: 20, fontWeight: 700, lineHeight: 1.1 }}>Team canvas</span>
<span style={{ fontSize: 13, color: 'var(--muted)' }}>{plural(vaults.length, 'vault')} · {plural(people.filter((p) => !p.invited).length, 'person', 'people')}</span>
</div>
</div>
<div className="float-card" style={{ display: 'flex', flexWrap: 'wrap', alignItems: 'center', gap: 8, padding: 6 }}>
<button className="btn btn-small btn-ghost" onClick={() => setSel({ kind: 'overview' })}>Vaults &amp; people</button>
<div className="seg" role="group" aria-label="Layout">
<button className="btn btn-small" aria-pressed={(blend ? blend.to : layout) === 'float'} onClick={() => setLayout('float')}>Float</button>
<button className="btn btn-small" aria-pressed={(blend ? blend.to : layout) === 'dock'} onClick={() => setLayout('dock')}>Dock</button>
</div>
{manages && <button className="btn btn-small btn-primary" onClick={() => setSheet('invite')}>Invite person</button>}
</div>
</header>
<div className="stage" onPointerDown={(e) => { if (e.target === e.currentTarget && !drag) setSel(null); }}>
{vaults.length === 0 ? (
<div className="empty"><div>
<h2 className="disp" style={{ margin: 0 }}>No vaults yet</h2>
<p className="muted">{data.me.owner ? 'Create one here, or move an existing vault onto the hub with `lunesync vault upload`.' : 'When someone gives you a vault, it shows up here.'}</p>
{data.me.owner && <button className="btn btn-primary" onClick={() => setSheet('vault')}>New vault</button>}
</div></div>
) : (
<div className="board" style={boardStyle}>
<svg ref={svgRef} viewBox={`0 0 ${W} ${H}`} role="img" aria-label="Vaults on the left, people on the right. Ribbons show who can sync which vault." style={{ display: 'block', width: '100%', height: 'auto', touchAction: 'none', userSelect: 'none' }} onPointerMove={onMove} onPointerUp={onUp} onPointerCancel={onUp}>
<defs>
<filter id="goo" x="-10%" y="-10%" width="120%" height="120%" colorInterpolationFilters="sRGB">
<feGaussianBlur in="SourceGraphic" stdDeviation="5" />
<feColorMatrix mode="matrix" values="1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 20 -8" />
</filter>
{grads.map((g) => (
<linearGradient key={g.id} id={g.id} gradientUnits="userSpaceOnUse" x1={g.x1} y1={g.y1} x2={g.x2} y2={g.y2}>
<stop offset="0.15" stopColor={g.c1} /><stop offset="0.85" stopColor={g.c2} />
</linearGradient>
))}
</defs>
<rect x="0" y="0" width={W} height={H} fill="transparent" onPointerDown={() => { if (!drag) setSel(null); }} />
<text x="200" y="44" textAnchor="middle" style={{ fontSize: 12, letterSpacing: 2, fill: 'var(--muted)' }}>VAULTS</text>
<text x="770" y="44" textAnchor="middle" style={{ fontSize: 12, letterSpacing: 2, fill: 'var(--muted)' }}>PEOPLE</text>
{/* Ribbons and node halos melt together (X4); a focused node's set is redrawn bright on top (X7). */}
<g className="fade" opacity={focus ? 0.22 : 0.85} filter="url(#goo)">
{ribbons.map((r, i) => <path key={`r${i}`} d={r.d} fill={r.fill} />)}
{blobs.map((b, i) => <path key={`b${i}`} className={bob} style={{ animationDelay: `${b.delay}s` }} d={b.d} fill={b.fill} />)}
{ghost && <><path d={ghost.d} fill="url(#g-ghost)" /><circle cx={ghost.cx} cy={ghost.cy} r="14" fill={ghost.c2} /></>}
</g>
<g className="fade" opacity="0.85" filter="url(#goo)">
{ribbons.filter((r) => r.dim !== undefined).map((r, i) => <path key={`dr${i}`} className="fade" d={r.d} fill={r.fill} opacity={r.dim} />)}
{blobs.map((b, i) => <path key={`db${i}`} className={`fade ${bob}`} style={{ animationDelay: `${b.delay}s` }} d={b.d} fill={b.fill} opacity={b.op} />)}
</g>
{ghost && <circle cx={ghost.cx} cy={ghost.cy} r="8" fill="#6A4BD0" />}
{grips.map((g, i) => <circle key={`gr${i}`} cx={g.x} cy={g.y} r={g.r} fill="#6A4BD0" stroke="#FFFFFF" strokeWidth="2" />)}
{vaults.map((v, i) => {
const p = pos(v.id), c = vaultColor(v.id), on = sel?.kind === 'vault' && sel.id === v.id, veil = relV(v.id) ? 0 : 0.65;
return (
<g key={v.id} transform={`translate(${p.x.toFixed(1)},${p.y.toFixed(1)})`}>
<g className={bob} style={{ animationDelay: `${(i * 0.7).toFixed(1)}s` }}>
<g
data-vault={v.name}
onPointerDown={(e) => (v.can_manage ? startGrant(v.id, e) : undefined)}
onClick={() => { if (!v.can_manage) setSel({ kind: 'vault', id: v.id }); }}
onPointerEnter={() => enter('vault', v.id)} onPointerLeave={leave}
style={{ cursor: v.can_manage ? 'grab' : 'pointer' }}
>
<rect x="-62" y="-28" width="124" height="56" rx="18" fill={hot && grantDrag?.v === v.id ? c.fill : c.tint} stroke={c.stroke} strokeWidth={on ? 3 : 1.5} />
<path d="M-50 -9 h14 l4 4 h8 v14 h-26 z" fill="none" stroke={c.stroke} strokeWidth="1.8" strokeLinejoin="round" />
<rect className="fade" x="-64" y="-30" width="128" height="60" rx="20" fill="#F5F3FB" opacity={veil} pointerEvents="none" />
</g>
</g>
</g>
);
})}
{people.map((pr, i) => {
const p = pos(pr.id), c = personColor(pr.id), on = sel?.kind === 'person' && sel.id === pr.id;
const veil = relP(pr.id) ? 0 : 0.65, n = pr.devices.length;
const angles = n === 1 ? [18] : n === 2 ? [-30, 30] : pr.devices.map((_, j) => -40 + (j * 80) / Math.max(1, n - 1));
return (
<g key={pr.id} className="fade" transform={`translate(${p.x.toFixed(1)},${p.y.toFixed(1)})`}>
<g className={bob} style={{ animationDelay: `${(0.35 + i * 0.6).toFixed(1)}s` }}>
{pr.devices.map((d, j) => {
const a = (angles[j] * Math.PI) / 180, cx = Math.cos(a) * 52, cy = Math.sin(a) * 52;
return (
<g key={d.id} className="fade" opacity={veil ? 0.35 : 1}>
<line x1="0" y1="0" x2={cx} y2={cy} stroke="#E2DDF0" strokeWidth="1.5" />
<circle cx={cx} cy={cy} r="6.5" fill={d.health.held_secrets > 0 ? SECRET_RED : STATUS[d.health.status]} stroke="#FFFFFF" strokeWidth="2" />
</g>
);
})}
<g data-person={pr.name} onClick={() => { if (!drag) setSel({ kind: 'person', id: pr.id }); }} onPointerEnter={() => enter('person', pr.id)} onPointerLeave={leave} style={{ cursor: 'pointer' }}>
<circle r="30" fill={pr.id === hot ? c.fill : c.tint} stroke={pr.invited ? c.ring : pr.removed ? STATUS.offline : STATUS[worst(pr)]} strokeWidth={pr.id === hot ? 6 : on ? 4.5 : 3} strokeDasharray={pr.invited || pr.removed ? '5 5' : 'none'} opacity={pr.removed ? 0.45 : 1} />
<circle className="fade" r="34" fill="#F5F3FB" opacity={veil} pointerEvents="none" />
</g>
</g>
</g>
);
})}
{handles.map((h) => (
<g key={h.key} data-ribbon={`${vault(h.key.split('|')[0]).name}|${person(h.key.split('|')[1]).name}`} transform={`translate(${h.x.toFixed(1)},${h.y.toFixed(1)})`} opacity={h.dim ? 0.15 : 1} onPointerDown={(e) => startDetach(h.key, e)} style={{ cursor: 'grab' }}>
<circle r="16" fill="transparent" />
<circle r="5.5" fill="#6A4BD0" stroke="#FFFFFF" strokeWidth="2" />
</g>
))}
</svg>
<div aria-hidden="true" style={{ position: 'absolute', inset: 0, pointerEvents: 'none' }}>
{labels.map((l, i) => <div key={i} style={l.style}><span className={bob} style={l.inner}>{l.text}</span></div>)}
{people.map((pr, i) => {
const p = pos(pr.id), n = pr.devices.length;
const angles = n === 1 ? [18] : n === 2 ? [-30, 30] : pr.devices.map((_, j) => -40 + (j * 80) / Math.max(1, n - 1));
return pr.devices.map((d, j) => {
const a = (angles[j] * Math.PI) / 180;
return (
<div key={d.id} style={{ ...pct(p.x + Math.cos(a) * 52 + 11, p.y + Math.sin(a) * 52), transform: 'translateY(-50%)', opacity: relP(pr.id) ? 1 : 0.35 }}>
<span className={bob} style={{ display: 'inline-block', whiteSpace: 'nowrap', fontSize: 'max(1.1cqw, 9px)', color: 'var(--muted)', animationDelay: `${(0.35 + i * 0.6).toFixed(1)}s` }}>{d.label}</span>
</div>
);
});
})}
{hot && grantDrag && (() => {
const q = pos(hot);
return <div style={{ ...pct(q.x, q.y - 64), transform: 'translate(-50%,-50%)' }}><span style={{ display: 'inline-block', background: 'var(--ink)', color: '#FFF', fontWeight: 700, fontSize: '1.3cqw', padding: '0.5em 1em', borderRadius: 999, whiteSpace: 'nowrap' }}>Give {person(hot).name} {vault(grantDrag.v).name}</span></div>;
})()}
</div>
</div>
)}
</div>
<div className="bottombar">
{hint && <span className={`chipbar${hintHot ? ' hot' : ''}`}>{hint}</span>}
<span className="chipbar legend" style={{ marginLeft: 'auto' }}>
{(Object.keys(STATUS) as Status[]).map((s) => <span key={s}><i style={{ background: STATUS[s] }} />{STATUS_WORDS[s]}</span>)}
<span><i style={{ background: SECRET_RED }} />Possible secret held</span>
</span>
</div>
{!onboarded && manages && vaults.length > 0 && (
<div className="coach" role="note" aria-label="Getting started">
<span className="disp" style={{ fontSize: 17, fontWeight: 700 }}>Two moves to know</span>
<div className="tip"><span className="tipn">1</span><span>Drag a vault onto a person to give them access.</span></div>
<div className="tip"><span className="tipn">2</span><span>Pull the dot on a ribbon until it snaps to take access back. You can undo.</span></div>
<span className="muted">Click any vault or person for details and buttons.</span>
<button className="btn btn-small btn-primary" style={{ alignSelf: 'flex-end' }} onClick={() => { store('lune.onboarded', '1'); setOnboarded(true); }}>Got it</button>
</div>
)}
{sel && (
<aside aria-label="Details" className="panel">
{back && <button className="backbtn" onClick={() => setSel(back)}>‹ {backLabel}</button>}
{sel.kind === 'overview' && <Overview data={data} members={members} log={log} open={open} close={() => setSel(null)} newVault={() => setSheet('vault')} signOut={onSignOut} />}
{sel.kind === 'vault' && vault(sel.id) && (
<VaultPanel v={vault(sel.id)} data={data} members={members} open={open} close={() => setSel(null)}
cycleRole={cycleRole} remove={(m) => revoke(keyOf(m))} grant={grant} run={run}
compare={(copy) => setSheet({ kind: 'compare', vault: vault(sel.id), copy })}
deleteVault={data.me.owner ? (v) => setSheet({ kind: 'delete', v }) : undefined}
toggleDelete={(v) => run(() => api.vaultSetting(v.name, !v.delete_from_devices), v.delete_from_devices ? `Removed people keep a read-only copy of ${v.name}.` : `Removed people's copies of ${v.name} are deleted from their devices.`)} />
)}
{sel.kind === 'person' && person(sel.id) && (
<PersonPanel p={person(sel.id)} data={data} members={members} open={open} close={() => setSel(null)} run={run}
removeFromTeam={(p) => setSheet({ kind: 'team', p })}
restore={(p) => api.teamRestore(p.name).then((r) => { setSheet({ kind: 'restored', p, link: r.link }); reload(); }).catch((e) => say(e.message))} />
)}
</aside>
)}
{sheet === 'invite' && <InviteDialog vaults={vaults.filter((v) => v.can_manage)} owner={data.me.owner} close={() => { setSheet(null); reload(); }} />}
{typeof sheet === 'object' && sheet?.kind === 'compare' && (
<CompareDialog vault={sheet.vault} copy={sheet.copy} canEdit={['edit', 'manage'].includes(members.find((m) => m.vault === sheet.vault.id && m.person === data.me.id)?.role ?? '')}
close={() => setSheet(null)}
resolve={(keep) => { const s = sheet; setSheet(null); run(async () => say((await api.resolve(s.vault.name, s.copy, keep)).message)); }} />
)}
{typeof sheet === 'object' && sheet?.kind === 'team' && (
<TeamDialog p={sheet.p} data={data} members={members} close={() => setSheet(null)}
confirm={() => { const p = sheet.p; setSheet(null); setSel({ kind: 'person', id: p.id }); run(() => api.teamRemove(p.name), `${p.name} was removed from the team. Their devices send unshared work, then delete every vault copy.`); }} />
)}
{typeof sheet === 'object' && sheet?.kind === 'delete' && (
<DeleteVaultDialog v={sheet.v} members={members} close={() => setSheet(null)}
confirm={() => { const v = sheet.v; setSheet(null); setSel(null); run(() => api.deleteVault(v.name), `${v.name} was deleted. Every device sends unshared work, then removes its copy.`); }} />
)}
{typeof sheet === 'object' && sheet?.kind === 'restored' && (
<div className="scrim" onPointerDown={(e) => { if (e.target === e.currentTarget) setSheet(null); }}>
<div className="dialog" role="dialog" aria-modal="true" aria-label={`${sheet.p.name} restored`}>
<h2 className="disp">{sheet.p.name} is back on the team</h2>
<p style={{ margin: 0, lineHeight: 1.5 }}>They start with no vaults — give them some by dragging. Send them this one-time sign-in link (7 days):</p>
<pre className="cmd">lunesync join {sheet.link} --name "&lt;their device&gt;"</pre>
<div className="actions"><button className="btn btn-primary" onClick={() => setSheet(null)}>Done</button></div>
</div>
</div>
)}
{sheet === 'vault' && <NewVaultDialog close={() => setSheet(null)} create={(name) => { setSheet(null); run(() => api.createVault(name), `${name} is ready. Drag it onto people to share it.`); }} />}
<div className="toast-wrap" aria-live="polite">
{toast && (
<div className="toast">
<span style={{ padding: '2px 8px 2px 0' }}>{toast.text}</span>
{toast.undo && <button className="undo" onClick={toast.undo}>Undo</button>}
</div>
)}
</div>
</div>
);
}
function Avatar({ p }: { p: Person }) {
const c = personColor(p.id);
const ring = p.invited ? c.ring : p.removed ? STATUS.offline : STATUS[worst(p)];
return <span className="avatar" style={{ background: c.tint, borderColor: ring, borderStyle: p.invited || p.removed ? 'dashed' : 'solid' }}>{p.name.charAt(0).toUpperCase()}</span>;
}
function Swatch({ v }: { v: Vault }) {
const c = vaultColor(v.id);
return (
<span className="swatch" style={{ background: c.tint, borderColor: c.fill }}>
<svg width="16" height="14" viewBox="0 0 18 16" aria-hidden="true"><path d="M1 2.5 h6 l2 2 h8 v10 h-16 z" fill="none" stroke={c.stroke} strokeWidth="1.8" strokeLinejoin="round" /></svg>
</span>
);
}
function CloseButton({ close }: { close: () => void }) {
return <button className="btn btn-small" aria-label="Close details" onClick={close}>✕</button>;
}
function Overview({ data, members, log, open, close, newVault, signOut }: {
data: CanvasData; members: Member[]; log: LogEntry[]; open: (s: Sel) => void; close: () => void; newVault: () => void; signOut: () => void;
}) {
return (
<>
<div className="panel-head"><h2 className="disp">Vaults &amp; people</h2><CloseButton close={close} /></div>
<section className="ov-sec" aria-label="Vaults">
<div className="ov-head"><h3>Vaults</h3><span className="ov-count">{data.vaults.length}</span></div>
{data.vaults.map((v) => (
<button key={v.id} className="row" onClick={() => open({ kind: 'vault', id: v.id })}>
<Swatch v={v} />
<span style={{ display: 'flex', flexDirection: 'column', flex: 1, minWidth: 0 }}><b>{v.name}</b><span className="sub">{plural(members.filter((m) => m.vault === v.id).length, 'person', 'people')}</span></span>
<span aria-hidden="true" className="chev">›</span>
</button>
))}
{data.me.owner && <button className="btn btn-small" style={{ alignSelf: 'flex-start', marginTop: 6 }} onClick={newVault}>New vault</button>}
</section>
<section className="ov-sec" aria-label="People">
<div className="ov-head"><h3>People</h3><span className="ov-count">{data.people.length}</span></div>
{data.people.map((p) => (
<button key={p.id} className="row" onClick={() => open({ kind: 'person', id: p.id })}>
<Avatar p={p} />
<span style={{ display: 'flex', flexDirection: 'column', flex: 1, minWidth: 0 }}>
<b>{p.name}</b>
<span className="sub">{p.invited ? 'Invited, not joined yet' : p.removed ? 'Removed from team' : p.owner ? 'Team owner' : plural(members.filter((m) => m.person === p.id).length, 'vault')}</span>
</span>
{!p.invited && !p.removed && (() => { const st = worst(p), [bg, fg] = PILL[st]; return <span className="pill" style={{ background: bg, color: fg }}>{STATUS_WORDS[st]}</span>; })()}
<span aria-hidden="true" className="chev">›</span>
</button>
))}
</section>
{data.me.owner && log.length > 0 && (
<section className="ov-sec" aria-label="Recent activity">
<div className="ov-head"><h3>Recent activity</h3></div>
<ol className="log">
{log.map((e, i) => (
<li key={i}><i /><span style={{ display: 'flex', flexDirection: 'column', gap: 2 }}><span>{e.actor} · {e.action}: {e.detail}</span><span className="muted">{new Date(e.at * 1000).toLocaleString()}</span></span></li>
))}
</ol>
</section>
)}
<MacSection />
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 }}>
<span className="muted">Signed in as {data.me.person}</span>
<button className="btn btn-small" onClick={signOut}>Sign out</button>
</div>
</>
);
}
function VaultPanel({ v, data, members, open, close, cycleRole, remove, grant, toggleDelete, run, compare, deleteVault }: {
v: Vault; data: CanvasData; members: Member[]; open: (s: Sel) => void; close: () => void; deleteVault?: (v: Vault) => void;
cycleRole: (m: Member) => void; remove: (m: Member) => void; grant: (v: string, p: string) => void; toggleDelete: (v: Vault) => void;
run: (action: () => Promise<unknown>, ok?: string) => Promise<void>; compare: (copy: string) => void;
}) {
const inVault = members.filter((m) => m.vault === v.id);
const outside = data.people.filter((p) => !p.removed && !inVault.some((m) => m.person === p.id));
const mine = inVault.find((m) => m.person === data.me.id);
return (
<>
<div className="panel-head">
<div><span className="eyebrow">Vault · {plural(inVault.length, 'person', 'people')}</span><h2 className="disp">{v.name}</h2></div>
<CloseButton close={close} />
</div>
{!v.can_manage && mine && <div className="note">You have {roleName(mine.role)} access. People with Manage decide who else can sync it.</div>}
{v.tidy.length > 0 && (
<div className="note amber">
<b>{plural(v.tidy.length, 'note')} to tidy</b>
<span>Changed in two places at once. Both versions are kept, so nothing is lost.</span>
{v.tidy.map((t) => (
<div key={t.copy} style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<span style={{ flex: 1, minWidth: 0, overflowWrap: 'anywhere' }}>{t.note}</span>
<button className="btn btn-small" onClick={() => compare(t.copy)}>Compare</button>
</div>
))}
</div>
)}
{v.handovers.map((h) => <HandoverCard key={h.id} h={h} vault={v} run={run} />)}
<div>
<h3>People with access</h3>
{inVault.map((m) => {
const p = data.people.find((x) => x.id === m.person)!;
// Your own row and the team owner's can't be changed here (no locking yourself out by accident).
const fixed = p.owner || p.id === data.me.id;
return (
<div key={m.person} className="member">
<Avatar p={p} />
<button className="namebtn" onClick={() => open({ kind: 'person', id: p.id })}>{p.name}{p.invited ? ' (invited)' : ''}</button>
{v.can_manage && !fixed ? (
<button className="btn btn-small" aria-label={`${p.name}'s role is ${roleName(m.role)}. Change role`} onClick={() => cycleRole(m)}>{roleName(m.role)}</button>
) : (
<span className="muted">{roleName(m.role)}</span>
)}
{v.can_manage && !fixed && (
<button className="btn btn-small btn-danger" aria-label={`Remove ${p.name} from ${v.name}`} onClick={() => remove(m)}>Remove</button>
)}
</div>
);
})}
</div>
{v.can_manage && outside.length > 0 && (
<div>
<h3>Give access</h3>
<div className="chips">{outside.map((p) => <button key={p.id} className="btn btn-small" onClick={() => grant(v.id, p.id)}>+ {p.name}</button>)}</div>
</div>
)}
{v.can_manage && (
<div style={{ borderTop: '1px solid #EEEAF6', paddingTop: 16, display: 'flex', flexDirection: 'column', gap: 6 }}>
<h3>When someone is removed</h3>
<label className="check">
<input type="checkbox" checked={v.delete_from_devices} onChange={() => toggleDelete(v)} />
<span>Delete this vault from their devices, after their unshared work is sent to you</span>
</label>
<p className="muted">Removing someone only affects this vault. Copies made elsewhere can't be recalled.</p>
</div>
)}
{deleteVault && (
<div style={{ borderTop: '1px solid #EEEAF6', paddingTop: 16 }}>
<button className="btn btn-danger" onClick={() => deleteVault(v)}>Delete vault…</button>
</div>
)}
</>
);
}
/** Deleting a vault asks first: it ends everyone's access at once (team owner only). */
function DeleteVaultDialog({ v, members, close, confirm }: { v: Vault; members: Member[]; close: () => void; confirm: () => void }) {
const people = members.filter((m) => m.vault === v.id).length;
return (
<div className="scrim" onPointerDown={(e) => { if (e.target === e.currentTarget) close(); }}>
<div className="dialog" role="dialog" aria-modal="true" aria-label={`Delete ${v.name}?`}>
<h2 className="disp">Delete {v.name}?</h2>
<p style={{ margin: 0, lineHeight: 1.5 }}>
{plural(people, 'person', 'people')} lose access. Their devices first send anything not yet shared, then remove their copy{v.delete_from_devices ? '' : ' (or keep it read-only, as this vault is set)'}.
</p>
<p className="muted">The vault's history stays archived on the hub, so nothing is lost; the name {v.name} is free for a new vault. Copies made elsewhere can't be recalled.</p>
<div className="actions">
<button className="btn" onClick={close}>Cancel</button>
<button className="btn btn-primary" style={{ background: '#A52A2F', borderColor: '#A52A2F' }} onClick={confirm}>Delete vault</button>
</div>
</div>
</div>
);
}
function PersonPanel({ p, data, members, open, close, run, removeFromTeam, restore }: {
p: Person; data: CanvasData; members: Member[]; open: (s: Sel) => void; close: () => void;
run: (action: () => Promise<unknown>, ok?: string) => Promise<void>; removeFromTeam: (p: Person) => void; restore: (p: Person) => void;
}) {
const [renaming, setRenaming] = useState<{ id: string; value: string } | null>(null);
const theirs = members.filter((m) => m.person === p.id);
const canEditDevices = p.id === data.me.id || data.me.owner;
const eyebrow = p.invited ? 'Invited' : p.removed ? 'Removed from team' : p.owner ? 'Team owner' : 'Team member';
const leaving = data.vaults.flatMap((v) => v.handovers.filter((h) => h.person === p.name && h.state === 'waiting').map((h) => ({ ...h, vault: v })));
return (
<>
<div className="panel-head">
<div><span className="eyebrow">{eyebrow}</span><h2 className="disp">{p.name}</h2></div>
<CloseButton close={close} />
</div>
{p.invited && <div className="note">{p.name} hasn't joined yet. Vaults you give them now arrive once they join with their invite link.</div>}
{p.removed && (
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
<p style={{ margin: 0, fontSize: 14, lineHeight: 1.5 }}>This account is disabled. Past changes keep this name in history.</p>
{data.me.owner && <button className="btn" style={{ alignSelf: 'flex-start' }} onClick={() => restore(p)}>Restore account</button>}
</div>
)}
{leaving.length > 0 && (
<div className="note">
<b>Leaving</b>
{leaving.map((h) => (
<div key={h.id} style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
<span>{h.device} hasn't reported in since losing {h.vault.name}. Its unshared work comes back when it's next online.</span>
<button className="btn btn-small btn-danger" style={{ alignSelf: 'flex-start' }} onClick={() => run(() => api.handoverDecide(h.id, 'skip'), `${h.device} will delete its copy of ${h.vault.name} without sending anything.`)}>Delete without saving</button>
</div>
))}
</div>
)}
{!p.invited && !p.removed && (
<div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
<h3>Devices</h3>
{p.devices.length === 0 && <p className="muted">{canEditDevices ? 'No devices yet.' : "Only their vault managers see someone's devices."}</p>}
{p.devices.map((d) => (
<div key={d.id} className="device">
{renaming?.id === d.id ? (
<form className="device-head" onSubmit={(e) => { e.preventDefault(); const label = renaming.value.trim(); setRenaming(null); if (label && label !== d.label) run(() => api.renameDevice(d.id, label), `Renamed to ${label}. New history entries carry this name.`); }}>
<label htmlFor={`rename-${d.id}`} className="eyebrow" style={{ position: 'absolute', left: -9999 }}>Device name</label>
<input id={`rename-${d.id}`} className="field" value={renaming.value} onChange={(e) => setRenaming({ id: d.id, value: e.target.value })} autoFocus maxLength={40} />
<button className="btn btn-small btn-primary" type="submit">Save</button>
<button className="btn btn-small" type="button" onClick={() => setRenaming(null)}>Cancel</button>
</form>
) : (
<>
<div className="device-head">
<i style={{ width: 12, height: 12, borderRadius: '50%', background: STATUS[d.health.status], display: 'inline-block', flex: 'none' }} />
<b style={{ flex: 1 }}>{d.label}</b>
<span className="muted">{STATUS_WORDS[d.health.status]}</span>
</div>
<span style={{ fontSize: 14, color: '#4A4560' }}>{healthLine(d.health)}</span>
{d.health.held_secrets > 0 && (
<span className="secret-note">{plural(d.health.held_secrets, 'note')} held back: possible secret, not shared. Its owner decides with <code>lunesync held</code>.</span>
)}
{d.health.holding && <span className="muted">A big change is held here, waiting for its owner to share or undo it.</span>}
</>
)}
{canEditDevices && renaming?.id !== d.id && (
<div className="chips">
{d.health.waiting > 0 && (
<button className="btn btn-small btn-primary" onClick={() => run(() => api.nudge(d.id), `Nudge sent to ${d.label}. It shares at its next check-in, as soon as it's online.`)}>Nudge</button>
)}
<button className="btn btn-small" onClick={() => setRenaming({ id: d.id, value: d.label })}>Rename</button>
<button className="btn btn-small btn-danger" aria-label={`Remove device ${d.label}`} onClick={() => run(() => api.removeDevice(d.id), `${d.label} is removed. It sends anything unshared, then deletes its vault copies and stops working.`)}>Remove device</button>
</div>
)}
</div>
))}
</div>
)}
<div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
<h3>Vaults</h3>
{theirs.length === 0 && <p className="muted">None yet. Drag a vault onto {p.name} to share it.</p>}
{theirs.map((m) => {
const v = data.vaults.find((x) => x.id === m.vault)!;
return (
<button key={m.vault} className="row" onClick={() => open({ kind: 'vault', id: v.id })}>
<Swatch v={v} /><b style={{ flex: 1 }}>{v.name}</b><span className="sub">{roleName(m.role)}</span>
</button>
);
})}
</div>
{data.me.owner && !p.owner && !p.removed && !p.invited && (
<div style={{ borderTop: '1px solid #EEEAF6', paddingTop: 16, display: 'flex', flexDirection: 'column', gap: 8 }}>
<button className="btn btn-danger" style={{ alignSelf: 'flex-start' }} onClick={() => removeFromTeam(p)}>Remove from team</button>
<p className="muted">Ends every vault and device for this person. The account is disabled and can be restored.</p>
</div>
)}
</>
);
}
/** A handover waiting for a manager: received work to review, or a device that hasn't reported in. */
function HandoverCard({ h, vault, run }: { h: Vault['handovers'][number]; vault: Vault; run: (action: () => Promise<unknown>, ok?: string) => Promise<void> }) {
const [files, setFiles] = useState<string[] | null>(null);
if (h.state === 'waiting') {
return (
<div className="note">
<b>{h.person} is leaving {vault.name}</b>
<span>{h.device} hasn't reported in yet. Its unshared work comes to you when it's next online.</span>
<button className="btn btn-small btn-danger" style={{ alignSelf: 'flex-start' }} onClick={() => run(() => api.handoverDecide(h.id, 'skip'), `${h.device} will delete its copy without sending anything.`)}>Delete without saving</button>
</div>
);
}
return (
<div className="note amber">
<b>{h.person}'s last changes from {h.device}</b>
<span>These arrived in a final sync after the removal. Review before they join the vault.</span>
{files === null ? (
<button className="btn btn-small" style={{ alignSelf: 'flex-start' }} onClick={() => api.handoverShow(h.id).then(setFiles).catch(() => setFiles([]))}>Show changes</button>
) : (
<ul className="files">{files.map((f) => <li key={f}>{f}</li>)}</ul>
)}
<div className="chips">
<button className="btn btn-small btn-primary" onClick={() => run(async () => (await api.handoverDecide(h.id, 'keep')).message, `Kept ${h.person}'s changes in ${vault.name}.`)}>Keep</button>
<button className="btn btn-small" onClick={() => run(() => api.handoverDecide(h.id, 'discard'), `${h.person}'s handover was discarded.`)}>Discard</button>
</div>
</div>
);
}
/** Both versions of a note side by side (J3); lines only in one version are highlighted. */
function CompareDialog({ vault, copy, canEdit, close, resolve }: {
vault: Vault; copy: string; canEdit: boolean; close: () => void; resolve: (keep: 'note' | 'copy' | 'both') => void;
}) {
const [c, setC] = useState<Comparison | null>(null);
const [error, setError] = useState('');
useEffect(() => { api.compare(vault.name, copy).then(setC).catch((e) => setError(e.message)); }, [vault, copy]);
const column = (title: string, text: string | null, other: string | null, tint: string) => {
const others = new Set((other ?? '').split('\n'));
return (
<div className="cmp-col">
<div className="cmp-head">{title}</div>
<div className="cmp-body">
{text === null ? <span className="muted">Not shown (not a text note, or very large).</span>
: text.split('\n').map((line, i) => <div key={i} style={others.has(line) ? undefined : { background: tint, margin: '0 -14px', padding: '0 14px' }}>{line || '\u00a0'}</div>)}
</div>
</div>
);
};
return (
<div className="scrim" onPointerDown={(e) => { if (e.target === e.currentTarget) close(); }}>
<div className="dialog wide" role="dialog" aria-modal="true" aria-label={`Compare versions of ${c?.note ?? copy}`}>
<div><span className="eyebrow">{vault.name} · {c?.note ?? ''}</span><h2 className="disp">Two versions of the same lines</h2></div>
{error && <p className="error">{error}</p>}
{c && (
<div className="cmp">
{column(c.note_exists ? 'In the vault' : 'In the vault (removed since)', c.note_text, c.copy_text, '#FBEBD3')}
{column(`${c.label}'s version · kept beside it`, c.copy_text, c.note_text, '#E8E1FB')}
</div>
)}
{c && !canEdit && <p className="muted">You have read access, so you can look but not choose.</p>}
<div className="actions">
<button className="btn" onClick={close}>Keep both for now</button>
{c && canEdit && (
<>
<button className="btn" onClick={() => resolve('both')}>Keep both as separate notes</button>
{c.note_exists && <button className="btn" onClick={() => resolve('note')}>Keep the one in the vault</button>}
<button className="btn btn-primary" onClick={() => resolve('copy')}>Keep {c.label}'s</button>
</>
)}
</div>
</div>
</div>
);
}
/** The only gesture on the canvas that asks first (X2, A8). */
function TeamDialog({ p, data, members, close, confirm }: { p: Person; data: CanvasData; members: Member[]; close: () => void; confirm: () => void }) {
const theirs = members.filter((m) => m.person === p.id).map((m) => data.vaults.find((v) => v.id === m.vault)?.name ?? '');
const waiting = p.devices.reduce((n, d) => n + d.health.waiting, 0);
return (
<div className="scrim" onPointerDown={(e) => { if (e.target === e.currentTarget) close(); }}>
<div className="dialog" role="dialog" aria-modal="true" aria-label={`Remove ${p.name} from the team?`}>
<h2 className="disp">Remove {p.name} from the team?</h2>
<p style={{ margin: 0, lineHeight: 1.5 }}>
{p.name} is in {plural(theirs.length, 'vault')}{theirs.length ? ` (${theirs.join(', ')})` : ''} on {plural(p.devices.length, 'device')}. All access ends and every vault copy is deleted from those devices.
</p>
{waiting > 0 && <p className="warn-box">{plural(waiting, 'change')} haven't been shared yet. They'll be sent to the team for review before anything is deleted.</p>}
<p className="muted">The account is disabled, not deleted, and can be restored. Past changes keep {p.name}'s name in history. Copies made elsewhere can't be recalled.</p>
<div className="actions">
<button className="btn" onClick={close}>Cancel</button>
<button className="btn btn-primary" style={{ background: '#A52A2F', borderColor: '#A52A2F' }} onClick={confirm}>Remove from team</button>
</div>
</div>
</div>
);
}
function InviteDialog({ vaults, owner, close }: { vaults: Vault[]; owner: boolean; close: () => void }) {
const [name, setName] = useState('');
const [picked, setPicked] = useState<Set<string>>(new Set());
const [link, setLink] = useState('');
const [error, setError] = useState('');
const [copied, setCopied] = useState(false);
const create = async (e: React.FormEvent) => {
e.preventDefault();
try {
const grants = vaults.filter((v) => picked.has(v.id)).map((v) => ({ vault: v.name, role: 'edit' as Role }));
setLink((await api.invite(name.trim(), grants)).link);
setError('');
} catch (err) {
setError((err as Error).message);
}
};
const command = `lunesync join ${link} --name "<their device>"`;
return (
<div className="scrim" onPointerDown={(e) => { if (e.target === e.currentTarget) close(); }}>
<div className="dialog" role="dialog" aria-modal="true" aria-label="Invite a person">
<h2 className="disp">Invite a person</h2>
{!link ? (
<form onSubmit={create} style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
<label className="lbl" htmlFor="invite-name">Name</label>
<input id="invite-name" className="field" value={name} onChange={(e) => setName(e.target.value)} placeholder="Sari" autoFocus />
{vaults.length > 0 && (
<fieldset style={{ border: 0, padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 8 }}>
<legend className="lbl" style={{ fontSize: 14, fontWeight: 700, marginBottom: 6 }}>Vaults they get (Edit){owner ? ' — optional' : ''}</legend>
{vaults.map((v) => (
<label key={v.id} className="check">
<input type="checkbox" checked={picked.has(v.id)} onChange={() => setPicked((s) => { const n = new Set(s); if (n.has(v.id)) n.delete(v.id); else n.add(v.id); return n; })} />
<span>{v.name}</span>
</label>
))}
</fieldset>
)}
<p className="muted">You'll get a one-time link to send them. They join with the sync app and appear here; give them more vaults by dragging.</p>
{error && <p className="error" role="alert">{error}</p>}
<div className="actions">
<button className="btn" type="button" onClick={close}>Cancel</button>
<button className="btn btn-primary" type="submit" disabled={!name.trim() || (!owner && picked.size === 0)}>Create invite link</button>
</div>
</form>
) : (
<>
<p style={{ margin: 0, lineHeight: 1.5 }}>Send this to {name.trim()} over a channel you trust. It works once, for 7 days. They run:</p>
<pre className="cmd">{command}</pre>
<div className="actions">
<button className="btn" onClick={() => navigator.clipboard?.writeText(command).then(() => setCopied(true))}>{copied ? 'Copied' : 'Copy'}</button>
<button className="btn btn-primary" onClick={close}>Done</button>
</div>
</>
)}
</div>
</div>
);
}
function NewVaultDialog({ close, create }: { close: () => void; create: (name: string) => void }) {
const [name, setName] = useState('');
return (
<div className="scrim" onPointerDown={(e) => { if (e.target === e.currentTarget) close(); }}>
<form className="dialog" role="dialog" aria-modal="true" aria-label="New vault" onSubmit={(e) => { e.preventDefault(); if (name.trim()) create(name.trim()); }}>
<h2 className="disp">New vault</h2>
<label className="lbl" htmlFor="vault-name">Name</label>
<input id="vault-name" className="field" value={name} onChange={(e) => setName(e.target.value)} placeholder="DevOps" autoFocus />
<p className="muted">It starts empty and arrives on your devices within a minute. To move an existing vault here, use <code>lunesync vault upload</code>.</p>
<div className="actions">
<button className="btn" type="button" onClick={close}>Cancel</button>
<button className="btn btn-primary" type="submit" disabled={!name.trim()}>Create</button>
</div>
</form>
</div>
);
}