Skip to content

refactor: centralize initial workspace selection for system pages - #8292

Merged
wangdan-fit2cloud merged 1 commit into
v3from
pr@v3@fix_workspace
Dec 3, 2026
Merged

wangdan-fit2cloud merged 1 commit into
v3from
pr@v3@fix_workspace

Conversation

@shaohuzhang1

Copy link
Copy Markdown
Contributor

refactor: centralize initial workspace selection for system pages


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.

@wangdan-fit2cloud
wangdan-fit2cloud merged commit fe6e2df into v3 Dec 3, 2026
3 of 4 checks passed
@wangdan-fit2cloud
wangdan-fit2cloud deleted the pr@v3@fix_workspace branch December 3, 2026 10:22
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.

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants