From b164e20697c52c2f6b255378b8bf228c40fb388c Mon Sep 17 00:00:00 2001 From: Patrik Oldsberg Date: Thu, 15 Jan 2026 11:40:36 +0100 Subject: [PATCH] frontend-plugin-api: added PluginWrapperBlueprint + implementation Signed-off-by: Patrik Oldsberg --- packages/frontend-plugin-api/report.api.md | 53 +++++++++ .../src/apis/definitions/PluginWrapperApi.ts | 41 +++++++ .../src/apis/definitions/index.ts | 1 + .../src/blueprints/PluginWrapperBlueprint.tsx | 56 +++++++++ .../src/blueprints/index.ts | 1 + .../src/components/ExtensionBoundary.tsx | 25 +++- .../DefaultPluginWrapperApi.test.tsx | 98 ++++++++++++++++ .../DefaultPluginWrapperApi.tsx | 107 ++++++++++++++++++ .../app/src/apis/PluginWrapperApi/index.ts | 17 +++ .../app/src/extensions/PluginWrapperApi.ts | 49 ++++++++ plugins/app/src/extensions/index.ts | 1 + 11 files changed, 448 insertions(+), 1 deletion(-) create mode 100644 packages/frontend-plugin-api/src/apis/definitions/PluginWrapperApi.ts create mode 100644 packages/frontend-plugin-api/src/blueprints/PluginWrapperBlueprint.tsx create mode 100644 plugins/app/src/apis/PluginWrapperApi/DefaultPluginWrapperApi.test.tsx create mode 100644 plugins/app/src/apis/PluginWrapperApi/DefaultPluginWrapperApi.tsx create mode 100644 plugins/app/src/apis/PluginWrapperApi/index.ts create mode 100644 plugins/app/src/extensions/PluginWrapperApi.ts diff --git a/packages/frontend-plugin-api/report.api.md b/packages/frontend-plugin-api/report.api.md index ceba08d7c3..9115d0732b 100644 --- a/packages/frontend-plugin-api/report.api.md +++ b/packages/frontend-plugin-api/report.api.md @@ -1868,6 +1868,59 @@ export interface PluginOptions< routes?: TRoutes; } +// @public +export type PluginWrapperApi = { + getPluginWrapper(pluginId: string): + | ComponentType<{ + children: ReactNode; + }> + | undefined; +}; + +// @public +export const pluginWrapperApiRef: ApiRef; + +// @public +export const PluginWrapperBlueprint: ExtensionBlueprint_2<{ + kind: 'plugin-wrapper'; + params: (params: { + loader: () => Promise<{ + component: ComponentType<{ + children: ReactNode; + }>; + }>; + }) => ExtensionBlueprintParams_2<{ + loader: () => Promise<{ + component: ComponentType<{ + children: ReactNode; + }>; + }>; + }>; + output: ExtensionDataRef_2< + () => Promise<{ + component: ComponentType<{ + children: ReactNode; + }>; + }>, + 'core.plugin-wrapper.loader', + {} + >; + inputs: {}; + config: {}; + configInput: {}; + dataRefs: { + wrapper: ConfigurableExtensionDataRef_2< + () => Promise<{ + component: ComponentType<{ + children: ReactNode; + }>; + }>, + 'core.plugin-wrapper.loader', + {} + >; + }; +}>; + // @public (undocumented) export type PortableSchema = { parse: (input: TInput) => TOutput; diff --git a/packages/frontend-plugin-api/src/apis/definitions/PluginWrapperApi.ts b/packages/frontend-plugin-api/src/apis/definitions/PluginWrapperApi.ts new file mode 100644 index 0000000000..b6c96dd760 --- /dev/null +++ b/packages/frontend-plugin-api/src/apis/definitions/PluginWrapperApi.ts @@ -0,0 +1,41 @@ +/* + * Copyright 2024 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 { ComponentType, ReactNode } from 'react'; +import { ApiRef, createApiRef } from '../system'; + +/** + * The Plugin Wrapper API allows plugins to wrap their extensions with providers. This API is only intended for internal use by the Backstage frontend system. To provide contexts to plugin components, use `ExtensionBoundary` instead. + * + * @public + */ +export type PluginWrapperApi = { + /** + * Returns a wrapper component for a specific plugin, or undefined if no wrappers exist. Do not use this API directly, instead use `ExtensionBoundary` to wrap your plugin components if needed. + */ + getPluginWrapper( + pluginId: string, + ): ComponentType<{ children: ReactNode }> | undefined; +}; + +/** + * The API reference of {@link PluginWrapperApi}. + * + * @public + */ +export const pluginWrapperApiRef: ApiRef = createApiRef({ + id: 'core.plugin-wrapper', +}); diff --git a/packages/frontend-plugin-api/src/apis/definitions/index.ts b/packages/frontend-plugin-api/src/apis/definitions/index.ts index 5e7f713fcf..7b90d38092 100644 --- a/packages/frontend-plugin-api/src/apis/definitions/index.ts +++ b/packages/frontend-plugin-api/src/apis/definitions/index.ts @@ -49,3 +49,4 @@ export * from './RouteResolutionApi'; export * from './StorageApi'; export * from './AnalyticsApi'; export * from './TranslationApi'; +export * from './PluginWrapperApi'; diff --git a/packages/frontend-plugin-api/src/blueprints/PluginWrapperBlueprint.tsx b/packages/frontend-plugin-api/src/blueprints/PluginWrapperBlueprint.tsx new file mode 100644 index 0000000000..a005342b31 --- /dev/null +++ b/packages/frontend-plugin-api/src/blueprints/PluginWrapperBlueprint.tsx @@ -0,0 +1,56 @@ +/* + * Copyright 2024 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 { ComponentType, ReactNode } from 'react'; +import { + createExtensionBlueprint, + createExtensionBlueprintParams, + createExtensionDataRef, +} from '../wiring'; + +const wrapperDataRef = createExtensionDataRef< + () => Promise<{ component: ComponentType<{ children: ReactNode }> }> +>().with({ id: 'core.plugin-wrapper.loader' }); + +/** + * Creates extensions that wrap plugin extensions with providers. + * + * @public + */ +export const PluginWrapperBlueprint = createExtensionBlueprint({ + kind: 'plugin-wrapper', + attachTo: { id: 'api:app/plugin-wrapper', input: 'wrappers' }, + output: [wrapperDataRef], + dataRefs: { + wrapper: wrapperDataRef, + }, + defineParams(params: { + loader: () => Promise<{ + component: ComponentType<{ children: ReactNode }>; + }>; + }) { + return createExtensionBlueprintParams( + params as { + loader: () => Promise<{ + component: ComponentType<{ children: ReactNode }>; + }>; + }, + ); + }, + *factory(params) { + yield wrapperDataRef(params.loader); + }, +}); diff --git a/packages/frontend-plugin-api/src/blueprints/index.ts b/packages/frontend-plugin-api/src/blueprints/index.ts index 379c8d237b..1d7e6eb478 100644 --- a/packages/frontend-plugin-api/src/blueprints/index.ts +++ b/packages/frontend-plugin-api/src/blueprints/index.ts @@ -21,6 +21,7 @@ export { export { ApiBlueprint } from './ApiBlueprint'; export { AppRootElementBlueprint } from './AppRootElementBlueprint'; export { AppRootWrapperBlueprint } from './AppRootWrapperBlueprint'; +export { PluginWrapperBlueprint } from './PluginWrapperBlueprint'; export { IconBundleBlueprint } from './IconBundleBlueprint'; export { NavContentBlueprint, diff --git a/packages/frontend-plugin-api/src/components/ExtensionBoundary.tsx b/packages/frontend-plugin-api/src/components/ExtensionBoundary.tsx index 6e4487ed9b..fefa2dc521 100644 --- a/packages/frontend-plugin-api/src/components/ExtensionBoundary.tsx +++ b/packages/frontend-plugin-api/src/components/ExtensionBoundary.tsx @@ -19,6 +19,7 @@ import { ReactNode, Suspense, useEffect, + useMemo, lazy as reactLazy, } from 'react'; import { AnalyticsContext, useAnalytics } from '../analytics'; @@ -27,6 +28,10 @@ import { ErrorApiBoundary } from './ErrorApiBoundary'; // eslint-disable-next-line @backstage/no-relative-monorepo-imports import { routableExtensionRenderedEvent } from '../../../core-plugin-api/src/analytics/Tracker'; import { AppNode, ErrorApi, errorApiRef, useApi } from '../apis'; +import { + PluginWrapperApi, + pluginWrapperApiRef, +} from '../apis/definitions/PluginWrapperApi'; import { coreExtensionData } from '../wiring'; import { AppNodeProvider } from './AppNodeProvider'; import { Progress } from './DefaultSwappableComponents'; @@ -39,6 +44,13 @@ function useOptionalErrorApi(): ErrorApi | undefined { } } +function useOptionalPluginWrapperApi(): PluginWrapperApi | undefined { + try { + return useApi(pluginWrapperApiRef); + } catch { + return undefined; + } +} type RouteTrackerProps = PropsWithChildren<{ enabled?: boolean; }>; @@ -78,11 +90,18 @@ export function ExtensionBoundary(props: ExtensionBoundaryProps) { ); const plugin = node.spec.plugin; + const pluginId = plugin.id ?? 'app'; + + const pluginWrapperApi = useOptionalPluginWrapperApi(); + + const PluginWrapper = useMemo(() => { + return pluginWrapperApi?.getPluginWrapper(pluginId); + }, [pluginWrapperApi, pluginId]); // Skipping "routeRef" attribute in the new system, the extension "id" should provide more insight const attributes = { extensionId: node.spec.id, - pluginId: plugin.id ?? 'app', + pluginId, }; let content = ( @@ -91,6 +110,10 @@ export function ExtensionBoundary(props: ExtensionBoundaryProps) { ); + if (PluginWrapper) { + content = {content}; + } + if (props.errorPresentation === 'error-api') { content = ( diff --git a/plugins/app/src/apis/PluginWrapperApi/DefaultPluginWrapperApi.test.tsx b/plugins/app/src/apis/PluginWrapperApi/DefaultPluginWrapperApi.test.tsx new file mode 100644 index 0000000000..c723222f2f --- /dev/null +++ b/plugins/app/src/apis/PluginWrapperApi/DefaultPluginWrapperApi.test.tsx @@ -0,0 +1,98 @@ +/* + * Copyright 2024 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 { render, screen } from '@testing-library/react'; +import { DefaultPluginWrapperApi } from './DefaultPluginWrapperApi'; + +describe('DefaultPluginWrapperApi', () => { + it('should wrap multiple components with a single wrapper', async () => { + const api = DefaultPluginWrapperApi.fromWrappers([ + { + loader: async () => ({ + component: ({ children }) => <>Wrapper({children}), + }), + pluginId: 'plugin-1', + }, + ]); + + const Wrapper1 = api.getPluginWrapper('plugin-1')!; + const Wrapper2 = api.getPluginWrapper('plugin-1')!; + const Wrapper3 = api.getPluginWrapper('plugin-1')!; + + expect(Wrapper1).toBeDefined(); + expect(Wrapper2).toBeDefined(); + expect(Wrapper3).toBeDefined(); + + render( + <> +
+ 1 +
+
+ 2 +
+
+ 3 +
+ , + ); + + await expect(screen.findByText('Wrapper(1)')).resolves.toBeInTheDocument(); + await expect(screen.findByText('Wrapper(2)')).resolves.toBeInTheDocument(); + await expect(screen.findByText('Wrapper(3)')).resolves.toBeInTheDocument(); + }); + + it('should wrap multiple components with multiple wrappers', async () => { + const api = DefaultPluginWrapperApi.fromWrappers([ + { + loader: async () => ({ + component: ({ children }) => <>WrapperA({children}), + }), + pluginId: 'plugin-1', + }, + { + loader: async () => ({ + component: ({ children }) => <>WrapperB({children}), + }), + pluginId: 'plugin-1', + }, + ]); + + const Wrapper1 = api.getPluginWrapper('plugin-1')!; + const Wrapper2 = api.getPluginWrapper('plugin-1')!; + + expect(Wrapper1).toBeDefined(); + expect(Wrapper2).toBeDefined(); + + render( + <> +
+ 1 +
+
+ 2 +
+ , + ); + + await expect( + screen.findByText('WrapperB(WrapperA(1))'), + ).resolves.toBeInTheDocument(); + await expect( + screen.findByText('WrapperB(WrapperA(2))'), + ).resolves.toBeInTheDocument(); + }); +}); diff --git a/plugins/app/src/apis/PluginWrapperApi/DefaultPluginWrapperApi.tsx b/plugins/app/src/apis/PluginWrapperApi/DefaultPluginWrapperApi.tsx new file mode 100644 index 0000000000..2bf2744f21 --- /dev/null +++ b/plugins/app/src/apis/PluginWrapperApi/DefaultPluginWrapperApi.tsx @@ -0,0 +1,107 @@ +/* + * Copyright 2024 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 { PluginWrapperApi } from '@backstage/frontend-plugin-api'; +import { ComponentType, ReactNode, useEffect, useState } from 'react'; + +type WrapperInput = { + loader: () => Promise<{ component: ComponentType<{ children: ReactNode }> }>; + pluginId: string; +}; + +/** + * Default implementation of PluginWrapperApi. + * + * @internal + */ +export class DefaultPluginWrapperApi implements PluginWrapperApi { + constructor( + private readonly pluginWrappers: Map< + string, + ComponentType<{ children: ReactNode }> + >, + ) {} + + getPluginWrapper( + pluginId: string, + ): ComponentType<{ children: ReactNode }> | undefined { + return this.pluginWrappers.get(pluginId); + } + + static fromWrappers(wrappers: Array): DefaultPluginWrapperApi { + const loadersByPlugin = new Map< + string, + Array< + () => Promise<{ component: ComponentType<{ children: ReactNode }> }> + > + >(); + + for (const wrapper of wrappers) { + let loaders = loadersByPlugin.get(wrapper.pluginId); + if (!loaders) { + loaders = []; + loadersByPlugin.set(wrapper.pluginId, loaders); + } + loaders.push(wrapper.loader); + } + + const composedWrappers = new Map< + string, + ComponentType<{ children: ReactNode }> + >(); + + for (const [pluginId, loaders] of loadersByPlugin) { + if (loaders.length === 0) { + continue; + } + + const ComposedWrapper = (props: { children: ReactNode }) => { + const [loadedWrappers, setLoadedWrappers] = useState< + Array> | undefined + >(undefined); + const [error, setError] = useState(undefined); + + useEffect(() => { + Promise.all(loaders.map(loader => loader())) + .then(results => { + setLoadedWrappers(results.map(r => r.component)); + }) + .catch(setError); + }, []); + + if (error) { + throw error; + } + + if (!loadedWrappers) { + return null; + } + + let content = props.children; + + for (const Wrapper of loadedWrappers) { + content = {content}; + } + + return <>{content}; + }; + + composedWrappers.set(pluginId, ComposedWrapper); + } + + return new DefaultPluginWrapperApi(composedWrappers); + } +} diff --git a/plugins/app/src/apis/PluginWrapperApi/index.ts b/plugins/app/src/apis/PluginWrapperApi/index.ts new file mode 100644 index 0000000000..f11e40fdf0 --- /dev/null +++ b/plugins/app/src/apis/PluginWrapperApi/index.ts @@ -0,0 +1,17 @@ +/* + * Copyright 2024 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. + */ + +export { DefaultPluginWrapperApi } from './DefaultPluginWrapperApi'; diff --git a/plugins/app/src/extensions/PluginWrapperApi.ts b/plugins/app/src/extensions/PluginWrapperApi.ts new file mode 100644 index 0000000000..14e41891a0 --- /dev/null +++ b/plugins/app/src/extensions/PluginWrapperApi.ts @@ -0,0 +1,49 @@ +/* + * Copyright 2024 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 { + PluginWrapperBlueprint, + createExtensionInput, + ApiBlueprint, + pluginWrapperApiRef, +} from '@backstage/frontend-plugin-api'; +import { DefaultPluginWrapperApi } from '../apis/PluginWrapperApi'; + +/** + * Contains the plugin wrappers installed into the app. + */ +export const PluginWrapperApi = ApiBlueprint.makeWithOverrides({ + name: 'plugin-wrapper', + inputs: { + wrappers: createExtensionInput([PluginWrapperBlueprint.dataRefs.wrapper]), + }, + factory: (originalFactory, { inputs }) => { + return originalFactory(defineParams => + defineParams({ + api: pluginWrapperApiRef, + deps: {}, + factory: () => { + return DefaultPluginWrapperApi.fromWrappers( + inputs.wrappers.map(wrapperInput => ({ + loader: wrapperInput.get(PluginWrapperBlueprint.dataRefs.wrapper), + pluginId: wrapperInput.node.spec.plugin.id ?? 'app', + })), + ); + }, + }), + ); + }, +}); diff --git a/plugins/app/src/extensions/index.ts b/plugins/app/src/extensions/index.ts index 0d3ad84e6f..17ac19ff4b 100644 --- a/plugins/app/src/extensions/index.ts +++ b/plugins/app/src/extensions/index.ts @@ -32,3 +32,4 @@ export { alertDisplayAppRootElement, } from './elements'; export { Progress, NotFoundErrorPage, ErrorDisplay } from './components'; +export { PluginWrapperApi } from './PluginWrapperApi';