From fbc6bb766fc1bb6c880887acbe5ee30066855062 Mon Sep 17 00:00:00 2001 From: Rodrigo Maia Date: Thu, 18 May 2023 03:22:27 +0000 Subject: [PATCH] fix(site): maintain initial workspace list order --- .../pages/WorkspacesPage/WorkspacesPage.tsx | 48 +++++++++++++++++-- 1 file changed, 45 insertions(+), 3 deletions(-) diff --git a/site/src/pages/WorkspacesPage/WorkspacesPage.tsx b/site/src/pages/WorkspacesPage/WorkspacesPage.tsx index f69baa7d8fc20..2e10359170496 100644 --- a/site/src/pages/WorkspacesPage/WorkspacesPage.tsx +++ b/site/src/pages/WorkspacesPage/WorkspacesPage.tsx @@ -1,12 +1,13 @@ import { useFilter } from "hooks/useFilter" import { usePagination } from "hooks/usePagination" -import { FC } from "react" +import { FC, useEffect, useState } from "react" import { Helmet } from "react-helmet-async" import { workspaceFilterQuery } from "utils/filters" import { pageTitle } from "utils/page" import { useWorkspacesData, useWorkspaceUpdate } from "./data" import { WorkspacesPageView } from "./WorkspacesPageView" import { useDashboard } from "components/Dashboard/DashboardProvider" +import { Workspace } from "api/typesGenerated" const WorkspacesPage: FC = () => { const filter = useFilter(workspaceFilterQuery.me) @@ -22,8 +23,49 @@ const WorkspacesPage: FC = () => { ...pagination, ...filter, }) + const updateWorkspace = useWorkspaceUpdate(queryKey) + const [displayedWorkspaces, setDisplayedWorkspaces] = useState( + [], + ) + + useEffect(() => { + const fetchedWorkspaces = data?.workspaces || [] + if (fetchedWorkspaces) { + if (displayedWorkspaces.length === 0) { + setDisplayedWorkspaces(fetchedWorkspaces) + } else { + // Merge the fetched workspaces with the displayed onws, without changing the order of the existing items + const mergedItems = displayedWorkspaces + .map((item) => { + const fetchedItem = fetchedWorkspaces.find( + (fItem) => fItem.id === item.id, + ) + + if (!fetchedItem) { + return null + } + + // If the fetched item already exists, update its data without changing its position + return { ...item, ...fetchedItem } + }) + .filter((item) => item !== null) // Remove the removed items (null values) + + // Add new items to the beginning of the list + fetchedWorkspaces.forEach((fetchedItem) => { + if (!mergedItems.some((item) => item?.id === fetchedItem.id)) { + mergedItems.unshift(fetchedItem) + } + }) + + setDisplayedWorkspaces( + mergedItems.filter((item) => item !== null) as Workspace[], + ) + } + } + }, [data?.workspaces, displayedWorkspaces]) + return ( <> @@ -31,11 +73,11 @@ const WorkspacesPage: FC = () => {