Merge pull request #22752 from backstage/camilaibs/migrate-api-docs-plugin-to-new-system

Migrate api docs plugin to new system
This commit is contained in:
Camila Belo
2024-02-09 20:26:00 +01:00
committed by GitHub
12 changed files with 1575 additions and 86 deletions
+5
View File
@@ -0,0 +1,5 @@
---
'@backstage/plugin-catalog': patch
---
Fix entity content extension filtering.
+5
View File
@@ -0,0 +1,5 @@
---
'@backstage/plugin-api-docs': minor
---
Migrate the `api-docs` to the new frontend system. It is experimental and available via alpha subpath.
+10
View File
@@ -1,6 +1,7 @@
app:
experimental:
packages: 'all' # ✨
routes:
bindings:
catalog.viewTechDoc: techdocs.docRoot
@@ -11,6 +12,7 @@ app:
# - apis.plugin.graphiql.browse.gitlab: true
- graphiql-endpoint:graphiql/gitlab: true
# Entity page cards
- entity-card:catalog/about
- entity-card:catalog/labels
- entity-card:catalog/links:
@@ -21,7 +23,15 @@ app:
config:
height: 300
- entity-card:azure-devops/readme
- entity-card:api-docs/has-apis
- entity-card:api-docs/consumed-apis
- entity-card:api-docs/provided-apis
- entity-card:api-docs/providing-components
- entity-card:api-docs/consuming-components
# Entity page content
- entity-content:api-docs/definition
- entity-content:api-docs/apis
- entity-content:techdocs
- entity-content:azure-devops/pipelines
- entity-content:azure-devops/pull-requests
File diff suppressed because it is too large Load Diff
+3
View File
@@ -1,5 +1,8 @@
# API Documentation
> Disclaimer:
> If you are looking for documentation on the experimental new frontend system support, please go [here](./README-alpha.md).
This is an extension for the catalog plugin that provides components to discover and display API entities.
APIs define the interface between components, see the [system model](https://backstage.io/docs/features/software-catalog/system-model) for details.
They are defined in machine readable formats and provide a human readable documentation.
+22
View File
@@ -0,0 +1,22 @@
## API Report File for "@backstage/plugin-api-docs"
> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/).
```ts
import { BackstagePlugin } from '@backstage/frontend-plugin-api';
import { ExternalRouteRef } from '@backstage/frontend-plugin-api';
import { RouteRef } from '@backstage/frontend-plugin-api';
// @public (undocumented)
const _default: BackstagePlugin<
{
root: RouteRef<undefined>;
},
{
registerApi: ExternalRouteRef<undefined, true>;
}
>;
export default _default;
// (No @packageDocumentation comment for this package)
```
+18 -3
View File
@@ -6,9 +6,22 @@
"types": "src/index.ts",
"license": "Apache-2.0",
"publishConfig": {
"access": "public",
"main": "dist/index.esm.js",
"types": "dist/index.d.ts"
"access": "public"
},
"exports": {
".": "./src/index.ts",
"./alpha": "./src/alpha.tsx",
"./package.json": "./package.json"
},
"typesVersions": {
"*": {
"alpha": [
"src/alpha.tsx"
],
"package.json": [
"package.json"
]
}
},
"backstage": {
"role": "frontend-plugin"
@@ -35,8 +48,10 @@
"dependencies": {
"@asyncapi/react-component": "1.2.13",
"@backstage/catalog-model": "workspace:^",
"@backstage/core-compat-api": "workspace:^",
"@backstage/core-components": "workspace:^",
"@backstage/core-plugin-api": "workspace:^",
"@backstage/frontend-plugin-api": "workspace:^",
"@backstage/plugin-catalog": "workspace:^",
"@backstage/plugin-catalog-common": "workspace:^",
"@backstage/plugin-catalog-react": "workspace:^",
+233
View File
@@ -0,0 +1,233 @@
/*
* 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 React from 'react';
import { Grid } from '@material-ui/core';
import {
createApiExtension,
createApiFactory,
createNavItemExtension,
createPageExtension,
createPlugin,
createSchemaFromZod,
} from '@backstage/frontend-plugin-api';
import {
compatWrapper,
convertLegacyRouteRef,
} from '@backstage/core-compat-api';
import { useApp } from '@backstage/core-plugin-api';
import {
createEntityCardExtension,
createEntityContentExtension,
} from '@backstage/plugin-catalog-react/alpha';
import {
ApiEntity,
parseEntityRef,
RELATION_HAS_PART,
} from '@backstage/catalog-model';
import { defaultDefinitionWidgets } from './components/ApiDefinitionCard';
import { rootRoute, registerComponentRouteRef } from './routes';
import { apiDocsConfigRef } from './config';
function ApiIcon() {
const app = useApp();
const KindApiSystemIcon = app.getSystemIcon('kind:api')!;
return <KindApiSystemIcon />;
}
const apiDocsNavItem = createNavItemExtension({
title: 'APIs',
routeRef: convertLegacyRouteRef(rootRoute),
icon: () => compatWrapper(<ApiIcon />),
});
const apiDocsConfigApi = createApiExtension({
factory: createApiFactory({
api: apiDocsConfigRef,
deps: {},
factory: () => {
const definitionWidgets = defaultDefinitionWidgets();
return {
getApiDefinitionWidget: (apiEntity: ApiEntity) => {
return definitionWidgets.find(d => d.type === apiEntity.spec.type);
},
};
},
}),
});
const apiDocsExplorerPage = createPageExtension({
defaultPath: '/api-docs',
routeRef: convertLegacyRouteRef(rootRoute),
// Mapping DefaultApiExplorerPageProps to config
configSchema: createSchemaFromZod(z =>
z.object({
path: z.string().default('/api-docs'),
initiallySelectedFilter: z.enum(['owned', 'starred', 'all']).optional(),
// Ommiting columns and actions for now as their types are too complex to map to zod
}),
),
loader: ({ config }) =>
import('./components/ApiExplorerPage').then(m =>
compatWrapper(
<m.ApiExplorerIndexPage
initiallySelectedFilter={config.initiallySelectedFilter}
/>,
),
),
});
const apiDocsHasApisEntityCard = createEntityCardExtension({
name: 'has-apis',
// Ommiting configSchema for now
// We are skipping variants and columns are too complex to map to zod
// See: https://github.com/backstage/backstage/pull/22619#discussion_r1477333252
filter: entity => {
return (
entity.kind === 'Component' &&
entity.relations?.some(
({ type, targetRef }) =>
type.toLocaleLowerCase('en-US') === RELATION_HAS_PART &&
parseEntityRef(targetRef).kind === 'API',
)!!
);
},
loader: () =>
import('./components/ApisCards').then(m =>
compatWrapper(<m.HasApisCard />),
),
});
const apiDocsDefinitionEntityCard = createEntityCardExtension({
name: 'definition',
filter: 'kind:api',
loader: () =>
import('./components/ApiDefinitionCard').then(m =>
compatWrapper(<m.ApiDefinitionCard />),
),
});
const apiDocsConsumedApisEntityCard = createEntityCardExtension({
name: 'consumed-apis',
// Ommiting configSchema for now
// We are skipping variants and columns are too complex to map to zod
// See: https://github.com/backstage/backstage/pull/22619#discussion_r1477333252
filter: 'kind:component',
loader: () =>
import('./components/ApisCards').then(m =>
compatWrapper(<m.ConsumedApisCard />),
),
});
const apiDocsProvidedApisEntityCard = createEntityCardExtension({
name: 'provided-apis',
// Ommiting configSchema for now
// We are skipping variants and columns are too complex to map to zod
// See: https://github.com/backstage/backstage/pull/22619#discussion_r1477333252
filter: 'kind:component',
loader: () =>
import('./components/ApisCards').then(m =>
compatWrapper(<m.ProvidedApisCard />),
),
});
const apiDocsConsumingComponentsEntityCard = createEntityCardExtension({
name: 'consuming-components',
// Ommiting configSchema for now
// We are skipping variants
// See: https://github.com/backstage/backstage/pull/22619#discussion_r1477333252
filter: 'kind:api',
loader: () =>
import('./components/ComponentsCards').then(m =>
compatWrapper(<m.ConsumingComponentsCard />),
),
});
const apiDocsProvidingComponentsEntityCard = createEntityCardExtension({
name: 'providing-components',
// Ommiting configSchema for now
// We are skipping variants
// See: https://github.com/backstage/backstage/pull/22619#discussion_r1477333252
filter: 'kind:api',
loader: () =>
import('./components/ComponentsCards').then(m =>
compatWrapper(<m.ProvidingComponentsCard />),
),
});
const apiDocsDefinitionEntityContent = createEntityContentExtension({
name: 'definition',
defaultPath: '/defintion',
defaultTitle: 'Definition',
filter: 'kind:api',
loader: async () =>
import('./components/ApiDefinitionCard').then(m =>
compatWrapper(
<Grid container spacing={3}>
<Grid item xs={12}>
<m.ApiDefinitionCard />
</Grid>
</Grid>,
),
),
});
const apiDocsApisEntityContent = createEntityContentExtension({
name: 'apis',
defaultPath: '/apis',
defaultTitle: 'APIs',
filter: 'kind:component',
loader: async () =>
import('./components/ApisCards').then(m =>
compatWrapper(
<Grid container spacing={3} alignItems="stretch">
<Grid item xs={12}>
<m.ProvidedApisCard />
</Grid>
<Grid item xs={12}>
<m.ConsumedApisCard />
</Grid>
</Grid>,
),
),
});
export default createPlugin({
id: 'api-docs',
routes: {
root: convertLegacyRouteRef(rootRoute),
},
externalRoutes: {
registerApi: convertLegacyRouteRef(registerComponentRouteRef),
},
extensions: [
apiDocsNavItem,
apiDocsConfigApi,
apiDocsExplorerPage,
apiDocsHasApisEntityCard,
apiDocsDefinitionEntityCard,
apiDocsProvidedApisEntityCard,
apiDocsConsumedApisEntityCard,
apiDocsConsumingComponentsEntityCard,
apiDocsProvidingComponentsEntityCard,
apiDocsDefinitionEntityContent,
apiDocsApisEntityContent,
],
});
@@ -17,8 +17,8 @@
import { Entity } from '@backstage/catalog-model';
import { useEntity } from '@backstage/plugin-catalog-react';
import Grid from '@material-ui/core/Grid';
import React, { useMemo } from 'react';
import { parseFilterExpression } from './filter/parseFilterExpression';
import React from 'react';
import { FilterWrapper } from './filter/FilterWrapper';
interface EntityOverviewPageProps {
cards: Array<{
@@ -28,80 +28,12 @@ interface EntityOverviewPageProps {
}>;
}
// Keeps track of what filter expression strings that we've seen duplicates of
// with functions, or which emitted parsing errors for so far
const seenParseErrorExpressionStrings = new Set<string>();
const seenDuplicateExpressionStrings = new Set<string>();
// Given an optional filter function and an optional filter expression, make
// sure that at most one of them was given, and return a filter function that
// does the right thing.
function buildFilterFn(
filterFunction?: (entity: Entity) => boolean,
filterExpression?: string,
): (entity: Entity) => boolean {
if (
filterFunction &&
filterExpression &&
!seenDuplicateExpressionStrings.has(filterExpression)
) {
// eslint-disable-next-line no-console
console.warn(
`Duplicate entity filter methods found, both '${filterExpression}' as well as a callback function, which is not permitted - using the callback`,
);
seenDuplicateExpressionStrings.add(filterExpression);
}
const filter = filterFunction || filterExpression;
if (!filter) {
return () => true;
} else if (typeof filter === 'function') {
return subject => filter(subject);
}
const result = parseFilterExpression(filter);
if (
result.expressionParseErrors.length &&
!seenParseErrorExpressionStrings.has(filter)
) {
// eslint-disable-next-line no-console
console.warn(
`Error(s) in entity filter expression '${filter}'`,
result.expressionParseErrors,
);
seenParseErrorExpressionStrings.add(filter);
}
return result.filterFn;
}
// Handles the memoized parsing of filter expressions for each card
function CardWrapper(props: {
entity: Entity;
element: React.JSX.Element;
filterFunction?: (entity: Entity) => boolean;
filterExpression?: string;
}) {
const { entity, element, filterFunction, filterExpression } = props;
const filterFn = useMemo(
() => buildFilterFn(filterFunction, filterExpression),
[filterFunction, filterExpression],
);
return filterFn(entity) ? (
<Grid item md={6} xs={12}>
{element}
</Grid>
) : null;
}
export function EntityOverviewPage(props: EntityOverviewPageProps) {
const { entity } = useEntity();
return (
<Grid container spacing={3} alignItems="stretch">
{props.cards.map((card, index) => (
<CardWrapper key={index} entity={entity} {...card} />
<FilterWrapper key={index} entity={entity} {...card} />
))}
</Grid>
);
@@ -0,0 +1,88 @@
/*
* 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 { Entity } from '@backstage/catalog-model';
import Grid from '@material-ui/core/Grid';
import React, { useMemo } from 'react';
import { parseFilterExpression } from './parseFilterExpression';
// Keeps track of what filter expression strings that we've seen duplicates of
// with functions, or which emitted parsing errors for so far
const seenParseErrorExpressionStrings = new Set<string>();
const seenDuplicateExpressionStrings = new Set<string>();
// Given an optional filter function and an optional filter expression, make
// sure that at most one of them was given, and return a filter function that
// does the right thing.
export function buildFilterFn(
filterFunction?: (entity: Entity) => boolean,
filterExpression?: string,
): (entity: Entity) => boolean {
if (
filterFunction &&
filterExpression &&
!seenDuplicateExpressionStrings.has(filterExpression)
) {
// eslint-disable-next-line no-console
console.warn(
`Duplicate entity filter methods found, both '${filterExpression}' as well as a callback function, which is not permitted - using the callback`,
);
seenDuplicateExpressionStrings.add(filterExpression);
}
const filter = filterFunction || filterExpression;
if (!filter) {
return () => true;
} else if (typeof filter === 'function') {
return subject => filter(subject);
}
const result = parseFilterExpression(filter);
if (
result.expressionParseErrors.length &&
!seenParseErrorExpressionStrings.has(filter)
) {
// eslint-disable-next-line no-console
console.warn(
`Error(s) in entity filter expression '${filter}'`,
result.expressionParseErrors,
);
seenParseErrorExpressionStrings.add(filter);
}
return result.filterFn;
}
// Handles the memoized parsing of filter expressions
export function FilterWrapper(props: {
entity: Entity;
element: React.JSX.Element;
filterFunction?: (entity: Entity) => boolean;
filterExpression?: string;
}) {
const { entity, element, filterFunction, filterExpression } = props;
const filterFn = useMemo(
() => buildFilterFn(filterFunction, filterExpression),
[filterFunction, filterExpression],
);
return filterFn(entity) ? (
<Grid item md={6} xs={12}>
{element}
</Grid>
) : null;
}
+18 -12
View File
@@ -31,6 +31,7 @@ import {
import { catalogExtensionData } from '@backstage/plugin-catalog-react/alpha';
import { rootRouteRef } from '../routes';
import { useEntityFromUrl } from '../components/CatalogEntityPage/useEntityFromUrl';
import { buildFilterFn } from './filter/FilterWrapper';
export const catalogPage = createPageExtension({
defaultPath: '/catalog',
@@ -57,24 +58,29 @@ export const catalogEntityPage = createPageExtension({
path: coreExtensionData.routePath,
routeRef: coreExtensionData.routeRef.optional(),
title: catalogExtensionData.entityContentTitle,
filterFunction: catalogExtensionData.entityFilterFunction.optional(),
filterExpression: catalogExtensionData.entityFilterExpression.optional(),
}),
},
loader: async ({ inputs }) => {
const { EntityLayout } = await import('../components/EntityLayout');
const Component = () => {
const { entity, ...rest } = useEntityFromUrl();
return (
<AsyncEntityProvider {...useEntityFromUrl()}>
<EntityLayout>
{inputs.contents.map(content => (
<EntityLayout.Route
key={content.output.path}
path={content.output.path}
title={content.output.title}
>
{content.output.element}
</EntityLayout.Route>
))}
</EntityLayout>
<AsyncEntityProvider entity={entity} {...rest}>
{entity ? (
<EntityLayout>
{inputs.contents
.filter(({ output: { filterFunction, filterExpression } }) =>
buildFilterFn(filterFunction, filterExpression)(entity),
)
.map(({ output: { path, title, element } }) => (
<EntityLayout.Route key={path} path={path} title={title}>
{element}
</EntityLayout.Route>
))}
</EntityLayout>
) : null}
</AsyncEntityProvider>
);
};
+2
View File
@@ -4557,9 +4557,11 @@ __metadata:
"@backstage/catalog-model": "workspace:^"
"@backstage/cli": "workspace:^"
"@backstage/core-app-api": "workspace:^"
"@backstage/core-compat-api": "workspace:^"
"@backstage/core-components": "workspace:^"
"@backstage/core-plugin-api": "workspace:^"
"@backstage/dev-utils": "workspace:^"
"@backstage/frontend-plugin-api": "workspace:^"
"@backstage/plugin-catalog": "workspace:^"
"@backstage/plugin-catalog-common": "workspace:^"
"@backstage/plugin-catalog-react": "workspace:^"