Skip to content

Commit

Permalink
Update/rewrite use my jetpack connection hook to typescript (Automatt…
Browse files Browse the repository at this point in the history
…ic#36300)

* Update useMyJetpackConnection hook to typescript

* changelog

* Return empty object instead of null

* Update other uses of null to object
  • Loading branch information
CodeyGuyDylan authored Mar 12, 2024
1 parent 2f10669 commit b3b74e7
Show file tree
Hide file tree
Showing 23 changed files with 123 additions and 82 deletions.
4 changes: 2 additions & 2 deletions projects/packages/my-jetpack/_inc/admin.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ import {
import RedeemTokenScreen from './components/redeem-token-screen';
import NoticeContextProvider from './context/notices/noticeContext';
import './style.module.scss';
import getMyJetpackWindowState from './data/utils/get-my-jetpack-window-state';
import { getMyJetpackWindowInitialState } from './data/utils/get-my-jetpack-window-state';

/**
* Component to scroll window to top on route change.
Expand All @@ -46,7 +46,7 @@ function ScrollToTop() {

const MyJetpack = () => {
const queryClient = new QueryClient();
const { loadAddLicenseScreen } = getMyJetpackWindowState();
const { loadAddLicenseScreen } = getMyJetpackWindowInitialState();

return (
<ThemeProvider>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import React, { useCallback, useState, useMemo } from 'react';
*/
import { QUERY_LICENSES_KEY } from '../../data/constants';
import useJetpackApiQuery from '../../data/use-jetpack-api-query';
import getMyJetpackWindowState from '../../data/utils/get-my-jetpack-window-state';
import { getMyJetpackWindowInitialState } from '../../data/utils/get-my-jetpack-window-state';
import useAnalytics from '../../hooks/use-analytics';
import GoBackLink from '../go-back-link';

Expand Down Expand Up @@ -50,7 +50,7 @@ export default function AddLicenseScreen() {
[ licenses ]
);

const { siteSuffix = '', adminUrl = '' } = getMyJetpackWindowState();
const { siteSuffix = '', adminUrl = '' } = getMyJetpackWindowInitialState();

return (
<AdminPage showHeader={ false } showBackground={ false }>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ import {
} from '../../data/constants';
import useProduct from '../../data/products/use-product';
import useSimpleQuery from '../../data/use-simple-query';
import getMyJetpackWindowState from '../../data/utils/get-my-jetpack-window-state';
import { getMyJetpackWindowInitialState } from '../../data/utils/get-my-jetpack-window-state';
import useAnalytics from '../../hooks/use-analytics';
import useConnectionWatcher from '../../hooks/use-connection-watcher';
import ConnectionsSection from '../connections-section';
Expand Down Expand Up @@ -94,9 +94,9 @@ const GlobalNotice = ( { message, options } ) => {
*/
export default function MyJetpackScreen() {
useConnectionWatcher();
const { hasBeenDismissed = false } = getMyJetpackWindowState( 'welcomeBanner' );
const { showFullJetpackStatsCard = false } = getMyJetpackWindowState( 'myJetpackFlags' );
const { jetpackManage = {}, adminUrl } = getMyJetpackWindowState();
const { hasBeenDismissed = false } = getMyJetpackWindowInitialState( 'welcomeBanner' );
const { showFullJetpackStatsCard = false } = getMyJetpackWindowInitialState( 'myJetpackFlags' );
const { jetpackManage = {}, adminUrl } = getMyJetpackWindowInitialState();

const { currentNotice } = useContext( NoticeContext );
const { message, options } = currentNotice || {};
Expand All @@ -116,7 +116,7 @@ export default function MyJetpackScreen() {

const shouldShowZendeskChatWidget =
! isJwtLoading && ! isChatAvailabilityLoading && isAvailable && jwt;
const isNewUser = getMyJetpackWindowState( 'userIsNewToJetpack' ) === '1';
const isNewUser = getMyJetpackWindowInitialState( 'userIsNewToJetpack' ) === '1';

const { recordEvent } = useAnalytics();
const [ reloading, setReloading ] = useState( false );
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { __, _n } from '@wordpress/i18n';
import { useCallback } from 'react';
import { QUERY_PURCHASES_KEY, REST_API_SITE_PURCHASES_ENDPOINT } from '../../data/constants';
import useSimpleQuery from '../../data/use-simple-query';
import getMyJetpackWindowState from '../../data/utils/get-my-jetpack-window-state';
import { getMyJetpackWindowInitialState } from '../../data/utils/get-my-jetpack-window-state';
import useAnalytics from '../../hooks/use-analytics';
import useMyJetpackConnection from '../../hooks/use-my-jetpack-connection';
import useMyJetpackNavigate from '../../hooks/use-my-jetpack-navigate';
Expand Down Expand Up @@ -123,7 +123,7 @@ function PlanSectionFooter( { numberOfPurchases } ) {
);
}

const { loadAddLicenseScreen = '', adminUrl = '' } = getMyJetpackWindowState();
const { loadAddLicenseScreen = '', adminUrl = '' } = getMyJetpackWindowInitialState();

return (
<ul>
Expand Down Expand Up @@ -162,7 +162,7 @@ function PlanSectionFooter( { numberOfPurchases } ) {
* @returns {object} PlansSection React component.
*/
export default function PlansSection() {
const userIsAdmin = !! getMyJetpackWindowState( 'userIsAdmin' );
const userIsAdmin = !! getMyJetpackWindowInitialState( 'userIsAdmin' );
const {
data: purchases,
isLoading,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import {
} from '../../../data/constants';
import useProduct from '../../../data/products/use-product';
import useSimpleQuery from '../../../data/use-simple-query';
import getMyJetpackWindowState from '../../../data/utils/get-my-jetpack-window-state';
import { getMyJetpackWindowInitialState } from '../../../data/utils/get-my-jetpack-window-state';
import useAnalytics from '../../../hooks/use-analytics';
import ProductCard from '../../connected-product-card';
import { PRODUCT_STATUSES } from '../../product-card/action-button';
Expand Down Expand Up @@ -145,7 +145,7 @@ const WithBackupsValueSection = ( { admin, slug } ) => {
const lastRewindableEventTime = lastRewindableEvent?.published;
const undoBackupId = data?.undo_backup_id;
const { recordEvent } = useAnalytics();
const { siteSuffix = '' } = getMyJetpackWindowState();
const { siteSuffix = '' } = getMyJetpackWindowInitialState();

const handleUndoClick = () => {
recordEvent( 'jetpack_myjetpack_backup_card_undo_click', {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { Popover } from '@wordpress/components';
import { useViewportMatch } from '@wordpress/compose';
import { __ } from '@wordpress/i18n';
import React, { useCallback, useEffect, useState } from 'react';
import getMyJetpackWindowState from '../../../data/utils/get-my-jetpack-window-state';
import { getMyJetpackWindowInitialState } from '../../../data/utils/get-my-jetpack-window-state';
import useAnalytics from '../../../hooks/use-analytics';
import useMyJetpackConnection from '../../../hooks/use-my-jetpack-connection';
import { useBoostTooltipCopy } from './use-boost-tooltip-copy';
Expand All @@ -25,7 +25,7 @@ const BoostSpeedScore: FC = () => {
const [ isTooltipVisible, setIsTooltipVisible ] = useState( false );
const isMobileViewport = useViewportMatch( 'medium', '<' );

const { siteSuffix: siteUrl = '', latestBoostSpeedScores } = getMyJetpackWindowState();
const { siteSuffix: siteUrl = '', latestBoostSpeedScores } = getMyJetpackWindowInitialState();
const { apiRoot, apiNonce, isSiteConnected } = useMyJetpackConnection();

const getAverageSpeedScore = ( mobileScore, desktopScore ) => {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Container, Col } from '@automattic/jetpack-components';
import React from 'react';
import getMyJetpackWindowState from '../../data/utils/get-my-jetpack-window-state';
import { getMyJetpackWindowInitialState } from '../../data/utils/get-my-jetpack-window-state';
import AiCard from './ai-card';
import AntiSpamCard from './anti-spam-card';
import BackupCard from './backup-card';
Expand All @@ -20,8 +20,8 @@ import VideopressCard from './videopress-card';
* @returns {object} ProductCardsSection React component.
*/
const ProductCardsSection = () => {
const { isAtomic = false, userIsAdmin = false } = getMyJetpackWindowState();
const { showFullJetpackStatsCard = false } = getMyJetpackWindowState( 'myJetpackFlags' );
const { isAtomic = false, userIsAdmin = false } = getMyJetpackWindowInitialState();
const { showFullJetpackStatsCard = false } = getMyJetpackWindowInitialState( 'myJetpackFlags' );

const items = {
backups: BackupCard,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
QUERY_VIDEOPRESS_STATS_KEY,
} from '../../data/constants';
import useSimpleQuery from '../../data/use-simple-query';
import { getMyJetpackWindowInitialState } from '../../data/utils/get-my-jetpack-window-state';
/**
* Internal dependencies
*/
Expand Down Expand Up @@ -54,7 +55,7 @@ const useVideoPressStats = () => {
};

const VideopressCard = ( { admin } ) => {
const { videoPressStats = false } = window.myJetpackInitialState?.myJetpackFlags ?? {};
const { videoPressStats = false } = getMyJetpackWindowInitialState( 'myJetpackFlags' );
const { loading, hasError, change, currentFormatted, changePercentage } = useVideoPressStats();

if ( ! videoPressStats || hasError ) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import { Icon, check, plus } from '@wordpress/icons';
import classnames from 'classnames';
import React, { useCallback } from 'react';
import useProduct from '../../data/products/use-product';
import getMyJetpackWindowState from '../../data/utils/get-my-jetpack-window-state';
import { getMyJetpackWindowInitialState } from '../../data/utils/get-my-jetpack-window-state';
import useAnalytics from '../../hooks/use-analytics';
import { useRedirectToReferrer } from '../../hooks/use-redirect-to-referrer';
import ProductDetailButton from '../product-detail-button';
Expand Down Expand Up @@ -89,7 +89,7 @@ const ProductDetailCard = ( {
siteSuffix = '',
adminUrl = '',
myJetpackCheckoutUri = '',
} = getMyJetpackWindowState();
} = getMyJetpackWindowInitialState();

const { detail } = useProduct( slug );

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import { sprintf, __ } from '@wordpress/i18n';
import PropTypes from 'prop-types';
import { useCallback, useMemo } from 'react';
import useProduct from '../../data/products/use-product';
import getMyJetpackWindowState from '../../data/utils/get-my-jetpack-window-state';
import { getMyJetpackWindowInitialState } from '../../data/utils/get-my-jetpack-window-state';
import { useRedirectToReferrer } from '../../hooks/use-redirect-to-referrer';

/**
Expand All @@ -38,7 +38,7 @@ const ProductDetailTableColumn = ( {
tier,
trackProductButtonClick,
} ) => {
const { siteSuffix = '', myJetpackCheckoutUri = '' } = getMyJetpackWindowState();
const { siteSuffix = '', myJetpackCheckoutUri = '' } = getMyJetpackWindowInitialState();

// Extract the product details.
const {
Expand Down Expand Up @@ -220,7 +220,7 @@ const ProductDetailTable = ( {
trackProductButtonClick,
isFetching,
} ) => {
const { fileSystemWriteAccess = 'no' } = getMyJetpackWindowState();
const { fileSystemWriteAccess = 'no' } = getMyJetpackWindowInitialState();

const { detail } = useProduct( slug );
const { description, featuresByTier = [], pluginSlug, status, tiers = [], title } = detail;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import React, { useCallback, useEffect } from 'react';
*/
import useActivate from '../../data/products/use-activate';
import useProduct from '../../data/products/use-product';
import getMyJetpackWindowState from '../../data/utils/get-my-jetpack-window-state';
import { getMyJetpackWindowInitialState } from '../../data/utils/get-my-jetpack-window-state';
import useAnalytics from '../../hooks/use-analytics';
import { useGoBack } from '../../hooks/use-go-back';
import useMyJetpackNavigate from '../../hooks/use-my-jetpack-navigate';
Expand Down Expand Up @@ -67,7 +67,7 @@ export default function ProductInterstitial( {
const { isUpgradableByBundle, tiers, pricingForUi } = detail;
const { recordEvent } = useAnalytics();
const { onClickGoBack } = useGoBack( { slug } );
const { myJetpackCheckoutUri = '' } = getMyJetpackWindowState();
const { myJetpackCheckoutUri = '' } = getMyJetpackWindowInitialState();

useEffect( () => {
recordEvent( 'jetpack_myjetpack_product_interstitial_view', { product: slug } );
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { useCallback } from 'react';
import { QUERY_STATS_COUNTS_KEY, getStatsHighlightsEndpoint } from '../../data/constants';
import useProduct from '../../data/products/use-product';
import useSimpleQuery from '../../data/use-simple-query';
import getMyJetpackWindowState from '../../data/utils/get-my-jetpack-window-state';
import { getMyJetpackWindowInitialState } from '../../data/utils/get-my-jetpack-window-state';
import useAnalytics from '../../hooks/use-analytics';
import useMyJetpackConnection from '../../hooks/use-my-jetpack-connection';
import ProductCard from '../connected-product-card';
Expand All @@ -15,7 +15,7 @@ const StatsSection = () => {
const { blogID } = useMyJetpackConnection();
const { detail } = useProduct( slug );
const { status } = detail;
const isAdmin = !! getMyJetpackWindowState( 'userIsAdmin' );
const isAdmin = !! getMyJetpackWindowInitialState( 'userIsAdmin' );
const { data: statsCounts } = useSimpleQuery( {
name: QUERY_STATS_COUNTS_KEY,
query: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { useConnection } from '@automattic/jetpack-connection';
import { __ } from '@wordpress/i18n';
import { close } from '@wordpress/icons';
import { useEffect, useCallback, useState } from 'react';
import getMyJetpackWindowState from '../../data/utils/get-my-jetpack-window-state';
import { getMyJetpackWindowInitialState } from '../../data/utils/get-my-jetpack-window-state';
import useWelcomeBanner from '../../data/welcome-banner/use-welcome-banner';
import useAnalytics from '../../hooks/use-analytics';
import useMyJetpackNavigate from '../../hooks/use-my-jetpack-navigate';
Expand All @@ -16,7 +16,7 @@ import styles from './style.module.scss';
* @returns {object} The WelcomeBanner component.
*/
const WelcomeBanner = () => {
const isNewUser = getMyJetpackWindowState( 'userIsNewToJetpack' ) === '1';
const isNewUser = getMyJetpackWindowInitialState( 'userIsNewToJetpack' ) === '1';
const { recordEvent } = useAnalytics();
const { isDismissed, dismissWelcomeBanner } = useWelcomeBanner();
const { isRegistered, isUserConnected } = useConnection();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { useCallback } from 'react';
import { REST_API_SITE_PRODUCTS_ENDPOINT } from '../constants';
import { QUERY_PRODUCT_KEY } from '../constants';
import useSimpleQuery from '../use-simple-query';
import getMyJetpackWindowState from '../utils/get-my-jetpack-window-state';
import { getMyJetpackWindowInitialState } from '../utils/get-my-jetpack-window-state';
import mapObjectKeysToCamel from '../utils/to-camel';
import type { ProductCamelCase, ProductSnakeCase, WP_Error } from '../types';
import type { RefetchOptions, QueryObserverResult } from '@tanstack/react-query';
Expand All @@ -20,7 +20,7 @@ const getDiscountPricePerMonth = ( product: ProductCamelCase ) => {
};

export const useAllProducts = () => {
const { items: products } = getMyJetpackWindowState( 'products' );
const { items: products } = getMyJetpackWindowInitialState( 'products' );

return products;
};
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import restApi from '@automattic/jetpack-api';
import { useQuery } from '@tanstack/react-query';
import { useFetchingErrorNotice } from './notices/use-fetching-error-notice';
import type { UseQueryResult } from '@tanstack/react-query';
import { getMyJetpackWindowRestState } from './utils/get-my-jetpack-window-state';

/**
* Custom hook for fetching data from the Jetpack API, utilizing the react-query library for data fetching and caching.
Expand All @@ -13,7 +13,6 @@ import type { UseQueryResult } from '@tanstack/react-query';
* @param {string} params.name - The unique name for the query. This name, along with the optional `explicitKey`, forms the cache key for the query's result.
* @param {Function} params.queryFn - The function to fetch data from the API. It receives a configured instance of `restApi` and must return a promise that resolves to the data of type `T`.
* @param {string} [params.errorMessage] - Optional. A custom error message to be displayed in case the query fails. This message overrides the default error handling behavior.
* @returns {UseQueryResult<T>} The result object from the useQuery hook, containing data and state information about the query (e.g., isLoading, isError).
*/
type QueryParams< T > = {
name: string;
Expand All @@ -24,7 +23,7 @@ const useJetpackApiQuery = < T >( { name, queryFn, errorMessage }: QueryParams<
const queryResult = useQuery( {
queryKey: [ name ],
queryFn: () => {
const { apiRoot, apiNonce } = window?.myJetpackRest || {};
const { apiRoot, apiNonce } = getMyJetpackWindowRestState();
restApi.setApiRoot( apiRoot );
restApi.setApiNonce( apiNonce );
return queryFn( restApi );
Expand Down
Original file line number Diff line number Diff line change
@@ -1,17 +1,37 @@
type MyJetpackState = Window[ 'myJetpackInitialState' ];
type InitialState = Window[ 'myJetpackInitialState' ];
type RestState = Window[ 'myJetpackRest' ];
type ConnectionState = Window[ 'JP_CONNECTION_INITIAL_STATE' ];

type ReturnType< A > = A extends undefined
? MyJetpackState
: MyJetpackState[ A extends keyof MyJetpackState ? A : never ];
// Handles typing based on whether or not a key is provided. S = type of state, A = type of key
type StateReturnType< S, A > = A extends undefined ? S : S[ A extends keyof S ? A : never ];

const getMyJetpackWindowState = < A extends keyof MyJetpackState | undefined = undefined >(
export const getMyJetpackWindowInitialState = <
A extends keyof InitialState | undefined = undefined,
>(
key?: A
): ReturnType< A > => {
): StateReturnType< InitialState, A > => {
if ( ! key ) {
return window?.myJetpackInitialState as ReturnType< A >;
return window?.myJetpackInitialState as StateReturnType< InitialState, A >;
}

return ( window?.myJetpackInitialState?.[ key ] ?? null ) as ReturnType< A >;
return ( window?.myJetpackInitialState?.[ key ] ?? {} ) as StateReturnType< InitialState, A >;
};

export default getMyJetpackWindowState;
export const getMyJetpackWindowRestState = () => {
return ( window?.myJetpackRest ?? {} ) as RestState;
};

export const getMyJetpackWindowConnectionState = <
A extends keyof ConnectionState | undefined = undefined,
>(
key?: A
): StateReturnType< ConnectionState, A > => {
if ( ! key ) {
return window?.JP_CONNECTION_INITIAL_STATE as StateReturnType< ConnectionState, A >;
}

return ( window?.JP_CONNECTION_INITIAL_STATE?.[ key ] ?? {} ) as StateReturnType<
ConnectionState,
A
>;
};
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@ import {
REST_API_SITE_DISMISS_BANNER,
} from '../../data/constants';
import useSimpleMutation from '../use-simple-mutation';
import getMyJetpackWindowState from '../utils/get-my-jetpack-window-state';
import { getMyJetpackWindowInitialState } from '../utils/get-my-jetpack-window-state';

const useWelcomeBanner = () => {
const { hasBeenDismissed: welcomeBannerHasBeenDismissed } =
getMyJetpackWindowState( 'welcomeBanner' );
getMyJetpackWindowInitialState( 'welcomeBanner' );

const [ isDismissed, setIsDismissed ] = useState( welcomeBannerHasBeenDismissed );

Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import jetpackAnalytics from '@automattic/jetpack-analytics';
import { useCallback, useEffect } from 'react';
import getMyJetpackWindowState from '../../data/utils/get-my-jetpack-window-state';
import { getMyJetpackWindowInitialState } from '../../data/utils/get-my-jetpack-window-state';
import useMyJetpackConnection from '../use-my-jetpack-connection';

const useAnalytics = () => {
const { isUserConnected, connectedPlugins, userConnectionData = {} } = useMyJetpackConnection();
const { login, ID } = userConnectionData.currentUser?.wpcomUser || {};
const { myJetpackVersion = '' } = getMyJetpackWindowState();
const { myJetpackVersion = '' } = getMyJetpackWindowInitialState();

/**
* Initialize tracks with user data.
Expand Down
Loading

0 comments on commit b3b74e7

Please sign in to comment.