From 458ee717984c3d6484fb5b5f6e1b21020af29dbc Mon Sep 17 00:00:00 2001 From: Eric Peterson Date: Tue, 5 Oct 2021 15:33:16 +0200 Subject: [PATCH] Manage via version-bridge. Signed-off-by: Eric Peterson --- .../src/analytics/AnalyticsContext.tsx | 38 ++++++++++++++----- 1 file changed, 28 insertions(+), 10 deletions(-) diff --git a/packages/core-plugin-api/src/analytics/AnalyticsContext.tsx b/packages/core-plugin-api/src/analytics/AnalyticsContext.tsx index f097fd577f..adbd9be6f3 100644 --- a/packages/core-plugin-api/src/analytics/AnalyticsContext.tsx +++ b/packages/core-plugin-api/src/analytics/AnalyticsContext.tsx @@ -14,23 +14,40 @@ * limitations under the License. */ -import React, { createContext, ReactNode, useContext } from 'react'; +import { + createVersionedContext, + createVersionedValueMap, +} from '@backstage/version-bridge'; +import React, { ReactNode, useContext } from 'react'; import { AnalyticsContextValue } from './types'; -// todo(iamEAP): Manage this using a version bridge. -const AnalyticsReactContext = createContext({ - routeRef: 'unknown', - pluginId: 'root', - extension: 'App', -}); +const AnalyticsReactContext = + createVersionedContext<{ 1: AnalyticsContextValue }>('analytics-context'); /** * A "private" (to this package) hook that enables context inheritance and a * way to read Analytics Context values at event capture-time. * @private */ -export const useAnalyticsContext = () => { - return useContext(AnalyticsReactContext); +export const useAnalyticsContext = (): AnalyticsContextValue => { + const theContext = useContext(AnalyticsReactContext); + + // Provide a default value if no value exists. + if (theContext === undefined) { + return { + routeRef: 'unknown', + pluginId: 'root', + extension: 'App', + }; + } + + // This should probably never happen, but check for it. + const theValue = theContext.atVersion(1); + if (theValue === undefined) { + throw new Error('No context found for version 1.'); + } + + return theValue; }; /** @@ -53,8 +70,9 @@ export const AnalyticsContext = ({ ...attributes, }; + const versionedCombinedValue = createVersionedValueMap({ 1: combinedValue }); return ( - + {children} );