Support creating and joining account workspaces
This commit is contained in:
@@ -0,0 +1,22 @@
|
||||
BEGIN;
|
||||
CREATE TABLE workspaces (
|
||||
id uuid PRIMARY KEY,
|
||||
owner_id uuid NOT NULL REFERENCES account_users(id),
|
||||
name text NOT NULL CHECK (char_length(name) BETWEEN 1 AND 40),
|
||||
purpose text NOT NULL CHECK (purpose IN ('工作与团队','个人创作','学习与研究')),
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE TABLE workspace_members (
|
||||
workspace_id uuid NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,
|
||||
user_id uuid NOT NULL REFERENCES account_users(id) ON DELETE CASCADE,
|
||||
PRIMARY KEY (workspace_id, user_id)
|
||||
);
|
||||
CREATE INDEX workspace_members_user ON workspace_members(user_id);
|
||||
CREATE TABLE workspace_invites (
|
||||
digest text PRIMARY KEY,
|
||||
workspace_id uuid NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,
|
||||
expires_at timestamptz NOT NULL
|
||||
);
|
||||
CREATE INDEX workspace_invites_workspace ON workspace_invites(workspace_id);
|
||||
INSERT INTO schema_migrations(version) VALUES ('018_workspaces');
|
||||
COMMIT;
|
||||
@@ -17,7 +17,8 @@ const purposes = [
|
||||
{label: '个人创作', detail: '收集灵感,让想法成形。', icon: House},
|
||||
{label: '学习与研究', detail: '梳理资料,记录研究过程。', icon: BookOpen},
|
||||
];
|
||||
type Space = {name: string; purpose: string};
|
||||
type Space = {id?: string; name: string; purpose: string; owner?: boolean};
|
||||
const spaceKey = (space: Space) => space.id ?? space.name;
|
||||
export type Subcanvas = {id: string; name: string; nodes: string[]; editedAt?: string};
|
||||
const personal = {name: '个人空间', purpose: ''};
|
||||
|
||||
@@ -33,7 +34,9 @@ export function WorkspaceShell({editor, liveNodes}: WorkspaceShellProps) {
|
||||
const [spaces, setSpaces] = useState<Space[]>([]);
|
||||
const [active, setActive] = useState(personal);
|
||||
const [query, setQuery] = useState('');
|
||||
const [step, setStep] = useState<'purpose' | 'name'>('purpose');
|
||||
const [step, setStep] = useState<'choice' | 'join' | 'purpose' | 'name' | 'invite'>('choice');
|
||||
const [code, setCode] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [purpose, setPurpose] = useState('');
|
||||
const [name, setName] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
@@ -63,13 +66,22 @@ export function WorkspaceShell({editor, liveNodes}: WorkspaceShellProps) {
|
||||
return;
|
||||
}
|
||||
setEmail(data.user.email);
|
||||
let local: Space[] = [];
|
||||
let activeKey = '';
|
||||
try {
|
||||
const saved = JSON.parse(localStorage.getItem('studio.workspace:' + data.user.email) || 'null');
|
||||
if (Array.isArray(saved?.spaces)) {
|
||||
setSpaces(saved.spaces);
|
||||
setActive(saved.spaces.find((space: Space) => space.name === saved.active) || personal);
|
||||
}
|
||||
if (Array.isArray(saved?.spaces)) local = saved.spaces.filter((space: Space) => !space.id);
|
||||
activeKey = saved?.active || '';
|
||||
} catch {}
|
||||
let shared: Space[] = [];
|
||||
try {
|
||||
const response = await fetch('/api/account/workspaces', {signal: request.signal});
|
||||
if (response.ok) shared = (await response.json()).spaces;
|
||||
} catch {}
|
||||
if (request.signal.aborted) return;
|
||||
const available = [...local, ...shared];
|
||||
setSpaces(available);
|
||||
setActive(available.find(space => spaceKey(space) === activeKey) || personal);
|
||||
setState('ready');
|
||||
}).catch(() => {
|
||||
if (!request.signal.aborted) setState('error');
|
||||
@@ -84,13 +96,13 @@ export function WorkspaceShell({editor, liveNodes}: WorkspaceShellProps) {
|
||||
}, [notice]);
|
||||
|
||||
function selectSpace(space: Space, next = spaces) {
|
||||
localStorage.setItem('studio.workspace:' + email, JSON.stringify({spaces: next, active: space.name}));
|
||||
localStorage.setItem('studio.workspace:' + email, JSON.stringify({spaces: next, active: spaceKey(space)}));
|
||||
setSpaces(next);
|
||||
setActive(space);
|
||||
switcher.current?.removeAttribute('open');
|
||||
}
|
||||
|
||||
const subsetKey = 'studio.subcanvases:' + email + ':' + active.name;
|
||||
const subsetKey = 'studio.subcanvases:' + email + ':' + spaceKey(active);
|
||||
useEffect(() => {
|
||||
if (!email) return;
|
||||
setSelectedCanvas(editor ? '' : 'history');
|
||||
@@ -151,25 +163,56 @@ export function WorkspaceShell({editor, liveNodes}: WorkspaceShellProps) {
|
||||
}
|
||||
|
||||
function openDialog() {
|
||||
setStep('purpose');
|
||||
setStep('choice');
|
||||
setCode('');
|
||||
setPurpose('');
|
||||
setName('');
|
||||
setError('');
|
||||
dialog.current?.showModal();
|
||||
}
|
||||
|
||||
function createSpace(event: React.FormEvent) {
|
||||
async function workspaceRequest(payload: object) {
|
||||
const response = await fetch('/api/account/workspaces', {method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify(payload)});
|
||||
const result = await response.json();
|
||||
if (!response.ok) throw new Error(result.error || '空间操作失败');
|
||||
return result;
|
||||
}
|
||||
|
||||
async function submitWorkspace(event: React.FormEvent) {
|
||||
event.preventDefault();
|
||||
if (busy) return;
|
||||
const clean = name.trim();
|
||||
if (!clean) return setError('请填写 Workspace 名称。');
|
||||
if ([personal, ...spaces].some(space => space.name === clean)) return setError('已有同名空间。');
|
||||
const space = {name: clean, purpose};
|
||||
if (step === 'name' && !clean) return setError('请填写 Workspace 名称。');
|
||||
if (step === 'join' && !code.trim()) return setError('请输入邀请码。');
|
||||
setBusy(true);
|
||||
setError('');
|
||||
try {
|
||||
selectSpace(space, [...spaces, space]);
|
||||
const {space} = await workspaceRequest(step === 'join' ? {action:'join', code:code.trim()} : {action:'create', name:clean, purpose});
|
||||
selectSpace(space, [...spaces.filter(item => spaceKey(item) !== spaceKey(space)), space]);
|
||||
dialog.current?.close();
|
||||
setNotice('已创建并切换到「' + clean + '」');
|
||||
} catch {
|
||||
setError('浏览器无法保存此空间,请检查存储权限后重试。');
|
||||
setNotice((step === 'join' ? '已加入' : '已创建') + '「' + space.name + '」');
|
||||
} catch (error) {
|
||||
setError(error instanceof Error ? error.message : '空间操作失败');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function inviteMember() {
|
||||
if (busy || !active.id) return;
|
||||
switcher.current?.removeAttribute('open');
|
||||
setCode('');
|
||||
setError('');
|
||||
setStep('invite');
|
||||
dialog.current?.showModal();
|
||||
setBusy(true);
|
||||
try {
|
||||
const result = await workspaceRequest({action:'invite', workspaceId:active.id});
|
||||
setCode(result.code);
|
||||
} catch (error) {
|
||||
setError(error instanceof Error ? error.message : '无法生成邀请码');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -208,11 +251,12 @@ export function WorkspaceShell({editor, liveNodes}: WorkspaceShellProps) {
|
||||
<details ref={switcher} className={s.switcher}>
|
||||
<summary><span className={s.avatar}>{Array.from(active.name)[0]}</span><strong>{active.name}</strong><ChevronDown size={14}/></summary>
|
||||
{state === 'ready' && <div className={s.menu}>
|
||||
<div className={s.menuIdentity}><span className={s.avatar}>{Array.from(active.name)[0]}</span><div><strong>{active.name}</strong><small>当前空间 · 保存在此浏览器</small></div></div>
|
||||
{email && <div className={s.menuSection}><small>{email}</small>
|
||||
{[personal, ...spaces].map(space => <button type="button" key={space.name} aria-pressed={space.name === active.name} onClick={() => {
|
||||
<div className={s.menuIdentity}><span className={s.avatar}>{Array.from(active.name)[0]}</span><div><strong>{active.name}</strong><small>{active.id ? '当前空间 · 共享空间' : '当前空间 · 保存在此浏览器'}</small></div></div>
|
||||
{email && <div className={s.menuSection}>
|
||||
{active.owner && <button type="button" onClick={() => void inviteMember()}><Plus size={16}/>邀请成员</button>}<small>{email}</small>
|
||||
{[personal, ...spaces].map(space => <button type="button" key={spaceKey(space)} aria-pressed={spaceKey(space) === spaceKey(active)} onClick={() => {
|
||||
try { selectSpace(space); } catch { setNotice('浏览器无法保存空间切换。'); }
|
||||
}}><span className={s.avatar}>{Array.from(space.name)[0]}</span><span>{space.name}</span>{space.name === active.name && <Check size={16}/>}</button>)}
|
||||
}}><span className={s.avatar}>{Array.from(space.name)[0]}</span><span>{space.name}</span>{spaceKey(space) === spaceKey(active) && <Check size={16}/>}</button>)}
|
||||
<button className={s.menuAdd} type="button" onClick={() => {switcher.current?.removeAttribute('open'); openDialog();}}><Plus size={16}/>添加 Workspace</button>
|
||||
</div>}
|
||||
<div className={s.menuSection}><a href="/account"><User size={16}/>账户管理</a>{email && <button type="button" onClick={() => void signOut()}><LogOut size={16}/>退出登录</button>}</div>
|
||||
@@ -284,21 +328,37 @@ export function WorkspaceShell({editor, liveNodes}: WorkspaceShellProps) {
|
||||
</dialog>
|
||||
<dialog className={s.dialog} ref={dialog} aria-labelledby="workspace-dialog-title">
|
||||
<div className={s.dialogTop}>
|
||||
{step === 'name' && <button type="button" aria-label="返回用途选择" onClick={() => setStep('purpose')}><ArrowLeft size={20}/></button>}
|
||||
<h2 id="workspace-dialog-title">{step === 'purpose' ? '这个空间用来做什么?' : '给你的 Workspace 命名'}</h2>
|
||||
{step !== 'choice' && step !== 'invite' && <button type="button" aria-label="返回上一步" onClick={() => {setError(''); setStep(step === 'name' ? 'purpose' : 'choice');}}><ArrowLeft size={20}/></button>}
|
||||
<h2 id="workspace-dialog-title">{{choice:'建立一个创作空间',join:'加入 Workspace',purpose:'这个空间用来做什么?',name:'给你的 Workspace 命名',invite:'邀请成员'}[step]}</h2>
|
||||
<button type="button" aria-label="关闭" onClick={() => dialog.current?.close()}><X size={20}/></button>
|
||||
</div>
|
||||
{step === 'purpose' ? <>
|
||||
<p>选择一个起点。空间设置仅保存在此浏览器。</p>
|
||||
{step === 'choice' ? <>
|
||||
<p>加入已有空间,或创建自己的 Workspace。</p>
|
||||
<div className={s.options}>
|
||||
<button type="button" onClick={() => setStep('join')}><User size={22}/><span><strong>加入已有空间</strong><small>使用空间所有者提供的邀请码</small></span></button>
|
||||
<button type="button" onClick={() => setStep('purpose')}><Plus size={22}/><span><strong>创建 Workspace</strong><small>为新项目建立一个空间</small></span></button>
|
||||
</div>
|
||||
</> : step === 'join' ? <form onSubmit={submitWorkspace}>
|
||||
<label htmlFor="workspace-invite">邀请码</label>
|
||||
<input id="workspace-invite" value={code} maxLength={80} onChange={event => setCode(event.target.value)}/>
|
||||
{error && <p className={s.error} role="alert">{error}</p>}
|
||||
<button className={s.primary} type="submit" disabled={busy}>加入 Workspace</button>
|
||||
</form> : step === 'invite' ? <>
|
||||
<p>邀请码有效期为 24 小时。把它交给要加入的成员。</p>
|
||||
{busy && <p role="status">正在生成邀请码…</p>}
|
||||
{error && <p className={s.error} role="alert">{error}</p>}
|
||||
{code && <input aria-label="邀请码" readOnly value={code} onFocus={event => event.target.select()}/>}
|
||||
</> : step === 'purpose' ? <>
|
||||
<p>选择一个起点。</p>
|
||||
<div className={s.options}>{purposes.map(({label, detail, icon: Icon}) => <button key={label} type="button" aria-pressed={purpose === label} onClick={() => setPurpose(label)}><Icon size={23}/><span><strong>{label}</strong><small>{detail}</small></span></button>)}</div>
|
||||
<button className={s.primary} type="button" disabled={!purpose} onClick={() => setStep('name')}>继续 <ArrowUpRight size={16}/></button>
|
||||
</> : <form onSubmit={createSpace}>
|
||||
</> : <form onSubmit={submitWorkspace}>
|
||||
<p>{purpose} · 一个空间,装下你的想法与作品。</p>
|
||||
<div className={s.iconPreview}><span className={s.avatar}>{Array.from(name.trim())[0] || '空'}</span>空间图标</div>
|
||||
<label htmlFor="workspace-name">Workspace 名称</label>
|
||||
<input id="workspace-name" autoFocus value={name} maxLength={40} onChange={e => {setName(e.target.value); setError('');}} aria-invalid={!!error} aria-describedby={error ? 'workspace-error' : undefined} placeholder="输入空间名称"/>
|
||||
{error && <p id="workspace-error" role="alert" className={s.error}>{error}</p>}
|
||||
<button className={s.primary} type="submit">创建 Workspace <ArrowUpRight size={16}/></button>
|
||||
<button className={s.primary} type="submit" disabled={busy}>创建 Workspace <ArrowUpRight size={16}/></button>
|
||||
</form>}
|
||||
</dialog>
|
||||
{notice && <div role="status" className={s.notice}>{notice}</div>}
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
import {randomUUID} from 'node:crypto';
|
||||
import type {NextApiRequest, NextApiResponse} from 'next';
|
||||
import {currentAccount} from '@/lib/account';
|
||||
import {newToken, tokenDigest, trustedOrigin} from '@/lib/account-crypto';
|
||||
import {db} from '@/lib/db';
|
||||
|
||||
const purposes = new Set(['工作与团队', '个人创作', '学习与研究']);
|
||||
|
||||
export default async function workspaces(req: NextApiRequest, res: NextApiResponse) {
|
||||
res.setHeader('Cache-Control', 'private, no-store');
|
||||
if (req.method !== 'GET' && req.method !== 'POST') {
|
||||
res.setHeader('Allow', 'GET, POST');
|
||||
return res.status(405).end();
|
||||
}
|
||||
const headers = new Headers(Object.entries(req.headers).filter(([, value]) => typeof value === 'string') as [string, string][]);
|
||||
try {
|
||||
const origin = process.env.ACCOUNT_PUBLIC_ORIGIN || 'http://' + req.headers.host;
|
||||
const request = new Request(new URL('/api/account/workspaces', origin), {headers});
|
||||
if (req.method === 'POST' && !trustedOrigin(request)) return res.status(403).json({error: '请求来源不受信任'});
|
||||
const user = await currentAccount(request);
|
||||
if (!user) return res.status(401).json({error: '请先登录邮箱账户'});
|
||||
const pool = db();
|
||||
if (req.method === 'GET') {
|
||||
const result = await pool.query(
|
||||
`SELECT w.id, w.name, w.purpose, w.owner_id = $1 AS owner
|
||||
FROM workspaces w JOIN workspace_members m ON m.workspace_id = w.id
|
||||
WHERE m.user_id = $1 ORDER BY w.created_at, w.id`, [user.id]);
|
||||
return res.json({spaces: result.rows});
|
||||
}
|
||||
const {action, name, purpose, code, workspaceId} = req.body ?? {};
|
||||
if (action === 'create') {
|
||||
const clean = typeof name === 'string' ? name.trim() : '';
|
||||
if (!clean || clean.length > 40 || !purposes.has(purpose)) return res.status(400).json({error: '请输入有效的空间名称并选择用途'});
|
||||
const id = randomUUID();
|
||||
await pool.query(
|
||||
`WITH created AS (INSERT INTO workspaces(id,owner_id,name,purpose) VALUES($1,$2,$3,$4) RETURNING id)
|
||||
INSERT INTO workspace_members(workspace_id,user_id) SELECT id,$2 FROM created`,
|
||||
[id, user.id, clean, purpose]);
|
||||
return res.status(201).json({space: {id, name: clean, purpose, owner: true}});
|
||||
}
|
||||
if (action === 'invite') {
|
||||
if (typeof workspaceId !== 'string' || !/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i.test(workspaceId)) return res.status(400).json({error: '无效的空间'});
|
||||
const token = newToken();
|
||||
const result = await pool.query(
|
||||
`INSERT INTO workspace_invites(digest,workspace_id,expires_at)
|
||||
SELECT $1,id,now()+interval '1 day' FROM workspaces WHERE id=$2 AND owner_id=$3 RETURNING expires_at`,
|
||||
[tokenDigest(token), workspaceId, user.id]);
|
||||
if (!result.rowCount) return res.status(404).json({error: '只有空间所有者可以邀请成员'});
|
||||
return res.json({code: token});
|
||||
}
|
||||
if (action === 'join') {
|
||||
if (typeof code !== 'string' || !/^[a-f0-9]{64}$/.test(code)) return res.status(400).json({error: '请输入有效的邀请码'});
|
||||
const result = await pool.query(
|
||||
`WITH target AS (
|
||||
SELECT w.id,w.name,w.purpose,w.owner_id=$2 AS owner
|
||||
FROM workspace_invites i JOIN workspaces w ON w.id=i.workspace_id
|
||||
WHERE i.digest=$1 AND i.expires_at>now()
|
||||
), joined AS (
|
||||
INSERT INTO workspace_members(workspace_id,user_id) SELECT id,$2 FROM target ON CONFLICT DO NOTHING
|
||||
) SELECT * FROM target`,
|
||||
[tokenDigest(code), user.id]);
|
||||
if (!result.rowCount) return res.status(404).json({error: '邀请不存在或已过期'});
|
||||
return res.json({space: result.rows[0]});
|
||||
}
|
||||
return res.status(400).json({error: '未知空间操作'});
|
||||
} catch {
|
||||
return res.status(503).json({error: '空间服务暂时不可用,请稍后再试'});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user