core-api: add mount point collection + extension tweaks

Co-authored-by: blam <ben@blam.sh>
This commit is contained in:
Patrik Oldsberg
2020-11-26 15:36:22 +01:00
parent 18821642ea
commit 632e198616
3 changed files with 239 additions and 6 deletions
+19 -6
View File
@@ -14,7 +14,11 @@
* limitations under the License.
*/
import React, { ExoticComponent, ComponentType } from 'react';
import React, {
NamedExoticComponent,
ComponentType,
PropsWithChildren,
} from 'react';
import { RouteRef } from '../routing';
import { attachComponentData } from './componentData';
import { Extension, BackstagePlugin } from '../plugin/types';
@@ -22,7 +26,12 @@ import { Extension, BackstagePlugin } from '../plugin/types';
export function createRoutableExtension<Props extends {}>(options: {
component: ComponentType<Props>;
mountPoint: RouteRef;
}): Extension<ExoticComponent<Props>> {
// TODO(Rugvip): We want to carry forward the exact props type from the inner component, with
// or without children. ComponentType stops us from doing that though, as it always
// adds children to the props internally. We may want to work around this with custom types.
}): Extension<
NamedExoticComponent<PropsWithChildren<Props & { path?: string }>>
> {
const { component, mountPoint } = options;
return createReactExtension({
component,
@@ -34,7 +43,7 @@ export function createRoutableExtension<Props extends {}>(options: {
export function createComponentExtension<Props extends {}>(options: {
component: ComponentType<Props>;
}): Extension<ExoticComponent<Props>> {
}): Extension<NamedExoticComponent<Props>> {
const { component } = options;
return createReactExtension({ component });
}
@@ -42,10 +51,10 @@ export function createComponentExtension<Props extends {}>(options: {
export function createReactExtension<Props extends {}>(options: {
component: ComponentType<Props>;
data?: Record<string, unknown>;
}): Extension<ExoticComponent<Props>> {
}): Extension<NamedExoticComponent<Props>> {
const { component: Component, data = {} } = options;
return {
expose(plugin: BackstagePlugin): ExoticComponent<Props> {
expose(plugin: BackstagePlugin): NamedExoticComponent<Props> {
const Result = (props: Props) => <Component {...props} />;
attachComponentData(Result, 'core.plugin', plugin);
@@ -53,7 +62,11 @@ export function createReactExtension<Props extends {}>(options: {
attachComponentData(Result, key, value);
}
return Result as ExoticComponent<Props>;
const name = Component.displayName || Component.name || 'Component';
if (name) {
Result.displayName = `Extension(${name})`;
}
return Result as NamedExoticComponent<Props>;
},
};
}
@@ -0,0 +1,145 @@
/*
* Copyright 2020 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, { PropsWithChildren } from 'react';
import { collectRoutes } from './discovery';
import { createRouteRef } from './RouteRef';
import { createPlugin } from '../plugin';
import { createRoutableExtension } from '../lib/extensions';
import { MemoryRouter, Routes, Route } from 'react-router-dom';
const mockConfig = () => ({ path: '/foo', title: 'Foo' });
const MockComponent = ({ children }: PropsWithChildren<{}>) => <>{children}</>;
const plugin = createPlugin({ id: 'my-plugin' });
const ref1 = createRouteRef(mockConfig());
const ref2 = createRouteRef(mockConfig());
const ref3 = createRouteRef(mockConfig());
const ref4 = createRouteRef(mockConfig());
const ref5 = createRouteRef(mockConfig());
const Extension1 = plugin.provide(
createRoutableExtension({ component: MockComponent, mountPoint: ref1 }),
);
const Extension2 = plugin.provide(
createRoutableExtension({ component: MockComponent, mountPoint: ref2 }),
);
const Extension3 = plugin.provide(
createRoutableExtension({ component: MockComponent, mountPoint: ref3 }),
);
const Extension4 = plugin.provide(
createRoutableExtension({ component: MockComponent, mountPoint: ref4 }),
);
const Extension5 = plugin.provide(
createRoutableExtension({ component: MockComponent, mountPoint: ref5 }),
);
describe('discovery', () => {
it('should collect routes', () => {
const list = [
<div key={0} />,
<div key={1} />,
<div key={3}>
<Extension5 path="/blop" />
</div>,
];
const routes = collectRoutes(
<MemoryRouter>
<Routes>
<Extension1 path="/foo">
<div>
<Extension2 path="/bar/:id">
<div>
<div />
Some text here shouldn't be a problem
<div />
{null}
<div />
<Extension3 path="/baz" />
</div>
</Extension2>
{false}
{list}
{true}
{0}
</div>
</Extension1>
<div>
<Route path="/divsoup" element={<Extension4 />} />
</div>
</Routes>
</MemoryRouter>,
);
expect(routes).toEqual(
new Map([
[ref1, '/foo'],
[ref2, '/bar/:id'],
[ref3, '/baz'],
[ref4, '/divsoup'],
[ref5, '/blop'],
]),
);
});
it('should handle all react router Route patterns', () => {
const routes = collectRoutes(
<MemoryRouter>
<Routes>
<Route
path="/foo"
element={
<Extension1>
<Routes>
<Extension2 path="/bar/:id" />
</Routes>
</Extension1>
}
/>
<Route path="/baz" element={<Extension3 path="/not-used" />}>
<Route path="/divsoup" element={<Extension4 />} />
<Extension5 path="/blop" />
</Route>
</Routes>
</MemoryRouter>,
);
expect(routes).toEqual(
new Map([
[ref1, '/foo'],
[ref2, '/bar/:id'],
[ref3, '/baz'],
[ref4, '/divsoup'],
[ref5, '/blop'],
]),
);
});
it('should not visit the same element twice', () => {
const element = <Extension3 path="/baz" />;
expect(() =>
collectRoutes(
<MemoryRouter>
<Extension1 path="/foo">{element}</Extension1>
<Extension2 path="/bar">{element}</Extension2>
</MemoryRouter>,
),
).toThrow(`Visited element Extension(MockComponent) twice`);
});
});
@@ -0,0 +1,75 @@
/*
* Copyright 2020 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, { isValidElement, ReactNode } from 'react';
import { RouteRef } from './types';
import { getComponentData } from '../lib/componentData';
export const collectRoutes = (tree: ReactNode) => {
const treeMap = new Map<RouteRef, string>();
const visited = new Set();
const nodes = [tree];
while (nodes.length !== 0) {
const node = nodes.shift();
if (!isIterableElement(node)) {
continue;
}
if (visited.has(node)) {
const anyType = node?.type as
| { displayName?: string; name?: string }
| undefined;
const name = anyType?.displayName || anyType?.name || String(anyType);
throw new Error(`Visited element ${name} twice`);
}
visited.add(node);
React.Children.forEach(node, child => {
if (!isIterableElement(child)) {
return;
}
const { path, element, children } = child.props as {
path?: string;
element?: ReactNode;
children?: ReactNode;
};
if (path) {
const routeRef = getComponentData<RouteRef>(child, 'core.mountPoint');
if (routeRef) {
treeMap.set(routeRef, path);
} else if (isIterableElement(element)) {
const elementRouteRef = getComponentData<RouteRef>(
element,
'core.mountPoint',
);
if (elementRouteRef) {
treeMap.set(elementRouteRef, path);
}
nodes.push(element.props?.children);
}
}
nodes.push(children);
});
}
return treeMap;
};
function isIterableElement(node: ReactNode): node is JSX.Element {
return isValidElement(node) || Array.isArray(node);
}