Milestone 5: canvas for access

The hub now serves a React canvas (web/, embedded at build time):
grant by dragging a vault onto a person, revoke by pulling a ribbon
until it snaps with an 8 s Undo the hub honours before anything reaches
devices, invites (including vaults dropped on invitees), device rename
and removal, Float/Dock, and panels with a button for every gesture.

Sign-in without passwords (SPEC §8): `lunesync open` one-time link or
a pairing code typed on the hub; 30-day HttpOnly session cookie plus an
X-Lune header on every canvas request.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-29 07:56:41 +07:00
parent 4025726083
commit 193cb06f85
27 changed files with 3574 additions and 39 deletions

791
web/src/Canvas.tsx Normal file
View File

@@ -0,0 +1,791 @@
// 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 { api, type CanvasData, type LogEntry, type Member, type Person, type Role, 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}`;
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 };
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<'invite' | 'vault' | 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) {
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;
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 = relP(pr.id) ? 1 : 0.35;
if (!pr.invited) 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.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={c.ring} 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={c.ring} strokeWidth={pr.id === hot ? 6 : on ? 4.5 : 3} strokeDasharray={pr.invited ? '5 5' : 'none'} />
<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>}</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}
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} />
)}
</aside>
)}
{sheet === 'invite' && <InviteDialog vaults={vaults.filter((v) => v.can_manage)} owner={data.me.owner} close={() => { setSheet(null); reload(); }} />}
{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);
return <span className="avatar" style={{ background: c.tint, borderColor: c.ring, borderStyle: p.invited ? '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.owner ? 'Team owner' : plural(members.filter((m) => m.person === p.id).length, 'vault')}</span>
</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>
)}
<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 }: {
v: Vault; data: CanvasData; members: Member[]; open: (s: Sel) => void; close: () => void;
cycleRole: (m: Member) => void; remove: (m: Member) => void; grant: (v: string, p: string) => void; toggleDelete: (v: Vault) => void;
}) {
const inVault = members.filter((m) => m.vault === v.id);
const outside = data.people.filter((p) => !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>}
<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>
)}
</>
);
}
function PersonPanel({ p, data, members, open, close, run }: {
p: Person; data: CanvasData; members: Member[]; open: (s: Sel) => void; close: () => void;
run: (action: () => Promise<unknown>, ok?: string) => Promise<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.owner ? 'Team owner' : 'Team member';
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.invited && (
<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: personColor(p.id).ring, display: 'inline-block', flex: 'none' }} />
<b style={{ flex: 1 }}>{d.label}</b>
</div>
)}
{canEditDevices && renaming?.id !== d.id && (
<div className="chips">
<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>
</>
);
}
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>
);
}

81
web/src/api.ts Normal file
View File

@@ -0,0 +1,81 @@
// Talking to the hub. The session cookie signs requests; X-Lune marks them as coming from the canvas.
export type Role = 'read' | 'edit' | 'manage';
export interface Vault {
id: string;
name: string;
can_manage: boolean;
delete_from_devices: boolean;
}
export interface Device {
id: string;
label: string;
}
export interface Person {
id: string;
name: string;
owner: boolean;
/** Invited but not joined yet. */
invited: boolean;
devices: Device[];
}
export interface Member {
vault: string;
person: string;
role: Role;
}
export interface CanvasData {
me: { id: string; person: string; owner: boolean };
vaults: Vault[];
people: Person[];
members: Member[];
/** Removals waiting out their Undo window. */
pending: { id: number; vault: string; person: string }[];
}
export interface LogEntry {
at: number;
actor: string;
action: string;
detail: string;
}
export class SignedOut extends Error {}
async function call<T>(method: string, path: string, body?: unknown): Promise<T> {
const res = await fetch(path, {
method,
credentials: 'same-origin',
headers: { 'X-Lune': '1', ...(body ? { 'Content-Type': 'application/json' } : {}) },
body: body ? JSON.stringify(body) : undefined,
});
const data = await res.json().catch(() => ({}));
if (res.status === 401) throw new SignedOut(data.error ?? 'please sign in');
if (!res.ok) throw new Error(data.error ?? 'something went wrong on the hub');
return data as T;
}
export const api = {
canvas: () => call<CanvasData>('GET', '/api/canvas'),
log: (count = 8) => call<LogEntry[]>('GET', `/api/log?count=${count}`),
signin: (code: string) => call<object>('POST', '/api/web/signin', { code }),
signout: () => call<object>('POST', '/api/web/signout'),
grant: (person: string, vault: string, role: Role) => call<object>('POST', '/api/grants', { person, vault, role }),
inviteGrant: (person: string, vault: string, role: Role | null, remove = false) =>
call<object>('POST', '/api/invites/grant', { person, vault, role, remove }),
remove: (person: string, vault: string, delaySeconds: number) =>
call<{ pending?: number }>('POST', '/api/remove', { person, vault, delay_seconds: delaySeconds }),
undoRemove: (pending: number) => call<object>('POST', '/api/remove/undo', { pending }),
invite: (person: string, grants: { vault: string; role: Role }[]) =>
call<{ link: string }>('POST', '/api/invites', { person, grants }),
createVault: (name: string) => call<object>('POST', '/api/vaults', { name }),
vaultSetting: (vault: string, deleteFromDevices: boolean) =>
call<object>('POST', '/api/vaults/settings', { vault, delete_from_devices: deleteFromDevices }),
renameDevice: (deviceId: string, label: string) => call<object>('POST', '/api/devices/rename', { device_id: deviceId, label }),
removeDevice: (deviceId: string) => call<object>('POST', '/api/device/remove', { device_id: deviceId }),
};

