| 10 | const WORKSPACE_COOKIE = "kb_workspace"; |
| 11 | |
| 12 | export function WorkspaceSwitcher() { |
| 13 | const t = useT(); |
| 14 | const [workspaces, setWorkspaces] = useState<string[]>([]); |
| 15 | const [current, setCurrent] = useState<string>(""); |
| 16 | |
| 17 | useEffect(() => { |
| 18 | let alive = true; |
| 19 | fetch("/api/workspaces") |
| 20 | .then((r) => r.json()) |
| 21 | .then((d) => { |
| 22 | if (!alive) return; |
| 23 | setWorkspaces(Array.isArray(d.workspaces) ? d.workspaces : []); |
| 24 | setCurrent(typeof d.current === "string" ? d.current : ""); |
| 25 | }) |
| 26 | .catch(() => {}); |
| 27 | return () => { |
| 28 | alive = false; |
| 29 | }; |
| 30 | }, []); |
| 31 | |
| 32 | // 只有一个(或零个)workspace 时无需切换器 |
| 33 | if (workspaces.length <= 1) return null; |
| 34 | |
| 35 | const onChange = (ws: string) => { |
| 36 | if (!ws || ws === current) return; |
| 37 | document.cookie = `${WORKSPACE_COOKIE}=${ws}; path=/; max-age=${60 * 60 * 24 * 365}; SameSite=Lax`; |
| 38 | // 页面级路由(/page/、/blocks/)的具体页在新 workspace 里多半不存在 → 回首页避免 404; |
| 39 | // 其余路由(/health、/graph 等 按当前 workspace 渲染)原地刷新即可。 |
| 40 | const p = window.location.pathname; |
| 41 | if (p.startsWith("/page/") || p.startsWith("/blocks/")) { |
| 42 | window.location.assign("/"); |
| 43 | } else { |
| 44 | window.location.reload(); |
| 45 | } |
| 46 | }; |
| 47 | |
| 48 | return ( |
| 49 | <select |
| 50 | value={current} |
| 51 | onChange={(e) => onChange(e.target.value)} |
| 52 | title={t("workspace.switch_title")} |
| 53 | aria-label={t("workspace.aria")} |
| 54 | className="h-8 rounded-md border border-input bg-background px-2 text-xs font-mono text-foreground hover:bg-accent hover:text-accent-foreground focus:outline-none focus:ring-1 focus:ring-ring" |
| 55 | > |
| 56 | {workspaces.map((ws) => ( |
| 57 | <option key={ws} value={ws}> |
| 58 | {ws} |
| 59 | </option> |
| 60 | ))} |
| 61 | </select> |
| 62 | ); |
| 63 | } |