From c324751332bf5dc9ae9c2469e269345f5567675c Mon Sep 17 00:00:00 2001 From: Stephanie Swaney Date: Thu, 7 Aug 2025 16:02:10 -0500 Subject: [PATCH 01/10] feat: add optional enrichVisit function onto VisitListener to add fields to customize chips Signed-off-by: Stephanie Swaney feat: add VisitInput which has visit before auto saved fields, used to enrich in consuming app Signed-off-by: Stephanie Swaney chore: Rename ItemCategoryContext to VisitDisplayContext fix: rename the remainder to VisitDisplayContext from ItemCategoryContext Signed-off-by: Stephanie Swaney test: Add tests for VisitListener component --- plugins/home/report-alpha.api.md | 2 +- plugins/home/report.api.md | 48 ++++++ .../home/src/components/VisitList/Context.tsx | 138 +++++++++++++++++ .../src/components/VisitList/ItemCategory.tsx | 45 +----- .../src/components/VisitList/ItemDetail.tsx | 3 + .../src/components/VisitList/VisitList.tsx | 3 + .../home/src/components/VisitList/index.ts | 9 +- .../src/components/VisitListener.test.tsx | 143 +++++++++++++++++- plugins/home/src/components/VisitListener.tsx | 50 +++++- plugins/home/src/components/index.ts | 1 + .../VisitedByType/Context.tsx | 16 +- .../VisitedByType/VisitedByType.tsx | 2 +- 12 files changed, 400 insertions(+), 60 deletions(-) create mode 100644 plugins/home/src/components/VisitList/Context.tsx diff --git a/plugins/home/report-alpha.api.md b/plugins/home/report-alpha.api.md index d2e5c22ef8..83568c0e45 100644 --- a/plugins/home/report-alpha.api.md +++ b/plugins/home/report-alpha.api.md @@ -105,7 +105,6 @@ export default _default; export const homeTranslationRef: TranslationRef< 'home', { - readonly 'starredEntities.noStarredEntitiesMessage': 'Click the star beside an entity name to add it to this list!'; readonly 'addWidgetDialog.title': 'Add new widget to dashboard'; readonly 'customHomepageButtons.clearAll': 'Clear all'; readonly 'customHomepageButtons.edit': 'Edit'; @@ -124,6 +123,7 @@ export const homeTranslationRef: TranslationRef< readonly 'quickStart.title': 'Onboarding'; readonly 'quickStart.description': 'Get started with Backstage'; readonly 'quickStart.learnMoreLinkTitle': 'Learn more'; + readonly 'starredEntities.noStarredEntitiesMessage': 'Click the star beside an entity name to add it to this list!'; readonly 'visitedByType.action.viewMore': 'View more'; readonly 'visitedByType.action.viewLess': 'View less'; readonly 'featuredDocsCard.empty.title': 'No documents to show'; diff --git a/plugins/home/report.api.md b/plugins/home/report.api.md index dd33b952ee..2f70f1a9c9 100644 --- a/plugins/home/report.api.md +++ b/plugins/home/report.api.md @@ -117,6 +117,12 @@ export type FeaturedDocsCardProps = { subLinkText?: string; }; +// @public +export type GetChipColorFunction = (visit: Visit) => string; + +// @public +export type GetLabelFunction = (visit: Visit) => string; + // @public export const HeaderWorldClock: (props: { clockConfigs: ClockConfig[]; @@ -245,6 +251,9 @@ export type ToolkitContentProps = { tools: Tool[]; }; +// @public +export const useVisitDisplay: () => VisitDisplayContextValue; + // @public export type Visit = { id: string; @@ -255,6 +264,31 @@ export type Visit = { entityRef?: string; }; +// @public +export interface VisitDisplayContextValue { + // (undocumented) + getChipColor: GetChipColorFunction; + // (undocumented) + getLabel: GetLabelFunction; +} + +// @public +export const VisitDisplayProvider: ({ + children, + getChipColor, + getLabel, +}: VisitDisplayProviderProps) => JSX_2.Element; + +// @public +export interface VisitDisplayProviderProps { + // (undocumented) + children: ReactNode; + // (undocumented) + getChipColor?: GetChipColorFunction; + // (undocumented) + getLabel?: GetLabelFunction; +} + // @public (undocumented) export type VisitedByTypeKind = 'recent' | 'top'; @@ -267,15 +301,29 @@ export type VisitedByTypeProps = { kind: VisitedByTypeKind; }; +// @public +export type VisitEnrichmentFunction = ( + visit: VisitInput, +) => Record | Promise>; + +// @public +export type VisitInput = { + name: string; + pathname: string; + entityRef?: string; +}; + // @public export const VisitListener: ({ children, toEntityRef, visitName, + enrichVisit, }: { children?: ReactNode; toEntityRef?: ({ pathname }: { pathname: string }) => string | undefined; visitName?: ({ pathname }: { pathname: string }) => string; + enrichVisit?: VisitEnrichmentFunction; }) => JSX.Element; // @public diff --git a/plugins/home/src/components/VisitList/Context.tsx b/plugins/home/src/components/VisitList/Context.tsx new file mode 100644 index 0000000000..299d88dc14 --- /dev/null +++ b/plugins/home/src/components/VisitList/Context.tsx @@ -0,0 +1,138 @@ +/* + * Copyright 2023 The Backstage Authors + * + * 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 + * + * http://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. + */ + +import { createContext, useContext, ReactNode } from 'react'; +import { CompoundEntityRef, parseEntityRef } from '@backstage/catalog-model'; +import { colorVariants } from '@backstage/theme'; +import { Visit } from '../../api/VisitsApi'; + +/** + * Type definition for the chip color function + * @public + */ +export type GetChipColorFunction = (visit: Visit) => string; + +/** + * Type definition for the label function + * @public + */ +export type GetLabelFunction = (visit: Visit) => string; + +/** + * Context value interface + * @public + */ +export interface VisitDisplayContextValue { + getChipColor: GetChipColorFunction; + getLabel: GetLabelFunction; +} + +/** + * Props for the VisitDisplayProvider + * @public + */ +export interface VisitDisplayProviderProps { + children: ReactNode; + getChipColor?: GetChipColorFunction; + getLabel?: GetLabelFunction; +} + +// Default implementations +const getColorByIndex = (index: number) => { + const variants = Object.keys(colorVariants); + const variantIndex = index % variants.length; + return colorVariants[variants[variantIndex]][0]; +}; + +const maybeEntity = (visit: Visit): CompoundEntityRef | undefined => { + try { + return parseEntityRef(visit?.entityRef ?? ''); + } catch (e) { + return undefined; + } +}; + +const defaultGetChipColor: GetChipColorFunction = (visit: Visit): string => { + const defaultColor = getColorByIndex(0); + const entity = maybeEntity(visit); + if (!entity) return defaultColor; + + // IDEA: Use or replicate useAllKinds hook thus supporting all software catalog + // registered kinds. See: + // plugins/catalog-react/src/components/EntityKindPicker/kindFilterUtils.ts + // Provide extension point to register your own color code. + const entityKinds = [ + 'component', + 'template', + 'api', + 'group', + 'user', + 'resource', + 'system', + 'domain', + 'location', + ]; + const foundIndex = entityKinds.indexOf( + entity.kind.toLocaleLowerCase('en-US'), + ); + return foundIndex === -1 ? defaultColor : getColorByIndex(foundIndex + 1); +}; + +const defaultGetLabel: GetLabelFunction = (visit: Visit): string => { + const entity = maybeEntity(visit); + return (entity?.kind ?? 'Other').toLocaleLowerCase('en-US'); +}; + +// Create the context +const VisitDisplayContext = createContext({ + getChipColor: defaultGetChipColor, + getLabel: defaultGetLabel, +}); + +/** + * Provider component for VisitDisplay customization + * @public + */ +export const VisitDisplayProvider = ({ + children, + getChipColor = defaultGetChipColor, + getLabel = defaultGetLabel, +}: VisitDisplayProviderProps) => { + const value: VisitDisplayContextValue = { + getChipColor, + getLabel, + }; + + return ( + + {children} + + ); +}; + +/** + * Hook to use the VisitDisplay context + * @public + */ +export const useVisitDisplay = (): VisitDisplayContextValue => { + const context = useContext(VisitDisplayContext); + if (!context) { + throw new Error( + 'useVisitDisplay must be used within a VisitDisplayProvider', + ); + } + return context; +}; diff --git a/plugins/home/src/components/VisitList/ItemCategory.tsx b/plugins/home/src/components/VisitList/ItemCategory.tsx index 7eaf54183d..140d9ada68 100644 --- a/plugins/home/src/components/VisitList/ItemCategory.tsx +++ b/plugins/home/src/components/VisitList/ItemCategory.tsx @@ -16,9 +16,8 @@ import Chip from '@material-ui/core/Chip'; import { makeStyles } from '@material-ui/core/styles'; -import { colorVariants } from '@backstage/theme'; import { Visit } from '../../api/VisitsApi'; -import { CompoundEntityRef, parseEntityRef } from '@backstage/catalog-model'; +import { useVisitDisplay } from './Context'; const useStyles = makeStyles(theme => ({ chip: { @@ -27,53 +26,17 @@ const useStyles = makeStyles(theme => ({ margin: 0, }, })); -const maybeEntity = (visit: Visit): CompoundEntityRef | undefined => { - try { - return parseEntityRef(visit?.entityRef ?? ''); - } catch (e) { - return undefined; - } -}; -const getColorByIndex = (index: number) => { - const variants = Object.keys(colorVariants); - const variantIndex = index % variants.length; - return colorVariants[variants[variantIndex]][0]; -}; -const getChipColor = (entity: CompoundEntityRef | undefined): string => { - const defaultColor = getColorByIndex(0); - if (!entity) return defaultColor; - - // IDEA: Use or replicate useAllKinds hook thus supporting all software catalog - // registered kinds. See: - // plugins/catalog-react/src/components/EntityKindPicker/kindFilterUtils.ts - // Provide extension point to register your own color code. - const entityKinds = [ - 'component', - 'template', - 'api', - 'group', - 'user', - 'resource', - 'system', - 'domain', - 'location', - ]; - const foundIndex = entityKinds.indexOf( - entity.kind.toLocaleLowerCase('en-US'), - ); - return foundIndex === -1 ? defaultColor : getColorByIndex(foundIndex + 1); -}; export const ItemCategory = ({ visit }: { visit: Visit }) => { const classes = useStyles(); - const entity = maybeEntity(visit); + const { getChipColor, getLabel } = useVisitDisplay(); return ( ); }; diff --git a/plugins/home/src/components/VisitList/ItemDetail.tsx b/plugins/home/src/components/VisitList/ItemDetail.tsx index 93194639cc..163e593808 100644 --- a/plugins/home/src/components/VisitList/ItemDetail.tsx +++ b/plugins/home/src/components/VisitList/ItemDetail.tsx @@ -39,6 +39,9 @@ const ItemDetailTimeAgo = ({ visit }: { visit: Visit }) => { ); }; +/** + * @internal + */ export type ItemDetailType = 'time-ago' | 'hits'; export const ItemDetail = ({ diff --git a/plugins/home/src/components/VisitList/VisitList.tsx b/plugins/home/src/components/VisitList/VisitList.tsx index 19d5a6fb88..75b3aa3291 100644 --- a/plugins/home/src/components/VisitList/VisitList.tsx +++ b/plugins/home/src/components/VisitList/VisitList.tsx @@ -24,6 +24,9 @@ import { VisitListEmpty } from './VisitListEmpty'; import { VisitListFew } from './VisitListFew'; import { VisitListSkeleton } from './VisitListSkeleton'; +/** + * @internal + */ export const VisitList = ({ detailType, visits = [], diff --git a/plugins/home/src/components/VisitList/index.ts b/plugins/home/src/components/VisitList/index.ts index 2d9513893b..d9e58fbf6d 100644 --- a/plugins/home/src/components/VisitList/index.ts +++ b/plugins/home/src/components/VisitList/index.ts @@ -14,4 +14,11 @@ * limitations under the License. */ -export { VisitList } from './VisitList'; +// Public API exports +export { VisitDisplayProvider, useVisitDisplay } from './Context'; +export type { + GetChipColorFunction, + GetLabelFunction, + VisitDisplayContextValue, + VisitDisplayProviderProps, +} from './Context'; diff --git a/plugins/home/src/components/VisitListener.test.tsx b/plugins/home/src/components/VisitListener.test.tsx index 7f7db95a9e..c9de01b45f 100644 --- a/plugins/home/src/components/VisitListener.test.tsx +++ b/plugins/home/src/components/VisitListener.test.tsx @@ -15,7 +15,7 @@ */ import { TestApiProvider, renderInTestApp } from '@backstage/test-utils'; import { Visit, visitsApiRef } from '../api'; -import { VisitListener } from './VisitListener'; +import { VisitListener, VisitEnrichmentFunction } from './VisitListener'; import { waitFor } from '@testing-library/react'; const visits: Array = [ @@ -130,4 +130,145 @@ describe('', () => { }), ); }); + + describe('requestId tests', () => { + beforeEach(() => { + // Mock requestAnimationFrame to execute immediately + global.requestAnimationFrame = jest.fn(callback => { + callback(0); + return 1; + }); + global.cancelAnimationFrame = jest.fn(); + }); + + afterEach(() => { + jest.restoreAllMocks(); + }); + + it('uses requestAnimationFrame to defer visit saving', async () => { + const pathname = '/catalog/default/component/test-component'; + + await renderInTestApp( + + + , + { routeEntries: [pathname] }, + ); + + expect(global.requestAnimationFrame).toHaveBeenCalledTimes(1); + await waitFor(() => expect(mockVisitsApi.save).toHaveBeenCalledTimes(1)); + }); + + it('saves base visit when no enrichment function is provided', async () => { + const pathname = '/catalog/default/component/test-component'; + + await renderInTestApp( + + + , + { routeEntries: [pathname] }, + ); + + await waitFor(() => + expect(mockVisitsApi.save).toHaveBeenCalledWith({ + visit: { + pathname, + entityRef: 'component:default/test-component', + name: 'test-component', + }, + }), + ); + }); + + it('enriches visit with additional data when enrichVisit function is provided', async () => { + const pathname = '/catalog/default/component/test-component'; + const enrichVisit: VisitEnrichmentFunction = jest.fn(async _visit => ({ + customProperty: 'custom-value', + category: 'test-category', + priority: 1, + })); + + await renderInTestApp( + + + , + { routeEntries: [pathname] }, + ); + + await waitFor(() => { + expect(enrichVisit).toHaveBeenCalledWith({ + pathname, + entityRef: 'component:default/test-component', + name: 'test-component', + }); + expect(mockVisitsApi.save).toHaveBeenCalledWith({ + visit: { + pathname, + entityRef: 'component:default/test-component', + name: 'test-component', + customProperty: 'custom-value', + category: 'test-category', + priority: 1, + }, + }); + }); + }); + + it('handles synchronous enrichment function', async () => { + const pathname = '/catalog/default/component/test-component'; + const enrichVisit: VisitEnrichmentFunction = jest.fn(_visit => ({ + syncProperty: 'sync-value', + })); + + await renderInTestApp( + + + , + { routeEntries: [pathname] }, + ); + + await waitFor(() => { + expect(enrichVisit).toHaveBeenCalledWith({ + pathname, + entityRef: 'component:default/test-component', + name: 'test-component', + }); + expect(mockVisitsApi.save).toHaveBeenCalledWith({ + visit: { + pathname, + entityRef: 'component:default/test-component', + name: 'test-component', + syncProperty: 'sync-value', + }, + }); + }); + }); + + it('enrichment function can override base visit properties', async () => { + const pathname = '/catalog/default/component/test-component'; + const enrichVisit: VisitEnrichmentFunction = jest.fn(async _visit => ({ + name: 'Overridden Name', + entityRef: 'overridden:ref/value', + customField: 'additional-data', + })); + + await renderInTestApp( + + + , + { routeEntries: [pathname] }, + ); + + await waitFor(() => { + expect(mockVisitsApi.save).toHaveBeenCalledWith({ + visit: { + pathname, + name: 'Overridden Name', + entityRef: 'overridden:ref/value', + customField: 'additional-data', + }, + }); + }); + }); + }); }); diff --git a/plugins/home/src/components/VisitListener.tsx b/plugins/home/src/components/VisitListener.tsx index ee4f4558c1..e7a8cf4a22 100644 --- a/plugins/home/src/components/VisitListener.tsx +++ b/plugins/home/src/components/VisitListener.tsx @@ -74,6 +74,25 @@ const getVisitName = return document.title; }; +/** + * @public + * Type definition for visit data before it's saved (without auto-generated fields) + */ +export type VisitInput = { + name: string; + pathname: string; + entityRef?: string; +}; + +/** + * @public + * Type definition for the visit enrichment function + * This allows adding custom properties to visits at save time + */ +export type VisitEnrichmentFunction = ( + visit: VisitInput, +) => Record | Promise>; + /** * @public * Component responsible for listening to location changes and calling @@ -83,29 +102,46 @@ export const VisitListener = ({ children, toEntityRef, visitName, + enrichVisit, }: { children?: ReactNode; toEntityRef?: ({ pathname }: { pathname: string }) => string | undefined; visitName?: ({ pathname }: { pathname: string }) => string; + enrichVisit?: VisitEnrichmentFunction; }): JSX.Element => { const visitsApi = useApi(visitsApiRef); const { pathname } = useLocation(); const toEntityRefImpl = toEntityRef ?? getToEntityRef(); const visitNameImpl = visitName ?? getVisitName(); + useEffect(() => { // Wait for the browser to finish with paint with the assumption react // has finished with dom reconciliation. - const requestId = requestAnimationFrame(() => { + const requestId = requestAnimationFrame(async () => { + const baseVisit = { + name: visitNameImpl({ pathname }), + pathname, + entityRef: toEntityRefImpl({ pathname }), + }; + + let visitToSave = baseVisit; + + if (enrichVisit) { + try { + const enrichedData = await enrichVisit(baseVisit); + visitToSave = { ...baseVisit, ...enrichedData }; + } catch (error) { + // If enrichment fails, save the base visit without enrichment + visitToSave = baseVisit; + } + } + visitsApi.save({ - visit: { - name: visitNameImpl({ pathname }), - pathname, - entityRef: toEntityRefImpl({ pathname }), - }, + visit: visitToSave, }); }); return () => cancelAnimationFrame(requestId); - }, [visitsApi, pathname, toEntityRefImpl, visitNameImpl]); + }, [visitsApi, pathname, toEntityRefImpl, visitNameImpl, enrichVisit]); return <>{children}; }; diff --git a/plugins/home/src/components/index.ts b/plugins/home/src/components/index.ts index a6a4148e36..90a921babc 100644 --- a/plugins/home/src/components/index.ts +++ b/plugins/home/src/components/index.ts @@ -17,3 +17,4 @@ export { HomepageCompositionRoot } from './HomepageCompositionRoot'; export * from './CustomHomepage'; export * from './VisitListener'; +export * from './VisitList'; diff --git a/plugins/home/src/homePageComponents/VisitedByType/Context.tsx b/plugins/home/src/homePageComponents/VisitedByType/Context.tsx index 572f897aee..1f3c8cc0f3 100644 --- a/plugins/home/src/homePageComponents/VisitedByType/Context.tsx +++ b/plugins/home/src/homePageComponents/VisitedByType/Context.tsx @@ -25,23 +25,23 @@ import { import { Visit } from '../../api/VisitsApi'; import { VisitedByTypeKind } from './Content'; -export type ContextValueOnly = { +export type ContextValueOnly = { collapsed: boolean; numVisitsOpen: number; numVisitsTotal: number; - visits: Array; + visits: Array; loading: boolean; kind: VisitedByTypeKind; }; -export type ContextValue = ContextValueOnly & { +export type ContextValue = ContextValueOnly & { setCollapsed: Dispatch>; setNumVisitsOpen: Dispatch>; setNumVisitsTotal: Dispatch>; - setVisits: Dispatch>>; + setVisits: Dispatch>>; setLoading: Dispatch>; setKind: Dispatch>; - setContext: Dispatch>; + setContext: Dispatch>>; }; const defaultContextValueOnly: ContextValueOnly = { @@ -79,9 +79,9 @@ const getFilteredSet = })); export const ContextProvider = ({ children }: { children: JSX.Element }) => { - const [context, setContext] = useState( - defaultContextValueOnly, - ); + const [context, setContext] = useState({ + ...defaultContextValueOnly, + }); const { setCollapsed, setNumVisitsOpen, diff --git a/plugins/home/src/homePageComponents/VisitedByType/VisitedByType.tsx b/plugins/home/src/homePageComponents/VisitedByType/VisitedByType.tsx index 5c76af57d3..7f0d7e8c94 100644 --- a/plugins/home/src/homePageComponents/VisitedByType/VisitedByType.tsx +++ b/plugins/home/src/homePageComponents/VisitedByType/VisitedByType.tsx @@ -14,7 +14,7 @@ * limitations under the License. */ -import { VisitList } from '../../components/VisitList'; +import { VisitList } from '../../components/VisitList/VisitList'; import { useContext } from './Context'; export const VisitedByType = () => { From c2e0020b978eaf43a3ee6d6478e365c48740dd6f Mon Sep 17 00:00:00 2001 From: Rajib Quayum Date: Mon, 11 Aug 2025 14:00:28 -0400 Subject: [PATCH 02/10] feat: adds transform path and can save to VisitListener, fixes and adds tests Signed-off-by: Rajib Quayum chore: update API reports --- plugins/home/report.api.md | 18 + .../src/components/VisitListener.test.tsx | 322 +++++++++++------- plugins/home/src/components/VisitListener.tsx | 75 +++- 3 files changed, 281 insertions(+), 134 deletions(-) diff --git a/plugins/home/report.api.md b/plugins/home/report.api.md index 2f70f1a9c9..3e6ff5de04 100644 --- a/plugins/home/report.api.md +++ b/plugins/home/report.api.md @@ -264,6 +264,13 @@ export type Visit = { entityRef?: string; }; +// @public +export type VisitCanSaveFunction = ({ + pathname, +}: { + pathname: string; +}) => boolean; + // @public export interface VisitDisplayContextValue { // (undocumented) @@ -319,11 +326,15 @@ export const VisitListener: ({ toEntityRef, visitName, enrichVisit, + transformPathname, + canSave, }: { children?: ReactNode; toEntityRef?: ({ pathname }: { pathname: string }) => string | undefined; visitName?: ({ pathname }: { pathname: string }) => string; enrichVisit?: VisitEnrichmentFunction; + transformPathname?: VisitTransformPathnameFunction; + canSave?: VisitCanSaveFunction; }) => JSX.Element; // @public @@ -382,6 +393,13 @@ export type VisitsWebStorageApiOptions = { errorApi: ErrorApi; }; +// @public +export type VisitTransformPathnameFunction = ({ + pathname, +}: { + pathname: string; +}) => string; + // @public export const WelcomeTitle: ({ language, diff --git a/plugins/home/src/components/VisitListener.test.tsx b/plugins/home/src/components/VisitListener.test.tsx index c9de01b45f..1661dc202c 100644 --- a/plugins/home/src/components/VisitListener.test.tsx +++ b/plugins/home/src/components/VisitListener.test.tsx @@ -49,7 +49,33 @@ const mockVisitsApi = { }; describe('', () => { - afterEach(jest.resetAllMocks); + beforeEach(() => { + jest + .spyOn(window, 'requestAnimationFrame') + .mockImplementation((cb: FrameRequestCallback): number => { + cb(0); + return 0; + }); + }); + + afterEach(() => { + jest.restoreAllMocks(); + jest.resetAllMocks(); + }); + + it('uses requestAnimationFrame to defer visit saving', async () => { + const pathname = '/catalog/default/component/test-component'; + + await renderInTestApp( + + + , + { routeEntries: [pathname] }, + ); + + expect(window.requestAnimationFrame).toHaveBeenCalledTimes(1); + await waitFor(() => expect(mockVisitsApi.save).toHaveBeenCalledTimes(1)); + }); it('registers a visit', async () => { const pathname = '/catalog/default/component/playback-order'; @@ -131,144 +157,182 @@ describe('', () => { ); }); - describe('requestId tests', () => { - beforeEach(() => { - // Mock requestAnimationFrame to execute immediately - global.requestAnimationFrame = jest.fn(callback => { - callback(0); - return 1; - }); - global.cancelAnimationFrame = jest.fn(); - }); + it('saves base visit when no enrichment function is provided', async () => { + const pathname = '/catalog/default/component/test-component'; - afterEach(() => { - jest.restoreAllMocks(); - }); + await renderInTestApp( + + + , + { routeEntries: [pathname] }, + ); - it('uses requestAnimationFrame to defer visit saving', async () => { - const pathname = '/catalog/default/component/test-component'; - - await renderInTestApp( - - - , - { routeEntries: [pathname] }, - ); - - expect(global.requestAnimationFrame).toHaveBeenCalledTimes(1); - await waitFor(() => expect(mockVisitsApi.save).toHaveBeenCalledTimes(1)); - }); - - it('saves base visit when no enrichment function is provided', async () => { - const pathname = '/catalog/default/component/test-component'; - - await renderInTestApp( - - - , - { routeEntries: [pathname] }, - ); - - await waitFor(() => - expect(mockVisitsApi.save).toHaveBeenCalledWith({ - visit: { - pathname, - entityRef: 'component:default/test-component', - name: 'test-component', - }, - }), - ); - }); - - it('enriches visit with additional data when enrichVisit function is provided', async () => { - const pathname = '/catalog/default/component/test-component'; - const enrichVisit: VisitEnrichmentFunction = jest.fn(async _visit => ({ - customProperty: 'custom-value', - category: 'test-category', - priority: 1, - })); - - await renderInTestApp( - - - , - { routeEntries: [pathname] }, - ); - - await waitFor(() => { - expect(enrichVisit).toHaveBeenCalledWith({ + await waitFor(() => + expect(mockVisitsApi.save).toHaveBeenCalledWith({ + visit: { pathname, entityRef: 'component:default/test-component', name: 'test-component', - }); - expect(mockVisitsApi.save).toHaveBeenCalledWith({ - visit: { - pathname, - entityRef: 'component:default/test-component', - name: 'test-component', - customProperty: 'custom-value', - category: 'test-category', - priority: 1, - }, - }); + }, + }), + ); + }); + + it('enriches visit with additional data when enrichVisit function is provided', async () => { + const pathname = '/catalog/default/component/test-component'; + const enrichVisit: VisitEnrichmentFunction = jest.fn(async _visit => ({ + customProperty: 'custom-value', + category: 'test-category', + priority: 1, + })); + + await renderInTestApp( + + + , + { routeEntries: [pathname] }, + ); + + await waitFor(() => { + expect(enrichVisit).toHaveBeenCalledWith({ + pathname, + entityRef: 'component:default/test-component', + name: 'test-component', }); - }); - - it('handles synchronous enrichment function', async () => { - const pathname = '/catalog/default/component/test-component'; - const enrichVisit: VisitEnrichmentFunction = jest.fn(_visit => ({ - syncProperty: 'sync-value', - })); - - await renderInTestApp( - - - , - { routeEntries: [pathname] }, - ); - - await waitFor(() => { - expect(enrichVisit).toHaveBeenCalledWith({ + expect(mockVisitsApi.save).toHaveBeenCalledWith({ + visit: { pathname, entityRef: 'component:default/test-component', name: 'test-component', - }); - expect(mockVisitsApi.save).toHaveBeenCalledWith({ - visit: { - pathname, - entityRef: 'component:default/test-component', - name: 'test-component', - syncProperty: 'sync-value', - }, - }); - }); - }); - - it('enrichment function can override base visit properties', async () => { - const pathname = '/catalog/default/component/test-component'; - const enrichVisit: VisitEnrichmentFunction = jest.fn(async _visit => ({ - name: 'Overridden Name', - entityRef: 'overridden:ref/value', - customField: 'additional-data', - })); - - await renderInTestApp( - - - , - { routeEntries: [pathname] }, - ); - - await waitFor(() => { - expect(mockVisitsApi.save).toHaveBeenCalledWith({ - visit: { - pathname, - name: 'Overridden Name', - entityRef: 'overridden:ref/value', - customField: 'additional-data', - }, - }); + customProperty: 'custom-value', + category: 'test-category', + priority: 1, + }, }); }); }); + + it('handles synchronous enrichment function', async () => { + const pathname = '/catalog/default/component/test-component'; + const enrichVisit: VisitEnrichmentFunction = jest.fn(_visit => ({ + syncProperty: 'sync-value', + })); + + await renderInTestApp( + + + , + { routeEntries: [pathname] }, + ); + + await waitFor(() => { + expect(enrichVisit).toHaveBeenCalledWith({ + pathname, + entityRef: 'component:default/test-component', + name: 'test-component', + }); + expect(mockVisitsApi.save).toHaveBeenCalledWith({ + visit: { + pathname, + entityRef: 'component:default/test-component', + name: 'test-component', + syncProperty: 'sync-value', + }, + }); + }); + }); + + it('enrichment function can override base visit properties', async () => { + const pathname = '/catalog/default/component/test-component'; + const enrichVisit: VisitEnrichmentFunction = jest.fn(async _visit => ({ + name: 'Overridden Name', + entityRef: 'overridden:ref/value', + customField: 'additional-data', + })); + + await renderInTestApp( + + + , + { routeEntries: [pathname] }, + ); + + await waitFor(() => { + expect(mockVisitsApi.save).toHaveBeenCalledWith({ + visit: { + pathname, + name: 'Overridden Name', + entityRef: 'overridden:ref/value', + customField: 'additional-data', + }, + }); + }); + }); + + it('is able to override transformPathname and change the pathname', async () => { + const pathname = '/catalog/default/component/playback-order-2/sub-path'; + + const transformPathnameOverride = ({ + pathname: mypathname, + }: { + pathname: string; + }) => mypathname.replace('/sub-path', ''); + + await renderInTestApp( + + + , + { routeEntries: [pathname] }, + ); + + await waitFor(() => + expect(mockVisitsApi.save).toHaveBeenCalledWith({ + visit: { + pathname: '/catalog/default/component/playback-order-2', + entityRef: 'component:default/playback-order-2', + name: 'playback-order-2', + }, + }), + ); + }); + + it('is able to override canSave and save under set conditions', async () => { + const pathname = '/catalog'; + + const canSaveOverride = ({ pathname: path }: { pathname: string }) => + path === '/catalog'; + + await renderInTestApp( + + + , + { routeEntries: [pathname] }, + ); + + await waitFor(() => + expect(mockVisitsApi.save).toHaveBeenCalledWith({ + visit: { + pathname, + entityRef: undefined, + name: 'catalog', + }, + }), + ); + }); + + it('is able to override canSave and not save under set conditions', async () => { + const pathname = '/catalog'; + + const canSaveOverride = ({ pathname: path }: { pathname: string }) => + path !== '/catalog'; + + await renderInTestApp( + + + , + { routeEntries: [pathname] }, + ); + + await waitFor(() => expect(mockVisitsApi.save).not.toHaveBeenCalled()); + }); }); diff --git a/plugins/home/src/components/VisitListener.tsx b/plugins/home/src/components/VisitListener.tsx index e7a8cf4a22..534e6805b2 100644 --- a/plugins/home/src/components/VisitListener.tsx +++ b/plugins/home/src/components/VisitListener.tsx @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import { ReactNode, useEffect } from 'react'; +import { ReactNode, useEffect, useRef } from 'react'; import { useLocation } from 'react-router-dom'; @@ -93,6 +93,48 @@ export type VisitEnrichmentFunction = ( visit: VisitInput, ) => Record | Promise>; +/** + * @public + * Type definition for the transform pathname function + * This allows transforming the pathname before it is considered for any other processing + */ +export type VisitTransformPathnameFunction = ({ + pathname, +}: { + pathname: string; +}) => string; + +/** + * @internal + * Default implementation of visit pathname transform function + */ +const getTransformPathname = + (): VisitTransformPathnameFunction => + ({ pathname }: { pathname: string }): string => { + return pathname; + }; + +/** + * @public + * Type definition for the can save function + * This allows checking whether a visit can be saved + */ +export type VisitCanSaveFunction = ({ + pathname, +}: { + pathname: string; +}) => boolean; + +/** + * @internal + * Default implementation of visit can save function + */ +const getCanSave = + (): VisitCanSaveFunction => + (_: { pathname: string }): boolean => { + return true; + }; + /** * @public * Component responsible for listening to location changes and calling @@ -103,25 +145,40 @@ export const VisitListener = ({ toEntityRef, visitName, enrichVisit, + transformPathname, + canSave, }: { children?: ReactNode; toEntityRef?: ({ pathname }: { pathname: string }) => string | undefined; visitName?: ({ pathname }: { pathname: string }) => string; enrichVisit?: VisitEnrichmentFunction; + transformPathname?: VisitTransformPathnameFunction; + canSave?: VisitCanSaveFunction; }): JSX.Element => { + const previousVisitPathname = useRef(''); const visitsApi = useApi(visitsApiRef); const { pathname } = useLocation(); const toEntityRefImpl = toEntityRef ?? getToEntityRef(); const visitNameImpl = visitName ?? getVisitName(); + const transformPathnameImpl = transformPathname ?? getTransformPathname(); + const canSaveImpl = canSave ?? getCanSave(); useEffect(() => { + const visitPathname = transformPathnameImpl({ pathname }); + if (previousVisitPathname.current === visitPathname) { + return () => {}; + } + previousVisitPathname.current = visitPathname; + if (!canSaveImpl({ pathname: visitPathname })) { + return () => {}; + } // Wait for the browser to finish with paint with the assumption react // has finished with dom reconciliation. const requestId = requestAnimationFrame(async () => { const baseVisit = { - name: visitNameImpl({ pathname }), - pathname, - entityRef: toEntityRefImpl({ pathname }), + name: visitNameImpl({ pathname: visitPathname }), + pathname: visitPathname, + entityRef: toEntityRefImpl({ pathname: visitPathname }), }; let visitToSave = baseVisit; @@ -141,7 +198,15 @@ export const VisitListener = ({ }); }); return () => cancelAnimationFrame(requestId); - }, [visitsApi, pathname, toEntityRefImpl, visitNameImpl, enrichVisit]); + }, [ + visitsApi, + pathname, + toEntityRefImpl, + visitNameImpl, + enrichVisit, + transformPathnameImpl, + canSaveImpl, + ]); return <>{children}; }; From 2ac5d29bf8c83f1932853085c5634cdb314be783 Mon Sep 17 00:00:00 2001 From: Stephanie Swaney Date: Thu, 14 Aug 2025 09:22:13 -0500 Subject: [PATCH 03/10] chore: add changeset Signed-off-by: Stephanie Swaney --- .changeset/eighty-mails-leave.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .changeset/eighty-mails-leave.md diff --git a/.changeset/eighty-mails-leave.md b/.changeset/eighty-mails-leave.md new file mode 100644 index 0000000000..4924b73056 --- /dev/null +++ b/.changeset/eighty-mails-leave.md @@ -0,0 +1,5 @@ +--- +'@backstage/plugin-home': patch +--- + +Allow customization of VisitList with optional enrichVisit, transformPathname, canSave functions along with VisitDisplayProvider for colors, labels From a4fc27f92518351d63421751fd9981a227e0b871 Mon Sep 17 00:00:00 2001 From: Stephanie Swaney Date: Thu, 14 Aug 2025 13:56:23 -0500 Subject: [PATCH 04/10] docs: add info to home plugin readme on how to customize VisitList Signed-off-by: Stephanie Swaney --- plugins/home/README.md | 91 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 91 insertions(+) diff --git a/plugins/home/README.md b/plugins/home/README.md index 3498d6700f..c62a09c0b4 100644 --- a/plugins/home/README.md +++ b/plugins/home/README.md @@ -356,6 +356,97 @@ home: In order to validate the config you can use `backstage/cli config:check` +### Customizing the VisitList + +If you want more control over the recent and top visited lists, you can write your own functions to transform the path names and determine which visits to save. Pass them to the `VisitListener` with `transformPathname` and `canSave`. + +```tsx + +``` + +You can also add the `enrichVisit` function to put additional values on each `Visit`. The values could later be used to customize the chips in the `VisitList`. For example, you could add the entity `type` on the `Visit` so that `type` is used for labels instead of `kind`. + +```tsx +import { VisitListener, VisitInput } from '@backstage/plugin-home'; +import { CatalogApi, catalogApiRef } from '@backstage/plugin-catalog-react'; + +type EnrichedVisit = VisitInput & { + type?: string; +}; + +const createEnrichVisit = + (catalogApi: CatalogApi) => + async (visit: VisitInput): Promise => { + if (!visit.entityRef) { + return visit; + } + try { + const entity = await catalogApi.getEntityByRef(visit.entityRef); + const type = entity?.spec?.type?.toString(); + return { ...visit, type }; + } catch (error) { + return visit; + } + }; +// This example requires its own component in order to use hook to look up entity in catalog +const AppVisitListener = ({ children }: { children: React.ReactNode }) => { + const catalogApi = useApi(catalogApiRef); + const enrichVisit = createEnrichVisit(catalogApi); + + return ( + <> + + {children} + + ); +}; +``` + +To provide your own chip colors and/or labels for the recent and top visited lists, wrap the components in `VisitDisplayProvider` with `getChipColor` and `getChipLabel` functions. The colors provided will be used instead of the hard coded [colorVariants](https://github.com/backstage/backstage/blob/2da352043425bcab4c4422e4d2820c26c0a83382/packages/theme/src/base/pageTheme.ts#L46) provided via `@backstage/theme`. + +```tsx +import { + CustomHomepageGrid, + HomePageTopVisited, + HomePageRecentlyVisited, + VisitDisplayProvider, +} from '@backstage/plugin-home'; + +const getChipColor = (visit: any) => { + const type = visit.type; + switch (type) { + case 'application': + return '#b39ddb'; + case 'service': + return '#90caf9'; + case 'account': + return '#a5d6a7'; + case 'suite': + return '#fff59d'; + default: + return '#ef9a9a'; + } +}; + +const getChipLabel = (visit?: any) => { + return visit?.type ? visit.type : 'Other'; +}; + +export default function HomePage() { + return ( + + + + + + + ); +} +``` + ## Contributing ### Homepage Components From 446415d052957dce880c967c326ba19591f6fb0d Mon Sep 17 00:00:00 2001 From: Madhav Peri Date: Thu, 14 Aug 2025 15:13:38 -0500 Subject: [PATCH 05/10] chore: Add transformPathname and canSave functions documentation Signed-off-by: Madhav Peri --- plugins/home/README.md | 41 ++++++++++++++++++++++++++++++++++++++--- 1 file changed, 38 insertions(+), 3 deletions(-) diff --git a/plugins/home/README.md b/plugins/home/README.md index c62a09c0b4..0747d439e0 100644 --- a/plugins/home/README.md +++ b/plugins/home/README.md @@ -132,7 +132,7 @@ export const RandomJokeHomePageComponent = homePlugin.provide( ); ``` -These settings can also be defined for components that use `createReactExtension` instead `createCardExtension` by using +These settings can also be defined for components that use `createReactExtension` instead of `createCardExtension` by using the data property: ```tsx @@ -367,6 +367,41 @@ If you want more control over the recent and top visited lists, you can write yo /> ``` +#### Transform Pathname Function + +You can provide a `transformPathname` function to transform the pathname before it's processed for visit tracking. This is useful for normalizing URLs or removing query parameters: + +```tsx +import { + VisitListener, + VisitTransformPathnameFunction, +} from '@backstage/plugin-home'; + +const transformPathname: VisitTransformPathnameFunction = ({ pathname }) => { + // Remove query parameters and hash fragments + return pathname.split('?')[0].split('#')[0]; +}; + +; +``` + +#### Can Save Function + +You can provide a `canSave` function to determine which visits should be tracked and saved. This allows you to filter out certain pages or paths: + +```tsx +import { VisitListener, VisitCanSaveFunction } from '@backstage/plugin-home'; + +const canSave: VisitCanSaveFunction = ({ pathname }) => { + // Don't save visits to admin or settings pages + return !pathname.startsWith('/admin') && !pathname.startsWith('/settings'); +}; + +; +``` + +#### Visit Enrichment + You can also add the `enrichVisit` function to put additional values on each `Visit`. The values could later be used to customize the chips in the `VisitList`. For example, you could add the entity `type` on the `Visit` so that `type` is used for labels instead of `kind`. ```tsx @@ -451,9 +486,9 @@ export default function HomePage() { ### Homepage Components -We believe that people have great ideas for what makes a useful Home Page, and we want to make it easy for every to benefit from the effort you put in to create something cool for the Home Page. Therefore, a great way of contributing is by simply creating more Home Page Components, than can then be used by everyone when composing their own Home Page. If they are tightly coupled to an existing plugin, it is recommended to allow them to live within that plugin, for convenience and to limit complex dependencies. On the other hand, if there's no clear plugin that the component is based on, it's also fine to contribute them into the [home plugin](/plugins/home/src/homePageComponents) +We believe that people have great ideas for what makes a useful Home Page, and we want to make it easy for everyone to benefit from the effort you put in to create something cool for the Home Page. Therefore, a great way of contributing is by simply creating more Home Page Components that can then be used by everyone when composing their own Home Page. If they are tightly coupled to an existing plugin, it is recommended to allow them to live within that plugin, for convenience and to limit complex dependencies. On the other hand, if there's no clear plugin that the component is based on, it's also fine to contribute them into the [home plugin](/plugins/home/src/homePageComponents) -Additionally, the API is at a very early state, so contributing with additional use cases may expose weaknesses in the current solution that we may iterate on, to provide more flexibility and ease of use for those who wish to develop components for the Home Page. +Additionally, the API is at a very early state, so contributing additional use cases may expose weaknesses in the current solution that we may iterate on to provide more flexibility and ease of use for those who wish to develop components for the Home Page. ### Homepage Templates From 2668aa6e2b5df68142d7a2c0863b247565ff6a37 Mon Sep 17 00:00:00 2001 From: Madhav Peri Date: Thu, 14 Aug 2025 16:05:35 -0500 Subject: [PATCH 06/10] docs: Edit titles and remove code block Signed-off-by: Madhav Peri --- plugins/home/README.md | 17 ++++++----------- 1 file changed, 6 insertions(+), 11 deletions(-) diff --git a/plugins/home/README.md b/plugins/home/README.md index 0747d439e0..40d200380f 100644 --- a/plugins/home/README.md +++ b/plugins/home/README.md @@ -358,18 +358,11 @@ In order to validate the config you can use `backstage/cli config:check` ### Customizing the VisitList -If you want more control over the recent and top visited lists, you can write your own functions to transform the path names and determine which visits to save. Pass them to the `VisitListener` with `transformPathname` and `canSave`. - -```tsx - -``` +If you want more control over the recent and top visited lists, you can write your own functions to transform the pathnames and determine which visits to save. Pass them to the `VisitListener` with `transformPathname` and `canSave`. #### Transform Pathname Function -You can provide a `transformPathname` function to transform the pathname before it's processed for visit tracking. This is useful for normalizing URLs or removing query parameters: +Provide a `transformPathname` function to transform the pathname before it's processed for visit tracking. This is useful for normalizing URLs or removing query parameters: ```tsx import { @@ -387,7 +380,7 @@ const transformPathname: VisitTransformPathnameFunction = ({ pathname }) => { #### Can Save Function -You can provide a `canSave` function to determine which visits should be tracked and saved. This allows you to filter out certain pages or paths: +Provide a `canSave` function to determine which visits should be tracked and saved. This allows you to filter out certain pages or paths: ```tsx import { VisitListener, VisitCanSaveFunction } from '@backstage/plugin-home'; @@ -400,7 +393,7 @@ const canSave: VisitCanSaveFunction = ({ pathname }) => { ; ``` -#### Visit Enrichment +#### Enrich Visit Function You can also add the `enrichVisit` function to put additional values on each `Visit`. The values could later be used to customize the chips in the `VisitList`. For example, you could add the entity `type` on the `Visit` so that `type` is used for labels instead of `kind`. @@ -440,6 +433,8 @@ const AppVisitListener = ({ children }: { children: React.ReactNode }) => { }; ``` +#### Custom Chip Colors and Labels + To provide your own chip colors and/or labels for the recent and top visited lists, wrap the components in `VisitDisplayProvider` with `getChipColor` and `getChipLabel` functions. The colors provided will be used instead of the hard coded [colorVariants](https://github.com/backstage/backstage/blob/2da352043425bcab4c4422e4d2820c26c0a83382/packages/theme/src/base/pageTheme.ts#L46) provided via `@backstage/theme`. ```tsx From 5d5f3b71ccb6c708c087e4a79835d48c1c440454 Mon Sep 17 00:00:00 2001 From: Stephanie Swaney Date: Fri, 15 Aug 2025 11:48:02 -0500 Subject: [PATCH 07/10] docs: summarize whole section vs first two headings Signed-off-by: Stephanie Swaney docs: remove line, can read rest to get the functions Signed-off-by: Stephanie Swaney --- plugins/home/README.md | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/plugins/home/README.md b/plugins/home/README.md index 40d200380f..92ad82424f 100644 --- a/plugins/home/README.md +++ b/plugins/home/README.md @@ -358,11 +358,11 @@ In order to validate the config you can use `backstage/cli config:check` ### Customizing the VisitList -If you want more control over the recent and top visited lists, you can write your own functions to transform the pathnames and determine which visits to save. Pass them to the `VisitListener` with `transformPathname` and `canSave`. +If you want more control over the recent and top visited lists, you can write your own functions to transform the pathnames and determine which visits to save. You can also enrich each visit with other fields and customize the chip colors/labels in the visit lists. #### Transform Pathname Function -Provide a `transformPathname` function to transform the pathname before it's processed for visit tracking. This is useful for normalizing URLs or removing query parameters: +Provide a `transformPathname` function to transform the pathname before it's processed for visit tracking. This can be used for transforming the pathname for the visit (before any other consideration). As an example, you can treat multiple sub-path visits to be counted as a singular path, e.g. `/entity-path/sub1` , `/entity-path/sub-2`, `/entity-path/sub-2/sub-sub-2` can all be mapped to `/entity-path` so visits to any of those routes are all counted as the same. ```tsx import { @@ -371,8 +371,12 @@ import { } from '@backstage/plugin-home'; const transformPathname: VisitTransformPathnameFunction = ({ pathname }) => { - // Remove query parameters and hash fragments - return pathname.split('?')[0].split('#')[0]; + const pathnameParts = pathname.split('/').filter(part => part !== ''); + const rootPathFromPathname = pathnameParts[0] ?? ''; + if (rootPathFromPathname === 'catalog' && pathnameParts.length >= 4) { + return `/${pathnameParts.slice(0, 4).join('/')}`; + } + return pathname; }; ; @@ -380,7 +384,7 @@ const transformPathname: VisitTransformPathnameFunction = ({ pathname }) => { #### Can Save Function -Provide a `canSave` function to determine which visits should be tracked and saved. This allows you to filter out certain pages or paths: +Provide a `canSave` function to determine which visits should be tracked and saved. This allows you to conditionally save visits to the list: ```tsx import { VisitListener, VisitCanSaveFunction } from '@backstage/plugin-home'; From 786e37bb91e0d97afceef82e08578851df3ee9b0 Mon Sep 17 00:00:00 2001 From: Stephanie Swaney Date: Fri, 15 Aug 2025 17:15:10 -0500 Subject: [PATCH 08/10] chore: weird change required for alpha docs Signed-off-by: Stephanie Swaney --- plugins/home/report-alpha.api.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugins/home/report-alpha.api.md b/plugins/home/report-alpha.api.md index 83568c0e45..d2e5c22ef8 100644 --- a/plugins/home/report-alpha.api.md +++ b/plugins/home/report-alpha.api.md @@ -105,6 +105,7 @@ export default _default; export const homeTranslationRef: TranslationRef< 'home', { + readonly 'starredEntities.noStarredEntitiesMessage': 'Click the star beside an entity name to add it to this list!'; readonly 'addWidgetDialog.title': 'Add new widget to dashboard'; readonly 'customHomepageButtons.clearAll': 'Clear all'; readonly 'customHomepageButtons.edit': 'Edit'; @@ -123,7 +124,6 @@ export const homeTranslationRef: TranslationRef< readonly 'quickStart.title': 'Onboarding'; readonly 'quickStart.description': 'Get started with Backstage'; readonly 'quickStart.learnMoreLinkTitle': 'Learn more'; - readonly 'starredEntities.noStarredEntitiesMessage': 'Click the star beside an entity name to add it to this list!'; readonly 'visitedByType.action.viewMore': 'View more'; readonly 'visitedByType.action.viewLess': 'View less'; readonly 'featuredDocsCard.empty.title': 'No documents to show'; From 30f4b44c7384886eec9e7203e12b3a9de52b058d Mon Sep 17 00:00:00 2001 From: Stephanie Swaney Date: Wed, 17 Sep 2025 20:55:21 -0500 Subject: [PATCH 09/10] feat: move new functions from VisitListener to VisitsStorageApi Signed-off-by: Stephanie Swaney --- .changeset/eighty-mails-leave.md | 2 +- plugins/home/README.md | 93 ++++++-- plugins/home/report-alpha.api.md | 2 +- plugins/home/report.api.md | 38 ++-- plugins/home/src/api/VisitsApi.ts | 18 ++ plugins/home/src/api/VisitsStorageApi.test.ts | 198 +++++++++++++++++ plugins/home/src/api/VisitsStorageApi.ts | 97 +++++++- plugins/home/src/api/index.ts | 1 + .../src/components/VisitListener.test.tsx | 209 +----------------- plugins/home/src/components/VisitListener.tsx | 117 +--------- 10 files changed, 403 insertions(+), 372 deletions(-) diff --git a/.changeset/eighty-mails-leave.md b/.changeset/eighty-mails-leave.md index 4924b73056..3c6ec5ab8f 100644 --- a/.changeset/eighty-mails-leave.md +++ b/.changeset/eighty-mails-leave.md @@ -2,4 +2,4 @@ '@backstage/plugin-home': patch --- -Allow customization of VisitList with optional enrichVisit, transformPathname, canSave functions along with VisitDisplayProvider for colors, labels +Allow customization of VisitList by adding optional enrichVisit, transformPathname, canSave functions to VisitsStorageApi, along with VisitDisplayProvider for colors, labels diff --git a/plugins/home/README.md b/plugins/home/README.md index 92ad82424f..b08e785403 100644 --- a/plugins/home/README.md +++ b/plugins/home/README.md @@ -366,11 +366,14 @@ Provide a `transformPathname` function to transform the pathname before it's pro ```tsx import { - VisitListener, - VisitTransformPathnameFunction, -} from '@backstage/plugin-home'; + AnyApiFactory, + createApiFactory, + identityApiRef, + storageApiRef, +} from '@backstage/core-plugin-api'; +import { VisitsStorageApi } from '@backstage/plugin-home'; -const transformPathname: VisitTransformPathnameFunction = ({ pathname }) => { +const transformPathname = (pathname: string) => { const pathnameParts = pathname.split('/').filter(part => part !== ''); const rootPathFromPathname = pathnameParts[0] ?? ''; if (rootPathFromPathname === 'catalog' && pathnameParts.length >= 4) { @@ -379,7 +382,21 @@ const transformPathname: VisitTransformPathnameFunction = ({ pathname }) => { return pathname; }; -; +export const apis: AnyApiFactory[] = [ + createApiFactory({ + api: visitsApiRef, + deps: { + storageApi: storageApiRef, + identityApi: identityApiRef, + }, + factory: ({ storageApi, identityApi }) => + VisitsStorageApi.create({ + storageApi, + identityApi, + transformPathname, + }), + }), +]; ``` #### Can Save Function @@ -387,14 +404,37 @@ const transformPathname: VisitTransformPathnameFunction = ({ pathname }) => { Provide a `canSave` function to determine which visits should be tracked and saved. This allows you to conditionally save visits to the list: ```tsx -import { VisitListener, VisitCanSaveFunction } from '@backstage/plugin-home'; +import { + AnyApiFactory, + createApiFactory, + identityApiRef, + storageApiRef, +} from '@backstage/core-plugin-api'; +import { VisitInput, VisitsStorageApi } from '@backstage/plugin-home'; -const canSave: VisitCanSaveFunction = ({ pathname }) => { +const canSave = (visit: VisitInput) => { // Don't save visits to admin or settings pages - return !pathname.startsWith('/admin') && !pathname.startsWith('/settings'); + return ( + !visit.pathname.startsWith('/admin') && + !visit.pathname.startsWith('/settings') + ); }; -; +export const apis: AnyApiFactory[] = [ + createApiFactory({ + api: visitsApiRef, + deps: { + storageApi: storageApiRef, + identityApi: identityApiRef, + }, + factory: ({ storageApi, identityApi }) => + VisitsStorageApi.create({ + storageApi, + identityApi, + canSave, + }), + }), +]; ``` #### Enrich Visit Function @@ -402,8 +442,14 @@ const canSave: VisitCanSaveFunction = ({ pathname }) => { You can also add the `enrichVisit` function to put additional values on each `Visit`. The values could later be used to customize the chips in the `VisitList`. For example, you could add the entity `type` on the `Visit` so that `type` is used for labels instead of `kind`. ```tsx -import { VisitListener, VisitInput } from '@backstage/plugin-home'; +import { + AnyApiFactory, + createApiFactory, + identityApiRef, + storageApiRef, +} from '@backstage/core-plugin-api'; import { CatalogApi, catalogApiRef } from '@backstage/plugin-catalog-react'; +import { VisitsStorageApi } from '@backstage/plugin-home'; type EnrichedVisit = VisitInput & { type?: string; @@ -423,18 +469,23 @@ const createEnrichVisit = return visit; } }; -// This example requires its own component in order to use hook to look up entity in catalog -const AppVisitListener = ({ children }: { children: React.ReactNode }) => { - const catalogApi = useApi(catalogApiRef); - const enrichVisit = createEnrichVisit(catalogApi); - return ( - <> - - {children} - - ); -}; +export const apis: AnyApiFactory[] = [ + createApiFactory({ + api: visitsApiRef, + deps: { + storageApi: storageApiRef, + identityApi: identityApiRef, + catalogApi: catalogApiRef, + }, + factory: ({ storageApi, identityApi, catalogApi }) => + VisitsStorageApi.create({ + storageApi, + identityApi, + enrichVisit: createEnrichVisit(catalogApi), + }), + }), +]; ``` #### Custom Chip Colors and Labels diff --git a/plugins/home/report-alpha.api.md b/plugins/home/report-alpha.api.md index d2e5c22ef8..83568c0e45 100644 --- a/plugins/home/report-alpha.api.md +++ b/plugins/home/report-alpha.api.md @@ -105,7 +105,6 @@ export default _default; export const homeTranslationRef: TranslationRef< 'home', { - readonly 'starredEntities.noStarredEntitiesMessage': 'Click the star beside an entity name to add it to this list!'; readonly 'addWidgetDialog.title': 'Add new widget to dashboard'; readonly 'customHomepageButtons.clearAll': 'Clear all'; readonly 'customHomepageButtons.edit': 'Edit'; @@ -124,6 +123,7 @@ export const homeTranslationRef: TranslationRef< readonly 'quickStart.title': 'Onboarding'; readonly 'quickStart.description': 'Get started with Backstage'; readonly 'quickStart.learnMoreLinkTitle': 'Learn more'; + readonly 'starredEntities.noStarredEntitiesMessage': 'Click the star beside an entity name to add it to this list!'; readonly 'visitedByType.action.viewMore': 'View more'; readonly 'visitedByType.action.viewLess': 'View less'; readonly 'featuredDocsCard.empty.title': 'No documents to show'; diff --git a/plugins/home/report.api.md b/plugins/home/report.api.md index 3e6ff5de04..7036e9d6d2 100644 --- a/plugins/home/report.api.md +++ b/plugins/home/report.api.md @@ -264,13 +264,6 @@ export type Visit = { entityRef?: string; }; -// @public -export type VisitCanSaveFunction = ({ - pathname, -}: { - pathname: string; -}) => boolean; - // @public export interface VisitDisplayContextValue { // (undocumented) @@ -308,11 +301,6 @@ export type VisitedByTypeProps = { kind: VisitedByTypeKind; }; -// @public -export type VisitEnrichmentFunction = ( - visit: VisitInput, -) => Record | Promise>; - // @public export type VisitInput = { name: string; @@ -325,22 +313,21 @@ export const VisitListener: ({ children, toEntityRef, visitName, - enrichVisit, - transformPathname, - canSave, }: { children?: ReactNode; toEntityRef?: ({ pathname }: { pathname: string }) => string | undefined; visitName?: ({ pathname }: { pathname: string }) => string; - enrichVisit?: VisitEnrichmentFunction; - transformPathname?: VisitTransformPathnameFunction; - canSave?: VisitCanSaveFunction; }) => JSX.Element; // @public export interface VisitsApi { + canSave?(visit: VisitInput): boolean | Promise; + enrichVisit?( + visit: VisitInput, + ): Promise> | Record; list(queryParams?: VisitsApiQueryParams): Promise; save(saveParams: VisitsApiSaveParams): Promise; + transformPathname?(pathname: string): string; } // @public @@ -367,10 +354,13 @@ export type VisitsApiSaveParams = { // @public export class VisitsStorageApi implements VisitsApi { + canSave(visit: VisitInput): Promise; // (undocumented) static create(options: VisitsStorageApiOptions): VisitsStorageApi; + enrichVisit(visit: VisitInput): Promise>; list(queryParams?: VisitsApiQueryParams): Promise; save(saveParams: VisitsApiSaveParams): Promise; + transformPathname(pathname: string): string; } // @public (undocumented) @@ -378,6 +368,11 @@ export type VisitsStorageApiOptions = { limit?: number; storageApi: StorageApi; identityApi: IdentityApi; + transformPathname?: (pathname: string) => string; + canSave?: (visit: VisitInput) => boolean | Promise; + enrichVisit?: ( + visit: VisitInput, + ) => Promise> | Record; }; // @public @@ -393,13 +388,6 @@ export type VisitsWebStorageApiOptions = { errorApi: ErrorApi; }; -// @public -export type VisitTransformPathnameFunction = ({ - pathname, -}: { - pathname: string; -}) => string; - // @public export const WelcomeTitle: ({ language, diff --git a/plugins/home/src/api/VisitsApi.ts b/plugins/home/src/api/VisitsApi.ts index 610f4be483..5cbd65fab3 100644 --- a/plugins/home/src/api/VisitsApi.ts +++ b/plugins/home/src/api/VisitsApi.ts @@ -15,6 +15,7 @@ */ import { createApiRef } from '@backstage/core-plugin-api'; +import { VisitInput } from './VisitsStorageApi'; /** * @public @@ -126,6 +127,23 @@ export interface VisitsApi { * @param queryParams - optional search query params. */ list(queryParams?: VisitsApiQueryParams): Promise; + /** + * Transform the pathname before it is considered for any other processing. + * @param pathname - the original pathname + */ + transformPathname?(pathname: string): string; + /** + * Determine whether a visit should be saved. + * @param visit - page visit data + */ + canSave?(visit: VisitInput): boolean | Promise; + /** + * Add additional data to the visit before saving. + * @param visit - page visit data + */ + enrichVisit?( + visit: VisitInput, + ): Promise> | Record; } /** @public */ diff --git a/plugins/home/src/api/VisitsStorageApi.test.ts b/plugins/home/src/api/VisitsStorageApi.test.ts index 55cf623149..c6629a39a0 100644 --- a/plugins/home/src/api/VisitsStorageApi.test.ts +++ b/plugins/home/src/api/VisitsStorageApi.test.ts @@ -359,4 +359,202 @@ describe('VisitsStorageApi.create', () => { expect(visits.length).toEqual(8); }); }); + describe('.save() with transformPathname', () => { + it('transforms pathname before saving', async () => { + const api = VisitsStorageApi.create({ + storageApi: mockApis.storage(), + identityApi: mockIdentityApi, + transformPathname: (pathname: string) => + pathname.replace(/\/admin$/, ''), + }); + + const visit = { + pathname: '/catalog/default/component/test/admin', + entityRef: 'component:default/test', + name: 'Test Component', + }; + + const savedVisit = await api.save({ visit }); + expect(savedVisit.pathname).toBe('/catalog/default/component/test'); + }); + }); + + describe('.save() with canSave', () => { + it('skips saving when canSave returns false', async () => { + const api = VisitsStorageApi.create({ + storageApi: mockApis.storage(), + identityApi: mockIdentityApi, + canSave: visitInput => !visitInput.pathname.includes('/private'), + }); + + const privateVisit = { + pathname: '/private/admin', + entityRef: 'component:default/admin', + name: 'Admin Component', + }; + + const result = await api.save({ visit: privateVisit }); + expect(result.id).toBe(''); + expect(result.hits).toBe(0); + + const visits = await api.list(); + expect(visits).toHaveLength(0); + }); + + it('saves when canSave returns true', async () => { + const api = VisitsStorageApi.create({ + storageApi: mockApis.storage(), + identityApi: mockIdentityApi, + canSave: visitInput => !visitInput.pathname.includes('/private'), + }); + + const publicVisit = { + pathname: '/catalog/default/component/public', + entityRef: 'component:default/public', + name: 'Public Component', + }; + + const result = await api.save({ visit: publicVisit }); + expect(result.id).toBeTruthy(); + expect(result.hits).toBe(1); + + const visits = await api.list(); + expect(visits).toHaveLength(1); + }); + + it('handles async canSave function', async () => { + const api = VisitsStorageApi.create({ + storageApi: mockApis.storage(), + identityApi: mockIdentityApi, + canSave: async visitInput => + Promise.resolve(!visitInput.pathname.includes('/restricted')), + }); + + const restrictedVisit = { + pathname: '/restricted/area', + entityRef: 'component:default/restricted', + name: 'Restricted Component', + }; + + const result = await api.save({ visit: restrictedVisit }); + expect(result.id).toBe(''); + + const visits = await api.list(); + expect(visits).toHaveLength(0); + }); + }); + + describe('.save() with enrichVisit', () => { + it('enriches visit data before saving', async () => { + const api = VisitsStorageApi.create({ + storageApi: mockApis.storage(), + identityApi: mockIdentityApi, + enrichVisit: visitInput => ({ + category: visitInput.entityRef?.split(':')[0] || 'unknown', + source: 'test', + }), + }); + + const visit = { + pathname: '/catalog/default/component/test', + entityRef: 'component:default/test', + name: 'Test Component', + }; + + const savedVisit = await api.save({ visit }); + expect(savedVisit).toEqual( + expect.objectContaining({ + ...visit, + category: 'component', + source: 'test', + }), + ); + + const visits = await api.list(); + expect(visits[0]).toEqual( + expect.objectContaining({ + category: 'component', + source: 'test', + }), + ); + }); + + it('handles async enrichVisit function', async () => { + const api = VisitsStorageApi.create({ + storageApi: mockApis.storage(), + identityApi: mockIdentityApi, + enrichVisit: async visitInput => + Promise.resolve({ + enrichedAt: Date.now(), + type: visitInput.entityRef?.split(':')[0], + }), + }); + + const visit = { + pathname: '/catalog/default/api/test-api', + entityRef: 'api:default/test-api', + name: 'Test API', + }; + + const savedVisit = await api.save({ visit }); + expect(savedVisit).toEqual( + expect.objectContaining({ + type: 'api', + enrichedAt: expect.any(Number), + }), + ); + }); + }); + + describe('.save() with combined options', () => { + it('applies transformPathname, canSave, and enrichVisit in sequence', async () => { + const api = VisitsStorageApi.create({ + storageApi: mockApis.storage(), + identityApi: mockIdentityApi, + transformPathname: pathname => pathname.toLowerCase(), + canSave: visitInput => !visitInput.pathname.includes('forbidden'), + enrichVisit: visitInput => ({ + processed: true, + originalPath: visitInput.pathname, + }), + }); + + const visit = { + pathname: '/CATALOG/Default/Component/Test', + entityRef: 'component:default/test', + name: 'Test Component', + }; + + const savedVisit = await api.save({ visit }); + expect(savedVisit).toEqual( + expect.objectContaining({ + pathname: '/catalog/default/component/test', + processed: true, + originalPath: '/catalog/default/component/test', + }), + ); + }); + + it('prevents saving when canSave returns false after pathname transformation', async () => { + const api = VisitsStorageApi.create({ + storageApi: mockApis.storage(), + identityApi: mockIdentityApi, + transformPathname: pathname => + pathname.replace('/test/', '/forbidden/'), + canSave: visitInput => !visitInput.pathname.includes('forbidden'), + }); + + const visit = { + pathname: '/catalog/test/component/sample', + entityRef: 'component:default/sample', + name: 'Sample Component', + }; + + const result = await api.save({ visit }); + expect(result.id).toBe(''); + + const visits = await api.list(); + expect(visits).toHaveLength(0); + }); + }); }); diff --git a/plugins/home/src/api/VisitsStorageApi.ts b/plugins/home/src/api/VisitsStorageApi.ts index da3adc285e..3a55a6b16f 100644 --- a/plugins/home/src/api/VisitsStorageApi.ts +++ b/plugins/home/src/api/VisitsStorageApi.ts @@ -21,11 +21,26 @@ import { VisitsApiSaveParams, } from './VisitsApi'; +/** + * @public + * Type definition for visit data before it's saved (without auto-generated fields) + */ +export type VisitInput = { + name: string; + pathname: string; + entityRef?: string; +}; + /** @public */ export type VisitsStorageApiOptions = { limit?: number; storageApi: StorageApi; identityApi: IdentityApi; + transformPathname?: (pathname: string) => string; + canSave?: (visit: VisitInput) => boolean | Promise; + enrichVisit?: ( + visit: VisitInput, + ) => Promise> | Record; }; type ArrayElement = A extends readonly (infer T)[] ? T : never; @@ -43,6 +58,13 @@ export class VisitsStorageApi implements VisitsApi { private readonly storageApi: StorageApi; private readonly storageKeyPrefix = '@backstage/plugin-home:visits'; private readonly identityApi: IdentityApi; + private readonly transformPathnameImpl?: (pathname: string) => string; + private readonly canSaveImpl?: ( + visit: VisitInput, + ) => boolean | Promise; + private readonly enrichVisitImpl?: ( + visit: VisitInput, + ) => Promise> | Record; static create(options: VisitsStorageApiOptions) { return new VisitsStorageApi(options); @@ -52,6 +74,9 @@ export class VisitsStorageApi implements VisitsApi { this.limit = Math.abs(options.limit ?? 100); this.storageApi = options.storageApi; this.identityApi = options.identityApi; + this.transformPathnameImpl = options.transformPathname; + this.canSaveImpl = options.canSave; + this.enrichVisitImpl = options.enrichVisit; } /** @@ -88,34 +113,90 @@ export class VisitsStorageApi implements VisitsApi { return visits.slice(0, queryParams?.limit ?? DEFAULT_LIST_LIMIT); } + /** + * Transform the pathname before it is considered for any other processing. + * @param pathname - the original pathname + * @returns the transformed pathname + */ + transformPathname(pathname: string): string { + return this.transformPathnameImpl?.(pathname) ?? pathname; + } + + /** + * Determine whether a visit should be saved. + * @param visit - page visit data + */ + async canSave(visit: VisitInput): Promise { + if (!this.canSaveImpl) { + return true; + } + return Promise.resolve(this.canSaveImpl(visit)); + } + + /** + * Add additional data to the visit before saving. + * @param visit - page visit data + */ + async enrichVisit(visit: VisitInput): Promise> { + if (!this.enrichVisitImpl) { + return {}; + } + return Promise.resolve(this.enrichVisitImpl(visit)); + } + /** * Saves a visit through the visitsApi */ async save(saveParams: VisitsApiSaveParams): Promise { + let visit = saveParams.visit; + + // Transform pathname if needed + visit = { + ...visit, + pathname: this.transformPathname(visit.pathname), + }; + + // Check if visit should be saved + if (!(await this.canSave(visit))) { + // Return a minimal visit object without saving + return { + ...visit, + id: '', + hits: 0, + timestamp: Date.now(), + }; + } + + // Enrich the visit + const enrichedData = await this.enrichVisit(visit); + const enrichedVisit = { ...visit, ...enrichedData }; + const visits: Visit[] = [...(await this.retrieveAll())]; - const visit: Visit = { - ...saveParams.visit, + const visitToSave: Visit = { + ...enrichedVisit, id: window.crypto.randomUUID(), hits: 1, timestamp: Date.now(), }; // Updates entry if pathname is already registered - const visitIndex = visits.findIndex(e => e.pathname === visit.pathname); + const visitIndex = visits.findIndex( + e => e.pathname === visitToSave.pathname, + ); if (visitIndex >= 0) { - visit.id = visits[visitIndex].id; - visit.hits = visits[visitIndex].hits + 1; - visits[visitIndex] = visit; + visitToSave.id = visits[visitIndex].id; + visitToSave.hits = visits[visitIndex].hits + 1; + visits[visitIndex] = visitToSave; } else { - visits.push(visit); + visits.push(visitToSave); } // Sort by time, most recent first visits.sort((a, b) => b.timestamp - a.timestamp); // Keep the most recent items up to limit await this.persistAll(visits.splice(0, this.limit)); - return visit; + return visitToSave; } private async persistAll(visits: Array) { diff --git a/plugins/home/src/api/index.ts b/plugins/home/src/api/index.ts index 944fa65330..3ac9d8fce8 100644 --- a/plugins/home/src/api/index.ts +++ b/plugins/home/src/api/index.ts @@ -17,3 +17,4 @@ export * from './VisitsStorageApi'; export * from './VisitsWebStorageApi'; export * from './VisitsApi'; +export type { VisitInput } from './VisitsStorageApi'; diff --git a/plugins/home/src/components/VisitListener.test.tsx b/plugins/home/src/components/VisitListener.test.tsx index 1661dc202c..7f7db95a9e 100644 --- a/plugins/home/src/components/VisitListener.test.tsx +++ b/plugins/home/src/components/VisitListener.test.tsx @@ -15,7 +15,7 @@ */ import { TestApiProvider, renderInTestApp } from '@backstage/test-utils'; import { Visit, visitsApiRef } from '../api'; -import { VisitListener, VisitEnrichmentFunction } from './VisitListener'; +import { VisitListener } from './VisitListener'; import { waitFor } from '@testing-library/react'; const visits: Array = [ @@ -49,33 +49,7 @@ const mockVisitsApi = { }; describe('', () => { - beforeEach(() => { - jest - .spyOn(window, 'requestAnimationFrame') - .mockImplementation((cb: FrameRequestCallback): number => { - cb(0); - return 0; - }); - }); - - afterEach(() => { - jest.restoreAllMocks(); - jest.resetAllMocks(); - }); - - it('uses requestAnimationFrame to defer visit saving', async () => { - const pathname = '/catalog/default/component/test-component'; - - await renderInTestApp( - - - , - { routeEntries: [pathname] }, - ); - - expect(window.requestAnimationFrame).toHaveBeenCalledTimes(1); - await waitFor(() => expect(mockVisitsApi.save).toHaveBeenCalledTimes(1)); - }); + afterEach(jest.resetAllMocks); it('registers a visit', async () => { const pathname = '/catalog/default/component/playback-order'; @@ -156,183 +130,4 @@ describe('', () => { }), ); }); - - it('saves base visit when no enrichment function is provided', async () => { - const pathname = '/catalog/default/component/test-component'; - - await renderInTestApp( - - - , - { routeEntries: [pathname] }, - ); - - await waitFor(() => - expect(mockVisitsApi.save).toHaveBeenCalledWith({ - visit: { - pathname, - entityRef: 'component:default/test-component', - name: 'test-component', - }, - }), - ); - }); - - it('enriches visit with additional data when enrichVisit function is provided', async () => { - const pathname = '/catalog/default/component/test-component'; - const enrichVisit: VisitEnrichmentFunction = jest.fn(async _visit => ({ - customProperty: 'custom-value', - category: 'test-category', - priority: 1, - })); - - await renderInTestApp( - - - , - { routeEntries: [pathname] }, - ); - - await waitFor(() => { - expect(enrichVisit).toHaveBeenCalledWith({ - pathname, - entityRef: 'component:default/test-component', - name: 'test-component', - }); - expect(mockVisitsApi.save).toHaveBeenCalledWith({ - visit: { - pathname, - entityRef: 'component:default/test-component', - name: 'test-component', - customProperty: 'custom-value', - category: 'test-category', - priority: 1, - }, - }); - }); - }); - - it('handles synchronous enrichment function', async () => { - const pathname = '/catalog/default/component/test-component'; - const enrichVisit: VisitEnrichmentFunction = jest.fn(_visit => ({ - syncProperty: 'sync-value', - })); - - await renderInTestApp( - - - , - { routeEntries: [pathname] }, - ); - - await waitFor(() => { - expect(enrichVisit).toHaveBeenCalledWith({ - pathname, - entityRef: 'component:default/test-component', - name: 'test-component', - }); - expect(mockVisitsApi.save).toHaveBeenCalledWith({ - visit: { - pathname, - entityRef: 'component:default/test-component', - name: 'test-component', - syncProperty: 'sync-value', - }, - }); - }); - }); - - it('enrichment function can override base visit properties', async () => { - const pathname = '/catalog/default/component/test-component'; - const enrichVisit: VisitEnrichmentFunction = jest.fn(async _visit => ({ - name: 'Overridden Name', - entityRef: 'overridden:ref/value', - customField: 'additional-data', - })); - - await renderInTestApp( - - - , - { routeEntries: [pathname] }, - ); - - await waitFor(() => { - expect(mockVisitsApi.save).toHaveBeenCalledWith({ - visit: { - pathname, - name: 'Overridden Name', - entityRef: 'overridden:ref/value', - customField: 'additional-data', - }, - }); - }); - }); - - it('is able to override transformPathname and change the pathname', async () => { - const pathname = '/catalog/default/component/playback-order-2/sub-path'; - - const transformPathnameOverride = ({ - pathname: mypathname, - }: { - pathname: string; - }) => mypathname.replace('/sub-path', ''); - - await renderInTestApp( - - - , - { routeEntries: [pathname] }, - ); - - await waitFor(() => - expect(mockVisitsApi.save).toHaveBeenCalledWith({ - visit: { - pathname: '/catalog/default/component/playback-order-2', - entityRef: 'component:default/playback-order-2', - name: 'playback-order-2', - }, - }), - ); - }); - - it('is able to override canSave and save under set conditions', async () => { - const pathname = '/catalog'; - - const canSaveOverride = ({ pathname: path }: { pathname: string }) => - path === '/catalog'; - - await renderInTestApp( - - - , - { routeEntries: [pathname] }, - ); - - await waitFor(() => - expect(mockVisitsApi.save).toHaveBeenCalledWith({ - visit: { - pathname, - entityRef: undefined, - name: 'catalog', - }, - }), - ); - }); - - it('is able to override canSave and not save under set conditions', async () => { - const pathname = '/catalog'; - - const canSaveOverride = ({ pathname: path }: { pathname: string }) => - path !== '/catalog'; - - await renderInTestApp( - - - , - { routeEntries: [pathname] }, - ); - - await waitFor(() => expect(mockVisitsApi.save).not.toHaveBeenCalled()); - }); }); diff --git a/plugins/home/src/components/VisitListener.tsx b/plugins/home/src/components/VisitListener.tsx index 534e6805b2..ee4f4558c1 100644 --- a/plugins/home/src/components/VisitListener.tsx +++ b/plugins/home/src/components/VisitListener.tsx @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import { ReactNode, useEffect, useRef } from 'react'; +import { ReactNode, useEffect } from 'react'; import { useLocation } from 'react-router-dom'; @@ -74,67 +74,6 @@ const getVisitName = return document.title; }; -/** - * @public - * Type definition for visit data before it's saved (without auto-generated fields) - */ -export type VisitInput = { - name: string; - pathname: string; - entityRef?: string; -}; - -/** - * @public - * Type definition for the visit enrichment function - * This allows adding custom properties to visits at save time - */ -export type VisitEnrichmentFunction = ( - visit: VisitInput, -) => Record | Promise>; - -/** - * @public - * Type definition for the transform pathname function - * This allows transforming the pathname before it is considered for any other processing - */ -export type VisitTransformPathnameFunction = ({ - pathname, -}: { - pathname: string; -}) => string; - -/** - * @internal - * Default implementation of visit pathname transform function - */ -const getTransformPathname = - (): VisitTransformPathnameFunction => - ({ pathname }: { pathname: string }): string => { - return pathname; - }; - -/** - * @public - * Type definition for the can save function - * This allows checking whether a visit can be saved - */ -export type VisitCanSaveFunction = ({ - pathname, -}: { - pathname: string; -}) => boolean; - -/** - * @internal - * Default implementation of visit can save function - */ -const getCanSave = - (): VisitCanSaveFunction => - (_: { pathname: string }): boolean => { - return true; - }; - /** * @public * Component responsible for listening to location changes and calling @@ -144,69 +83,29 @@ export const VisitListener = ({ children, toEntityRef, visitName, - enrichVisit, - transformPathname, - canSave, }: { children?: ReactNode; toEntityRef?: ({ pathname }: { pathname: string }) => string | undefined; visitName?: ({ pathname }: { pathname: string }) => string; - enrichVisit?: VisitEnrichmentFunction; - transformPathname?: VisitTransformPathnameFunction; - canSave?: VisitCanSaveFunction; }): JSX.Element => { - const previousVisitPathname = useRef(''); const visitsApi = useApi(visitsApiRef); const { pathname } = useLocation(); const toEntityRefImpl = toEntityRef ?? getToEntityRef(); const visitNameImpl = visitName ?? getVisitName(); - const transformPathnameImpl = transformPathname ?? getTransformPathname(); - const canSaveImpl = canSave ?? getCanSave(); - useEffect(() => { - const visitPathname = transformPathnameImpl({ pathname }); - if (previousVisitPathname.current === visitPathname) { - return () => {}; - } - previousVisitPathname.current = visitPathname; - if (!canSaveImpl({ pathname: visitPathname })) { - return () => {}; - } // Wait for the browser to finish with paint with the assumption react // has finished with dom reconciliation. - const requestId = requestAnimationFrame(async () => { - const baseVisit = { - name: visitNameImpl({ pathname: visitPathname }), - pathname: visitPathname, - entityRef: toEntityRefImpl({ pathname: visitPathname }), - }; - - let visitToSave = baseVisit; - - if (enrichVisit) { - try { - const enrichedData = await enrichVisit(baseVisit); - visitToSave = { ...baseVisit, ...enrichedData }; - } catch (error) { - // If enrichment fails, save the base visit without enrichment - visitToSave = baseVisit; - } - } - + const requestId = requestAnimationFrame(() => { visitsApi.save({ - visit: visitToSave, + visit: { + name: visitNameImpl({ pathname }), + pathname, + entityRef: toEntityRefImpl({ pathname }), + }, }); }); return () => cancelAnimationFrame(requestId); - }, [ - visitsApi, - pathname, - toEntityRefImpl, - visitNameImpl, - enrichVisit, - transformPathnameImpl, - canSaveImpl, - ]); + }, [visitsApi, pathname, toEntityRefImpl, visitNameImpl]); return <>{children}; }; From 52452db1e3dfbb69d9a9c21a17640f2967fa04b5 Mon Sep 17 00:00:00 2001 From: Stephanie Swaney Date: Thu, 18 Sep 2025 09:59:49 -0500 Subject: [PATCH 10/10] chore: run all api reports, not single plugin Signed-off-by: Stephanie Swaney --- plugins/home/report-alpha.api.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugins/home/report-alpha.api.md b/plugins/home/report-alpha.api.md index 83568c0e45..d2e5c22ef8 100644 --- a/plugins/home/report-alpha.api.md +++ b/plugins/home/report-alpha.api.md @@ -105,6 +105,7 @@ export default _default; export const homeTranslationRef: TranslationRef< 'home', { + readonly 'starredEntities.noStarredEntitiesMessage': 'Click the star beside an entity name to add it to this list!'; readonly 'addWidgetDialog.title': 'Add new widget to dashboard'; readonly 'customHomepageButtons.clearAll': 'Clear all'; readonly 'customHomepageButtons.edit': 'Edit'; @@ -123,7 +124,6 @@ export const homeTranslationRef: TranslationRef< readonly 'quickStart.title': 'Onboarding'; readonly 'quickStart.description': 'Get started with Backstage'; readonly 'quickStart.learnMoreLinkTitle': 'Learn more'; - readonly 'starredEntities.noStarredEntitiesMessage': 'Click the star beside an entity name to add it to this list!'; readonly 'visitedByType.action.viewMore': 'View more'; readonly 'visitedByType.action.viewLess': 'View less'; readonly 'featuredDocsCard.empty.title': 'No documents to show';