Просмотр исходного кода

✨ 团队空间:头像弹窗切换身份,未支持的模块置灰

把 group 当作团队空间用:头像弹窗「切换到团队空间」里点团队即切过去,
点自己切回个人空间;user token 不变,身份只存 localStorage 的 teamspace 键。

- 顶栏显示「团队空间:xxx」标签,关掉即切回个人
- 主导航按 features/teamspace/scope.ts 置灰:可团队化的模块要等各自资源迁 v3
  (后端才认 owner 是 group)后逐个开放,个人专属模块永远置灰;直接输入地址也会被拦
- 启动时先按 localStorage 恢复,group 列表回来后校验成员资格,不在团队里就回个人空间;
  登出一并清掉。顺带修了 recallCurrStudio 永远取第一个的 bug
- 可团队化页面改用 useActiveStudio() 取 studioName,个人空间下行为不变
- 主导航「协作」下的团队页改名「团队空间」
- dashboard-test 新增 teamspace.spec

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
visuddhinanda 3 дней назад
Родитель
Сommit
7002064ade
32 измененных файлов с 500 добавлено и 89 удалено
  1. 117 0
      dashboard-test/src/tests/teamspace.spec.ts
  2. 44 7
      dashboard-v6/src/components/auth/SignInAvatar.tsx
  3. 61 10
      dashboard-v6/src/components/navigation/MainMenu.tsx
  4. 43 0
      dashboard-v6/src/features/teamspace/TeamspaceBadge.tsx
  5. 40 0
      dashboard-v6/src/features/teamspace/TeamspaceGuard.tsx
  6. 61 0
      dashboard-v6/src/features/teamspace/scope.ts
  7. 23 0
      dashboard-v6/src/hooks/useActiveStudio.ts
  8. 9 0
      dashboard-v6/src/hooks/useCurrentRouteId.ts
  9. 6 1
      dashboard-v6/src/layouts/workspace/index.tsx
  10. 2 0
      dashboard-v6/src/load.ts
  11. 2 0
      dashboard-v6/src/locales/en-US/buttons.ts
  12. 4 0
      dashboard-v6/src/locales/en-US/label.ts
  13. 2 0
      dashboard-v6/src/locales/zh-Hans/buttons.ts
  14. 4 0
      dashboard-v6/src/locales/zh-Hans/label.ts
  15. 2 0
      dashboard-v6/src/locales/zh-Hant/buttons.ts
  16. 4 0
      dashboard-v6/src/locales/zh-Hant/label.ts
  17. 3 4
      dashboard-v6/src/pages/workspace/anthology/edit.tsx
  18. 2 4
      dashboard-v6/src/pages/workspace/anthology/index.tsx
  19. 2 4
      dashboard-v6/src/pages/workspace/article/index.tsx
  20. 2 4
      dashboard-v6/src/pages/workspace/channel/list.tsx
  21. 2 4
      dashboard-v6/src/pages/workspace/channel/setting.tsx
  22. 2 4
      dashboard-v6/src/pages/workspace/course/edit.tsx
  23. 2 4
      dashboard-v6/src/pages/workspace/course/index.tsx
  24. 2 4
      dashboard-v6/src/pages/workspace/driver/list.tsx
  25. 2 4
      dashboard-v6/src/pages/workspace/tag/edit.tsx
  26. 2 4
      dashboard-v6/src/pages/workspace/tag/index.tsx
  27. 3 4
      dashboard-v6/src/pages/workspace/task/project-edit.tsx
  28. 3 4
      dashboard-v6/src/pages/workspace/task/project.tsx
  29. 3 4
      dashboard-v6/src/pages/workspace/task/projects.tsx
  30. 3 4
      dashboard-v6/src/pages/workspace/task/workflow.tsx
  31. 2 4
      dashboard-v6/src/pages/workspace/term/list.tsx
  32. 41 11
      dashboard-v6/src/reducers/current-user.ts

+ 117 - 0
dashboard-test/src/tests/teamspace.spec.ts

