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

💄 (dashboard-v6): 头像弹窗「切换到团队空间」改为「切换账号」

- 账号列表:个人账号与团队之间加分隔线,团队后标注我的角色
- 切到团队后,主导航顶部头像、名字与弹窗标题都换成团队,标题下用彩色 Tag 标角色
- 去掉主工具栏上的团队空间标签(TeamspaceBadge),切回个人空间走账号列表
- 账号名过长时省略(主导航、弹窗标题、账号列表),角色标签与当前标记始终可见
- dashboard-test:teamspace / channel-teamspace 改用主导航当前账号断言

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
visuddhinanda 19 часов назад
Родитель
Сommit
180dfb78a8

+ 7 - 2
dashboard-test/src/tests/channel-teamspace.spec.ts

@@ -62,7 +62,7 @@ test.describe('团队空间里的 channel', () => {
       );
       await page.goto('workspace/channel', { waitUntil: 'networkidle' });
       expect((await listed).status()).toBe(200);
-      await expect(page.getByTestId('teamspace-badge')).toContainText(TEAM);
+      await expect(page.getByTestId('active-account')).toHaveText(new RegExp(`${TEAM}$`));
       await expect(row(page, TEAM_CHANNEL)).toBeVisible();
       // 个人名下的 channel 不出现:随便取一个个人 channel 名核对
       const personal = await call(request, 'GET', `/v3/studios/${mine.body.data.id}/channels?relation=own&per_page=1`);
@@ -103,7 +103,12 @@ test.describe('团队空间里的 channel', () => {
           r.url().includes(`/api/v3/studios/${mine.body.data.id}/channels`) &&
           new URL(r.url()).searchParams.get('per_page') !== '1',
       );
-      await page.getByTestId('teamspace-badge').locator('.ant-tag-close-icon').click();
+      await page.getByTestId('active-account').hover();
+      const popover = page.locator('.ant-popover:visible');
+      if (!(await popover.getByTestId('account-personal').isVisible())) {
+        await popover.getByText('切换账号').click();
+      }
+      await popover.getByTestId('account-personal').click();
       await relisted;
       await expect(row(page, TEAM_CHANNEL)).toHaveCount(0);
       await shot(page, '03-back-to-personal');

+ 47 - 16
dashboard-test/src/tests/teamspace.spec.ts

@@ -5,7 +5,7 @@ import { collect } from '../lib/collect.js';
 import { shotDir } from '../lib/env.js';
 
 /**
- * 团队空间(P0):头像弹窗里切到团队空间、顶栏标签、菜单置灰、直接访问被拦、
+ * 团队空间(P0):头像弹窗里切到团队空间、主导航顶部换成团队、菜单置灰、直接访问被拦、
  * 刷新后保持、切回个人空间、localStorage 里的过期团队被清掉。
  *
  * 团队空间 = 以某个 group 为 owner 浏览资源。P0 阶段所有可团队化的模块都还没迁 v3,
@@ -17,7 +17,13 @@ const TEAM2 = 'e2e 团队空间 2';
 
 const shot = (page: Page, name: string) =>
   page.screenshot({ path: `${SHOT}/${name}.png`, fullPage: true });
-const badge = (page: Page) => page.getByTestId('teamspace-badge');
+/** 主导航顶部的当前账号(头像 + 名字);团队空间里显示团队名 */
+const active = (page: Page) => page.getByTestId('active-account');
+/** 当前账号是某个团队(TEAM 是 TEAM2 的前缀,所以要锚定结尾) */
+const isTeam = (page: Page, name: string) =>
+  expect(active(page)).toHaveText(new RegExp(`${name}$`));
+/** 当前是个人账号:顶部名字不是任何一个测试团队 */
+const isPersonal = (page: Page) => expect(active(page)).not.toContainText('e2e 团队空间');
 const menuItem = (page: Page, label: string) =>
   page.locator('.ant-layout-sider .ant-menu-item').filter({ hasText: label });
 /** 展开主导航的「协作」子菜单(inline 子菜单收起时子项不渲染) */
@@ -41,15 +47,26 @@ async function ensureTeam(request: APIRequestContext, name: string): Promise<str
 
 /** 头像弹窗里选一个团队空间 */
 async function switchTo(page: Page, name: string) {
-  await page.locator('.ant-layout-sider .ant-avatar').first().hover();
+  await active(page).hover();
   const popover = page.locator('.ant-popover:visible');
-  const title = popover.getByText('切换到团队空间');
+  const title = popover.getByText('切换账号');
   if (!(await popover.getByText(name, { exact: true }).isVisible())) {
     await title.click();
   }
   await popover.getByText(name, { exact: true }).click();
 }
 
+/** 头像弹窗里选个人账号 */
+async function switchToPersonal(page: Page) {
+  await active(page).hover();
+  const popover = page.locator('.ant-popover:visible');
+  const personal = popover.getByTestId('account-personal');
+  if (!(await personal.isVisible())) {
+    await popover.getByText('切换账号').click();
+  }
+  await personal.click();
+}
+
 let teamId = '';
 let team2Id = '';
 
@@ -66,13 +83,27 @@ test.describe('团队空间切换', () => {
       await page.goto('workspace', { waitUntil: 'networkidle' });
       await page.evaluate(() => localStorage.removeItem('teamspace'));
       await page.reload({ waitUntil: 'networkidle' });
-      await expect(badge(page)).toHaveCount(0);
+      await isPersonal(page);
 
       await switchTo(page, TEAM);
 
-      await expect(badge(page)).toContainText(TEAM);
+      await isTeam(page, TEAM);
       expect(JSON.parse((await stored(page)) ?? '{}').id).toBe(teamId);
       await shot(page, '01-switched');
+    });
+
+    await test.step('1b. 主导航头像与弹窗换成团队账号,标注我的角色', async () => {
+      // 主导航顶部显示团队名
+      await isTeam(page, TEAM);
+      await active(page).hover();
+      const popover = page.locator('.ant-popover:visible');
+      await expect(popover.locator('h3')).toHaveText(TEAM);
+      await expect(popover.getByTestId('account-role')).toHaveText('拥有者');
+      // 账号列表:个人账号与团队之间有分隔线,团队带角色
+      const list = popover.locator('.ant-menu-sub');
+      await expect(list.locator('.ant-menu-item-divider')).toHaveCount(1);
+      await expect(list.locator('.ant-menu-item').filter({ hasText: TEAM2 })).toContainText('拥有者');
+      await shot(page, '01b-account-popover');
       log.dump('1. 切到团队空间');
     });
 
@@ -100,14 +131,14 @@ test.describe('团队空间切换', () => {
 
     await test.step('2c. 在成员管理页切换团队空间,成员列表跟着换', async () => {
       await page.goto('workspace/members', { waitUntil: 'networkidle' });
-      await expect(badge(page)).toContainText(TEAM);
+      await isTeam(page, TEAM);
 
       const refetched = page.waitForResponse(
         (r) => r.url().includes(`/api/v3/groups/${team2Id}/members`) && r.request().method() === 'GET',
       );
       await switchTo(page, TEAM2);
       expect((await refetched).status()).toBe(200);
-      await expect(badge(page)).toContainText(TEAM2);
+      await isTeam(page, TEAM2);
       await expect(page).toHaveURL(/workspace\/members$/);
       await shot(page, '02c-switched-members');
 
@@ -115,7 +146,7 @@ test.describe('团队空间切换', () => {
       const back = page.waitForResponse((r) => r.url().includes(`/api/v3/groups/${teamId}/members`));
       await switchTo(page, TEAM);
       await back;
-      await expect(badge(page)).toContainText(TEAM);
+      await isTeam(page, TEAM);
     });
 
     await test.step('3a. 已迁 v3 的术语在团队空间可用,列的是团队的术语', async () => {
@@ -137,13 +168,13 @@ test.describe('团队空间切换', () => {
 
     await test.step('4. 刷新后仍在团队空间', async () => {
       await page.reload({ waitUntil: 'networkidle' });
-      await expect(badge(page)).toContainText(TEAM);
+      await isTeam(page, 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 isPersonal(page);
       await expect(page.locator('.ant-table')).toBeVisible();
       expect(await stored(page)).toBeNull();
       await shot(page, '05-personal');
@@ -159,16 +190,16 @@ test.describe('团队空间切换', () => {
       await expect(page.getByTestId('teamspace-blocked').getByRole('button')).toHaveCount(0);
     });
 
-    await test.step('6. 顶栏标签关掉也能切回个人空间', async () => {
+    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);
+      await isTeam(page, TEAM);
+      await switchToPersonal(page);
+      await isPersonal(page);
       expect(await stored(page)).toBeNull();
     });
   });
@@ -188,7 +219,7 @@ test.describe('团队空间切换', () => {
     await page.reload({ waitUntil: 'networkidle' });
 
     // group 列表回来后校验成员资格,不是成员就回到个人空间
-    await expect(badge(page)).toHaveCount(0);
+    await isPersonal(page);
     await expect.poll(() => stored(page)).toBeNull();
   });
 });

+ 28 - 0
dashboard-v6/src/components/auth/SignInAvatar.css

@@ -0,0 +1,28 @@
+/* 账号名过长时省略,角色标签与当前标记始终可见 */
+.account-item {
+  display: flex;
+  align-items: center;
+  min-width: 0;
+}
+.account-item__name {
+  flex: 0 1 auto;
+  min-width: 0;
+  overflow: hidden;
+}
+.account-item__name .ant-space {
+  display: flex;
+  min-width: 0;
+}
+.account-item__name .ant-space-item:last-child {
+  min-width: 0;
+  overflow: hidden;
+  text-overflow: ellipsis;
+  white-space: nowrap;
+}
+.account-item__name .ant-space-item:last-child .ant-typography {
+  white-space: nowrap;
+}
+.account-item > .ant-tag,
+.account-item > .anticon {
+  flex: none;
+}

+ 105 - 22
dashboard-v6/src/components/auth/SignInAvatar.tsx

@@ -1,7 +1,7 @@
 import { useIntl } from "react-intl";
 import { useState } from "react";
 import { useNavigate } from "react-router";
-import { Divider, Menu, Typography } from "antd";
+import { Divider, Menu, Tag, Typography } from "antd";
 import { Avatar } from "antd";
 import { Popover } from "antd";
 
@@ -30,6 +30,8 @@ import User from "./User";
 import { fullUrl } from "../../utils";
 import Studio from "./Studio";
 import LoginButton from "./LoginButton";
+import "./SignInAvatar.css";
+import { getAvatarColor } from "./utils";
 
 const { Title, Paragraph, Text } = Typography;
 
@@ -37,6 +39,14 @@ const { Title, Paragraph, Text } = Typography;
 const PERSONAL_KEY = "space:personal";
 const TEAMSPACE_PREFIX = "space:team:";
 
+/** 团队角色标签的颜色(antd 预设色:浅色底、同色边框与文字) */
+const ROLE_COLOR: Record<string, string> = {
+  owner: "gold",
+  manager: "blue",
+  editor: "green",
+  reader: "default",
+};
+
 interface IWidget {
   placement?: TooltipPlacement;
   style?: React.CSSProperties;
@@ -57,20 +67,52 @@ const SignInAvatar = ({
   const studios = useAppSelector(studioList);
   const teamspace = useAppSelector(currentStudio);
 
-  console.debug("user", user);
-
   const canManage =
     user?.roles?.includes("root") || user?.roles?.includes("administrator");
 
   if (typeof user === "undefined") {
     return <LoginButton />;
   } else {
+    /** 团队角色的显示名;没有对应文案的(如旧数据里的 member)原样显示 */
+    const roleLabel = (role?: string) =>
+      role
+        ? intl.formatMessage({
+            id: `labels.group.role.${role}`,
+            defaultMessage: role,
+          })
+        : undefined;
+
+    // 当前账号:团队空间里是团队,否则是登录用户本人
+    const activeName = teamspace ? teamspace.nickName : user.nickName;
+    const activeAvatar = teamspace ? teamspace.avatar : user.avatar;
+
     const welcome = (
       <Paragraph>
-        <Title level={3} style={{ fontSize: 22 }}>
-          {user.nickName}
+        <Title
+          level={3}
+          style={{ fontSize: 22 }}
+          ellipsis={{ tooltip: activeName }}
+        >
+          {activeName}
         </Title>
-        <Text type="secondary">账户名 {user.realName}</Text>
+        {teamspace ? (
+          teamspace.role && (
+            <Tag
+              data-testid="account-role"
+              color={ROLE_COLOR[teamspace.role] ?? "default"}
+            >
+              {roleLabel(teamspace.role)}
+            </Tag>
+          )
+        ) : (
+          <Text
+            type="secondary"
+            style={{ display: "block" }}
+            ellipsis={{ tooltip: user.realName }}
+          >
+            账户名 {user.realName}
+          </Text>
+        )}
         <Paragraph style={{ textAlign: "right", paddingTop: 30 }}>
           {intl.formatMessage({
             id: "buttons.welcome",
@@ -80,14 +122,19 @@ const SignInAvatar = ({
     );
 
     const current = <CheckOutlined style={{ marginLeft: 8 }} />;
-    let userList = [
+    type AccountItem =
+      | { key: string; label: React.ReactNode }
+      | { type: "divider"; key: string };
+    let userList: AccountItem[] = [
       {
         key: PERSONAL_KEY,
         label: (
-          <>
-            <User {...user} />
+          <span className="account-item" data-testid="account-personal">
+            <span className="account-item__name">
+              <User {...user} />
+            </span>
             {!teamspace && current}
-          </>
+          </span>
         ),
       },
     ];
@@ -95,15 +142,24 @@ const SignInAvatar = ({
       return {
         key: TEAMSPACE_PREFIX + item.id,
         label: (
-          <>
-            <Studio data={item} />
+          <span className="account-item">
+            <span className="account-item__name">
+              <Studio data={item} />
+            </span>
+            {item.role && (
+              <Tag style={{ marginInlineStart: 8 }}>{roleLabel(item.role)}</Tag>
+            )}
             {teamspace?.id === item.id && current}
-          </>
+          </span>
         ),
       };
     });
-    if (studioList) {
-      userList = [...userList, ...studioList];
+    if (studioList?.length) {
+      userList = [
+        ...userList,
+        { type: "divider", key: "space:divider" },
+        ...studioList,
+      ];
     }
     return (
       <>
@@ -121,7 +177,7 @@ const SignInAvatar = ({
                     {
                       key: "account",
                       label: intl.formatMessage({
-                        id: "buttons.teamspace.switch",
+                        id: "buttons.account.switch",
                       }),
                       icon: <SwapOutlined />,
                       children: userList,
@@ -194,16 +250,43 @@ const SignInAvatar = ({
           }
           placement={placement}
         >
-          <span style={style}>
+          <span
+            style={{
+              display: "inline-flex",
+              alignItems: "center",
+              flex: "0 1 auto",
+              minWidth: 0,
+              ...style,
+            }}
+            data-testid="active-account"
+          >
             <Avatar
-              style={{ backgroundColor: "#87d068" }}
-              icon={<UserOutlined />}
-              src={user?.avatar}
+              style={{
+                flex: "none",
+                backgroundColor: teamspace
+                  ? getAvatarColor(activeName)
+                  : "#87d068",
+              }}
+              icon={teamspace ? undefined : <UserOutlined />}
+              src={activeAvatar}
               size="small"
             >
-              {user.nickName?.slice(0, 2)}
+              {activeName?.slice(0, 2)}
             </Avatar>
-            {!hideName && user.nickName}
+            {!hideName && (
+              <span
+                style={{
+                  marginInlineStart: 8,
+                  minWidth: 0,
+                  overflow: "hidden",
+                  textOverflow: "ellipsis",
+                  whiteSpace: "nowrap",
+                }}
+                title={activeName}
+              >
+                {activeName}
+              </span>
+            )}
           </span>
         </Popover>
         <SettingModal

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

@@ -1,43 +0,0 @@
-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;

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

@@ -11,7 +11,6 @@ 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";
 import {
   WORKSPACE_CONTENT_PADDING,
@@ -73,6 +72,7 @@ const Widget = () => {
           <SignInAvatar hideName={collapsed} />
           <Button
             type="text"
+            style={{ flex: "none" }}
             icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
             onClick={toggleCollapsed}
           />
@@ -96,7 +96,6 @@ const Widget = () => {
         >
           <HeaderBreadcrumb />
           <Space size="middle">
-            <TeamspaceBadge />
             <SentCart />
             <NotificationIcon />
             <NetworkStatus />

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

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

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

@@ -172,7 +172,6 @@ const items = {
   "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",

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

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

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

@@ -177,7 +177,6 @@ const items = {
   "labels.pagination.total": "结果: {total}",
   "labels.channel.select": "版本选择",
   "labels.teamspace": "团队空间",
-  "labels.teamspace.current": "团队空间:{name}",
   "labels.teamspace.personal-only": "个人专属功能,团队空间下不可用",
   "labels.teamspace.unsupported": "该模块暂不支持团队空间",
   "labels.group.role.owner": "拥有者",

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

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

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

@@ -177,7 +177,6 @@ const items = {
   "labels.pagination.total": "結果: {total}",
   "labels.channel.select": "版本選擇",
   "labels.teamspace": "團隊空間",
-  "labels.teamspace.current": "團隊空間:{name}",
   "labels.teamspace.personal-only": "個人專屬功能,團隊空間下不可用",
   "labels.teamspace.unsupported": "該模組暫不支援團隊空間",
   "labels.group.role.owner": "擁有者",