Merge pull request #5993 from backstage/mob/feature-flag-component

feat: Feature Flag Component + Simplify the traversal for composability
This commit is contained in:
Ben Lambert
2021-06-17 15:20:05 +02:00
committed by GitHub
27 changed files with 974 additions and 371 deletions
+2
View File
@@ -33,6 +33,7 @@
"@backstage/catalog-client": "^0.3.13",
"@backstage/catalog-model": "^0.8.3",
"@backstage/core": "^0.7.13",
"@backstage/core-plugin-api": "^0.1.2",
"@backstage/errors": "^0.1.1",
"@backstage/integration": "^0.5.6",
"@backstage/integration-react": "^0.1.3",
@@ -54,6 +55,7 @@
},
"devDependencies": {
"@backstage/cli": "^0.7.1",
"@backstage/core-app-api": "^0.1.2",
"@backstage/dev-utils": "^0.1.17",
"@backstage/test-utils": "^0.1.13",
"@testing-library/jest-dom": "^5.10.1",
@@ -29,6 +29,7 @@ import {
Progress,
RoutedTabs,
} from '@backstage/core';
import { useElementFilter } from '@backstage/core-plugin-api';
import {
EntityContext,
EntityRefLinks,
@@ -37,14 +38,7 @@ import {
} from '@backstage/plugin-catalog-react';
import { Box, TabProps } from '@material-ui/core';
import { Alert } from '@material-ui/lab';
import {
Children,
default as React,
Fragment,
isValidElement,
useContext,
useState,
} from 'react';
import React, { useContext, useState } from 'react';
import { useNavigate } from 'react-router';
import { EntityContextMenu } from '../EntityContextMenu/EntityContextMenu';
import { FavouriteEntity } from '../FavouriteEntity/FavouriteEntity';
@@ -58,46 +52,14 @@ type SubRoute = {
tabProps?: TabProps<React.ElementType, { component?: React.ElementType }>;
};
const dataKey = 'plugin.catalog.entityLayoutRoute';
const Route: (props: SubRoute) => null = () => null;
attachComponentData(Route, dataKey, true);
// This causes all mount points that are discovered within this route to use the path of the route itself
attachComponentData(Route, 'core.gatherMountPoints', true);
function createSubRoutesFromChildren(
childrenProps: React.ReactNode,
entity: Entity | undefined,
): SubRoute[] {
// Directly comparing child.type with Route will not work with in
// combination with react-hot-loader in storybook
// https://github.com/gaearon/react-hot-loader/issues/304
const routeType = (
<Route path="" title="">
<div />
</Route>
).type;
return Children.toArray(childrenProps).flatMap(child => {
if (!isValidElement(child)) {
return [];
}
if (child.type === Fragment) {
return createSubRoutesFromChildren(child.props.children, entity);
}
if (child.type !== routeType) {
throw new Error('Child of EntityLayout must be an EntityLayout.Route');
}
const { path, title, children, if: condition, tabProps } = child.props;
if (condition && entity && !condition(entity)) {
return [];
}
return [{ path, title, children, tabProps }];
});
}
const EntityLayoutTitle = ({
entity,
title,
@@ -195,7 +157,29 @@ export const EntityLayout = ({
const { kind, namespace, name } = useEntityCompoundName();
const { entity, loading, error } = useContext(EntityContext);
const routes = createSubRoutesFromChildren(children, entity);
const routes = useElementFilter(children, elements =>
elements
.selectByComponentData({
key: dataKey,
withStrictError: 'Child of EntityLayout must be an EntityLayout.Route',
})
.getElements<SubRoute>() // all nodes, element data, maintain structure or not?
.flatMap(({ props }) => {
if (props.if && entity && !props.if(entity)) {
return [];
}
return [
{
path: props.path,
title: props.title,
children: props.children,
tabProps: props.tabProps,
},
];
}),
);
const { headerTitle, headerType } = headerProps(
kind,
namespace,
@@ -20,6 +20,19 @@ import { render } from '@testing-library/react';
import React from 'react';
import { isKind } from './conditions';
import { EntitySwitch } from './EntitySwitch';
import { featureFlagsApiRef } from '@backstage/core-plugin-api';
import {
LocalStorageFeatureFlags,
ApiProvider,
ApiRegistry,
} from '@backstage/core-app-api';
const mockFeatureFlagsApi = new LocalStorageFeatureFlags();
const Wrapper = ({ children }: { children?: React.ReactNode }) => (
<ApiProvider apis={ApiRegistry.with(featureFlagsApiRef, mockFeatureFlagsApi)}>
{children}
</ApiProvider>
);
describe('EntitySwitch', () => {
it('should switch child when entity switches', () => {
@@ -32,15 +45,17 @@ describe('EntitySwitch', () => {
);
const rendered = render(
<EntityContext.Provider
value={{
entity: { kind: 'component' } as Entity,
loading: false,
error: undefined,
}}
>
{content}
</EntityContext.Provider>,
<Wrapper>
<EntityContext.Provider
value={{
entity: { kind: 'component' } as Entity,
loading: false,
error: undefined,
}}
>
{content}
</EntityContext.Provider>
</Wrapper>,
);
expect(rendered.queryByText('A')).toBeInTheDocument();
@@ -48,15 +63,17 @@ describe('EntitySwitch', () => {
expect(rendered.queryByText('C')).not.toBeInTheDocument();
rendered.rerender(
<EntityContext.Provider
value={{
entity: { kind: 'template' } as Entity,
loading: false,
error: undefined,
}}
>
{content}
</EntityContext.Provider>,
<Wrapper>
<EntityContext.Provider
value={{
entity: { kind: 'template' } as Entity,
loading: false,
error: undefined,
}}
>
{content}
</EntityContext.Provider>
</Wrapper>,
);
expect(rendered.queryByText('A')).not.toBeInTheDocument();
@@ -64,15 +81,17 @@ describe('EntitySwitch', () => {
expect(rendered.queryByText('C')).not.toBeInTheDocument();
rendered.rerender(
<EntityContext.Provider
value={{
entity: { kind: 'derp' } as Entity,
loading: false,
error: undefined,
}}
>
{content}
</EntityContext.Provider>,
<Wrapper>
<EntityContext.Provider
value={{
entity: { kind: 'derp' } as Entity,
loading: false,
error: undefined,
}}
>
{content}
</EntityContext.Provider>
</Wrapper>,
);
expect(rendered.queryByText('A')).not.toBeInTheDocument();
@@ -88,24 +107,28 @@ describe('EntitySwitch', () => {
};
const rendered = render(
<EntityContext.Provider value={entityContextValue}>
<EntitySwitch>
<EntitySwitch.Case if={isKind('component')} children="A" />
<EntitySwitch.Case children="B" />
</EntitySwitch>
</EntityContext.Provider>,
<Wrapper>
<EntityContext.Provider value={entityContextValue}>
<EntitySwitch>
<EntitySwitch.Case if={isKind('component')} children="A" />
<EntitySwitch.Case children="B" />
</EntitySwitch>
</EntityContext.Provider>
</Wrapper>,
);
expect(rendered.queryByText('A')).toBeInTheDocument();
expect(rendered.queryByText('B')).not.toBeInTheDocument();
rendered.rerender(
<EntityContext.Provider value={entityContextValue}>
<EntitySwitch>
<EntitySwitch.Case if={isKind('template')} children="A" />
<EntitySwitch.Case children="B" />
</EntitySwitch>
</EntityContext.Provider>,
<Wrapper>
<EntityContext.Provider value={entityContextValue}>
<EntitySwitch>
<EntitySwitch.Case if={isKind('template')} children="A" />
<EntitySwitch.Case children="B" />
</EntitySwitch>
</EntityContext.Provider>
</Wrapper>,
);
expect(rendered.queryByText('A')).not.toBeInTheDocument();
@@ -16,49 +16,40 @@
import { Entity } from '@backstage/catalog-model';
import { useEntity } from '@backstage/plugin-catalog-react';
import { PropsWithChildren, ReactNode } from 'react';
import {
Children,
Fragment,
isValidElement,
PropsWithChildren,
ReactNode,
useMemo,
} from 'react';
attachComponentData,
useElementFilter,
} from '@backstage/core-plugin-api';
const ENTITY_SWITCH_KEY = 'core.backstage.entitySwitch';
const EntitySwitchCase = (_: {
if?: (entity: Entity) => boolean;
children: ReactNode;
}) => null;
attachComponentData(EntitySwitchCase, ENTITY_SWITCH_KEY, true);
type SwitchCase = {
if?: (entity: Entity) => boolean;
children: JSX.Element;
};
function createSwitchCasesFromChildren(childrenNode: ReactNode): SwitchCase[] {
return Children.toArray(childrenNode).flatMap(child => {
if (!isValidElement(child)) {
return [];
}
if (child.type === Fragment) {
return createSwitchCasesFromChildren(child.props.children);
}
if (child.type !== EntitySwitchCase) {
throw new Error(`Child of EntitySwitch is not an EntitySwitch.Case`);
}
const { if: condition, children } = child.props;
return [{ if: condition, children }];
});
}
export const EntitySwitch = ({ children }: PropsWithChildren<{}>) => {
const { entity } = useEntity();
const switchCases = useMemo(() => createSwitchCasesFromChildren(children), [
children,
]);
const switchCases = useElementFilter(children, collection =>
collection
.selectByComponentData({
key: ENTITY_SWITCH_KEY,
withStrictError: 'Child of EntitySwitch is not an EntitySwitch.Case',
})
.getElements()
.flatMap<SwitchCase>((element: React.ReactElement) => {
const { if: condition, children: elementsChildren } = element.props;
return [{ if: condition, children: elementsChildren }];
}),
);
const matchingCase = switchCases.find(switchCase =>
switchCase.if ? switchCase.if(entity) : true,
+4 -3
View File
@@ -33,11 +33,12 @@
"@backstage/catalog-client": "^0.3.13",
"@backstage/catalog-model": "^0.8.2",
"@backstage/config": "^0.1.5",
"@backstage/errors": "^0.1.1",
"@backstage/core": "^0.7.12",
"@backstage/integration": "^0.5.6",
"@backstage/integration-react": "^0.1.3",
"@backstage/plugin-catalog-react": "^0.2.2",
"@backstage/core-plugin-api": "^0.1.2",
"@backstage/errors": "^0.1.1",
"@backstage/theme": "^0.2.8",
"@material-ui/core": "^4.11.0",
"@material-ui/icons": "^4.9.1",
@@ -46,10 +47,10 @@
"@rjsf/material-ui": "^2.4.0",
"@types/react": "^16.9",
"classnames": "^2.2.6",
"json-schema": "^0.3.0",
"git-url-parse": "^11.4.4",
"humanize-duration": "^3.25.1",
"immer": "^9.0.1",
"json-schema": "^0.3.0",
"luxon": "^1.25.0",
"react": "^16.13.1",
"react-dom": "^16.13.1",
@@ -66,9 +67,9 @@
"@backstage/test-utils": "^0.1.13",
"@testing-library/jest-dom": "^5.10.1",
"@testing-library/react": "^11.2.5",
"@testing-library/react-hooks": "^3.3.0",
"@testing-library/user-event": "^13.1.8",
"@types/humanize-duration": "^3.18.1",
"@testing-library/react-hooks": "^3.3.0",
"@types/jest": "^26.0.7",
"@types/node": "^14.14.32",
"cross-fetch": "^3.0.6",
+14 -11
View File
@@ -14,7 +14,7 @@
* limitations under the License.
*/
import React, { useMemo } from 'react';
import React from 'react';
import { Routes, Route, useOutlet } from 'react-router';
import { ScaffolderPage } from './ScaffolderPage';
import { TemplatePage } from './TemplatePage';
@@ -27,21 +27,24 @@ import {
FIELD_EXTENSION_KEY,
DEFAULT_SCAFFOLDER_FIELD_EXTENSIONS,
} from '../extensions';
import { collectComponentData, collectChildren } from '../extensions/helpers';
import { useElementFilter } from '@backstage/core-plugin-api';
export const Router = () => {
const outlet = useOutlet();
const fieldExtensions = useMemo(() => {
const registeredExtensions = collectComponentData<FieldExtensionOptions>(
collectChildren(outlet, FIELD_EXTENSION_WRAPPER_KEY).flat(),
FIELD_EXTENSION_KEY,
);
const foundExtensions = useElementFilter(outlet, elements =>
elements
.selectByComponentData({
key: FIELD_EXTENSION_WRAPPER_KEY,
})
.findComponentData<FieldExtensionOptions>({
key: FIELD_EXTENSION_KEY,
}),
);
return registeredExtensions.length
? registeredExtensions
: DEFAULT_SCAFFOLDER_FIELD_EXTENSIONS;
}, [outlet]);
const fieldExtensions = foundExtensions.length
? foundExtensions
: DEFAULT_SCAFFOLDER_FIELD_EXTENSIONS;
return (
<Routes>
@@ -1,107 +0,0 @@
/*
* Copyright 2021 Spotify AB
*
* 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 { collectComponentData, collectChildren } from './helpers';
import { attachComponentData } from '@backstage/core';
describe('Extension Helpers', () => {
const createElementWithComponentData = ({
type,
data,
}: {
type: string;
data: any;
}) => {
const element: React.ComponentType = () => null;
attachComponentData(element, type, data);
return element;
};
describe('collectChildren', () => {
it('should return the children of the component which has the correct componentData flag', () => {
const SearchElement = createElementWithComponentData({
type: 'find.me',
data: {},
});
const DontCareAboutme = createElementWithComponentData({
type: 'dont.find.me',
data: {},
});
const child1 = (
<div>
<b>hello</b>
</div>
);
const child2 = (
<div>
<p>Hello2</p>
</div>
);
const testCase = (
<div>
<SearchElement>
{child1}
{child1}
</SearchElement>
<SearchElement>{child2}</SearchElement>
<DontCareAboutme>
<p>Hello!</p>
<SearchElement>{child1}</SearchElement>
</DontCareAboutme>
</div>
);
const children = collectChildren(testCase, 'find.me');
expect(children).toEqual([[child1, child1], child2, child1]);
});
});
describe('collectComponentData', () => {
it('should return the componentData for particular nodes', () => {
const componentData1 = { help: 'im something' };
const componentData2 = { help: 'im something else' };
const FirstElement = createElementWithComponentData({
type: 'find.me',
data: componentData1,
});
const SecondElement = createElementWithComponentData({
type: 'dont.find.me',
data: componentData2,
});
const testCase = [
<FirstElement />,
<FirstElement />,
<SecondElement />,
<FirstElement />,
];
const returnedData = collectComponentData(testCase, 'find.me');
expect(returnedData).toEqual([
componentData1,
componentData1,
componentData1,
]);
});
});
});
@@ -1,73 +0,0 @@
/*
* Copyright 2021 Spotify AB
*
* 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 { getComponentData } from '@backstage/core';
export const collectComponentData = <T>(
children: React.ReactNode,
componentDataKey: string,
) => {
const stack = [children];
const found: T[] = [];
while (stack.length) {
const current: React.ReactNode = stack.pop()!;
React.Children.forEach(current, child => {
if (!React.isValidElement(child)) {
return;
}
const data = getComponentData<T>(child, componentDataKey);
if (data) {
found.push(data);
}
if (child.props.children) {
stack.push(child.props.children);
}
});
}
return found;
};
export const collectChildren = (
component: React.ReactNode,
componentDataKey: string,
) => {
const stack = [component];
const found: React.ReactNode[] = [];
while (stack.length) {
const current: React.ReactNode = stack.pop()!;
React.Children.forEach(current, child => {
if (!React.isValidElement(child)) {
return;
}
if (child.props.children) {
if (getComponentData(child, componentDataKey)) {
found.push(child.props.children);
}
stack.push(child.props.children);
}
});
}
return found;
};