// SPDX-License-Identifier: AGPL-3.0-or-later import type { Workspace, WorkspaceRole } from "@docwell/api-client"; import { defineStore } from "pinia"; import { computed, ref } from "vue"; import { useApi } from "../api"; import { useAuthStore } from "./auth"; const rank: Record = { guest: 1, member: 2, admin: 3, owner: 4 }; /** Whether workspace role has is at least need (mirrors the server's ranking). */ export function atLeast(has: WorkspaceRole | "" | undefined, need: WorkspaceRole): boolean { return !!has && rank[has] >= rank[need]; } /** The workspace roles a user with role actor may hand out. */ export function grantableRoles(actor: WorkspaceRole): WorkspaceRole[] { return (["owner", "admin", "member", "guest"] as WorkspaceRole[]).filter((r) => rank[r] <= rank[actor]); } const currentKey = "docwell.workspace"; function remembered(): string { try { return localStorage.getItem(currentKey) ?? ""; } catch { return ""; } } export const useWorkspacesStore = defineStore("workspaces", () => { const api = useApi(); const auth = useAuthStore(); const items = ref([]); const loaded = ref(false); const currentId = ref(remembered()); /** The workspace shown in the sidebar: the remembered one, else the first. */ const current = computed(() => items.value.find((w) => w.id === currentId.value) ?? items.value[0] ?? null); async function load() { items.value = await api.workspaces.list(); loaded.value = true; } function select(id: string) { currentId.value = id; try { localStorage.setItem(currentKey, id); } catch { // per-browser convenience only } } /** Org admins (in their organization) and superadmins create workspaces. */ function canCreate(): boolean { const u = auth.user; return !!u && (u.role === "superadmin" || (u.role === "admin" && !!u.organization)); } return { items, loaded, current, load, select, canCreate }; });