81
web/src/geometry.ts Normal file
View File

@@ -0,0 +1,81 @@
// Shapes and places on the canvas. Coordinates are in the board's viewBox: 1000 wide, height grows with the team.
export type Pt = { x: number; y: number };
export type Layout = 'float' | 'dock';
export const W = 1000;
/** How far along a ribbon (vault → person) its grab dot sits. */
export const HANDLE_T = 0.8;
export function boardHeight(nVaults: number, nPeople: number): number {
return Math.max(620, 140 + Math.max(nVaults, nPeople) * 120);
}
/** Where each vault (left) and person (right) sits. Float is a loose scatter, Dock a tidy column. */
export function positions(vaults: string[], people: string[], layout: Layout, h: number): Record<string, Pt> {
const out: Record<string, Pt> = {};
const jitter = [35, -40, 45, -25, 20, -35];
const column = (ids: string[], x: number) => {
const top = 120, bottom = h - 90, n = ids.length;
ids.forEach((id, i) => {
const y = n === 1 ? h / 2 : top + (i * (bottom - top)) / (n - 1);
out[id] = { x: layout === 'float' ? x + jitter[i % jitter.length] : x, y };
});
};
column(vaults, 200);
column(people, 770);
return out;
}
export const lerp = (a: number, b: number, t: number) => a + (b - a) * t;
export function easeBack(t: number) {
const c = 1.3;
return 1 + (c + 1) * Math.pow(t - 1, 3) + c * Math.pow(t - 1, 2);
}
/** A ribbon from (x1,y1) to (x2,y2): w1/w2 half-widths at the ends, wm at the waist. */
export function ribbon(x1: number, y1: number, x2: number, y2: number, w1: number, wm: number, w2: number): string {
const dx = x2 - x1, dy = y2 - y1, L = Math.max(1, Math.hypot(dx, dy));
const ux = dx / L, uy = dy / L, nx = -uy, ny = ux, k = L * 0.35;
const f = (x: number, y: number) => `${x.toFixed(1)} ${y.toFixed(1)}`;
return (
`M${f(x1 + nx * w1, y1 + ny * w1)} C${f(x1 + ux * k + nx * wm, y1 + uy * k + ny * wm)} ${f(x2 - ux * k + nx * wm, y2 - uy * k + ny * wm)} ${f(x2 + nx * w2, y2 + ny * w2)}` +
` L${f(x2 - nx * w2, y2 - ny * w2)} C${f(x2 - ux * k - nx * wm, y2 - uy * k - ny * wm)} ${f(x1 + ux * k - nx * wm, y1 + uy * k - ny * wm)} ${f(x1 - nx * w1, y1 - ny * w1)} Z`
);
}
export function roundRect(cx: number, cy: number, w: number, h: number, r: number): string {
const x = cx - w / 2, y = cy - h / 2;
return `M${x + r} ${y} h${w - 2 * r} a${r} ${r} 0 0 1 ${r} ${r} v${h - 2 * r} a${r} ${r} 0 0 1 ${-r} ${r} h${-(w - 2 * r)} a${r} ${r} 0 0 1 ${-r} ${-r} v${-(h - 2 * r)} a${r} ${r} 0 0 1 ${r} ${-r} Z`;
}
export function circle(cx: number, cy: number, r: number): string {
return `M${cx - r} ${cy} a${r} ${r} 0 1 0 ${2 * r} 0 a${r} ${r} 0 1 0 ${-2 * r} 0 Z`;
}
/** Identity colors (X5): no green, amber, grey or red — those mean status. */
const VAULT_COLORS = [
{ fill: '#9B85F0', tint: '#ECE6FD', stroke: '#6A4BD0' },
{ fill: '#6FB4EA', tint: '#E2F0FB', stroke: '#2B78B0' },
{ fill: '#EE97B4', tint: '#FCE8EF', stroke: '#B9476E' },
{ fill: '#8FA0F5', tint: '#E8ECFD', stroke: '#3F51B5' },
{ fill: '#C58AE8', tint: '#F5EAFC', stroke: '#8A3FB0' },
{ fill: '#7CC3E0', tint: '#E3F4FA', stroke: '#2A7FA0' },
];
const PERSON_COLORS = [
{ fill: '#B3A2F6', tint: '#F2EEFE', ring: '#6A4BD0' },
{ fill: '#F0A6CA', tint: '#FDEEF5', ring: '#B0457A' },
{ fill: '#86CCD8', tint: '#E7F6F8', ring: '#2A8296' },
{ fill: '#D4A2E4', tint: '#F8EEFB', ring: '#8E4AA8' },
{ fill: '#9DB4F2', tint: '#ECF1FD', ring: '#3D5BB8' },
{ fill: '#E9A6E0', tint: '#FBEDF8', ring: '#A2448F' },
];
function pick<T>(list: T[], id: string): T {
let h = 0;
for (const c of id) h = (h * 31 + c.charCodeAt(0)) >>> 0;
return list[h % list.length];
}
export const vaultColor = (id: string) => pick(VAULT_COLORS, id);
export const personColor = (id: string) => pick(PERSON_COLORS, id);

