frontend-plugin-api: added PluginWrapperBlueprint + implementation

Signed-off-by: Patrik Oldsberg <poldsberg@gmail.com>
This commit is contained in:
Patrik Oldsberg
2026-01-15 11:40:36 +01:00
parent c4e03c31ac
commit b164e20697
11 changed files with 448 additions and 1 deletions
@@ -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<PluginWrapperApi>;
// @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<TOutput, TInput = TOutput> = {
parse: (input: TInput) => TOutput;
@@ -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<PluginWrapperApi> = createApiRef({
id: 'core.plugin-wrapper',
});
@@ -49,3 +49,4 @@ export * from './RouteResolutionApi';
export * from './StorageApi';
export * from './AnalyticsApi';
export * from './TranslationApi';
export * from './PluginWrapperApi';
@@ -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);
},
});
@@ -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,
@@ -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) {
</AnalyticsContext>
);
if (PluginWrapper) {
content = <PluginWrapper>{content}</PluginWrapper>;
}
if (props.errorPresentation === 'error-api') {
content = (
<ErrorApiBoundary node={node} errorApi={errorApi}>
@@ -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(
<>
<div>
<Wrapper1>1</Wrapper1>
</div>
<div>
<Wrapper2>2</Wrapper2>
</div>
<div>
<Wrapper3>3</Wrapper3>
</div>
</>,
);
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(
<>
<div>
<Wrapper1>1</Wrapper1>
</div>
<div>
<Wrapper2>2</Wrapper2>
</div>
</>,
);
await expect(
screen.findByText('WrapperB(WrapperA(1))'),
).resolves.toBeInTheDocument();
await expect(
screen.findByText('WrapperB(WrapperA(2))'),
).resolves.toBeInTheDocument();
});
});
@@ -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<WrapperInput>): 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<ComponentType<{ children: ReactNode }>> | undefined
>(undefined);
const [error, setError] = useState<Error | undefined>(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 = <Wrapper>{content}</Wrapper>;
}
return <>{content}</>;
};
composedWrappers.set(pluginId, ComposedWrapper);
}
return new DefaultPluginWrapperApi(composedWrappers);
}
}
@@ -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';
@@ -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',
})),
);
},
}),
);
},
});
+1
View File
@@ -32,3 +32,4 @@ export {
alertDisplayAppRootElement,
} from './elements';
export { Progress, NotFoundErrorPage, ErrorDisplay } from './components';
export { PluginWrapperApi } from './PluginWrapperApi';