@@ -0,0 +1,117 @@
+import { test, expect, type Page } from '@playwright/test';
+import { call } from '../lib/api.js';
+import { collect } from '../lib/collect.js';
+import { USER, shotDir } from '../lib/env.js';
+
+/**
+ * 团队空间(P0):头像弹窗里切到团队空间、顶栏标签、菜单置灰、直接访问被拦、
+ * 刷新后保持、切回个人空间、localStorage 里的过期团队被清掉。
+ *
+ * 团队空间 = 以某个 group 为 owner 浏览资源。P0 阶段所有可团队化的模块都还没迁 v3,
+ * 所以切过去之后它们一律置灰;随各资源迁完再逐个改这里的断言。
+ */
+const SHOT = shotDir('teamspace');
+const TEAM = 'e2e 团队空间';
+
+const shot = (page: Page, name: string) =>
+  page.screenshot({ path: `${SHOT}/${name}.png`, fullPage: true });
+const badge = (page: Page) => page.getByTestId('teamspace-badge');
+const menuItem = (page: Page, label: string) =>
+  page.locator('.ant-layout-sider .ant-menu-item').filter({ hasText: label });
+const stored = (page: Page) => page.evaluate(() => localStorage.getItem('teamspace'));
+
+let teamId = '';
+
+test.beforeAll(async ({ request }) => {
+  // 测试账号名下建一个团队;已存在时后端回 ok:false,忽略即可(本地测试数据保留不删)
+  await call(request, 'POST', '/v2/group', { name: TEAM, studio_name: USER });
+  const { body } = await call(request, 'GET', '/v2/group-member?view=user');
+  const rows = (body?.data?.rows ?? []) as { group?: { id: string; name: string } }[];
+  teamId = rows.find((row) => row.group?.name === TEAM)?.group?.id ?? '';
+  expect(teamId, '测试账号应当是该团队的成员').not.toBe('');
+});
+
+test.describe('团队空间切换', () => {
+  test('切过去、菜单置灰、直接访问被拦、刷新保持、切回个人', async ({ page }) => {
+    const log = collect(page);
+
+    await test.step('1. 头像弹窗里选团队', async () => {
+      await page.goto('workspace', { waitUntil: 'networkidle' });
+      await page.evaluate(() => localStorage.removeItem('teamspace'));
+      await page.reload({ waitUntil: 'networkidle' });
+      await expect(badge(page)).toHaveCount(0);
+
+      await page.locator('.ant-layout-sider .ant-avatar').first().hover();
+      const popover = page.locator('.ant-popover:visible');
+      await popover.getByText('切换到团队空间').click();
+      await popover.getByText(TEAM, { exact: true }).click();
+
+      await expect(badge(page)).toContainText(TEAM);
+      expect(JSON.parse((await stored(page)) ?? '{}').id).toBe(teamId);
+      await shot(page, '01-switched');
+      log.dump('1. 切到团队空间');
+    });
+
+    await test.step('2. 主导航:可团队化与个人专属的模块置灰,全局模块照常', async () => {
+      await expect(menuItem(page, '版本风格')).toHaveClass(/ant-menu-item-disabled/);
+      await expect(menuItem(page, '术语')).toHaveClass(/ant-menu-item-disabled/);
+      await expect(menuItem(page, '最近')).toHaveClass(/ant-menu-item-disabled/);
+      await expect(menuItem(page, '主页')).not.toHaveClass(/ant-menu-item-disabled/);
+      await shot(page, '02-menu');
+    });
+
+    await test.step('3. 直接输入地址也进不去', async () => {
+      await page.goto('workspace/channel', { waitUntil: 'networkidle' });
+      await expect(page.getByTestId('teamspace-blocked')).toContainText('该模块暂不支持团队空间');
+      await expect(page.locator('.ant-table')).toHaveCount(0);
+      await shot(page, '03-blocked');
+    });
+
+    await test.step('4. 刷新后仍在团队空间', async () => {
+      await page.reload({ waitUntil: 'networkidle' });
+      await expect(badge(page)).toContainText(TEAM);
+      await expect(page.getByTestId('teamspace-blocked')).toBeVisible();
+    });
+
+    await test.step('5. 拦截页上切回个人空间', async () => {
+      await page.getByTestId('teamspace-blocked').getByRole('button', { name: '切回个人空间' }).click();
+      await expect(badge(page)).toHaveCount(0);
+      await expect(page.locator('.ant-table')).toBeVisible();
+      expect(await stored(page)).toBeNull();
+      await shot(page, '05-personal');
+      log.dump('5. 切回个人空间');
+    });
+
+    await test.step('6. 顶栏标签关掉也能切回个人空间', async () => {
+      await page.evaluate(
+        ([id, name]) =>
+          localStorage.setItem('teamspace', JSON.stringify({ id, nickName: name, realName: id })),
+        [teamId, TEAM],
+      );
+      await page.goto('workspace', { waitUntil: 'networkidle' });
+      await expect(badge(page)).toBeVisible();
+      await badge(page).locator('.ant-tag-close-icon').click();
+      await expect(badge(page)).toHaveCount(0);
+      expect(await stored(page)).toBeNull();
+    });
+  });
+
+  test('localStorage 里已不是成员的团队会被清掉', async ({ page }) => {
+    await page.goto('workspace', { waitUntil: 'networkidle' });
+    await page.evaluate(() =>
+      localStorage.setItem(
+        'teamspace',
+        JSON.stringify({
+          id: '00000000-0000-4000-8000-000000000000',
+          nickName: 'ghost',
+          realName: '00000000-0000-4000-8000-000000000000',
+        }),
+      ),
+    );
+    await page.reload({ waitUntil: 'networkidle' });
+
+    // group 列表回来后校验成员资格,不是成员就回到个人空间
+    await expect(badge(page)).toHaveCount(0);
+    await expect.poll(() => stored(page)).toBeNull();
+  });
+});

+ 44 - 7
dashboard-v6/src/components/auth/SignInAvatar.tsx

@@ -10,12 +10,17 @@ import {
   HomeOutlined,
   LogoutOutlined,
   SettingOutlined,
+  CheckOutlined,
+  SwapOutlined,
 } from "@ant-design/icons";
 
-import { useAppSelector } from "../../hooks";
+import { useAppDispatch, useAppSelector } from "../../hooks";
 import {
   currentUser as _currentUser,
+  currentStudio,
+  setCurrStudio,
   studioList,
+  studioSignOut,
   TO_SIGN_IN,
 } from "../../reducers/current-user";
 import type { TooltipPlacement } from "antd/lib/tooltip";
@@ -28,6 +33,10 @@ import LoginButton from "./LoginButton";
 
 const { Title, Paragraph, Text } = Typography;
 