81
web/src/main.tsx Normal file
View File

@@ -0,0 +1,81 @@
import { StrictMode, useEffect, useState } from 'react';
import { createRoot } from 'react-dom/client';
import { api, SignedOut, type CanvasData } from './api';
import { Canvas } from './Canvas';
import './styles.css';
/** Sign in with a code from one of your devices (no passwords, §8). */
function SignIn({ onDone }: { onDone: () => void }) {
const expired = new URLSearchParams(location.search).has('expired');
const [code, setCode] = useState('');
const [error, setError] = useState(expired ? 'That sign-in link was used or expired. Run `lunesync open` again, or use a code.' : '');
const submit = async (e: React.FormEvent) => {
e.preventDefault();
try {
await api.signin(code);
history.replaceState(null, '', '/');
onDone();
} catch (err) {
setError((err as Error).message);
}
};
return (
<main className="page">
<form className="card" onSubmit={submit}>
<span className="eyebrow">Lune</span>
<h1 className="disp">Sign in to the team canvas</h1>
<label htmlFor="code">Code from one of your devices</label>
<input id="code" className="field code" value={code} onChange={(e) => setCode(e.target.value)} placeholder="K7QD-4MXA" autoComplete="one-time-code" autoFocus />
{error && <p className="error" role="alert">{error}</p>}
<button className="btn btn-primary" type="submit" disabled={!code.trim()}>Sign in</button>
<p className="muted">Get a code with <code>lunesync pair</code>, or run <code>lunesync open</code> on a device to skip this page.</p>
</form>
</main>
);
}
/** What an invite link shows in a browser: how to join with the app. */
function Join() {
const link = location.href;
return (
<main className="page">
<div className="card">
<span className="eyebrow">Lune · invite</span>
<h1 className="disp">You're invited to a team</h1>
<p>Install the sync app, then join from the device you'll use (this link works once):</p>
<pre className="cmd">lunesync join {link} --name "My laptop"</pre>
<p className="muted">Pick any name for the device; your team sees it next to your changes. Shared vaults arrive in <code>~/Vaults</code>.</p>
</div>
</main>
);
}
function App() {
const [data, setData] = useState<CanvasData | null>(null);
const [state, setState] = useState<'loading' | 'signin' | 'ready' | 'error'>('loading');
const [error, setError] = useState('');
const load = async () => {
try {
setData(await api.canvas());
setState('ready');
} catch (e) {
if (e instanceof SignedOut) setState('signin');
else {
setError((e as Error).message);
setState('error');
}
}
};
useEffect(() => {
if (!location.pathname.startsWith('/join/')) load();
}, []);
if (location.pathname.startsWith('/join/')) return <Join />;
if (state === 'signin') return <SignIn onDone={load} />;
if (state === 'error') return <main className="page"><div className="card"><p className="error">{error}</p><button className="btn" onClick={load}>Try again</button></div></main>;
if (!data) return <main className="page" aria-busy="true" />;
return <Canvas data={data} reload={load} onSignOut={async () => { await api.signout().catch(() => {}); setState('signin'); }} />;
}
createRoot(document.getElementById('root')!).render(<StrictMode><App /></StrictMode>);

