Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions ui/src/router/ROUTE_README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,9 @@ Workspace 根地址为 `/admin/workspace/:workspaceId`。`workspaceId` 只以当
没有时进入 `/admin/workspace/default`。顶部 `LayoutHeader` 切换到 System 时将当前
工作空间 ID 保存到 localStorage 的 `workspaceId`;该组件返回 Workspace 时读取缓存,
无缓存时使用用户首个工作空间或 `default`。退出登录时由 Admin `clearToken()` 清除缓存。
系统用户组与资源授权页的工作空间筛选器也优先读取该缓存,无缓存时使用用户首个工作空间或 `default`;
该缓存仅用于初始化筛选项,Workspace 路由的工作空间上下文仍以路由参数为准,其他位置不得读取该缓存。若当前用户
系统用户组与资源授权页通过 `getInitialWorkspaceId(workspaceList)` 初始化工作空间筛选项。在当前用户具有空间管理员角色的
工作空间中优先使用缓存项,其次使用首个有有效 ID 的工作空间,最后回退到 `default`。
Workspace 路由的工作空间上下文以路由参数为准。该缓存的读取仅限顶部 `LayoutHeader` 和上述筛选项初始化。若当前用户
只属于 `workspace_list` 中的部分工作空间且目标 `workspaceId` 不在其中,路由守卫会自动重定向到
其首个可访问工作空间(仅对携带 `workspaceId` 参数的工作空间路由生效)。父路由的 `scope`
会合并到匹配的子路由 `meta` 中。
Expand Down
28 changes: 17 additions & 11 deletions ui/src/utils/workspace-selection.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,25 @@
/** 工作空间选择。 */
/** 系统用户组与资源授权页的工作空间初始化。 */
import type { WorkspaceItem } from '@/api/types'
import { ROLE_TYPE } from '@/api/enums'
import { ADMIN_STORAGE_KEY } from '@/constants/storage-key'