+/** 账户列表里个人空间与各团队空间的菜单 key */
+const PERSONAL_KEY = "space:personal";
+const TEAMSPACE_PREFIX = "space:team:";
+
 interface IWidget {
   placement?: TooltipPlacement;
   style?: React.CSSProperties;
@@ -41,10 +50,12 @@ const SignInAvatar = ({
 }: IWidget) => {
   const intl = useIntl();
   const navigate = useNavigate();
+  const dispatch = useAppDispatch();
   const [settingOpen, setSettingOpen] = useState(false);
 
   const user = useAppSelector(_currentUser);
   const studios = useAppSelector(studioList);
+  const teamspace = useAppSelector(currentStudio);
 
   console.debug("user", user);
 
@@ -68,16 +79,27 @@ const SignInAvatar = ({
       </Paragraph>
     );
 
+    const current = <CheckOutlined style={{ marginLeft: 8 }} />;
     let userList = [
       {
-        key: user.realName,
-        label: <User {...user} />,
+        key: PERSONAL_KEY,
+        label: (
+          <>
+            <User {...user} />
+            {!teamspace && current}
+          </>
+        ),
       },
     ];
     const studioList = studios?.map((item) => {
       return {
-        key: item.realName ?? "",
-        label: <Studio data={item} />,
+        key: TEAMSPACE_PREFIX + item.id,
+        label: (
+          <>
+            <Studio data={item} />
+            {teamspace?.id === item.id && current}
+          </>
+        ),
       };
     });
     if (studioList) {
@@ -98,8 +120,10 @@ const SignInAvatar = ({
                   items={[
                     {
                       key: "account",
-                      label: "选择账户",
-                      icon: <UserOutlined />,
+                      label: intl.formatMessage({
+                        id: "buttons.teamspace.switch",
+                      }),
+                      icon: <SwapOutlined />,
                       children: userList,
                     },
                     {
@@ -131,6 +155,18 @@ const SignInAvatar = ({
                     },
                   ].filter((value) => !value.disabled)}
                   onClick={(info) => {
+                    if (info.key === PERSONAL_KEY) {
+                      dispatch(studioSignOut());
+                      return;
+                    }
+                    if (info.key.startsWith(TEAMSPACE_PREFIX)) {
+                      const id = info.key.slice(TEAMSPACE_PREFIX.length);
+                      const studio = studios?.find((item) => item.id === id);
+                      if (studio) {
+                        dispatch(setCurrStudio(studio));
+                      }
+                      return;
+                    }
                     switch (info.key) {
                       case "setting":
                         setSettingOpen(true);
@@ -147,6 +183,7 @@ const SignInAvatar = ({
                       case "logout":
                         sessionStorage.removeItem("token");
                         localStorage.removeItem("token");
+                        dispatch(studioSignOut());
                         navigate(TO_SIGN_IN);
                         break;
                     }

+ 61 - 10
dashboard-v6/src/components/navigation/MainMenu.tsx

@@ -1,4 +1,4 @@
-import { Menu, type MenuProps } from "antd";
+import { Menu, Tooltip, type MenuProps } from "antd";
 import {
   SearchOutlined,
   HomeOutlined,
@@ -10,7 +10,7 @@ import {
   ToolOutlined,
   TeamOutlined,
 } from "@ant-design/icons";
-import { useNavigate, useMatches, type UIMatch } from "react-router";
+import { useNavigate, type UIMatch } from "react-router";
 import {
   ChannelIcon,
   CourseOutLinedIcon,
@@ -24,6 +24,12 @@ import RecentModal from "../recent/RecentModal.tsx";
 import SettingModal from "../setting/SettingModal.tsx";
 import { useIntl } from "react-intl";
 import { fullUrl } from "../../utils";
+import { useActiveStudio } from "../../hooks/useActiveStudio";
+import { useCurrentRouteId } from "../../hooks/useCurrentRouteId";
+import {
+  TEAMSPACE_HINT,
+  teamspaceAvailability,
+} from "../../features/teamspace/scope";
 
 /* ================= 类型 ================= */
 
@@ -38,18 +44,17 @@ interface MenuItem {
 
   /** ⭐ 用于高亮匹配 */
   activeId?: string | string[];
+
+  /** 判断团队空间下是否可用的路由 id;不写则取 activeId(打开弹窗、没有路由的菜单要写) */
+  scopeId?: string;
+
+  disabled?: boolean;
 }
 
 export interface RouteHandle {
   id?: string;
   crumb?: string | ((match: UIMatch) => string);
 }
-/* ================= 当前路由ID ================= */
-
-function useCurrentRouteId(): string | undefined {
-  const matches = useMatches() as UIMatch<number, RouteHandle>[];
-  return [...matches].reverse().find((match) => match.handle?.id)?.handle?.id;
-}
 
 /* ================= 匹配算法 ================= */
 
@@ -114,6 +119,44 @@ function findOpenKeys(
   return [];
 }
 
+/* ================= 团队空间置灰 ================= */
+
+/**
+ * 团队空间下把不可用的菜单置灰并给出原因;有子菜单的,子项全灰才灰。
+ */
+function applyTeamspace(
+  items: MenuItem[],
+  hint: (id: string) => string
+): MenuItem[] {
+  return items.map((item) => {
+    if (item.children) {
+      const children = applyTeamspace(item.children, hint);
+      return {
+        ...item,
+        children,
+        disabled: children.every((child) => child.disabled),
+      };
+    }
+    const scopeId =
+      item.scopeId ??
+      (typeof item.activeId === "string" ? item.activeId : undefined);
+    const availability = teamspaceAvailability(scopeId);
+    if (item.type === "divider" || availability === "available") {
+      return item;
+    }
+    return {
+      ...item,
+      disabled: true,
+      extra: undefined,
+      label: (
+        <Tooltip title={hint(TEAMSPACE_HINT[availability])} placement="right">
+          <span>{item.label}</span>
+        </Tooltip>
+      ),
+    };
+  });
+}
+
 /* ================= 组件 ================= */
 interface Props {
   onSearch?: () => void;
@@ -123,13 +166,14 @@ const Widget = ({ onSearch }: Props) => {
 
   const navigate = useNavigate();
   const routeId = useCurrentRouteId();
+  const { isTeamspace } = useActiveStudio();
 
   const [recentOpen, setRecentOpen] = useState(false);
   const [openSetting, setOpenSetting] = useState(false);
 
   /* ================= 菜单配置 ================= */
 
-  const items: MenuItem[] = [
+  const allItems: MenuItem[] = [
     {
       key: "search",
       icon: <SearchOutlined />,
@@ -173,6 +217,7 @@ const Widget = ({ onSearch }: Props) => {
         id: "columns.studio.setting.title",
       }),
       activeId: "workspace.setting",
+      scopeId: "workspace.settings",
     },
     { type: "divider", key: "d1" },
 
@@ -182,6 +227,7 @@ const Widget = ({ onSearch }: Props) => {
       label: intl.formatMessage({
         id: "columns.studio.recent.title",
       }),
+      scopeId: "workspace.recent",
     },
 
     {
@@ -232,6 +278,7 @@ const Widget = ({ onSearch }: Props) => {
       label: intl.formatMessage({
         id: "columns.library.course.title",
       }),
+      scopeId: "workspace.course",
     },
     {
       key: "/workspace/task",
@@ -324,7 +371,7 @@ const Widget = ({ onSearch }: Props) => {
         {
           key: "/workspace/team",
           label: intl.formatMessage({
-            id: "columns.studio.group.title",
+            id: "labels.teamspace",
           }),
           activeId: "workspace.team",
         },
@@ -345,6 +392,10 @@ const Widget = ({ onSearch }: Props) => {
       ],
     },
   ];
+  const items = isTeamspace
+    ? applyTeamspace(allItems, (id) => intl.formatMessage({ id }))
+    : allItems;
+
   /** 当前选中 */
   const selectedKey = findSelectedKey(items, routeId);
 

+ 43 - 0
dashboard-v6/src/features/teamspace/TeamspaceBadge.tsx

@@ -0,0 +1,43 @@
+import { Tag, Tooltip } from "antd";
+import { TeamOutlined } from "@ant-design/icons";
+import { useIntl } from "react-intl";
+
+import { useAppDispatch } from "../../hooks";
+import { studioSignOut } from "../../reducers/current-user";
+import { useActiveStudio } from "../../hooks/useActiveStudio";
+
+/**
+ * 顶栏上的「当前团队空间」标签;关闭即切回个人空间。个人空间下不渲染。
+ */
+const TeamspaceBadge = () => {
+  const intl = useIntl();
+  const dispatch = useAppDispatch();
+  const { teamspace } = useActiveStudio();
+
+  if (!teamspace) {
+    return null;
+  }
+
+  return (
+    <Tooltip title={intl.formatMessage({ id: "buttons.teamspace.leave" })}>
+      <Tag
+        data-testid="teamspace-badge"
+        color="processing"
+        icon={<TeamOutlined />}
+        closable
+        onClose={(e) => {
+          e.preventDefault();
+          dispatch(studioSignOut());
+        }}
+        style={{ marginInlineEnd: 0 }}
+      >
+        {intl.formatMessage(
+          { id: "labels.teamspace.current" },
+          { name: teamspace.nickName }
+        )}
+      </Tag>
+    </Tooltip>
+  );
+};
+
+export default TeamspaceBadge;

+ 40 - 0
dashboard-v6/src/features/teamspace/TeamspaceGuard.tsx

@@ -0,0 +1,40 @@
+import { Button, Result } from "antd";
+import { useIntl } from "react-intl";
+
+import { useAppDispatch } from "../../hooks";
+import { studioSignOut } from "../../reducers/current-user";
+import { useActiveStudio } from "../../hooks/useActiveStudio";
+import { useCurrentRouteId } from "../../hooks/useCurrentRouteId";
+import { TEAMSPACE_HINT, teamspaceAvailability } from "./scope";
+
+/**
+ * 团队空间下拦住还不能用的页面(菜单置灰之外,直接输入地址也进不去)。
+ * 个人空间下原样渲染。
+ */
+const TeamspaceGuard = ({ children }: { children: React.ReactNode }) => {
+  const intl = useIntl();
+  const dispatch = useAppDispatch();
+  const routeId = useCurrentRouteId();
+  const { isTeamspace } = useActiveStudio();
+
+  const availability = teamspaceAvailability(routeId);
+  if (!isTeamspace || availability === "available") {
+    return <>{children}</>;
+  }
+
+  return (
+    <div data-testid="teamspace-blocked">
+      <Result
+        status="info"
+        title={intl.formatMessage({ id: TEAMSPACE_HINT[availability] })}
+        extra={
+          <Button type="primary" onClick={() => dispatch(studioSignOut())}>
+            {intl.formatMessage({ id: "buttons.teamspace.leave" })}
+          </Button>
+        }
+      />
+    </div>
+  );
+};
+
+export default TeamspaceGuard;

+ 61 - 0
dashboard-v6/src/features/teamspace/scope.ts

@@ -0,0 +1,61 @@
+/**
+ * 团队空间下各模块的可用性。
+ *
+ * 团队空间 = 以某个 group 为 owner 浏览资源。后端只有迁到 v3 的资源才认
+ * 「owner 是 group、成员按角色拥有权限」,所以模块要等它的资源迁完才能开放。
+ * 每迁完一个,就把它的路由 id 从 NOT_YET_SUPPORTED 删掉;全部删完后这一组连同
+ * 菜单上的置灰逻辑一起去掉,只留 PERSONAL_ONLY。
+ *
+ * 值是路由的 handle.id,前缀匹配(`workspace.task` 同时覆盖 `workspace.task.list`)。
+ */
+
+/** 只属于个人、团队空间下永远不可用 */
+const PERSONAL_ONLY = [
+  "workspace.settings",
+  "workspace.recent",
+  "workspace.dict",
+  "workspace.invite",
+  "workspace.transfer",
+];
+
+/** 可以团队化、但资源还没迁到 v3,暂不可用 */
+const NOT_YET_SUPPORTED = [
+  "workspace.article",
+  "workspace.anthology",
+  "workspace.channel",
+  "workspace.term",
+  "workspace.course",
+  "workspace.task",
+  "workspace.tag",
+  "workspace.driver",
+];
+
+export type TeamspaceAvailability = "available" | "personal" | "unsupported";
+
+const matches = (routeId: string, list: string[]) =>
+  list.some((id) => routeId === id || routeId.startsWith(id + "."));
+
+/** 某个路由在团队空间下能不能用;没有 id 的路由一律可用 */
+export function teamspaceAvailability(
+  routeId: string | undefined
+): TeamspaceAvailability {
+  if (!routeId) {
+    return "available";
+  }
+  if (matches(routeId, PERSONAL_ONLY)) {
+    return "personal";
+  }
+  if (matches(routeId, NOT_YET_SUPPORTED)) {
+    return "unsupported";
+  }
+  return "available";
+}
+
+/** 不可用时给用户看的提示文案的 i18n id */
+export const TEAMSPACE_HINT: Record<
+  Exclude<TeamspaceAvailability, "available">,
+  string
+> = {
+  personal: "labels.teamspace.personal-only",
+  unsupported: "labels.teamspace.unsupported",
+};

+ 23 - 0
dashboard-v6/src/hooks/useActiveStudio.ts

@@ -0,0 +1,23 @@
+import { useAppSelector } from "../hooks";
+import {
+  currentStudio,
+  currentUser,
+} from "../reducers/current-user";
+
+/**
+ * 当前「以谁的名义」浏览资源:团队空间里是 group,否则是登录用户本人。
+ *
+ * `studioName` 直接传给 v2 接口的 `studio` / `name` 参数——后端
+ * `StudioApi::getIdByName()` 对用户认 username、对 group 认 uid,
+ * 所以 group 这里取的是 `realName`(= group uid)。
+ */
+export function useActiveStudio() {
+  const user = useAppSelector(currentUser);
+  const teamspace = useAppSelector(currentStudio);
+
+  return {
+    studioName: teamspace ? teamspace.realName : user?.realName,
+    teamspace,
+    isTeamspace: !!teamspace,
+  };
+}

+ 9 - 0
dashboard-v6/src/hooks/useCurrentRouteId.ts

@@ -0,0 +1,9 @@
+import { useMatches, type UIMatch } from "react-router";
+
+import type { RouteHandle } from "../components/navigation/MainMenu";
+
+/** 当前页面最深一层带 handle.id 的路由 id,如 `workspace.channel` */
+export function useCurrentRouteId(): string | undefined {
+  const matches = useMatches() as UIMatch<number, RouteHandle>[];
+  return [...matches].reverse().find((match) => match.handle?.id)?.handle?.id;
+}

+ 6 - 1
dashboard-v6/src/layouts/workspace/index.tsx

@@ -11,6 +11,8 @@ import { useAuth } from "../../hooks/useAuth";
 import UiLangSelect from "../../components/general/UiLangSelect";
 import SentCart from "../../components/sentence/SentCart";
 import NotificationIcon from "../../components/notification/NotificationIcon";
+import TeamspaceBadge from "../../features/teamspace/TeamspaceBadge";
+import TeamspaceGuard from "../../features/teamspace/TeamspaceGuard";
 
 const { Sider, Content } = Layout;
 const Widget = () => {
@@ -57,6 +59,7 @@ const Widget = () => {
         >
           <HeaderBreadcrumb />
           <Space size="middle">
+            <TeamspaceBadge />
             <SentCart />
             <NotificationIcon />
             <NetworkStatus />
@@ -66,7 +69,9 @@ const Widget = () => {
         </div>
 
         <Content style={{ padding: 12 }}>
-          <Outlet />
+          <TeamspaceGuard>
+            <Outlet />
+          </TeamspaceGuard>
         </Content>
       </Layout>
     </Layout>

+ 2 - 0
dashboard-v6/src/load.ts

@@ -6,6 +6,7 @@ import {
   guest,
   signIn,
   studioSignIn,
+  recallCurrStudio,
 } from "./reducers/current-user";
 import { remove as removeToken } from "./reducers/session";
 import { fetchMe } from "./api/session";
@@ -101,6 +102,7 @@ const init = () => {
             return item.group;
           });
           store.dispatch(studioSignIn(it));
+          store.dispatch(recallCurrStudio());
         }
       }
     );

+ 2 - 0
dashboard-v6/src/locales/en-US/buttons.ts

@@ -117,6 +117,8 @@ const items = {
   "buttons.get_template": "Get Template",
   "buttons.duplicate": "Duplicate",
   "buttons.word_count": "Word Count",
+  "buttons.teamspace.switch": "Switch to teamspace",
+  "buttons.teamspace.leave": "Back to personal space",
 };
 
 export default items;

+ 4 - 0
dashboard-v6/src/locales/en-US/label.ts

@@ -147,6 +147,10 @@ const items = {
   "labels.paragraph-count": "Paras",
   "labels.pagination.total": "Total: {total}",
   "labels.channel.select": "Select version",
+  "labels.teamspace": "Teamspaces",
+  "labels.teamspace.current": "Teamspace: {name}",
+  "labels.teamspace.personal-only": "Personal only — not available in a teamspace",
+  "labels.teamspace.unsupported": "This module does not support teamspaces yet",
 };
 
 export default items;

+ 2 - 0
dashboard-v6/src/locales/zh-Hans/buttons.ts

@@ -118,6 +118,8 @@ const items = {
   "buttons.get_template": "获取引用模版",
   "buttons.duplicate": "创建副本",
   "buttons.word_count": "字数统计",
+  "buttons.teamspace.switch": "切换到团队空间",
+  "buttons.teamspace.leave": "切回个人空间",
 };
 
 export default items;

+ 4 - 0
dashboard-v6/src/locales/zh-Hans/label.ts

@@ -154,6 +154,10 @@ const items = {
   "labels.paragraph-count": "段落",
   "labels.pagination.total": "结果: {total}",
   "labels.channel.select": "版本选择",
+  "labels.teamspace": "团队空间",
+  "labels.teamspace.current": "团队空间:{name}",
+  "labels.teamspace.personal-only": "个人专属功能,团队空间下不可用",
+  "labels.teamspace.unsupported": "该模块暂不支持团队空间",
 };
 
 export default items;

+ 2 - 0
dashboard-v6/src/locales/zh-Hant/buttons.ts

@@ -118,6 +118,8 @@ const items = {
   "buttons.get_template": "獲取引用模版",
   "buttons.duplicate": "建立副本",
   "buttons.word_count": "字數統計",
+  "buttons.teamspace.switch": "切換到團隊空間",
+  "buttons.teamspace.leave": "切回個人空間",
 };
 
 export default items;

+ 4 - 0
dashboard-v6/src/locales/zh-Hant/label.ts

@@ -154,6 +154,10 @@ const items = {
   "labels.paragraph-count": "段落",
   "labels.pagination.total": "結果: {total}",
   "labels.channel.select": "版本選擇",
+  "labels.teamspace": "團隊空間",
+  "labels.teamspace.current": "團隊空間:{name}",
+  "labels.teamspace.personal-only": "個人專屬功能,團隊空間下不可用",
+  "labels.teamspace.unsupported": "該模組暫不支援團隊空間",
 };
 
 export default items;

+ 3 - 4
dashboard-v6/src/pages/workspace/anthology/edit.tsx

@@ -2,12 +2,11 @@ import { useMatches, useParams } from "react-router";
 import { useIntl } from "react-intl";
 
 import AnthologyTocEdit from "../../../components/anthology/AnthologyTocEdit";
-import { useAppSelector } from "../../../hooks";
-import { currentUser } from "../../../reducers/current-user";
+import { useActiveStudio } from "../../../hooks/useActiveStudio";
 
 const Widget = () => {
   const { anthologyId } = useParams(); //url 参数
-  const user = useAppSelector(currentUser);
+  const { studioName } = useActiveStudio();
   const intl = useIntl();
   const matches = useMatches() as {
     data?: { title?: string; name?: string; word?: string };
@@ -19,7 +18,7 @@ const Widget = () => {
   return (
     <>
       <title>{name ? `${prefix}-${name}` : prefix}</title>
-      <AnthologyTocEdit id={anthologyId} editorStudioName={user?.realName} />
+      <AnthologyTocEdit id={anthologyId} editorStudioName={studioName} />
     </>
   );
 };

+ 2 - 4
dashboard-v6/src/pages/workspace/anthology/index.tsx

@@ -1,12 +1,10 @@
 import { useIntl } from "react-intl";
-import { useAppSelector } from "../../../hooks";
-import { currentUser } from "../../../reducers/current-user";
 import AnthologyList from "../../../components/anthology/AnthologyList";
 import { useNavigate, useSearchParams } from "react-router";
+import { useActiveStudio } from "../../../hooks/useActiveStudio";
 
 const Widget = () => {
-  const user = useAppSelector(currentUser);
-  const studioName = user?.realName;
+  const { studioName } = useActiveStudio();
   const navigate = useNavigate();
   const intl = useIntl();
 

+ 2 - 4
dashboard-v6/src/pages/workspace/article/index.tsx

@@ -1,12 +1,10 @@
 import { useIntl } from "react-intl";
-import { useAppSelector } from "../../../hooks";
-import { currentUser } from "../../../reducers/current-user";
 import { useSearchParams } from "react-router";
 import ArticleList from "../../../components/article/ArticleList";
+import { useActiveStudio } from "../../../hooks/useActiveStudio";
 
 const Widget = () => {
-  const user = useAppSelector(currentUser);
-  const studioName = user?.realName;
+  const { studioName } = useActiveStudio();
   const intl = useIntl();
 
   const [searchParams, setSearchParams] = useSearchParams();

+ 2 - 4
dashboard-v6/src/pages/workspace/channel/list.tsx

@@ -3,12 +3,10 @@ import { useIntl } from "react-intl";
 
 import ChannelTable from "../../../components/channel/ChannelTable";
 import type { IChannel } from "../../../api/channel";
-import { useAppSelector } from "../../../hooks";
-import { currentUser } from "../../../reducers/current-user";
+import { useActiveStudio } from "../../../hooks/useActiveStudio";
 
 const Widget = () => {
-  const user = useAppSelector(currentUser);
-  const studioName = user?.realName;
+  const { studioName } = useActiveStudio();
   const navigate = useNavigate();
   const intl = useIntl();
   console.debug("channel list", studioName);

+ 2 - 4
dashboard-v6/src/pages/workspace/channel/setting.tsx

@@ -11,8 +11,7 @@ import WebhookList from "../../../components/webhook/WebhookList";
 import WebhookEdit from "../../../components/webhook/WebhookEdit";
 import { EResType } from "../../../components/share/utils";
 import type { IApiResponseChannelData } from "../../../api/channel";
-import { useAppSelector } from "../../../hooks";
-import { currentUser } from "../../../reducers/current-user";
+import { useActiveStudio } from "../../../hooks/useActiveStudio";
 
 const Widget = () => {
   const intl = useIntl();
@@ -24,8 +23,7 @@ const Widget = () => {
     id: "columns.studio.channel.title",
   });
   const navigate = useNavigate();
-  const user = useAppSelector(currentUser);
-  const studioName = user?.realName;
+  const { studioName } = useActiveStudio();
 
   return (
     <>

+ 2 - 4
dashboard-v6/src/pages/workspace/course/edit.tsx

@@ -8,14 +8,12 @@ import CourseMemberList, {
   type ICourseMember,
 } from "../../../components/course/CourseMemberList";
 import CourseMemberTimeLine from "../../../components/course/CourseMemberTimeLine";
-import { useAppSelector } from "../../../hooks";
-import { currentUser } from "../../../reducers/current-user";
+import { useActiveStudio } from "../../../hooks/useActiveStudio";
 
 const Widget = () => {
   const intl = useIntl();
   const { courseId } = useParams(); //url 参数
-  const user = useAppSelector(currentUser);
-  const studioName = user?.realName;
+  const { studioName } = useActiveStudio();
   const [title, setTitle] = useState("loading");
   const [selected, setSelected] = useState<string>();
   const courseTitle = intl.formatMessage({

+ 2 - 4
dashboard-v6/src/pages/workspace/course/index.tsx

@@ -1,12 +1,10 @@
 import { useIntl } from "react-intl";
-import { useAppSelector } from "../../../hooks";
-import { currentUser } from "../../../reducers/current-user";
 
 import List from "../../../components/course/List";
+import { useActiveStudio } from "../../../hooks/useActiveStudio";
 
 const Widget = () => {
-  const user = useAppSelector(currentUser);
-  const studioName = user?.realName;
+  const { studioName } = useActiveStudio();
   const intl = useIntl();
   return (
     <>

+ 2 - 4
dashboard-v6/src/pages/workspace/driver/list.tsx

@@ -1,11 +1,9 @@
 import { useIntl } from "react-intl";
 import AttachmentList from "../../../components/attachment/AttachmentList";
-import { useAppSelector } from "../../../hooks";
-import { currentUser } from "../../../reducers/current-user";
+import { useActiveStudio } from "../../../hooks/useActiveStudio";
 
 const Widget = () => {
-  const user = useAppSelector(currentUser);
-  const studioName = user?.realName;
+  const { studioName } = useActiveStudio();
   const intl = useIntl();
 
   return (

+ 2 - 4
dashboard-v6/src/pages/workspace/tag/edit.tsx

@@ -2,13 +2,11 @@ import { useMatches, useParams } from "react-router";
 import { useIntl } from "react-intl";
 
 import TagCreate from "../../../components/tag/TagCreate";
-import { useAppSelector } from "../../../hooks";
-import { currentUser } from "../../../reducers/current-user";
+import { useActiveStudio } from "../../../hooks/useActiveStudio";
 
 const Widget = () => {
   const { tagId } = useParams(); //url 参数
-  const user = useAppSelector(currentUser);
-  const studioName = user?.realName;
+  const { studioName } = useActiveStudio();
   const intl = useIntl();
   const matches = useMatches() as {
     data?: { title?: string; name?: string; word?: string };

+ 2 - 4
dashboard-v6/src/pages/workspace/tag/index.tsx

@@ -2,13 +2,11 @@ import { useNavigate } from "react-router";
 import { useIntl } from "react-intl";
 
 import TagList from "../../../components/tag/TagList";
+import { useActiveStudio } from "../../../hooks/useActiveStudio";
 
-import { useAppSelector } from "../../../hooks";
-import { currentUser } from "../../../reducers/current-user";
 
 const Widget = () => {
-  const user = useAppSelector(currentUser);
-  const studioName = user?.realName;
+  const { studioName } = useActiveStudio();
   const navigate = useNavigate();
   const intl = useIntl();
   return (

+ 3 - 4
dashboard-v6/src/pages/workspace/task/project-edit.tsx

@@ -2,11 +2,10 @@ import { useMatches, useParams } from "react-router";
 import { useIntl } from "react-intl";
 
 import ProjectEdit from "../../../components/task/ProjectEdit";
-import { useAppSelector } from "../../../hooks";
-import { currentUser } from "../../../reducers/current-user";
+import { useActiveStudio } from "../../../hooks/useActiveStudio";
 
 const Widget = () => {
-  const currUser = useAppSelector(currentUser);
+  const { studioName } = useActiveStudio();
 
   const { projectId } = useParams();
   const intl = useIntl();
@@ -20,7 +19,7 @@ const Widget = () => {
   return (
     <>
       <title>{name ? `${prefix}-${name}` : prefix}</title>
-      <ProjectEdit studioName={currUser?.realName} projectId={projectId} />
+      <ProjectEdit studioName={studioName} projectId={projectId} />
     </>
   );
 };

+ 3 - 4
dashboard-v6/src/pages/workspace/task/project.tsx

@@ -2,11 +2,10 @@ import { useMatches, useNavigate, useParams } from "react-router";
 import { useIntl } from "react-intl";
 
 import ProjectWithTasks from "../../../components/task/ProjectWithTasks";
-import { useAppSelector } from "../../../hooks";
-import { currentUser } from "../../../reducers/current-user";
+import { useActiveStudio } from "../../../hooks/useActiveStudio";
 
 const Widget = () => {
-  const currUser = useAppSelector(currentUser);
+  const { studioName } = useActiveStudio();
 
   const { projectId } = useParams();
   const navigate = useNavigate();
@@ -22,7 +21,7 @@ const Widget = () => {
     <>
       <title>{name ? `${prefix}-${name}` : prefix}</title>
       <ProjectWithTasks
-        studioName={currUser?.realName}
+        studioName={studioName}
         projectId={projectId}
         onChange={(id: string) => {
           navigate(`/workspace/task/project/${id}`);

+ 3 - 4
dashboard-v6/src/pages/workspace/task/projects.tsx

@@ -1,16 +1,15 @@
 import { useIntl } from "react-intl";
 import TaskProjects from "../../../components/task/ProjectTable";
-import { useAppSelector } from "../../../hooks";
-import { currentUser } from "../../../reducers/current-user";
+import { useActiveStudio } from "../../../hooks/useActiveStudio";
 
 const Widget = () => {
-  const currUser = useAppSelector(currentUser);
+  const { studioName } = useActiveStudio();
   const intl = useIntl();
 
   return (
     <>
       <title>{intl.formatMessage({ id: "labels.task.my.project" })}</title>
-      <TaskProjects studioName={currUser?.realName} />
+      <TaskProjects studioName={studioName} />
     </>
   );
 };

+ 3 - 4
dashboard-v6/src/pages/workspace/task/workflow.tsx

@@ -1,16 +1,15 @@
 import { useIntl } from "react-intl";
 import Workflow from "../../../components/task/Workflow";
-import { useAppSelector } from "../../../hooks";
-import { currentUser } from "../../../reducers/current-user";
+import { useActiveStudio } from "../../../hooks/useActiveStudio";
 
 const Widget = () => {
-  const currUser = useAppSelector(currentUser);
+  const { studioName } = useActiveStudio();
   const intl = useIntl();
 
   return (
     <>
       <title>{intl.formatMessage({ id: "labels.task.workflows" })}</title>
-      <Workflow studioName={currUser?.realName} />
+      <Workflow studioName={studioName} />
     </>
   );
 };

+ 2 - 4
dashboard-v6/src/pages/workspace/term/list.tsx

@@ -1,11 +1,9 @@
 import { useIntl } from "react-intl";
 import TermList from "../../../components/term/TermList";
-import { useAppSelector } from "../../../hooks";
-import { currentUser } from "../../../reducers/current-user";
+import { useActiveStudio } from "../../../hooks/useActiveStudio";
 
 const Widget = () => {
-  const user = useAppSelector(currentUser);
-  const studioName = user?.realName;
+  const { studioName } = useActiveStudio();
   const intl = useIntl();
 
   return (

+ 41 - 11
dashboard-v6/src/reducers/current-user.ts

@@ -12,7 +12,8 @@ export const TO_HOME = "/";
 export const TO_WORKSPACE = "/workspace";
 
 const KEY = "token";
-const STUDIO_KEY = "studio";
+/** 当前团队空间(一个 group)。只存在 localStorage,user token 不变 */
+const TEAMSPACE_KEY = "teamspace";
 export const DURATION = 60 * 60 * 24;
 
 export const get = (): string | null => {
@@ -38,12 +39,27 @@ const remove = () => {
   localStorage.removeItem(KEY);
 };
 
-const removeStudio = () => {
-  localStorage.removeItem(STUDIO_KEY);
+const removeTeamspace = () => {
+  localStorage.removeItem(TEAMSPACE_KEY);
 };
 
-const setStudio = (id: string) => {
-  localStorage.setItem(STUDIO_KEY, id);
+const saveTeamspace = (studio: IStudio) => {
+  localStorage.setItem(TEAMSPACE_KEY, JSON.stringify(studio));
+};
+
+/**
+ * 启动时先按 localStorage 恢复团队空间,避免页面先以个人身份取一次数据;
+ * 成员资格等 group 列表回来后由 recallCurrStudio 校验。
+ */
+const loadTeamspace = (): IStudio | undefined => {
+  try {
+    const raw = localStorage.getItem(TEAMSPACE_KEY);
+    const studio = raw ? (JSON.parse(raw) as IStudio) : undefined;
+    return studio?.id ? studio : undefined;
+  } catch {
+    removeTeamspace();
+    return undefined;
+  }
 };
 
 export interface IUser {
@@ -58,10 +74,11 @@ interface IState {
   payload?: IUser;
   studio?: IStudio[];
   guest?: boolean;
+  /** 当前团队空间;undefined 表示个人空间 */
   currStudio?: IStudio;
 }
 
-const initialState: IState = {};
+const initialState: IState = { currStudio: loadTeamspace() };
 
 export const slice = createSlice({
   name: "current-user",
@@ -75,7 +92,9 @@ export const slice = createSlice({
     signOut: (state) => {
       state.payload = undefined;
       state.guest = undefined;
+      state.currStudio = undefined;
       remove();
+      removeTeamspace();
     },
     guest: (state, action: PayloadAction<boolean>) => {
       state.guest = action.payload;
@@ -83,18 +102,29 @@ export const slice = createSlice({
     studioSignIn: (state, action: PayloadAction<IStudio[]>) => {
       state.studio = action.payload;
     },
+    /** 切换到团队空间 */
     setCurrStudio: (state, action: PayloadAction<IStudio>) => {
       state.currStudio = action.payload;
-      setStudio(action.payload.id);
+      saveTeamspace(action.payload);
     },
+    /** 切回个人空间 */
     studioSignOut: (state) => {
       state.currStudio = undefined;
-      removeStudio();
+      removeTeamspace();
     },
+    /** group 列表到手后校验:已不在该 group 里就回到个人空间,否则用最新的 group 信息 */
     recallCurrStudio: (state) => {
-      const id = localStorage.getItem(STUDIO_KEY);
-      if (id && state.studio) {
-        state.currStudio = state.studio.find((value) => value.id);
+      const id = state.currStudio?.id;
+      if (!id || !state.studio) {
+        return;
+      }
+      const studio = state.studio.find((value) => value.id === id);
+      if (studio) {
+        state.currStudio = studio;
+        saveTeamspace(studio);
+      } else {
+        state.currStudio = undefined;
+        removeTeamspace();
       }
     },
   },