129
web/src/styles.css Normal file
View File

@@ -0,0 +1,129 @@
/* The team canvas, after Sen's prototype: ink on lavender paper, display type for names, a calm purple accent.
Status colors (green/amber/grey/red) are reserved for M6 and not used here (X6). */
:root {
--paper: #F5F3FB;
--dots: #DCD5EE;
--surface: #FFFFFF;
--ink: #221E33;
--muted: #6A6480;
--line: #E2DDF0;
--line-strong: #D7D0EC;
--accent: #6A4BD0;
--accent-hover: #5A3CC0;
--accent-soft: #F1EDFB;
--accent-tint: #E8E1FB;
--focus: #9B84EA;
--danger-ink: #A52A2F;
--font-display: 'Bricolage Grotesque', 'Avenir Next', system-ui, sans-serif;
--font-body: 'Atkinson Hyperlegible', system-ui, -apple-system, sans-serif;
}
* { box-sizing: border-box; }
html, body { margin: 0; height: 100%; }
body { background: var(--paper); color: var(--ink); font-family: var(--font-body); font-size: 15px; }
code, pre { font-family: ui-monospace, Menlo, monospace; font-size: 0.9em; }
.disp { font-family: var(--font-display); }
.muted { color: var(--muted); font-size: 13px; line-height: 1.5; margin: 0; }
.eyebrow { font-size: 12px; letter-spacing: 1.5px; text-transform: uppercase; color: var(--muted); font-weight: 700; }
.error { color: var(--danger-ink); margin: 0; font-size: 14px; }
.btn { font: inherit; font-size: 14px; min-height: 40px; padding: 8px 14px; border-radius: 12px; border: 1px solid var(--line-strong); background: var(--surface); color: var(--ink); cursor: pointer; }
.btn:hover { background: var(--accent-soft); }
.btn:disabled { opacity: 0.55; cursor: default; }
.btn-primary { background: var(--accent); border-color: var(--accent); color: #FFFFFF; }
.btn-primary:hover { background: var(--accent-hover); }
.btn-danger { color: var(--danger-ink); border-color: #EBC5C7; }
.btn-danger:hover { background: #FBEDED; }
.btn-small { min-height: 32px; padding: 4px 10px; font-size: 13px; border-radius: 10px; }
.btn-ghost { border-color: transparent; background: transparent; }
button:focus-visible, input:focus-visible, a:focus-visible { outline: 3px solid var(--focus); outline-offset: 2px; }
.field { font: inherit; font-size: 15px; padding: 10px 12px; border-radius: 12px; border: 1px solid var(--line-strong); background: var(--surface); color: var(--ink); width: 100%; }
.field.code { font-family: var(--font-display); font-size: 24px; letter-spacing: 3px; text-transform: uppercase; }
/* Sign-in and join pages */
.page { min-height: 100%; display: flex; align-items: center; justify-content: center; padding: 24px 16px; }
.card { background: var(--surface); border: 1px solid var(--line); border-radius: 24px; padding: 28px; width: 100%; max-width: 460px; display: flex; flex-direction: column; gap: 14px; box-shadow: 0 16px 40px rgba(34, 30, 51, 0.08); }
.card h1 { margin: 0; font-size: 26px; line-height: 1.15; }
.card p { margin: 0; line-height: 1.5; }
.card label { font-weight: 700; font-size: 14px; }
.cmd { background: #1E1B2E; color: #EDE9F8; border-radius: 12px; padding: 12px 14px; margin: 0; overflow-x: auto; white-space: pre-wrap; word-break: break-all; }
/* Canvas */
.root { height: 100vh; height: 100dvh; overflow: hidden; position: relative; background-color: var(--paper); background-image: radial-gradient(var(--dots) 1.2px, transparent 1.4px); background-size: 24px 24px; }
.bob { animation: bob 4.6s ease-in-out infinite; }
@keyframes bob { 0%, 100% { transform: translateY(0); } 50% { transform: translateY(-4px); } }
.fade { transition: opacity 0.2s ease; }
.stage { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; padding: 88px 24px 84px; transition: padding 0.3s ease; }
.board { position: relative; container-type: inline-size; }
.open .stage { padding-right: 428px; }
.topbar { position: absolute; top: 0; left: 0; right: 0; display: flex; flex-wrap: wrap; justify-content: space-between; align-items: flex-start; gap: 10px; padding: 16px; pointer-events: none; z-index: 12; }
.topbar > * { pointer-events: auto; }
.float-card { background: rgba(255, 255, 255, 0.94); border: 1px solid var(--line); border-radius: 18px; box-shadow: 0 6px 20px rgba(34, 30, 51, 0.08); }
.seg { display: flex; padding: 4px; gap: 4px; background: var(--accent-soft); border-radius: 14px; }
.seg .btn { border-color: transparent; background: transparent; color: var(--muted); }
.seg .btn[aria-pressed='true'] { background: #FFFFFF; color: var(--ink); font-weight: 700; box-shadow: 0 1px 3px rgba(34, 30, 51, 0.12); }
.bottombar { position: absolute; left: 16px; right: 16px; bottom: 16px; display: flex; flex-wrap: wrap; justify-content: space-between; align-items: flex-end; gap: 8px; pointer-events: none; z-index: 11; transition: right 0.3s ease; }
.open .bottombar { right: 428px; }
.chipbar { background: rgba(255, 255, 255, 0.94); border: 1px solid var(--line); border-radius: 999px; padding: 8px 14px; font-size: 13px; color: var(--muted); }
.chipbar.hot { color: #4B2FB0; font-weight: 700; }
.empty { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; pointer-events: none; }
.empty > div { pointer-events: auto; text-align: center; max-width: 360px; display: flex; flex-direction: column; gap: 10px; align-items: center; }
.panel { position: absolute; top: 84px; right: 16px; bottom: 16px; width: 396px; max-width: calc(100% - 32px); overflow-y: auto; background: var(--surface); border: 1px solid var(--line); border-radius: 24px; padding: 20px; display: flex; flex-direction: column; gap: 20px; box-shadow: 0 16px 40px rgba(34, 30, 51, 0.14); z-index: 15; animation: slidein 0.25s ease-out; }
.panel h2 { margin: 0; font-size: 24px; }
.panel h3 { margin: 0 0 6px; font-size: 12px; letter-spacing: 1.5px; color: var(--muted); font-weight: 700; text-transform: uppercase; }
.panel-head { display: flex; justify-content: space-between; align-items: flex-start; gap: 12px; }
.panel-head > div { display: flex; flex-direction: column; gap: 2px; min-width: 0; }
.backbtn { font: inherit; font-size: 13px; font-weight: 700; background: none; border: 0; color: var(--accent); cursor: pointer; padding: 6px 8px; margin: -8px 0 -6px -8px; border-radius: 8px; align-self: flex-start; }
.backbtn:hover { background: var(--accent-soft); }
.ov-sec { background: #F8F6FC; border: 1px solid #ECE8F5; border-radius: 18px; padding: 12px; display: flex; flex-direction: column; gap: 2px; }
.ov-head { display: flex; align-items: center; justify-content: space-between; padding: 2px 6px 8px; }
.ov-count { font-size: 12px; color: var(--muted); background: #FFFFFF; border: 1px solid var(--line); border-radius: 999px; padding: 1px 9px; }
.row { font: inherit; display: flex; align-items: center; gap: 12px; width: 100%; background: transparent; border: 0; border-radius: 12px; padding: 8px 6px; cursor: pointer; text-align: left; color: var(--ink); }
.row:hover { background: #FFFFFF; }
.row .sub { font-size: 13px; color: var(--muted); }
.chev { color: #A39DB8; font-size: 20px; line-height: 1; flex: none; }
.member { display: flex; align-items: center; gap: 10px; padding: 6px 0; }
.namebtn { font: inherit; font-weight: 700; flex: 1; text-align: left; background: none; border: 0; padding: 4px 0; cursor: pointer; color: var(--ink); min-width: 0; overflow: hidden; text-overflow: ellipsis; }
.namebtn:hover { color: var(--accent); text-decoration: underline; }
.avatar { width: 34px; height: 34px; border-radius: 50%; border: 3px solid; display: flex; align-items: center; justify-content: center; font-weight: 700; flex: none; }
.swatch { width: 34px; height: 34px; border-radius: 11px; border: 2px solid; display: flex; align-items: center; justify-content: center; flex: none; }
.device { border: 1px solid var(--line); border-radius: 16px; padding: 12px; display: flex; flex-direction: column; gap: 8px; }
.device-head { display: flex; align-items: center; gap: 10px; }
.chips { display: flex; gap: 8px; flex-wrap: wrap; }
.note { background: var(--accent-soft); border: 1px solid var(--line-strong); border-radius: 16px; padding: 14px; display: flex; flex-direction: column; gap: 8px; font-size: 14px; line-height: 1.45; }
.check { display: flex; gap: 10px; align-items: flex-start; font-size: 14px; cursor: pointer; line-height: 1.45; }
.check input { width: 18px; height: 18px; margin: 1px 0 0; accent-color: var(--accent); flex: none; }
.log { list-style: none; margin: 0; padding: 0 6px; display: flex; flex-direction: column; }
.log li { display: grid; grid-template-columns: 12px minmax(0, 1fr); gap: 10px; padding: 7px 0; font-size: 14px; line-height: 1.4; }
.log li i { width: 8px; height: 8px; border-radius: 50%; background: #BBA8F2; margin-top: 6px; display: block; }
.coach { position: absolute; left: 16px; bottom: 68px; z-index: 13; width: 320px; max-width: calc(100% - 32px); background: #FFFFFF; border: 1px solid var(--line); border-radius: 20px; padding: 16px; box-shadow: 0 12px 32px rgba(34, 30, 51, 0.14); display: flex; flex-direction: column; gap: 10px; }
.tip { display: flex; gap: 10px; font-size: 14px; line-height: 1.45; }
.tipn { width: 22px; height: 22px; border-radius: 50%; background: var(--accent-tint); color: #4B2FB0; font-weight: 700; font-size: 12px; display: flex; align-items: center; justify-content: center; flex: none; }
.scrim { position: fixed; inset: 0; background: rgba(34, 30, 51, 0.38); display: flex; align-items: center; justify-content: center; padding: 16px; z-index: 20; }
.dialog { background: #FFFFFF; border-radius: 24px; padding: 24px; width: 100%; max-width: 460px; display: flex; flex-direction: column; gap: 14px; max-height: calc(100dvh - 32px); overflow-y: auto; }
.dialog h2 { margin: 0; font-size: 22px; }
.dialog label.lbl { font-size: 14px; font-weight: 700; }
.actions { display: flex; justify-content: flex-end; gap: 10px; flex-wrap: wrap; }
.toast-wrap { position: fixed; left: 50%; bottom: 20px; transform: translateX(-50%); z-index: 30; width: max-content; max-width: calc(100% - 32px); }
.toast { background: var(--ink); color: #FFFFFF; padding: 10px 10px 10px 18px; border-radius: 14px; font-size: 14px; line-height: 1.4; box-shadow: 0 8px 24px rgba(34, 30, 51, 0.25); display: flex; align-items: center; gap: 12px; }
.undo { font: inherit; font-size: 14px; font-weight: 700; background: none; border: 0; color: #C9B8FF; cursor: pointer; padding: 6px 8px; border-radius: 8px; }
.undo:hover { background: rgba(255, 255, 255, 0.1); }
@keyframes slidein { from { transform: translateX(24px); opacity: 0; } to { transform: none; opacity: 1; } }
@keyframes slideup { from { transform: translateY(24px); opacity: 0; } to { transform: none; opacity: 1; } }
@media (max-width: 720px) {
.stage { padding: 136px 8px 64px; }
.open .stage { padding-right: 8px; padding-bottom: 58vh; }
.panel { top: auto; left: 8px; right: 8px; bottom: 8px; width: auto; max-width: none; height: 56vh; animation-name: slideup; }
.open .bottombar { display: none; }
.coach { bottom: 16px; }
}
@media (prefers-reduced-motion: reduce) {
.bob { animation: none; }
.panel { animation: none; }
.stage, .bottombar, .fade { transition: none; }
}