function hasWorkspaceManagerRole(workspace: WorkspaceItem) {
return workspace.role_info?.some(({ role_type }) => role_type === ROLE_TYPE.WORKSPACE_MANAGE) ?? false
}
/** 在具有空间管理员角色的工作空间中优先选择缓存项,其次选择首个有效项,最后回退到 `default`。 */
export function getInitialWorkspaceId(workspaceList?: WorkspaceItem[]): string {
let preferredWorkspaceId = localStorage.getItem(ADMIN_STORAGE_KEY.WORKSPACE_ID)
let firstManagedWorkspaceId: string | undefined

for (const { id, role_info } of workspaceList ?? []) {
if (!id) continue

/** 优先使用当前用户具有空间管理员角色的缓存工作空间,否则选择第一个可管理的工作空间。 */
export function getInitialWorkspaceId(cachedWorkspaceId: string | null, workspaceList?: WorkspaceItem[]): string {
if (cachedWorkspaceId) {
const cachedWorkspace = workspaceList?.find(({ id }) => id === cachedWorkspaceId)
if (cachedWorkspace && hasWorkspaceManagerRole(cachedWorkspace)) {
return cachedWorkspaceId
const hasManagerRole = role_info?.some(({ role_type }) => role_type === ROLE_TYPE.WORKSPACE_MANAGE)
if (id === preferredWorkspaceId) {
if (hasManagerRole) return id
preferredWorkspaceId = null
}

if (hasManagerRole) firstManagedWorkspaceId ??= id
if (!preferredWorkspaceId && firstManagedWorkspaceId) return firstManagedWorkspaceId
}

return workspaceList?.find((workspace) => workspace.id && hasWorkspaceManagerRole(workspace))?.id ?? 'default'
return firstManagedWorkspaceId ?? 'default'
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here's my review of the diff:

Irregularities / Potential Issues

  1. preferredWorkspaceId is typed as string | null implicitly but declared with let and reassigned to null — TypeScript may infer the type from localStorage.getItem(...) which returns string | null. That's fine, but the mutation (preferredWorkspaceId = null) inside the loop makes the logic harder to follow than necessary. Consider a clearer variable naming (e.g., cachedWorkspaceId, keep the original signature).

  2. Early-return micro-optimization is fragile.

if (!preferredWorkspaceId && firstManagedWorkspaceId) return firstManagedWorkspaceId

This runs at the end of every iteration. It works, but it relies on the invariant that once the cached ID is cleared, the first managed workspace has already been captured. If the loop order or the meaning of "first" changes later, this becomes a subtle bug source. A cleaner structure: collect firstManagedWorkspaceId in one pass, then decide at the end.

  1. Behavioral change: the function signature changed from (cachedWorkspaceId, workspaceList) to (workspaceList?). The function now reads from localStorage directly. This:

    • Makes it impure / harder to unit test (requires mocking localStorage).
    • Couples a pure selection utility to storage. Previously callers could inject the cached value. Recommend keeping the cache read in the caller and keeping this function pure — arguably the biggest regression here.
    • Verify all call sites were updated; any caller still passing two args will silently ignore the second argument (no TS error if the second value is compatible... actually TS would error on arity). Confirm callers.
  2. ADMIN_STORAGE_KEY.WORKSPACE_ID scope assumption. Reading global localStorage assumes browser environment (no SSR guard). If this module can run server-side, this throws ReferenceError. Consider a guard or injection.

  3. Duplicate role_info lookup logic — hasWorkspaceManagerRole was removed and inlined. That loses the named helper's readability/reuse. Minor, but the inline check appears once, so acceptable; just note it reduces future reuse.

  4. Empty-string id handling — if (!id) continue skips empty IDs, good. But for the cached branch, if id === preferredWorkspaceId where both are ''... preferredWorkspaceId can't be '' unless stored; edge case, low risk.

  5. 'default' fallback semantics unchanged, fine.

Optimization Suggestions

  • Revert to a pure function taking cachedWorkspaceId as a parameter (better testability and separation of concerns), or at minimum wrap localStorage access behind a safe helper.
  • Restructure to a single clear flow:
export function getInitialWorkspaceId(
  cachedWorkspaceId: string | null,
  workspaceList?: WorkspaceItem[],
): string {
  const managed = (workspaceList ?? []).filter(
    ({ id, role_info }) =>
      id && role_info?.some(({ role_type }) => role_type === ROLE_TYPE.WORKSPACE_MANAGE),
  )
  if (cachedWorkspaceId && managed.some(({ id }) => id === cachedWorkspaceId)) {
    return cachedWorkspaceId
  }
  return managed[0]?.id ?? 'default'
}

This removes the inline early-return and the mutable preferredWorkspaceId = null trick while preserving the same behavior (cached-if-managed, else first managed, else default).

  • Add a small unit test matrix: cached valid / cached present-but-not-manager / cached missing / empty list / no managers / manager without id.

Summary of most important fixes

  • Pure function over direct localStorage access (testability/SSR safety).
  • Remove the mid-loop early return — restructure for clarity.
  • Confirm all call sites updated for the new signature.

5 changes: 1 addition & 4 deletions ui/src/views/system/identity/groups/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import WorkspaceDropdown from '@/components/business/workspace-dropdown/index.vu
import CreateGroupMemberDialog from './dialog/CreateGroupMemberDialog.vue'
import CreateOrUpdateGroupDialog from './dialog/CreateOrUpdateGroupDialog.vue'
import { LOGIN_METHOD_LABELS } from '@/constants'
import { ADMIN_STORAGE_KEY } from '@/constants/storage-key'
import { useStore } from '@/stores'
import { MsgConfirm, MsgSuccess } from '@/utils/message'
import { getRoleName } from '@/utils/role-name'
Expand All @@ -19,9 +18,7 @@ const { auth, user } = useStore()
const { t } = useI18n({ useScope: 'global' })

/* 选择工作空间列表 */
const selectedWorkspaceId = ref(
getInitialWorkspaceId(localStorage.getItem(ADMIN_STORAGE_KEY.WORKSPACE_ID), user.userInfo?.workspace_list),
)
const selectedWorkspaceId = ref(getInitialWorkspaceId(user.userInfo?.workspace_list))
const workspaceOptions = ref<WorkspaceItem[]>([])
const loadingView = ref(false)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here are my observations:

1. Behavior change risk (most important)
The refactor drops the persisted localStorage value (ADMIN_STORAGE_KEY.WORKSPACE_ID) as an input to getInitialWorkspaceId. Previously, a user's last-selected workspace would be restored on page load. Now the initial selection will always be derived from user.userInfo?.workspace_list. Confirm this is intentional; if persistence is still desired, pass the stored ID through (or let getInitialWorkspaceId read storage), otherwise users lose their previous selection after refresh.

2. Function signature consistency
Ensure getInitialWorkspaceId has actually been updated to accept a single argument. If the function still expects two parameters, the call is fine but the first param becomes undefined for the storage key — verify the new definition matches this call site (and any other call sites).

3. Fallback / edge cases

  • What happens when user.userInfo?.workspace_list is undefined, empty, or lacks the previously selected ID? Confirm getInitialWorkspaceId returns a safe default (e.g., first workspace or null).
  • If it returns null/empty, downstream code using selectedWorkspaceId should handle that gracefully.

4. Removal of the import
Since ADMIN_STORAGE_KEY is no longer imported here, make sure nothing else in this file references it (looks clean in the diff) and that clearing the persisted key elsewhere isn't now orphaned/dead logic. Also check whether the constants module still needs WORKSPACE_ID for other consumers.

5. Reactivity of user info
user.userInfo?.workspace_list is read once at setup. If userInfo loads asynchronously, the initial selectedWorkspaceId may compute before data arrives. Consider guarding with a watcher or initializing after user info is ready.

6. Type safety (minor)
getInitialWorkspaceId(user.userInfo?.workspace_list) — ensure the function signature reflects a possibly-undefined list, so TS doesn't silently accept mismatched types.

Optimization suggestions

  • If losing persistence is unintended, prefer passing localStorage.getItem(ADMIN_STORAGE_KEY.WORKSPACE_ID) as an optional second param rather than embedding storage access inside the helper (keeps the helper pure/testable).
  • Add/update unit tests covering: no persisted value, invalid persisted ID, empty workspace list, and successful restore — to lock in the new expected behavior.
  • Consider a small comment noting why persistence was removed, to prevent regression.

Overall the change itself is clean; the main concern is the dropped localStorage-backed selection — please verify that's deliberate.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ import PermissionTable from './components/PermissionTable.vue'
import UserAuthorizationList from './components/UserAuthorizationList.vue'
import UserGroupAuthorizationList from './components/user-group/UserGroupAuthorizationList.vue'
import { RESOURCE_AUTHORIZATION_LABELS } from './constants'
import { ADMIN_STORAGE_KEY } from '@/constants/storage-key'
import { useStore } from '@/stores'
import { MsgSuccess } from '@/utils/message'
import { getInitialWorkspaceId } from '@/utils/workspace-selection'
Expand Down Expand Up @@ -54,9 +53,7 @@ const resourceTypeOptions = computed<OptionItem<ResourceAuthorizationType>[]>(()

/* 选择工作空间列表 */
const loadingView = ref(false)
const selectedWorkspaceId = ref(
getInitialWorkspaceId(localStorage.getItem(ADMIN_STORAGE_KEY.WORKSPACE_ID), user.userInfo?.workspace_list),
)
const selectedWorkspaceId = ref(getInitialWorkspaceId(user.userInfo?.workspace_list))
const workspaceOptions = ref<WorkspaceItem[]>([])

function handleWorkspaceSelect(workspace: WorkspaceItem) {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

1. Removed import — make sure it's truly unused

ADMIN_STORAGE_KEY is removed, but also verify:

  • localStorage isn't used elsewhere in the file.
  • No other references to ADMIN_STORAGE_KEY remain (the diff only shows one usage site, but double-check).

2. Behavior change in getInitialWorkspaceId signature

The call changed from:

getInitialWorkspaceId(storedId, workspaceList)

to:

getInitialWorkspaceId(workspaceList)

Potential issues:

  • Loss of persistence preference: Previously, the app restored the last-selected workspace from localStorage. Now it relies solely on user.userInfo?.workspace_list. If that function now just picks a default (e.g., first item), users lose their previous selection on reload — is that intentional?
  • Ordering dependency: The ref initialization runs at setup time. If user.userInfo is populated after this runs (e.g., async fetch), workspace_list may be undefined, producing an incorrect/empty initial value that won't reactively update. Consider computing/watching instead of a one-shot ref().
  • Verify the new implementation: Confirm getInitialWorkspaceId(workspaceList) handles undefined/empty arrays gracefully and has predictable fallback behavior.

3. Reactive staleness

const selectedWorkspaceId = ref(getInitialWorkspaceId(user.userInfo?.workspace_list))

Since this is evaluated once, if user loads asynchronously the initial ID can become stale. Prefer:

watch(() => user.userInfo?.workspace_list, (list) => {
  if (list?.length) selectedWorkspaceId.value = getInitialWorkspaceId(list)
}, { immediate: true })

…unless user info is guaranteed available before component setup.

4. Persistence / UX regression

If you no longer read from storage here, ensure something still writes the selected workspace (in handleWorkspaceSelect) so cross-session selection is preserved — otherwise this is an unintended UX regression.

5. Optimization notes

  • Keep handleWorkspaceSelect updating both state and any persisted store consistently.
  • If workspaceOptions derives from user.userInfo.workspace_list, consider computed instead of a manually assigned ref.
  • Minor: ensure the removed blank line/formatting aligns with lint rules (trailing comma style is consistent — good).

Summary

The edit is syntactically fine, but it changes persistence semantics. Confirm that (a) dropping localStorage restoration is intended, (b) the new getInitialWorkspaceId handles async/undefined input safely, and (c) selected workspace is still persisted somewhere for continuity.

Expand Down
73 changes: 0 additions & 73 deletions ui/tests/workspace-selection.test.mjs

This file was deleted.

Loading