Skip to content

extract DeleteWorkspaceFlow component from WorkspacesListPage#93717

Open
WojtekBoman wants to merge 1 commit into
Expensify:mainfrom
software-mansion-labs:perf/workspaces-list-page-composition-1
Open

extract DeleteWorkspaceFlow component from WorkspacesListPage#93717
WojtekBoman wants to merge 1 commit into
Expensify:mainfrom
software-mansion-labs:perf/workspaces-list-page-composition-1

Conversation

@WojtekBoman

@WojtekBoman WojtekBoman commented Jun 16, 2026

Copy link
Copy Markdown
Contributor

Explanation of Change

This is the first in a series of smaller PRs splitting a larger WorkspacesListPage composition refactor (#93293) into incremental steps to catch regressions early.

This PR extracts all workspace deletion logic from WorkspacesListPage into a new DeleteWorkspaceFlow component that mounts only when a deletion is in progress. Heavy Onyx subscriptions (full policy collection, card feeds, reports, transaction violations) are now scoped to the flow's lifetime instead of living on the list page for every row. The page retains only the primitive-valued subscriptions it needs for delete menu item configuration (canDowngrade, amountOwed, isLoadingBill, owned-policy counts via a stable selector).

Fixed Issues

$ #91175
PROPOSAL:

Tests

  • Verify that no errors appear in the JS console
  1. Go to Settings → Workspaces (the workspaces list page).

  2. Open the three-dots menu for any workspace you own and tap Delete.

  3. Verify the delete confirmation modal appears and the workspace is removed after confirming.

  4. With a paid workspace as the only active owned workspace, open the three-dots menu and tap Delete.

  5. Verify the bill calculation flow runs (loading spinner appears on the delete item) and the confirmation modal opens correctly after the bill is calculated.

  6. Open the three-dots menu for a workspace you don't own.

  7. Verify the Delete option is not present and the Leave/Transfer options still appear and work normally.

Offline tests

  1. Turn off network, go to Settings → Workspaces.
  2. Tap Delete on any owned workspace and confirm.
  3. Verify the workspace enters a pending-delete state and the error modal appears if the deletion fails.
  4. Restore network and verify the workspace is eventually deleted or the error state is cleared correctly.

QA Steps

Same as tests.

PR Author Checklist

  • I linked the correct issue in the ### Fixed Issues section above
  • I wrote clear testing steps that cover the changes made in this PR
    • I added steps for local testing in the Tests section
    • I added steps for the expected offline behavior in the Offline steps section
    • I added steps for Staging and/or Production testing in the QA steps section
    • I added steps to cover failure scenarios (i.e. verify an input displays the correct error message if the entered data is not correct)
    • I turned off my network connection and tested it while offline to ensure it matches the expected behavior (i.e. verify the default avatar icon is displayed if app is offline)
    • I tested this PR with a High Traffic account against the staging or production API to ensure there are no regressions (e.g. long loading states that impact usability).
  • I included screenshots or videos for tests on all platforms
  • I ran the tests on all platforms & verified they passed on:
    • Android: Native
    • Android: mWeb Chrome
    • iOS: Native
    • iOS: mWeb Safari
    • MacOS: Chrome / Safari
  • I verified there are no console errors (if there's a console error not related to the PR, report it or open an issue for it to be fixed)
  • I followed proper code patterns (see Reviewing the code)
    • I verified that any callback methods that were added or modified are named for what the method does and never what callback they handle (i.e. toggleReport and not onIconClick)
    • I verified that comments were added to code that is not self explanatory
    • I verified that any new or modified comments were clear, correct English, and explained "why" the code was doing something instead of only explaining "what" the code was doing.
    • I verified any copy / text shown in the product is localized by adding it to src/languages/* files and using the translation method
    • I verified all numbers, amounts, dates and phone numbers shown in the product are using the localization methods
    • I verified any copy / text that was added to the app is grammatically correct in English. It adheres to proper capitalization guidelines (note: only the first word of header/labels should be capitalized), and is either coming verbatim from figma or has been approved by marketing (in order to get marketing approval, ask the Bug Zero team member to add the Waiting for copy label to the issue)
    • I verified proper file naming conventions were followed for any new files or renamed files. All non-platform specific files are named after what they export and are not named "index.js". All platform-specific files are named for the platform the code supports as outlined in the README.
    • I verified the JSDocs style guidelines (in STYLE.md) were followed
  • If a new code pattern is added I verified it was agreed to be used by multiple Expensify engineers
  • I followed the guidelines as stated in the Review Guidelines
  • I tested other components that can be impacted by my changes (i.e. if the PR modifies a shared library or component like Avatar, I verified the components using Avatar are working as expected)
  • I verified all code is DRY (the PR doesn't include any logic written more than once, with the exception of tests)
  • I verified any variables that can be defined as constants (ie. in CONST.ts or at the top of the file that uses the constant) are defined as such
  • I verified that if a function's arguments changed that all usages have also been updated correctly
  • If any new file was added I verified that:
    • The file has a description of what it does and/or why is needed at the top of the file if the code is not self explanatory
  • If a new CSS style is added I verified that:
    • A similar style doesn't already exist
    • The style can't be created with an existing StyleUtils function (i.e. StyleUtils.getBackgroundAndBorderStyle(theme.componentBG))
  • If new assets were added or existing ones were modified, I verified that:
    • The assets are optimized and compressed (for SVG files, run npm run compress-svg)
    • The assets load correctly across all supported platforms.
  • If the PR modifies code that runs when editing or sending messages, I tested and verified there is no unexpected behavior for all supported markdown - URLs, single line code, code blocks, quotes, headings, bold, strikethrough, and italic.
  • If the PR modifies a generic component, I tested and verified that those changes do not break usages of that component in the rest of the App (i.e. if a shared library or component like Avatar is modified, I verified that Avatar is working as expected in all cases)
  • If the PR modifies a component related to any of the existing Storybook stories, I tested and verified all stories for that component are still working as expected.
  • If the PR modifies a component or page that can be accessed by a direct deeplink, I verified that the code functions as expected when the deeplink is used - from a logged in and logged out account.
  • If the PR modifies the UI (e.g. new buttons, new UI components, changing the padding/spacing/sizing, moving components, etc) or modifies the form input styles:
    • I verified that all the inputs inside a form are aligned with each other.
    • I added Design label and/or tagged @Expensify/design so the design team can review the changes.
  • If a new page is added, I verified it's using the ScrollView component to make it scrollable when more elements are added to the page.
  • I added unit tests for any new feature or bug fix in this PR to help automatically prevent regressions in this user flow.
  • If the main branch was merged into this PR after a review, I tested again and verified the outcome was still expected according to the Test steps.

Screenshots/Videos

Android: Native
Android: mWeb Chrome
iOS: Native
iOS: mWeb Safari
MacOS: Chrome / Safari

@codecov

codecov Bot commented Jun 16, 2026

Copy link
Copy Markdown

Codecov Report

❌ Looks like you've decreased code coverage for some files. Please write tests to increase, or at least maintain, the existing level of code coverage. See our documentation here for how to interpret this table.

Files with missing lines Coverage Δ
...ts/Tables/WorkspaceListTable/WorkspaceTableRow.tsx 89.65% <100.00%> (-0.18%) ⬇️
src/components/Tables/WorkspaceListTable/index.tsx 71.87% <ø> (ø)
src/hooks/useOutstandingBalanceGuard.tsx 100.00% <100.00%> (ø)
src/selectors/Account.ts 100.00% <100.00%> (ø)
src/selectors/Policy.ts 74.31% <80.00%> (+0.27%) ⬆️
src/pages/workspace/WorkspacesListPage.tsx 56.32% <86.66%> (+1.04%) ⬆️
src/libs/actions/Policy/Policy.ts 71.16% <0.00%> (-0.43%) ⬇️
.../workspace/deleteWorkspace/DeleteWorkspaceFlow.tsx 0.00% <0.00%> (ø)
... and 101 files with indirect coverage changes

@WojtekBoman WojtekBoman force-pushed the perf/workspaces-list-page-composition-1 branch from f73cec4 to 6c06845 Compare June 16, 2026 15:09
@WojtekBoman WojtekBoman marked this pull request as ready for review June 16, 2026 15:14
@WojtekBoman WojtekBoman requested review from a team as code owners June 16, 2026 15:14
@melvin-bot melvin-bot Bot requested review from abzokhattab and removed request for a team June 16, 2026 15:14
@melvin-bot

melvin-bot Bot commented Jun 16, 2026

Copy link
Copy Markdown

@abzokhattab Please copy/paste the Reviewer Checklist from here into a new comment on this PR and complete it. If you have the K2 extension, you can simply click: [this button]

@WojtekBoman

Copy link
Copy Markdown
Contributor Author

@abzokhattab All yours!

@abzokhattab

Copy link
Copy Markdown
Contributor

Great ... reviewing!

@abzokhattab

Copy link
Copy Markdown
Contributor

@MelvinBot, review the PR

return;
}
isErrorModalShowingRef.current = true;
showConfirmModal({

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

❌ CONSISTENCY-3 (docs)

The error-modal block in this effect is duplicated almost verbatim. The showConfirmModal({...}).then(...) call at the bottom of the effect (the non-offline branch) is identical to the one in the offline branch above it (same title, prompt: policyLatestErrorMessage, confirmText, cancelText, success: false, shouldShowCancelButton: false, and the same .then handler calling hideDeleteWorkspaceErrorModal()). Maintaining two copies risks them drifting apart.

Extract the shared modal into a single local helper and call it from both branches:

const showErrorModal = () => {
    if (isErrorModalShowingRef.current) {
        return;
    }
    isErrorModalShowingRef.current = true;
    showConfirmModal({
        title: translate('workspace.common.delete'),
        prompt: policyLatestErrorMessage,
        confirmText: translate('common.buttonConfirm'),
        cancelText: translate('common.cancel'),
        success: false,
        shouldShowCancelButton: false,
    }).then(() => {
        isErrorModalShowingRef.current = false;
        hideDeleteWorkspaceErrorModal();
    });
};

Then call showErrorModal() in both the offline branch and the post-pending-delete branch.


Reviewed at: 6c06845 | Please rate this suggestion with 👍 or 👎 to help us improve! Reactions are used to monitor reviewer efficiency.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 6c06845b55

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

const {reportsToArchive, transactionViolations} = useTransactionViolationOfWorkspace(policyID);
const [accountIDToLogin] = useOnyx(ONYXKEYS.PERSONAL_DETAILS_LIST, {selector: accountIDToLoginSelector(reportsToArchive)});

const isLoadingData = isLoadingOnyxValue(policiesResult, accountResult, amountOwedResult, privateSubscriptionResult, cardFeedsResult, cardsListResult);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Wait for report data before starting deletion

When the delete flow is mounted on demand, useTransactionViolationOfWorkspace() starts loading the report and transaction collections at the same time as this readiness check, but isLoadingData does not include those Onyx results. On accounts where reports/transactions hydrate slower than the policy/account/card keys, the effect can call continueDeleteWorkspace() with an empty reportsToArchive / transactionViolations, so deleteWorkspace skips archiving the workspace chats and clearing their violations. Please include those loading states (or otherwise defer until the hook's data is ready) before starting the deletion.

Useful? React with 👍 / 👎.

@melvin-bot melvin-bot Bot requested review from joekaufmanexpensify and removed request for a team June 16, 2026 15:24
@MelvinBot

Copy link
Copy Markdown
Contributor

Code review

Reviewed this as a behavior-preserving refactor. The extraction is clean and the ported logic is faithful — I verified the inlined helpers against their originals:

  • shouldCalculateBillNewDot (!!canDowngrade && counts.total === 1) matches SubscriptionUtils.shouldCalculateBillNewDot.
  • wouldBlockDeletion ((amountOwed ?? 0) > 0 && counts.active === 1) matches the hook's internal value in useOutstandingBalanceGuard.tsx:25.
  • The offline/online error-modal + isPendingDelete transition logic is ported intact, plus a correct new onDismiss() on success so the flow unmounts.

No blockers found. A few things worth confirming before merge:

1. accountID source changed from currentUserPersonalDetails to session (verify)

The new flow derives owned-policy counts and the delete payload from session?.accountID:

The original used currentUserPersonalDetails.accountID throughout (and the list page still does at WorkspacesListPage.tsx:111). These are normally the same account, but it's now inconsistent between the two components. Recommend using one source for both so the page's menu config (shouldCalculateBillNewDot/wouldBlockDeletion) can never disagree with the flow's checks.

2. Pay-and-downgrade path may leave the flow mounted (verify)

When shouldCalculateBillNewDot and the bill says shouldBillWhenDowngrading, usePayAndDowngrade navigates to WORKSPACE_PAY_AND_DOWNGRADE and never calls continueDeleteWorkspace or onDismiss. DeleteWorkspaceFlow then stays mounted (with its heavy subscriptions) while the user is on that page, and won't restart for the same policyID. This roughly matches the old behavior (subscriptions were always on), but since the goal here is scoping subscriptions to the flow's lifetime, please confirm the flow unmounts cleanly after the pay-and-downgrade detour.

3. Delete spinner timing (verify)

The spinner is now !!isLoadingBill && policyIDToDelete === item.policyID (WorkspacesListPage.tsx:291) rather than a synchronously-set index. isLoadingBill only flips true after the flow mounts, its data loads, and calculateBillNewDot() runs — so there may be a brief gap between tapping Delete and the spinner appearing on a last-paid-workspace delete. Worth a quick visual check.

Nits

  • The start effect at DeleteWorkspaceFlow.tsx:135 has no dependency array and relies on a hasStartedRef guard, so it re-runs on every render (cheap, but unusual). A [isLoadingData] dep array would express the intent more clearly.
  • On the list page, the createOwnedPaidPoliciesCountsSelector subscription is redundant for re-render purposes — the page already has a full useOnyx(ONYXKEYS.COLLECTION.POLICY) subscription at WorkspacesListPage.tsx:91, so the selector doesn't reduce renders here (no action needed; just noting the perf win comes entirely from the extracted flow, not this selector).

Since this is a refactor with no automated coverage of the deletion paths, the offline + Expensify-card error path and the last-paid-workspace bill path are the highest-risk regressions to exercise manually.

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.

3 participants