Skip to content

Commit

Permalink
Refactor code and set current tab
Browse files Browse the repository at this point in the history
  • Loading branch information
mohdsayed committed Jan 31, 2025
1 parent a25aad8 commit 90a84cd
Show file tree
Hide file tree
Showing 11 changed files with 126 additions and 8 deletions.
1 change: 1 addition & 0 deletions packages/common/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ export { default as getLegendDescription } from './utils/getLegendDescription';
export { default as extractCookies } from './utils/extractCookies';
export { default as extractReportData } from './utils/extractReportData';
export { default as reshapeCookies } from './utils/reshapeCookies';
export * from './utils/sessionStorage';
export * from './worker/enums';
export * from './utils/generateReports';
export * from './cookies.types';
Expand Down
91 changes: 91 additions & 0 deletions packages/common/src/utils/sessionStorage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
/*
* Copyright 2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

export type SessionData = Record<string, unknown> | undefined;

/**
* Updates session storage for the current tab with the given items.
* The items are stored under a key format: `{tabId}-{name}-{key}`.
* @param {SessionData} items - The session data to be stored.
* @param {string} name - A namespace to distinguish different storage sets (e.g., "persistentSetting").
* @returns {Promise<SessionData>} - The updated session data.
*/
export const updateSessionStorage = async (
items: SessionData,
name: string
): Promise<SessionData> => {
const tabId = chrome.devtools.inspectedWindow.tabId;

if (!tabId) {
return {};
}

const data = (await chrome.storage.session.get()) || {};

let updatedData: SessionData = undefined;

if (items) {
// Merge new items with tab-specific keys
updatedData = {
...data,
...Object.fromEntries(
Object.entries(items).map(([key, value]) => [
`${tabId}-${name}-${key}`,
value,
])
),
};

await chrome.storage.session.set(updatedData);
}

return updatedData || data;
};

/**
* Retrieves session storage for the current tab, grouping stored data by tab ID.
* The function filters data based on the provided name (namespace).
* @param {string} name - A namespace to filter session storage keys (e.g., "persistentSetting").
* @returns {Promise<Record<string, any>>} - The session data grouped under the current tab ID.
*/
export const getSessionStorage = async (
name: string
): Promise<Record<string, any>> => {
const data = (await chrome.storage.session.get()) || {};

const groupedData: Record<string, any> = {};

Object.entries(data).forEach(([key, value]) => {
const match = key.match(new RegExp(`^(\\d+)-${name}-(.+)$`)); // Extract tab ID dynamically

if (match) {
const tabId = match[1]; // Get tab ID
const originalKey = match[2]; // Extract the actual key

if (!groupedData[tabId]) {
groupedData[tabId] = {};
}
groupedData[tabId][originalKey] = value;
} else {
// Global data (not associated with any tab)
groupedData[key] = value;
}
});

const tabId = chrome.devtools.inspectedWindow.tabId;

return groupedData[tabId];
};
23 changes: 23 additions & 0 deletions packages/design-system/src/components/tabs/useTabs/provider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import React, {
useMemo,
useState,
} from 'react';
import { getSessionStorage, updateSessionStorage } from '@google-psat/common';

/**
* Internal dependencies.
Expand All @@ -33,13 +34,35 @@ import { TabsContext } from './context';
export const TabsProvider = ({
children,
items,
name,
}: PropsWithChildren<TabsProviderProps>) => {
const [tabItems, setTabItems] = useState(items);
const [activeTab, setActiveTab] = useState(0);
const [storage, _setStorage] = useState<string[]>(
Array(items.length).fill('')
);

useEffect(() => {
(async () => {
const settings = await getSessionStorage('persistentSettingsTabs');

if (settings && settings[name]) {
setActiveTab(settings[name]);
}
})();
}, [name]);

useEffect(() => {
(async () => {
await updateSessionStorage(
{
[name]: activeTab,
},
'persistentSettingsTabs'
);
})();
}, [activeTab, name]);

useEffect(() => {
setTabItems(items);
_setStorage(Array(items.length).fill(''));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
export type TabsProviderProps = {
children: React.ReactNode;
items: TabItems;
name: string;
};

export type TabItems = Array<{
Expand Down
2 changes: 1 addition & 1 deletion packages/extension/src/view/devtools/app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import {
SidebarProvider,
} from '@google-psat/design-system';
import { I18n } from '@google-psat/i18n';
import { getSessionStorage } from '@google-psat/common';

/**
* Internal dependencies.
Expand All @@ -31,7 +32,6 @@ import TABS, { collapsedSidebarData } from './tabs';
import './app.css';
import { Layout } from './components';
import useContextInvalidated from './hooks/useContextInvalidated';
import { getSessionStorage } from '../../utils/sessionStorage';

const App: React.FC = () => {
const [sidebarData, setSidebarData] = useState(TABS);
Expand Down
6 changes: 4 additions & 2 deletions packages/extension/src/view/devtools/components/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,10 @@ import React, {
useRef,
useState,
} from 'react';
import { type CookieTableData } from '@google-psat/common';
import {
type CookieTableData,
updateSessionStorage,
} from '@google-psat/common';
import {
Sidebar,
useSidebar,
Expand All @@ -49,7 +52,6 @@ import {
useProtectedAudience,
useSettings,
} from '../stateProviders';
import { updateSessionStorage } from '../../../utils/sessionStorage';

interface LayoutProps {
setSidebarData: React.Dispatch<React.SetStateAction<SidebarItems>>;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -256,7 +256,7 @@ const ExplorableExplanation = () => {
);

return (
<TabsProvider items={tabItems}>
<TabsProvider items={tabItems} name="explorableExplanation">
<Panel
currentSiteData={currentSiteData}
setCurrentSite={_setCurrentSiteData}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ const ProtectedAudience = () => {
);

return (
<TabsProvider items={tabItems}>
<TabsProvider items={tabItems} name="protectedAudience">
<Panel />
</TabsProvider>
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ const ExplorableExplanation = () => {
);

return (
<TabsProvider items={tabItems}>
<TabsProvider items={tabItems} name="topics-ee">
<Panel
topicsTableData={topicsTableData}
setTopicsTableData={setTopicsTableData}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ const Topics = () => {
);

return (
<TabsProvider items={tabItems}>
<TabsProvider items={tabItems} name="topics">
<Panel />
</TabsProvider>
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ const RelatedWebsiteSets = () => {
);

return (
<TabsProvider items={tabItems}>
<TabsProvider items={tabItems} name="relatedWebsiteSets">
<Panel />
</TabsProvider>
);
Expand Down

0 comments on commit 90a84cd

Please sign in to comment.