Merge branch 'master' of github.com:spotify/backstage into mob/create-vcs-step
This commit is contained in:
@@ -5,3 +5,4 @@
|
||||
registry "https://registry.npmjs.org/"
|
||||
lastUpdateCheck 1580389148099
|
||||
yarn-path ".yarn/releases/yarn-1.22.1.js"
|
||||
network-timeout 600000
|
||||
|
||||
+51
-55
@@ -15,11 +15,11 @@ No, but it can be! Backstage is designed to be a developer portal for all your
|
||||
infrastructure tooling, services, and documentation. So, it's not a monitoring
|
||||
platform — but that doesn't mean you can't integrate a monitoring tool into
|
||||
Backstage by writing
|
||||
[a plugin](https://github.com/spotify/backstage/blob/master/docs/FAQ.md#what-is-a-plugin-in-backstage).
|
||||
[a plugin](/docs/FAQ.md#what-is-a-plugin-in-backstage).
|
||||
|
||||
### How is Backstage licensed?
|
||||
|
||||
Backstage was released as open sourced software by Spotify and is licensed under
|
||||
Backstage was released as open source software by Spotify and is licensed under
|
||||
[Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0).
|
||||
|
||||
### Why did we open source Backstage?
|
||||
@@ -36,16 +36,16 @@ more, read our blog post,
|
||||
|
||||
Yes, we've already started releasing open source versions of some of the plugins
|
||||
we use here, and we'll continue to do so.
|
||||
[Plugins](https://github.com/spotify/faq#what-is-a-plugin-in-backstage) are the
|
||||
[Plugins](/docs/FAQ.md#what-is-a-plugin-in-backstage) are the
|
||||
building blocks of functionality in Backstage. We have over 120 plugins inside
|
||||
Spotify — many of those are specialized for our use, so will remain internal and
|
||||
proprietary to us. But we estimate that about a third of our existing plugins
|
||||
make good open source candidates. (And we'll probably end up writing some brand
|
||||
new ones, too.)
|
||||
new ones, too.)
|
||||
|
||||
### What's the roadmap for Backstage?
|
||||
|
||||
We envision three phases, which you can learn about in
|
||||
We envision three phases, which you can learn about in
|
||||
[our project roadmap](https://github.com/spotify/backstage#project-roadmap).
|
||||
Even though the open source version of Backstage is relatively new compared to
|
||||
our internal version, we have already begun work on various aspects of all three
|
||||
@@ -80,142 +80,138 @@ knew that we would like to use.
|
||||
It strikes a good balance between power, customizability, and ease of use. A
|
||||
core focus of Backstage is to make plugin developers productive with as few
|
||||
hurdles as possible. Material-UI lets plugin makers get going easily with both
|
||||
well-known tech and a large flora of components.
|
||||
well-known tech and a large flora of components.
|
||||
|
||||
### What technology does Backstage use?
|
||||
|
||||
The code base is a large-scale React application that uses TypeScript. For
|
||||
The code base is a large-scale React application that uses TypeScript. For
|
||||
[Phase 2](https://github.com/spotify/backstage#project-roadmap), we plan to use
|
||||
Node.js and GraphQL.
|
||||
Node.js and GraphQL.
|
||||
|
||||
### What is the end-to-end user flow? The happy path story.
|
||||
|
||||
There are three main user profiles for Backstage: the integrator, the
|
||||
contributor, and the software engineer. The **integrator** hosts the Backstage
|
||||
app and configures which plugins are available to use in the app. The
|
||||
**contributor** adds functionality to the app by writing plugins. The
|
||||
**software engineer** uses the app's functionality and interacts with its
|
||||
plugins.
|
||||
There are three main user profiles for Backstage: the integrator, the
|
||||
contributor, and the software engineer.
|
||||
|
||||
### What is the use of a "plugin" in Backstage?
|
||||
The **integrator** hosts the Backstage app and configures which plugins are available to use in the app.
|
||||
|
||||
A Backstage Plugin adds functionality to Backstage.
|
||||
The **contributor** adds functionality to the app by writing plugins.
|
||||
|
||||
The **software engineer** uses the app's functionality and interacts with its plugins.
|
||||
|
||||
### What is a "plugin" in Backstage?
|
||||
|
||||
Plugins are what provide the feature functionality in Backstage. They are used to integrate different systems into Backstage's frontend, so that the developer gets a consistent UX, no matter what tool or service is being accessed on the other side.
|
||||
|
||||
Each plugin is treated as a self-contained web app and can include almost any type of content. Plugins all use a common set of platform APIs and reusable UI components. Plugins can fetch data either from the backend or an API exposed through the proxy.
|
||||
|
||||
Learn more about [the different components](https://github.com/spotify/backstage#overview) that make up Backstage.
|
||||
|
||||
### Do I have to write plugins in TypeScript?
|
||||
|
||||
No, you can use JavaScript if you prefer. We want to keep the Backstage core
|
||||
APIs in TypeScript, but aren't forcing it on individual plugins.
|
||||
No, you can use JavaScript if you prefer. We want to keep the Backstage core
|
||||
APIs in TypeScript, but aren't forcing it on individual plugins.
|
||||
|
||||
### How do I find out if a plugin already exists?
|
||||
|
||||
Before you write a plugin,
|
||||
Before you write a plugin,
|
||||
[search the plugin issues](https://github.com/spotify/backstage/issues?q=is%3Aissue+label%3Aplugin+)
|
||||
to see if it already exists or is in the works. If no one's thought of it yet,
|
||||
great! Open a new issue as
|
||||
[a plugin suggestion](https://github.com/spotify/backstage/issues/new/choose)
|
||||
and describe what your plugin will do. This will help coordinate our
|
||||
contributors' efforts and avoid duplicating existing functionality. In the
|
||||
contributors' efforts and avoid duplicating existing functionality. In the
|
||||
future, we will create
|
||||
[a plugin gallery](https://github.com/spotify/backstage/issues/260) where people
|
||||
can browse and search for all available plugins.
|
||||
can browse and search for all available plugins.
|
||||
|
||||
### Which plugin is used the most at Spotify?
|
||||
|
||||
By far, our most-used plugin is our TechDocs plugin, which we use for creating
|
||||
technical documentation. Our philosophy at Spotify is to treat "docs like code",
|
||||
where you write documentation using the same workflow as you write your code.
|
||||
This makes it easier to create, find, and update documentation. We hope to
|
||||
release
|
||||
[the open source version](https://github.com/spotify/backstage/issues/687) in
|
||||
the future. (See also:
|
||||
"[Will Spotify's internal plugins be open sourced, too?](https://github.com/spotify/faq#will-spotifys-internal-plugins-be-open-sourced-too)"
|
||||
above)
|
||||
By far, our most-used plugin is our TechDocs plugin, which we use for creating technical documentation. Our philosophy at Spotify is to treat "docs like code", where you write documentation using the same workflow as you write your code. This makes it easier to create, find, and update documentation. We hope to release [the open source version](https://github.com/spotify/backstage/issues/687) in the future. (See also: "[Will Spotify's internal plugins be open sourced, too?](/docs/FAQ.md#will-spotifys-internal-plugins-be-open-sourced-too)" above)
|
||||
|
||||
### Are you planning to have plugins baked into the repo? Or should they be developed in separate repos?
|
||||
|
||||
Contributors can add open source plugins to the plugins directory in
|
||||
Contributors can add open source plugins to the plugins directory in
|
||||
[this monorepo](https://github.com/spotify/backstage). Integrators can then
|
||||
configure which open source plugins are available to use in their instance of
|
||||
the app. Open source plugins are downloaded as npm packages published in the
|
||||
open source repository. While we encourage using the open source model, we
|
||||
open source repository. While we encourage using the open source model, we
|
||||
know there are cases where contributors might want to experiment internally or
|
||||
keep their plugins closed source. Contributors writing closed source plugins
|
||||
should develop them in the plugins directory in their own Backstage repository.
|
||||
Integrators also configure closed source plugins locally from the monorepo.
|
||||
Integrators also configure closed source plugins locally from the monorepo.
|
||||
|
||||
### Any plans for integrating with other repository managers, such as GitLab or Bitbucket?
|
||||
|
||||
We chose GitHub because it is the tool that we are most familiar with, so that
|
||||
We chose GitHub because it is the tool that we are most familiar with, so that
|
||||
will naturally lead to integrations for GitHub being developed at an early
|
||||
stage. Hosting this project on GitHub does not exclude integrations with
|
||||
stage. Hosting this project on GitHub does not exclude integrations with
|
||||
alternatives, such as
|
||||
[GitLab](https://github.com/spotify/backstage/issues?q=is%3Aissue+is%3Aopen+GitLab)
|
||||
or Bitbucket. We believe that in time there will be plugins that will provide
|
||||
functionality for these tools as well. Hopefully, contributed by the community!
|
||||
Also note, implementations of Backstage can be hosted wherever you feel suits
|
||||
your needs best.
|
||||
functionality for these tools as well. Hopefully, contributed by the community! Also note, implementations of Backstage can be hosted wherever you feel suits
|
||||
your needs best.
|
||||
|
||||
### Who maintains Backstage?
|
||||
|
||||
Spotify will maintain the open source core, but we envision different parts of
|
||||
Spotify will maintain the open source core, but we envision different parts of
|
||||
the project being maintained by various companies and contributors. We also
|
||||
envision a large, diverse ecosystem of open source plugins, which would be
|
||||
maintained by their original authors/contributors or by the community. When it
|
||||
maintained by their original authors/contributors or by the community. When it
|
||||
comes to
|
||||
[deployment](https://github.com/spotify/backstage/blob/master/DEPLOYMENT.md),
|
||||
the system integrator (typically, the infrastructure team in your organization)
|
||||
maintains Backstage in your own environment.
|
||||
maintains Backstage in your own environment.
|
||||
|
||||
### Does Spotify provide a managed version of Backstage?
|
||||
|
||||
No, this is not a service offering. We build the piece of software, and
|
||||
No, this is not a service offering. We build the piece of software, and
|
||||
someone in your infrastructure team is responsible for
|
||||
[deploying](https://github.com/spotify/backstage/blob/master/DEPLOYMENT.md) and
|
||||
maintaining it.
|
||||
maintaining it.
|
||||
|
||||
### How secure is Backstage?
|
||||
|
||||
We take security seriously. When it comes to packages and code we scan our
|
||||
We take security seriously. When it comes to packages and code we scan our
|
||||
repositories periodically and update our packages to the latest versions. When
|
||||
it comes to deployment of Backstage within an organisation it depends on the
|
||||
deployment and security setup in your organisation. Reach out to us on
|
||||
[Discord](https://discord.gg/MUpMjP2) if you have specific queries.
|
||||
|
||||
Please report sensitive security issues via Spotify's
|
||||
[bug-bounty program](https://hackerone.com/spotify) rather than GitHub.
|
||||
[bug-bounty program](https://hackerone.com/spotify) rather than GitHub.
|
||||
|
||||
### Does Backstage collect any information that is shared with Spotify?
|
||||
|
||||
No. Backstage does not collect any telemetry from any third party using the
|
||||
No. Backstage does not collect any telemetry from any third party using the
|
||||
platform. Spotify, and the open source community, does have access to
|
||||
[GitHub Insights](https://github.com/features/insights), which contains
|
||||
information such as contributors, commits, traffic, and dependencies.
|
||||
information such as contributors, commits, traffic, and dependencies.
|
||||
Backstage is an open platform, but you are in control of your own data. You
|
||||
control who has access to any data you provide to your version of Backstage and
|
||||
who that data is shared with.
|
||||
who that data is shared with.
|
||||
|
||||
### Can Backstage be used to build something other than a developer portal?
|
||||
|
||||
Yes. The core frontend framework could be used for building any large-scale
|
||||
Yes. The core frontend framework could be used for building any large-scale
|
||||
web application where (1) multiple teams are building separate parts of the app,
|
||||
and (2) you want the overall experience to be consistent. That being said, in
|
||||
and (2) you want the overall experience to be consistent. That being said, in
|
||||
[Phase 2](https://github.com/spotify/backstage#project-roadmap) of the project
|
||||
we will add features that are needed for developer portals and systems for
|
||||
managing software ecosystems. Our ambition will be to keep Backstage modular.
|
||||
managing software ecosystems. Our ambition will be to keep Backstage modular.
|
||||
|
||||
### How can I get involved?
|
||||
|
||||
Jump right in! Come help us fix some of the
|
||||
Jump right in! Come help us fix some of the
|
||||
[early bugs and first issues](https://github.com/spotify/backstage/labels/good%20first%20issue)
|
||||
or reach [a new milestone](https://github.com/spotify/backstage/milestones). Or
|
||||
write an open source plugin for Backstage, like this
|
||||
[Lighthouse plugin](https://github.com/spotify/backstage/tree/master/plugins/lighthouse).
|
||||
See all the ways you can
|
||||
See all the ways you can
|
||||
[contribute here](https://github.com/spotify/backstage/blob/master/CONTRIBUTING.md).
|
||||
We'd love to have you as part of the community.
|
||||
We'd love to have you as part of the community.
|
||||
|
||||
### Can I join the Backstage team?
|
||||
|
||||
If you're interested in being part of the Backstage team, reach out to
|
||||
If you're interested in being part of the Backstage team, reach out to
|
||||
[fossopportunities@spotify.com](mailto:fossopportunities@spotify.com)
|
||||
|
||||
+2
-2
@@ -80,7 +80,7 @@ sign-in methods.
|
||||
|
||||
More details are provided in dedicated sections of the documentation.
|
||||
|
||||
- [OAuth](./oauth): Description of the generic OAuth flow implemented by the
|
||||
- [OAuth](./oauth.md): Description of the generic OAuth flow implemented by the
|
||||
[auth-backend](../../plugins/auth-backend).
|
||||
- [Glossary](./glossary): Glossary of some common terms related to the auth
|
||||
- [Glossary](./glossary.md): Glossary of some common terms related to the auth
|
||||
flows.
|
||||
|
||||
@@ -31,7 +31,7 @@ const app = createApp({
|
||||
plugins: Object.values(plugins),
|
||||
components: {
|
||||
SignInPage: props => (
|
||||
<SignInPage {...props} providers={['guest', 'google', 'custom']} />
|
||||
<SignInPage {...props} providers={['guest', 'google', 'custom', 'okta']} />
|
||||
),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -26,10 +26,12 @@ import {
|
||||
FeatureFlags,
|
||||
GoogleAuth,
|
||||
GithubAuth,
|
||||
OktaAuth,
|
||||
oauthRequestApiRef,
|
||||
OAuthRequestManager,
|
||||
googleAuthApiRef,
|
||||
githubAuthApiRef,
|
||||
oktaAuthApiRef,
|
||||
storageApiRef,
|
||||
WebStorage,
|
||||
} from '@backstage/core';
|
||||
@@ -91,6 +93,15 @@ export const apis = (config: ConfigApi) => {
|
||||
}),
|
||||
);
|
||||
|
||||
builder.add(
|
||||
oktaAuthApiRef,
|
||||
OktaAuth.create({
|
||||
apiOrigin: 'http://localhost:7000',
|
||||
basePath: '/auth/',
|
||||
oauthRequestApi,
|
||||
}),
|
||||
);
|
||||
|
||||
builder.add(
|
||||
techRadarApiRef,
|
||||
new TechRadar({
|
||||
|
||||
@@ -22,6 +22,7 @@ import ExploreIcon from '@material-ui/icons/Explore';
|
||||
import BuildIcon from '@material-ui/icons/BuildRounded';
|
||||
import RuleIcon from '@material-ui/icons/AssignmentTurnedIn';
|
||||
import MapIcon from '@material-ui/icons/MyLocation';
|
||||
import LibraryBooks from '@material-ui/icons/LibraryBooks';
|
||||
import CreateComponentIcon from '@material-ui/icons/AddCircleOutline';
|
||||
import LogoFull from './LogoFull';
|
||||
import LogoIcon from './LogoIcon';
|
||||
@@ -89,6 +90,7 @@ const Root: FC<{}> = ({ children }) => (
|
||||
{/* Global nav, not org-specific */}
|
||||
<SidebarItem icon={HomeIcon} to="./" text="Home" />
|
||||
<SidebarItem icon={ExploreIcon} to="explore" text="Explore" />
|
||||
<SidebarItem icon={LibraryBooks} to="docs" text="Docs" />
|
||||
<SidebarItem icon={CreateComponentIcon} to="create" text="Create..." />
|
||||
{/* End global nav */}
|
||||
<SidebarDivider />
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
FROM node:12
|
||||
|
||||
WORKDIR /usr/src/app
|
||||
|
||||
COPY . .
|
||||
|
||||
RUN yarn install --frozen-lockfile --production
|
||||
|
||||
CMD ["node", "packages/backend"]
|
||||
@@ -10,6 +10,7 @@
|
||||
},
|
||||
"scripts": {
|
||||
"build": "backstage-cli backend:build",
|
||||
"build-image": "backstage-cli backend:build-image example-backend",
|
||||
"start": "backstage-cli backend:dev",
|
||||
"lint": "backstage-cli lint",
|
||||
"test": "backstage-cli test",
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import { buildPackage, Output } from '../../lib/packager';
|
||||
import { buildPackage, Output } from '../../lib/builder';
|
||||
|
||||
export default async () => {
|
||||
await buildPackage({
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
/*
|
||||
* 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 fs from 'fs-extra';
|
||||
import { createDistWorkspace } from '../../lib/packager';
|
||||
import { paths } from '../../lib/paths';
|
||||
import { run } from '../../lib/run';
|
||||
|
||||
export default async (imageTag: string) => {
|
||||
const tempDistWorkspace = await createDistWorkspace(['example-backend'], {
|
||||
files: [
|
||||
'package.json',
|
||||
'yarn.lock',
|
||||
'app-config.yaml',
|
||||
{ src: paths.resolveTarget('Dockerfile'), dest: 'Dockerfile' },
|
||||
],
|
||||
});
|
||||
|
||||
console.log(`Dist workspace ready at ${tempDistWorkspace}`);
|
||||
|
||||
await run('docker', ['build', '.', '-t', imageTag], {
|
||||
cwd: tempDistWorkspace,
|
||||
});
|
||||
|
||||
await fs.remove(tempDistWorkspace);
|
||||
};
|
||||
@@ -14,7 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import { buildPackage, Output } from '../lib/packager';
|
||||
import { buildPackage, Output } from '../lib/builder';
|
||||
import { Command } from 'commander';
|
||||
|
||||
export default async (cmd: Command) => {
|
||||
|
||||
@@ -19,10 +19,15 @@ import { paths } from '../lib/paths';
|
||||
|
||||
const SKIPPED_KEYS = ['access', 'registry', 'tag'];
|
||||
|
||||
export const pre = async () => {
|
||||
const pkgPath = paths.resolveTarget('package.json');
|
||||
const PKG_PATH = 'package.json';
|
||||
const PKG_BACKUP_PATH = 'package.json-prepack';
|
||||
|
||||
const pkg = await fs.readJson(pkgPath);
|
||||
export const pre = async () => {
|
||||
const pkgPath = paths.resolveTarget(PKG_PATH);
|
||||
|
||||
const pkgContent = await fs.readFile(pkgPath, 'utf8');
|
||||
const pkg = JSON.parse(pkgContent);
|
||||
await fs.writeFile(PKG_BACKUP_PATH, pkgContent);
|
||||
|
||||
for (const key of Object.keys(pkg.publishConfig ?? {})) {
|
||||
if (!SKIPPED_KEYS.includes(key)) {
|
||||
@@ -33,5 +38,6 @@ export const pre = async () => {
|
||||
};
|
||||
|
||||
export const post = async () => {
|
||||
// postpack is a noop for now, since it's not called anyway
|
||||
// postpack isn't called by yarn right now, so it needs to be called manually
|
||||
await fs.move(PKG_BACKUP_PATH, PKG_PATH, { overwrite: true });
|
||||
};
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import { buildPackage, Output } from '../../lib/packager';
|
||||
import { buildPackage, Output } from '../../lib/builder';
|
||||
|
||||
export default async () => {
|
||||
await buildPackage({
|
||||
|
||||
@@ -46,6 +46,15 @@ const main = (argv: string[]) => {
|
||||
.description('Build a backend plugin')
|
||||
.action(lazyAction(() => import('./commands/backend/build'), 'default'));
|
||||
|
||||
program
|
||||
.command('backend:build-image <image-tag>')
|
||||
.description(
|
||||
'Builds a docker image from the package, with all local deps included',
|
||||
)
|
||||
.action(
|
||||
lazyAction(() => import('./commands/backend/buildImage'), 'default'),
|
||||
);
|
||||
|
||||
program
|
||||
.command('backend:dev')
|
||||
.description('Start local development server with HMR for the backend')
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
/*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
export { buildPackage } from './packager';
|
||||
export { Output } from './types';
|
||||
export type { BuildOptions } from './types';
|
||||
@@ -14,6 +14,133 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
export { buildPackage } from './packager';
|
||||
export { Output } from './types';
|
||||
export type { BuildOptions } from './types';
|
||||
import fs from 'fs-extra';
|
||||
import { resolve as resolvePath, relative as relativePath } from 'path';
|
||||
import { paths } from '../paths';
|
||||
import { run } from '../run';
|
||||
import tar from 'tar';
|
||||
import { tmpdir } from 'os';
|
||||
|
||||
type LernaPackage = {
|
||||
name: string;
|
||||
private: boolean;
|
||||
location: string;
|
||||
scripts: Record<string, string>;
|
||||
};
|
||||
|
||||
type FileEntry =
|
||||
| string
|
||||
| {
|
||||
src: string;
|
||||
dest: string;
|
||||
};
|
||||
|
||||
type Options = {
|
||||
/**
|
||||
* Target directory for the dist workspace, defaults to a temporary directory
|
||||
*/
|
||||
targetDir?: string;
|
||||
|
||||
/**
|
||||
* Files to copy into the target workspace.
|
||||
*
|
||||
* Defaults to ['yarn.lock', 'package.json'].
|
||||
*/
|
||||
files?: FileEntry[];
|
||||
};
|
||||
|
||||
/**
|
||||
* Uses `yarn pack` to package local packages and unpacks them into a dist workspace.
|
||||
* The target workspace will end up containing dist version of each package and
|
||||
* will be suitable for packaging e.g. into a docker image.
|
||||
*
|
||||
* This creates a structure that is functionally similar to if the packages where
|
||||
* installed from NPM, but uses yarn workspaces to link to them at runtime.
|
||||
*/
|
||||
export async function createDistWorkspace(
|
||||
packageNames: string[],
|
||||
options: Options,
|
||||
) {
|
||||
const targetDir =
|
||||
options.targetDir ??
|
||||
(await fs.mkdtemp(resolvePath(tmpdir(), 'dist-workspace')));
|
||||
|
||||
const targets = await findTargetPackages(packageNames);
|
||||
|
||||
await moveToDistWorkspace(targetDir, targets);
|
||||
|
||||
const files: FileEntry[] = options.files ?? ['yarn.lock', 'package.json'];
|
||||
|
||||
for (const file of files) {
|
||||
const src = typeof file === 'string' ? file : file.src;
|
||||
const dest = typeof file === 'string' ? file : file.dest;
|
||||
await fs.copy(paths.resolveTargetRoot(src), resolvePath(targetDir, dest));
|
||||
}
|
||||
return targetDir;
|
||||
}
|
||||
|
||||
async function moveToDistWorkspace(
|
||||
workspaceDir: string,
|
||||
localPackages: LernaPackage[],
|
||||
): Promise<void> {
|
||||
await Promise.all(
|
||||
localPackages.map(async (target, index) => {
|
||||
console.log(`Repacking ${target.name} into dist workspace`);
|
||||
const archive = `temp-package-${index}.tgz`;
|
||||
const archivePath = resolvePath(workspaceDir, archive);
|
||||
|
||||
await run('yarn', ['pack', '--filename', archivePath], {
|
||||
cwd: target.location,
|
||||
});
|
||||
// TODO(Rugvip): yarn pack doesn't call postpack, once the bug is fixed this can be removed
|
||||
if (target.scripts.postpack) {
|
||||
await run('yarn', ['postpack'], { cwd: target.location });
|
||||
}
|
||||
|
||||
const outputDir = relativePath(paths.targetRoot, target.location);
|
||||
const absoluteOutputPath = resolvePath(workspaceDir, outputDir);
|
||||
await fs.ensureDir(absoluteOutputPath);
|
||||
|
||||
await tar.extract({
|
||||
file: archivePath,
|
||||
cwd: absoluteOutputPath,
|
||||
strip: 1,
|
||||
});
|
||||
await fs.remove(archivePath);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
async function findTargetPackages(pkgNames: string[]): Promise<LernaPackage[]> {
|
||||
const LernaProject = require('@lerna/project');
|
||||
const PackageGraph = require('@lerna/package-graph');
|
||||
|
||||
const project = new LernaProject(paths.targetDir);
|
||||
const packages = await project.getPackages();
|
||||
const graph = new PackageGraph(packages);
|
||||
|
||||
const targets = new Map<string, any>();
|
||||
const searchNames = pkgNames.slice();
|
||||
|
||||
while (searchNames.length) {
|
||||
const name = searchNames.pop()!;
|
||||
|
||||
if (targets.has(name)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const node = graph.get(name);
|
||||
if (!node) {
|
||||
throw new Error(`Package '${name}' not found`);
|
||||
}
|
||||
|
||||
const pkgDeps = Object.keys(node.pkg.dependencies);
|
||||
const localDeps: string[] = Array.from(node.localDependencies.keys());
|
||||
const filteredDeps = localDeps.filter(dep => pkgDeps.includes(dep));
|
||||
|
||||
searchNames.push(...filteredDeps);
|
||||
targets.set(name, node.pkg);
|
||||
}
|
||||
|
||||
return Array.from(targets.values());
|
||||
}
|
||||
|
||||
@@ -233,3 +233,20 @@ export const githubAuthApiRef = createApiRef<
|
||||
id: 'core.auth.github',
|
||||
description: 'Provides authentication towards Github APIs',
|
||||
});
|
||||
|
||||
/**
|
||||
* Provides authentication towards Okta APIs.
|
||||
*
|
||||
* See https://developer.okta.com/docs/guides/implement-oauth-for-okta/scopes/
|
||||
* for a full list of supported scopes.
|
||||
*/
|
||||
export const oktaAuthApiRef = createApiRef<
|
||||
OAuthApi &
|
||||
OpenIdConnectApi &
|
||||
ProfileInfoApi &
|
||||
BackstageIdentityApi &
|
||||
SessionStateApi
|
||||
>({
|
||||
id: 'core.auth.okta',
|
||||
description: 'Provides authentication towards Okta APIs',
|
||||
});
|
||||
|
||||
@@ -16,3 +16,4 @@
|
||||
|
||||
export * from './google';
|
||||
export * from './github';
|
||||
export * from './okta';
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
/*
|
||||
* 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 OktaAuth from './OktaAuth';
|
||||
|
||||
const theFuture = new Date(Date.now() + 3600000);
|
||||
const thePast = new Date(Date.now() - 10);
|
||||
|
||||
const PREFIX = 'okta.';
|
||||
|
||||
describe('OktaAuth', () => {
|
||||
it('should get refreshed access token', async () => {
|
||||
const getSession = jest.fn().mockResolvedValue({
|
||||
providerInfo: { accessToken: 'access-token', expiresAt: theFuture },
|
||||
});
|
||||
const oktaAuth = new OktaAuth({ getSession } as any);
|
||||
|
||||
expect(await oktaAuth.getAccessToken()).toBe('access-token');
|
||||
expect(getSession).toBeCalledTimes(1);
|
||||
});
|
||||
|
||||
it('should get refreshed id token', async () => {
|
||||
const getSession = jest.fn().mockResolvedValue({
|
||||
providerInfo: { idToken: 'id-token', expiresAt: theFuture },
|
||||
});
|
||||
const oktaAuth = new OktaAuth({ getSession } as any);
|
||||
|
||||
expect(await oktaAuth.getIdToken()).toBe('id-token');
|
||||
expect(getSession).toBeCalledTimes(1);
|
||||
});
|
||||
|
||||
it('should get optional id token', async () => {
|
||||
const getSession = jest.fn().mockResolvedValue({
|
||||
providerInfo: { idToken: 'id-token', expiresAt: theFuture },
|
||||
});
|
||||
const oktaAuth = new OktaAuth({ getSession } as any);
|
||||
|
||||
expect(await oktaAuth.getIdToken({ optional: true })).toBe('id-token');
|
||||
expect(getSession).toBeCalledTimes(1);
|
||||
});
|
||||
|
||||
it('should share popup closed errors', async () => {
|
||||
const error = new Error('NOPE');
|
||||
error.name = 'RejectedError';
|
||||
const getSession = jest
|
||||
.fn()
|
||||
.mockResolvedValueOnce({
|
||||
providerInfo: {
|
||||
accessToken: 'access-token',
|
||||
expiresAt: theFuture,
|
||||
scopes: new Set([`not-a-scope`]),
|
||||
},
|
||||
})
|
||||
.mockRejectedValue(error);
|
||||
const oktaAuth = new OktaAuth({ getSession } as any);
|
||||
|
||||
// Make sure we have a session before we do the double request, so that we get past the !this.currentSession check
|
||||
await expect(oktaAuth.getAccessToken()).resolves.toBe('access-token');
|
||||
|
||||
const promise1 = oktaAuth.getAccessToken('more');
|
||||
const promise2 = oktaAuth.getAccessToken('more');
|
||||
await expect(promise1).rejects.toBe(error);
|
||||
await expect(promise2).rejects.toBe(error);
|
||||
expect(getSession).toBeCalledTimes(3);
|
||||
});
|
||||
|
||||
it('should wait for all session refreshes', async () => {
|
||||
const initialSession = {
|
||||
providerInfo: {
|
||||
idToken: 'token1',
|
||||
expiresAt: theFuture,
|
||||
scopes: new Set(),
|
||||
},
|
||||
};
|
||||
const getSession = jest
|
||||
.fn()
|
||||
.mockResolvedValueOnce(initialSession)
|
||||
.mockResolvedValue({
|
||||
providerInfo: {
|
||||
idToken: 'token2',
|
||||
expiresAt: theFuture,
|
||||
scopes: new Set(),
|
||||
},
|
||||
});
|
||||
const oktaAuth = new OktaAuth({ getSession } as any);
|
||||
|
||||
// Grab the expired session first
|
||||
await expect(oktaAuth.getIdToken()).resolves.toBe('token1');
|
||||
expect(getSession).toBeCalledTimes(1);
|
||||
|
||||
initialSession.providerInfo.expiresAt = thePast;
|
||||
|
||||
const promise1 = oktaAuth.getIdToken();
|
||||
const promise2 = oktaAuth.getIdToken();
|
||||
const promise3 = oktaAuth.getIdToken();
|
||||
await expect(promise1).resolves.toBe('token2');
|
||||
await expect(promise2).resolves.toBe('token2');
|
||||
await expect(promise3).resolves.toBe('token2');
|
||||
expect(getSession).toBeCalledTimes(4); // De-duping of session requests happens in client
|
||||
});
|
||||
|
||||
it.each([
|
||||
['openid', ['openid']],
|
||||
['profile email', ['profile', 'email']],
|
||||
[`${PREFIX}groups.manage`, [`${PREFIX}groups.manage`]],
|
||||
['groups.read', [`${PREFIX}groups.read`]],
|
||||
[`${PREFIX}groups.manage groups.read, openid`, [`${PREFIX}groups.manage`, `${PREFIX}groups.read`, 'openid']],
|
||||
[`email\t ${PREFIX}groups.read`, ['email', `${PREFIX}groups.read`]],
|
||||
|
||||
// Some incorrect scopes that we don't try to fix
|
||||
[`${PREFIX}email`, [`${PREFIX}email`]],
|
||||
[`${PREFIX}profile`, [`${PREFIX}profile`]],
|
||||
[`${PREFIX}openid`, [`${PREFIX}openid`]],
|
||||
])(`should normalize scopes correctly - %p`, (scope, scopes) => {
|
||||
expect(OktaAuth.normalizeScopes(scope)).toEqual(new Set(scopes));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,186 @@
|
||||
/*
|
||||
* 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 OktaIcon from '@material-ui/icons/AcUnit';
|
||||
import { DefaultAuthConnector } from '../../../../lib/AuthConnector';
|
||||
import { OktaSession } from './types';
|
||||
import {
|
||||
OAuthApi,
|
||||
OpenIdConnectApi,
|
||||
ProfileInfoApi,
|
||||
ProfileInfo,
|
||||
SessionStateApi,
|
||||
SessionState,
|
||||
BackstageIdentityApi,
|
||||
AuthRequestOptions,
|
||||
BackstageIdentity,
|
||||
} from '../../../definitions/auth';
|
||||
import { OAuthRequestApi, AuthProvider } from '../../../definitions';
|
||||
import { SessionManager } from '../../../../lib/AuthSessionManager/types';
|
||||
import { RefreshingAuthSessionManager } from '../../../../lib/AuthSessionManager';
|
||||
import { Observable } from '../../../../types';
|
||||
|
||||
type CreateOptions = {
|
||||
apiOrigin: string;
|
||||
basePath: string;
|
||||
|
||||
oauthRequestApi: OAuthRequestApi;
|
||||
|
||||
environment?: string;
|
||||
provider?: AuthProvider & { id: string };
|
||||
};
|
||||
|
||||
export type OktaAuthResponse = {
|
||||
providerInfo: {
|
||||
accessToken: string;
|
||||
idToken: string;
|
||||
scope: string;
|
||||
expiresInSeconds: number;
|
||||
};
|
||||
profile: ProfileInfo;
|
||||
backstageIdentity: BackstageIdentity;
|
||||
};
|
||||
|
||||
const DEFAULT_PROVIDER = {
|
||||
id: 'okta',
|
||||
title: 'Okta',
|
||||
icon: OktaIcon,
|
||||
};
|
||||
|
||||
const OKTA_OIDC_SCOPES: Set<String> = new Set(
|
||||
['openid', 'profile', 'email', 'phone', 'address', 'groups', 'offline_access']
|
||||
)
|
||||
|
||||
const OKTA_SCOPE_PREFIX: string = 'okta.'
|
||||
|
||||
class OktaAuth implements
|
||||
OAuthApi,
|
||||
OpenIdConnectApi,
|
||||
ProfileInfoApi,
|
||||
BackstageIdentityApi,
|
||||
SessionStateApi
|
||||
{
|
||||
static create({
|
||||
apiOrigin,
|
||||
basePath,
|
||||
environment = 'development',
|
||||
provider = DEFAULT_PROVIDER,
|
||||
oauthRequestApi,
|
||||
}: CreateOptions) {
|
||||
const connector = new DefaultAuthConnector({
|
||||
apiOrigin,
|
||||
basePath,
|
||||
environment,
|
||||
provider,
|
||||
oauthRequestApi: oauthRequestApi,
|
||||
sessionTransform(res: OktaAuthResponse): OktaSession {
|
||||
return {
|
||||
...res,
|
||||
providerInfo: {
|
||||
idToken: res.providerInfo.idToken,
|
||||
accessToken: res.providerInfo.accessToken,
|
||||
scopes: OktaAuth.normalizeScopes(res.providerInfo.scope),
|
||||
expiresAt: new Date(
|
||||
Date.now() + res.providerInfo.expiresInSeconds * 1000,
|
||||
),
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
const sessionManager = new RefreshingAuthSessionManager({
|
||||
connector,
|
||||
defaultScopes: new Set([
|
||||
'openid',
|
||||
'email',
|
||||
'profile',
|
||||
'offline_access',
|
||||
]),
|
||||
sessionScopes: session => session.scopes,
|
||||
sessionShouldRefresh: session => {
|
||||
const expiresInSec =
|
||||
(session.providerInfo.expiresAt.getTime() - Date.now()) / 1000;
|
||||
return expiresInSec < 60 * 5;
|
||||
},
|
||||
});
|
||||
|
||||
return new OktaAuth(sessionManager);
|
||||
}
|
||||
|
||||
sessionState$(): Observable<SessionState> {
|
||||
return this.sessionManager.sessionState$();
|
||||
}
|
||||
|
||||
constructor(private readonly sessionManager: SessionManager<OktaSession>) {}
|
||||
|
||||
async getAccessToken(
|
||||
scope?: string,
|
||||
options?: AuthRequestOptions
|
||||
) {
|
||||
const session = await this.sessionManager.getSession({
|
||||
...options,
|
||||
scopes: OktaAuth.normalizeScopes(scope),
|
||||
});
|
||||
return session?.providerInfo.accessToken ?? '';
|
||||
}
|
||||
|
||||
async getIdToken(options: AuthRequestOptions = {}) {
|
||||
const session = await this.sessionManager.getSession(options);
|
||||
return session?.providerInfo.idToken ?? '';
|
||||
}
|
||||
|
||||
async logout() {
|
||||
await this.sessionManager.removeSession();
|
||||
}
|
||||
|
||||
async getBackstageIdentity(
|
||||
options: AuthRequestOptions = {},
|
||||
): Promise<BackstageIdentity | undefined> {
|
||||
const session = await this.sessionManager.getSession(options);
|
||||
return session?.backstageIdentity;
|
||||
}
|
||||
|
||||
async getProfile(options: AuthRequestOptions = {}) {
|
||||
const session = await this.sessionManager.getSession(options);
|
||||
return session?.profile;
|
||||
}
|
||||
|
||||
static normalizeScopes(scopes?: string | string[]): Set<string> {
|
||||
if (!scopes) {
|
||||
return new Set();
|
||||
}
|
||||
|
||||
const scopeList = Array.isArray(scopes)
|
||||
? scopes
|
||||
: scopes.split(/[\s|,]/).filter(Boolean);
|
||||
|
||||
const normalizedScopes = scopeList.map(scope => {
|
||||
if (OKTA_OIDC_SCOPES.has(scope)) {
|
||||
return scope;
|
||||
}
|
||||
|
||||
if (scope.startsWith(OKTA_SCOPE_PREFIX)) {
|
||||
return scope;
|
||||
}
|
||||
|
||||
return `${OKTA_SCOPE_PREFIX}${scope}`
|
||||
});
|
||||
|
||||
return new Set(normalizedScopes);
|
||||
}
|
||||
}
|
||||
|
||||
export default OktaAuth;
|
||||
@@ -0,0 +1,18 @@
|
||||
/*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
export * from './types';
|
||||
export { default as OktaAuth } from './OktaAuth';
|
||||
@@ -0,0 +1,27 @@
|
||||
/*
|
||||
* 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 { ProfileInfo, BackstageIdentity } from '../../../definitions';
|
||||
|
||||
export type OktaSession = {
|
||||
providerInfo: {
|
||||
idToken: string;
|
||||
accessToken: string;
|
||||
scopes: Set<string>;
|
||||
expiresAt: Date;
|
||||
};
|
||||
profile: ProfileInfo;
|
||||
backstageIdentity: BackstageIdentity;
|
||||
};
|
||||
@@ -40,7 +40,7 @@
|
||||
"classnames": "^2.2.6",
|
||||
"clsx": "^1.1.0",
|
||||
"lodash": "^4.17.15",
|
||||
"material-table": "^1.58.0",
|
||||
"material-table": "1.62.x",
|
||||
"prop-types": "^15.7.2",
|
||||
"rc-progress": "^3.0.0",
|
||||
"react": "^16.12.0",
|
||||
|
||||
@@ -14,18 +14,8 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import React, { FC, forwardRef } from 'react';
|
||||
import MTable, {
|
||||
MTableCell,
|
||||
MTableHeader,
|
||||
MTableToolbar,
|
||||
MaterialTableProps,
|
||||
Options,
|
||||
Column,
|
||||
} from 'material-table';
|
||||
import { BackstageTheme } from '@backstage/theme';
|
||||
import { makeStyles, useTheme, Typography } from '@material-ui/core';
|
||||
|
||||
import { makeStyles, Typography, useTheme } from '@material-ui/core';
|
||||
// Material-table is not using the standard icons available in in material-ui. https://github.com/mbrn/material-table/issues/51
|
||||
import AddBox from '@material-ui/icons/AddBox';
|
||||
import ArrowUpward from '@material-ui/icons/ArrowUpward';
|
||||
@@ -42,6 +32,15 @@ import Remove from '@material-ui/icons/Remove';
|
||||
import SaveAlt from '@material-ui/icons/SaveAlt';
|
||||
import Search from '@material-ui/icons/Search';
|
||||
import ViewColumn from '@material-ui/icons/ViewColumn';
|
||||
import MTable, {
|
||||
Column,
|
||||
MaterialTableProps,
|
||||
MTableCell,
|
||||
MTableHeader,
|
||||
MTableToolbar,
|
||||
Options,
|
||||
} from 'material-table';
|
||||
import React, { forwardRef } from 'react';
|
||||
|
||||
const tableIcons = {
|
||||
Add: forwardRef((props, ref: React.Ref<SVGSVGElement>) => (
|
||||
@@ -131,10 +130,10 @@ const useToolbarStyles = makeStyles<BackstageTheme>(theme => ({
|
||||
},
|
||||
}));
|
||||
|
||||
const convertColumns = (
|
||||
columns: TableColumn[],
|
||||
function convertColumns<T extends object>(
|
||||
columns: TableColumn<T>[],
|
||||
theme: BackstageTheme,
|
||||
): TableColumn[] => {
|
||||
): TableColumn<T>[] {
|
||||
return columns.map(column => {
|
||||
const headerStyle: React.CSSProperties = {};
|
||||
const cellStyle: React.CSSProperties = {};
|
||||
@@ -150,25 +149,26 @@ const convertColumns = (
|
||||
cellStyle,
|
||||
};
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
export interface TableColumn extends Column<{}> {
|
||||
export interface TableColumn<T extends object = {}> extends Column<T> {
|
||||
highlight?: boolean;
|
||||
width?: string;
|
||||
}
|
||||
|
||||
export interface TableProps extends MaterialTableProps<{}> {
|
||||
columns: TableColumn[];
|
||||
export interface TableProps<T extends object = {}>
|
||||
extends MaterialTableProps<T> {
|
||||
columns: TableColumn<T>[];
|
||||
subtitle?: string;
|
||||
}
|
||||
|
||||
export const Table: FC<TableProps> = ({
|
||||
export function Table<T extends object = {}>({
|
||||
columns,
|
||||
options,
|
||||
title,
|
||||
subtitle,
|
||||
...props
|
||||
}) => {
|
||||
}: TableProps<T>) {
|
||||
const cellClasses = useCellStyles();
|
||||
const headerClasses = useHeaderStyles();
|
||||
const toolbarClasses = useToolbarStyles();
|
||||
@@ -183,7 +183,7 @@ export const Table: FC<TableProps> = ({
|
||||
};
|
||||
|
||||
return (
|
||||
<MTable
|
||||
<MTable<T>
|
||||
components={{
|
||||
Cell: cellProps => (
|
||||
<MTableCell className={cellClasses.root} {...cellProps} />
|
||||
@@ -211,4 +211,4 @@ export const Table: FC<TableProps> = ({
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
@@ -15,5 +15,5 @@
|
||||
*/
|
||||
|
||||
export { Table } from './Table';
|
||||
export type { TableColumn } from './Table';
|
||||
export type { TableColumn, TableProps } from './Table';
|
||||
export { SubvalueCell } from './SubvalueCell';
|
||||
|
||||
@@ -42,14 +42,15 @@ export type Tab = {
|
||||
id: string;
|
||||
label: string;
|
||||
};
|
||||
|
||||
export const HeaderTabs: React.FC<{
|
||||
tabs: Tab[];
|
||||
onChange?: (index: Number) => void;
|
||||
onChange?: (index: number) => void;
|
||||
}> = ({ tabs, onChange }) => {
|
||||
const [selectedTab, setSelectedTab] = useState<Number>(0);
|
||||
const [selectedTab, setSelectedTab] = useState<number>(0);
|
||||
const styles = useStyles();
|
||||
|
||||
const handleChange = (_: React.ChangeEvent<{}>, index: Number) => {
|
||||
const handleChange = (_: React.ChangeEvent<{}>, index: number) => {
|
||||
setSelectedTab(index);
|
||||
if (onChange) onChange(index);
|
||||
};
|
||||
|
||||
@@ -23,6 +23,7 @@ import {
|
||||
googleAuthApiRef,
|
||||
githubAuthApiRef,
|
||||
identityApiRef,
|
||||
oktaAuthApiRef,
|
||||
useApi,
|
||||
} from '@backstage/core-api';
|
||||
import {
|
||||
@@ -56,6 +57,11 @@ export function SidebarUserSettings() {
|
||||
apiRef={githubAuthApiRef}
|
||||
icon={Star}
|
||||
/>
|
||||
<OIDCProviderSettings
|
||||
title="Okta"
|
||||
apiRef={oktaAuthApiRef}
|
||||
icon={Star}
|
||||
/>
|
||||
<SidebarItem
|
||||
icon={SignOutIcon}
|
||||
text="Sign Out"
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
/*
|
||||
* 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 from 'react';
|
||||
import { Grid, Typography, Button } from '@material-ui/core';
|
||||
import { InfoCard } from '../InfoCard/InfoCard';
|
||||
import { ProviderComponent, ProviderLoader, SignInProvider } from './types';
|
||||
import {
|
||||
useApi,
|
||||
oktaAuthApiRef,
|
||||
errorApiRef,
|
||||
} from '@backstage/core-api';
|
||||
|
||||
const Component: ProviderComponent = ({ onResult }) => {
|
||||
const oktaAuthApi = useApi(oktaAuthApiRef);
|
||||
const errorApi = useApi(errorApiRef);
|
||||
|
||||
const handleLogin = async () => {
|
||||
try {
|
||||
const identity = await oktaAuthApi.getBackstageIdentity({
|
||||
instantPopup: true,
|
||||
});
|
||||
|
||||
const profile = await oktaAuthApi.getProfile();
|
||||
|
||||
onResult({
|
||||
userId: identity!.id,
|
||||
profile: profile!,
|
||||
getIdToken: () =>
|
||||
oktaAuthApi.getBackstageIdentity().then(i => i!.idToken),
|
||||
logout: async () => {
|
||||
await oktaAuthApi.logout();
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
errorApi.post(error);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Grid item>
|
||||
<InfoCard
|
||||
title="Okta"
|
||||
actions={
|
||||
<Button color="primary" variant="outlined" onClick={handleLogin}>
|
||||
Sign In
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
<Typography variant="body1">Sign In using Okta</Typography>
|
||||
</InfoCard>
|
||||
</Grid>
|
||||
);
|
||||
};
|
||||
|
||||
const loader: ProviderLoader = async apis => {
|
||||
const oktaAuthApi = apis.get(oktaAuthApiRef)!;
|
||||
|
||||
const identity = await oktaAuthApi.getBackstageIdentity({
|
||||
optional: true,
|
||||
});
|
||||
|
||||
if (!identity) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const profile = await oktaAuthApi.getProfile();
|
||||
|
||||
return {
|
||||
userId: identity.id,
|
||||
profile: profile!,
|
||||
getIdToken: () =>
|
||||
oktaAuthApi.getBackstageIdentity().then(i => i!.idToken),
|
||||
logout: async () => {
|
||||
await oktaAuthApi.logout();
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
export const oktaProvider: SignInProvider = { Component, loader };
|
||||
@@ -18,6 +18,7 @@ import React, { useLayoutEffect, useState, useMemo, useCallback } from 'react';
|
||||
import { guestProvider } from './guestProvider';
|
||||
import { googleProvider } from './googleProvider';
|
||||
import { customProvider } from './customProvider';
|
||||
import { oktaProvider } from './oktaProvider';
|
||||
import {
|
||||
SignInPageProps,
|
||||
SignInResult,
|
||||
@@ -30,12 +31,13 @@ import { SignInProvider } from './types';
|
||||
const PROVIDER_STORAGE_KEY = '@backstage/core:SignInPage:provider';
|
||||
|
||||
// Separate list here to avoid exporting internal types
|
||||
export type SignInProviderId = 'guest' | 'google' | 'custom';
|
||||
export type SignInProviderId = 'guest' | 'google' | 'custom' | 'okta';
|
||||
|
||||
const signInProviders: { [id in SignInProviderId]: SignInProvider } = {
|
||||
guest: guestProvider,
|
||||
google: googleProvider,
|
||||
custom: customProvider,
|
||||
okta: oktaProvider,
|
||||
};
|
||||
|
||||
export const useSignInProviders = (
|
||||
|
||||
@@ -6,11 +6,13 @@ import {
|
||||
OAuthRequestManager,
|
||||
googleAuthApiRef,
|
||||
githubAuthApiRef,
|
||||
oktaAuthApiRef,
|
||||
AlertApiForwarder,
|
||||
ErrorApiForwarder,
|
||||
ErrorAlerter,
|
||||
GoogleAuth,
|
||||
GithubAuth,
|
||||
OktaAuth,
|
||||
identityApiRef,
|
||||
} from '@backstage/core';
|
||||
|
||||
@@ -50,4 +52,13 @@ builder.add(
|
||||
}),
|
||||
);
|
||||
|
||||
builder.add(
|
||||
oktaAuthApiRef,
|
||||
OktaAuth.create({
|
||||
apiOrigin: 'http://localhost:7000',
|
||||
basePath: '/auth/',
|
||||
oauthRequestApi,
|
||||
}),
|
||||
);
|
||||
|
||||
export const apis = builder.build();
|
||||
|
||||
@@ -41,7 +41,8 @@
|
||||
"react": "^16.12.0",
|
||||
"react-dom": "^16.12.0",
|
||||
"react-router": "^6.0.0-alpha.5",
|
||||
"react-router-dom": "^6.0.0-alpha.5"
|
||||
"react-router-dom": "^6.0.0-alpha.5",
|
||||
"zen-observable": "^0.8.15"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/jest": "^25.2.2",
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
/*
|
||||
* 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 { MockStorageApi } from './MockStorageApi';
|
||||
import { StorageApi } from '@backstage/core-api';
|
||||
|
||||
describe('WebStorage Storage API', () => {
|
||||
const createMockStorage = (): StorageApi => {
|
||||
return MockStorageApi.create();
|
||||
};
|
||||
|
||||
it('should return undefined for values which are unset', async () => {
|
||||
const storage = createMockStorage();
|
||||
|
||||
expect(storage.get('myfakekey')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should allow the setting and getting of the simple data structures', async () => {
|
||||
const storage = createMockStorage();
|
||||
|
||||
await storage.set('myfakekey', 'helloimastring');
|
||||
await storage.set('mysecondfakekey', 1234);
|
||||
await storage.set('mythirdfakekey', true);
|
||||
expect(storage.get('myfakekey')).toBe('helloimastring');
|
||||
expect(storage.get('mysecondfakekey')).toBe(1234);
|
||||
expect(storage.get('mythirdfakekey')).toBe(true);
|
||||
});
|
||||
|
||||
it('should allow setting of complex datastructures', async () => {
|
||||
const storage = createMockStorage();
|
||||
|
||||
const mockData = {
|
||||
something: 'here',
|
||||
is: [{ super: { complex: [{ but: 'something', why: true }] } }],
|
||||
};
|
||||
|
||||
await storage.set('myfakekey', mockData);
|
||||
|
||||
expect(storage.get('myfakekey')).toEqual(mockData);
|
||||
});
|
||||
|
||||
it('should subscribe to key changes when setting a new value', async () => {
|
||||
const storage = createMockStorage();
|
||||
|
||||
const wrongKeyNextHandler = jest.fn();
|
||||
const selectedKeyNextHandler = jest.fn();
|
||||
const mockData = { hello: 'im a great new value' };
|
||||
|
||||
await new Promise(resolve => {
|
||||
storage.observe$<String>('correctKey').subscribe({
|
||||
next: (...args) => {
|
||||
selectedKeyNextHandler(...args);
|
||||
resolve();
|
||||
},
|
||||
});
|
||||
|
||||
storage.observe$('wrongKey').subscribe({ next: wrongKeyNextHandler });
|
||||
|
||||
storage.set('correctKey', mockData);
|
||||
});
|
||||
|
||||
expect(wrongKeyNextHandler).not.toHaveBeenCalled();
|
||||
expect(selectedKeyNextHandler).toHaveBeenCalledTimes(1);
|
||||
expect(selectedKeyNextHandler).toHaveBeenCalledWith({
|
||||
key: 'correctKey',
|
||||
newValue: mockData,
|
||||
});
|
||||
});
|
||||
|
||||
it('should subscribe to key changes when deleting a value', async () => {
|
||||
const storage = createMockStorage();
|
||||
|
||||
const wrongKeyNextHandler = jest.fn();
|
||||
const selectedKeyNextHandler = jest.fn();
|
||||
const mockData = { hello: 'im a great new value' };
|
||||
|
||||
storage.set('correctKey', mockData);
|
||||
|
||||
await new Promise(resolve => {
|
||||
storage.observe$('correctKey').subscribe({
|
||||
next: (...args) => {
|
||||
selectedKeyNextHandler(...args);
|
||||
resolve();
|
||||
},
|
||||
});
|
||||
|
||||
storage.observe$('wrongKey').subscribe({ next: wrongKeyNextHandler });
|
||||
|
||||
storage.remove('correctKey');
|
||||
});
|
||||
|
||||
expect(wrongKeyNextHandler).not.toHaveBeenCalled();
|
||||
expect(selectedKeyNextHandler).toHaveBeenCalledTimes(1);
|
||||
expect(selectedKeyNextHandler).toHaveBeenCalledWith({
|
||||
key: 'correctKey',
|
||||
newValue: undefined,
|
||||
});
|
||||
});
|
||||
|
||||
it('should be able to create different buckets for different uses', async () => {
|
||||
const rootStorage = createMockStorage();
|
||||
|
||||
const firstStorage = rootStorage.forBucket('userSettings');
|
||||
const secondStorage = rootStorage.forBucket('profileSettings');
|
||||
const keyName = 'blobby';
|
||||
|
||||
await firstStorage.set(keyName, 'boop');
|
||||
await secondStorage.set(keyName, 'deerp');
|
||||
|
||||
expect(firstStorage.get(keyName)).not.toBe(secondStorage.get(keyName));
|
||||
expect(firstStorage.get(keyName)).toBe('boop');
|
||||
expect(secondStorage.get(keyName)).toBe('deerp');
|
||||
});
|
||||
|
||||
it('should not clash with other namesapces when creating buckets', async () => {
|
||||
const rootStorage = createMockStorage();
|
||||
|
||||
// when getting key test2 it will translate to /profile/something/deep/test2
|
||||
const firstStorage = rootStorage
|
||||
.forBucket('profile')
|
||||
.forBucket('something')
|
||||
.forBucket('deep');
|
||||
// when getting key deep/test2 it will translate to /profile/something/deep/test2
|
||||
const secondStorage = rootStorage.forBucket('profile/something');
|
||||
|
||||
await firstStorage.set('test2', { error: true });
|
||||
|
||||
expect(secondStorage.get('deep/test2')).toBe(undefined);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,90 @@
|
||||
/*
|
||||
* 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 {
|
||||
Observable,
|
||||
StorageApi,
|
||||
storageApiRef,
|
||||
StorageValueChange,
|
||||
} from '@backstage/core-api';
|
||||
import ObservableImpl from 'zen-observable';
|
||||
|
||||
export type MockStorageBucket = { [key: string]: any };
|
||||
|
||||
export class MockStorageApi implements StorageApi {
|
||||
static factory = {
|
||||
implements: storageApiRef,
|
||||
deps: {},
|
||||
factory: () => MockStorageApi.create(),
|
||||
};
|
||||
|
||||
private readonly namespace: string;
|
||||
private readonly data: MockStorageBucket;
|
||||
|
||||
private constructor(namespace: string, data?: MockStorageBucket) {
|
||||
this.namespace = namespace;
|
||||
this.data = { ...data };
|
||||
}
|
||||
|
||||
static create(data?: MockStorageBucket) {
|
||||
return new MockStorageApi('', data);
|
||||
}
|
||||
|
||||
forBucket(name: string): StorageApi {
|
||||
return new MockStorageApi(`${this.namespace}/${name}`, this.data);
|
||||
}
|
||||
|
||||
get<T>(key: string): T | undefined {
|
||||
return this.data[this.getKeyName(key)];
|
||||
}
|
||||
|
||||
async set<T>(key: string, data: T): Promise<void> {
|
||||
this.data[this.getKeyName(key)] = data;
|
||||
this.notifyChanges({ key, newValue: data });
|
||||
}
|
||||
|
||||
async remove(key: string): Promise<void> {
|
||||
delete this.data[this.getKeyName(key)];
|
||||
this.notifyChanges({ key, newValue: undefined });
|
||||
}
|
||||
|
||||
observe$<T>(key: string): Observable<StorageValueChange<T>> {
|
||||
return this.observable.filter(({ key: messageKey }) => messageKey === key);
|
||||
}
|
||||
|
||||
private getKeyName(key: string) {
|
||||
return `${this.namespace}/${encodeURIComponent(key)}`;
|
||||
}
|
||||
|
||||
private notifyChanges<T>(message: StorageValueChange<T>) {
|
||||
for (const subscription of this.subscribers) {
|
||||
subscription.next(message);
|
||||
}
|
||||
}
|
||||
|
||||
private subscribers = new Set<
|
||||
ZenObservable.SubscriptionObserver<StorageValueChange>
|
||||
>();
|
||||
|
||||
private readonly observable = new ObservableImpl<StorageValueChange>(
|
||||
subscriber => {
|
||||
this.subscribers.add(subscriber);
|
||||
return () => {
|
||||
this.subscribers.delete(subscriber);
|
||||
};
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
/*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
export { MockStorageApi } from './MockStorageApi';
|
||||
export type { MockStorageBucket } from './MockStorageApi';
|
||||
@@ -15,3 +15,4 @@
|
||||
*/
|
||||
|
||||
export * from './ErrorApi';
|
||||
export * from './StorageApi';
|
||||
|
||||
@@ -15,12 +15,13 @@
|
||||
*/
|
||||
|
||||
import { ApiTestRegistry } from '@backstage/core-api';
|
||||
import { MockErrorApi } from './apis';
|
||||
import { MockErrorApi, MockStorageApi } from './apis';
|
||||
|
||||
export function createMockApiRegistry(): ApiTestRegistry {
|
||||
const registry = new ApiTestRegistry();
|
||||
|
||||
registry.register(MockErrorApi.factory);
|
||||
registry.register(MockStorageApi.factory);
|
||||
|
||||
return registry;
|
||||
}
|
||||
|
||||
@@ -40,6 +40,8 @@
|
||||
"passport": "^0.4.1",
|
||||
"passport-github2": "^0.1.12",
|
||||
"passport-google-oauth20": "^2.0.0",
|
||||
"passport-oauth2": "^1.5.0",
|
||||
"passport-okta-oauth": "^0.0.1",
|
||||
"passport-saml": "^1.3.3",
|
||||
"uuid": "^8.0.0",
|
||||
"winston": "^3.2.1",
|
||||
@@ -57,6 +59,7 @@
|
||||
"jest-fetch-mock": "^3.0.3"
|
||||
},
|
||||
"files": [
|
||||
"dist"
|
||||
"dist",
|
||||
"migrations"
|
||||
]
|
||||
}
|
||||
|
||||
@@ -18,6 +18,7 @@ import Router from 'express-promise-router';
|
||||
import { createGithubProvider } from './github';
|
||||
import { createGoogleProvider } from './google';
|
||||
import { createSamlProvider } from './saml';
|
||||
import { createOktaProvider } from './okta';
|
||||
import { AuthProviderFactory, AuthProviderConfig } from './types';
|
||||
import { Logger } from 'winston';
|
||||
import { TokenIssuer } from '../identity';
|
||||
@@ -26,6 +27,7 @@ const factories: { [providerId: string]: AuthProviderFactory } = {
|
||||
google: createGoogleProvider,
|
||||
github: createGithubProvider,
|
||||
saml: createSamlProvider,
|
||||
okta: createOktaProvider,
|
||||
};
|
||||
|
||||
export const createAuthProviderRouter = (
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
/*
|
||||
* 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.
|
||||
*/
|
||||
export { createOktaProvider } from './provider';
|
||||
@@ -0,0 +1,213 @@
|
||||
/*
|
||||
* 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 express from 'express';
|
||||
import { OAuthProvider } from '../../lib/OAuthProvider';
|
||||
import { Strategy as OktaStrategy } from 'passport-okta-oauth';
|
||||
import passport from 'passport';
|
||||
import {
|
||||
executeFrameHandlerStrategy,
|
||||
executeRedirectStrategy,
|
||||
executeRefreshTokenStrategy,
|
||||
makeProfileInfo,
|
||||
executeFetchUserProfileStrategy,
|
||||
} from '../../lib/PassportStrategyHelper';
|
||||
import {
|
||||
OAuthProviderHandlers,
|
||||
RedirectInfo,
|
||||
AuthProviderConfig,
|
||||
EnvironmentProviderConfig,
|
||||
OAuthProviderOptions,
|
||||
OAuthProviderConfig,
|
||||
OAuthResponse,
|
||||
PassportDoneCallback,
|
||||
} from '../types';
|
||||
import {
|
||||
EnvironmentHandler,
|
||||
EnvironmentHandlers,
|
||||
} from '../../lib/EnvironmentHandler';
|
||||
import { Logger } from 'winston';
|
||||
import { StateStore } from 'passport-oauth2';
|
||||
import { TokenIssuer } from '../../identity';
|
||||
|
||||
type PrivateInfo = {
|
||||
refreshToken: string;
|
||||
};
|
||||
|
||||
export class OktaAuthProvider implements OAuthProviderHandlers {
|
||||
|
||||
private readonly _strategy: any;
|
||||
|
||||
/**
|
||||
* Due to passport-okta-oauth forcing options.state = true,
|
||||
* passport-oauth2 requires express-session to be installed
|
||||
* so that the 'state' parameter of the oauth2 flow can be stored.
|
||||
* This implementation of StateStore matches the NullStore found within
|
||||
* passport-oauth2, which is the StateStore implementation used when options.state = false,
|
||||
* allowing us to avoid using express-session in order to integrate with Okta.
|
||||
*/
|
||||
private _store: StateStore = {
|
||||
store(_req: express.Request, cb: any) {
|
||||
cb(null, null);
|
||||
},
|
||||
verify(_req: express.Request, _state: string, cb: any) {
|
||||
cb(null, true);
|
||||
},
|
||||
}
|
||||
|
||||
constructor(options: OAuthProviderOptions) {
|
||||
this._strategy = new OktaStrategy({
|
||||
passReqToCallback: false as true,
|
||||
...options,
|
||||
store: this._store,
|
||||
response_type: 'code',
|
||||
}, (
|
||||
accessToken: any,
|
||||
refreshToken: any,
|
||||
params: any,
|
||||
rawProfile: passport.Profile,
|
||||
done: PassportDoneCallback<OAuthResponse, PrivateInfo>,
|
||||
) => {
|
||||
const profile = makeProfileInfo(rawProfile, params.id_token);
|
||||
|
||||
done(
|
||||
undefined,
|
||||
{
|
||||
providerInfo: {
|
||||
idToken: params.id_token,
|
||||
accessToken,
|
||||
scope: params.scope,
|
||||
expiresInSeconds: params.expires_in,
|
||||
},
|
||||
profile,
|
||||
},
|
||||
{
|
||||
refreshToken,
|
||||
},
|
||||
)
|
||||
});
|
||||
}
|
||||
|
||||
async start(
|
||||
req: express.Request,
|
||||
options: Record<string, string>
|
||||
): Promise<RedirectInfo> {
|
||||
const providerOptions = {
|
||||
...options,
|
||||
accessType: 'offline',
|
||||
prompt: 'consent',
|
||||
};
|
||||
return await executeRedirectStrategy(req, this._strategy, providerOptions);
|
||||
}
|
||||
|
||||
async handler(
|
||||
req: express.Request
|
||||
): Promise<{ response: OAuthResponse; refreshToken: string }> {
|
||||
const { response, privateInfo } = await executeFrameHandlerStrategy<
|
||||
OAuthResponse,
|
||||
PrivateInfo
|
||||
>(req, this._strategy);
|
||||
|
||||
return {
|
||||
response: await this.populateIdentity(response),
|
||||
refreshToken: privateInfo.refreshToken,
|
||||
};
|
||||
}
|
||||
|
||||
async refresh(refreshToken: string, scope: string): Promise<OAuthResponse> {
|
||||
const { accessToken, params } = await executeRefreshTokenStrategy(
|
||||
this._strategy,
|
||||
refreshToken,
|
||||
scope,
|
||||
);
|
||||
|
||||
const profile = await executeFetchUserProfileStrategy(
|
||||
this._strategy,
|
||||
accessToken,
|
||||
params.id_token,
|
||||
);
|
||||
|
||||
return this.populateIdentity({
|
||||
providerInfo: {
|
||||
accessToken,
|
||||
idToken: params.id_token,
|
||||
expiresInSeconds: params.expires_in,
|
||||
scope: params.scope,
|
||||
},
|
||||
profile,
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
private async populateIdentity(
|
||||
response: OAuthResponse,
|
||||
): Promise<OAuthResponse> {
|
||||
const { profile } = response;
|
||||
|
||||
if (!profile.email) {
|
||||
throw new Error('Okta profile contained no email');
|
||||
}
|
||||
|
||||
// TODO(Rugvip): Hardcoded to the local part of the email for now
|
||||
const id = profile.email.split('@')[0];
|
||||
|
||||
return { ...response, backstageIdentity: { id } };
|
||||
}
|
||||
}
|
||||
|
||||
export function createOktaProvider(
|
||||
{ baseUrl }: AuthProviderConfig,
|
||||
providerConfig: EnvironmentProviderConfig,
|
||||
logger: Logger,
|
||||
tokenIssuer: TokenIssuer,
|
||||
) {
|
||||
const envProviders: EnvironmentHandlers = {};
|
||||
|
||||
for (const [env, envConfig] of Object.entries(providerConfig)) {
|
||||
const config = (envConfig as unknown) as OAuthProviderConfig;
|
||||
const { secure, appOrigin } = config;
|
||||
const callbackURLParam = `?env=${env}`;
|
||||
const opts = {
|
||||
audience: config.audience,
|
||||
clientID: config.clientId,
|
||||
clientSecret: config.clientSecret,
|
||||
callbackURL: `${baseUrl}/okta/handler/frame${callbackURLParam}`,
|
||||
};
|
||||
|
||||
if (!opts.clientID || !opts.clientSecret || !opts.audience) {
|
||||
if (process.env.NODE_ENV !== 'development') {
|
||||
throw new Error(
|
||||
'Failed to initialize Okta auth provider, set AUTH_OKTA_CLIENT_ID, AUTH_OKTA_CLIENT_SECRET, and AUTH_OKTA_AUDIENCE env vars',
|
||||
);
|
||||
}
|
||||
|
||||
logger.warn(
|
||||
'Okta auth provider disabled, set AUTH_OKTA_CLIENT_ID, AUTH_OKTA_CLIENT_SECRET, and AUTH_OKTA_AUDIENCE env vars to enable',
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
envProviders[env] = new OAuthProvider(new OktaAuthProvider(opts), {
|
||||
disableRefresh: false,
|
||||
providerId: 'okta',
|
||||
secure,
|
||||
baseUrl,
|
||||
appOrigin,
|
||||
tokenIssuer,
|
||||
});
|
||||
}
|
||||
|
||||
return new EnvironmentHandler(envProviders);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
/*
|
||||
* 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.
|
||||
*/
|
||||
declare module 'passport-okta-oauth' {
|
||||
|
||||
export class Strategy {
|
||||
constructor(options: any, verify: any)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -55,6 +55,10 @@ export type OAuthProviderConfig = {
|
||||
* Client Secret of the auth provider.
|
||||
*/
|
||||
clientSecret: string;
|
||||
/**
|
||||
* The location of the OAuth Authorization Server
|
||||
*/
|
||||
audience?: string;
|
||||
};
|
||||
|
||||
export type EnvironmentProviderConfig = {
|
||||
|
||||
@@ -82,6 +82,15 @@ export async function createRouter(
|
||||
issuer: 'passport-saml',
|
||||
},
|
||||
},
|
||||
okta: {
|
||||
development: {
|
||||
appOrigin: 'http://localhost:3000',
|
||||
secure: false,
|
||||
clientId: process.env.AUTH_OKTA_CLIENT_ID!,
|
||||
clientSecret: process.env.AUTH_OKTA_CLIENT_SECRET!,
|
||||
audience: process.env.AUTH_OKTA_AUDIENCE,
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
@@ -15,4 +15,5 @@ for URL in \
|
||||
--request POST 'localhost:7000/catalog/locations' \
|
||||
--header 'Content-Type: application/json' \
|
||||
--data-raw "{\"type\": \"github\", \"target\": \"https://github.com/spotify/backstage/blob/master/packages/catalog-model/examples/${URL}\"}"
|
||||
echo
|
||||
done
|
||||
|
||||
@@ -14,195 +14,248 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import { Entity } from '@backstage/catalog-model';
|
||||
import {
|
||||
ApiProvider,
|
||||
ApiRegistry,
|
||||
IdentityApi,
|
||||
identityApiRef,
|
||||
storageApiRef,
|
||||
} from '@backstage/core';
|
||||
import { MockStorageApi, wrapInTestApp } from '@backstage/test-utils';
|
||||
import { fireEvent, render, waitFor } from '@testing-library/react';
|
||||
import React from 'react';
|
||||
import { render, fireEvent } from '@testing-library/react';
|
||||
import { wrapInTestApp } from '@backstage/test-utils';
|
||||
import { CatalogFilter, CatalogFilterGroup } from './CatalogFilter';
|
||||
import { EntityGroup } from '../../data/filters';
|
||||
import { CatalogApi, catalogApiRef } from '../../api/types';
|
||||
import { EntityFilterGroupsProvider } from '../../filter';
|
||||
import { ButtonGroup, CatalogFilter } from './CatalogFilter';
|
||||
|
||||
describe('Catalog Filter', () => {
|
||||
const comp1 = {
|
||||
apiVersion: 'backstage.io/v1alpha1',
|
||||
kind: 'Component',
|
||||
metadata: {
|
||||
name: 'my-component-1',
|
||||
},
|
||||
spec: {
|
||||
owner: 'team',
|
||||
},
|
||||
const catalogApi: Partial<CatalogApi> = {
|
||||
getEntities: () =>
|
||||
Promise.resolve([
|
||||
{
|
||||
apiVersion: 'backstage.io/v1alpha1',
|
||||
kind: 'Component',
|
||||
metadata: {
|
||||
name: 'Entity1',
|
||||
},
|
||||
spec: {
|
||||
owner: 'tools@example.com',
|
||||
type: 'service',
|
||||
},
|
||||
},
|
||||
{
|
||||
apiVersion: 'backstage.io/v1alpha1',
|
||||
kind: 'Component',
|
||||
metadata: {
|
||||
name: 'Entity2',
|
||||
},
|
||||
spec: {
|
||||
owner: 'not-tools@example.com',
|
||||
type: 'service',
|
||||
},
|
||||
},
|
||||
] as Entity[]),
|
||||
};
|
||||
const comp2 = {
|
||||
apiVersion: 'backstage.io/v1alpha1',
|
||||
kind: 'Component',
|
||||
metadata: {
|
||||
name: 'my-component-2',
|
||||
},
|
||||
spec: {
|
||||
owner: 'team',
|
||||
},
|
||||
|
||||
const indentityApi: Partial<IdentityApi> = {
|
||||
getUserId: () => 'tools@example.com',
|
||||
};
|
||||
const comp3 = {
|
||||
apiVersion: 'backstage.io/v1alpha1',
|
||||
kind: 'Component',
|
||||
metadata: {
|
||||
name: 'my-component-3',
|
||||
},
|
||||
spec: {
|
||||
owner: '',
|
||||
},
|
||||
};
|
||||
const defaultFilterProps = {
|
||||
selectedFilter: EntityGroup.ALL,
|
||||
onFilterChange: (type: EntityGroup) => type,
|
||||
entitiesByFilter: {
|
||||
[EntityGroup.ALL]: [comp1, comp2, comp3],
|
||||
[EntityGroup.STARRED]: [comp1],
|
||||
[EntityGroup.OWNED]: [comp1],
|
||||
},
|
||||
};
|
||||
it('should render the different groups', async () => {
|
||||
const mockGroups: CatalogFilterGroup[] = [
|
||||
{ name: 'Test Group 1', items: [] },
|
||||
{ name: 'Test Group 2', items: [] },
|
||||
];
|
||||
const { findByText } = render(
|
||||
|
||||
const renderWrapped = (children: React.ReactNode) =>
|
||||
render(
|
||||
wrapInTestApp(
|
||||
<CatalogFilter {...defaultFilterProps} groups={mockGroups} />,
|
||||
<ApiProvider
|
||||
apis={ApiRegistry.from([
|
||||
[catalogApiRef, catalogApi],
|
||||
[identityApiRef, indentityApi],
|
||||
[storageApiRef, MockStorageApi.create()],
|
||||
])}
|
||||
>
|
||||
<EntityFilterGroupsProvider>{children}</EntityFilterGroupsProvider>,
|
||||
</ApiProvider>,
|
||||
),
|
||||
);
|
||||
|
||||
it('should render the different groups', async () => {
|
||||
const mockGroups: ButtonGroup[] = [
|
||||
{ name: 'Test Group 1', items: [] },
|
||||
{ name: 'Test Group 2', items: [] },
|
||||
];
|
||||
const { findByText } = renderWrapped(
|
||||
<CatalogFilter buttonGroups={mockGroups} initiallySelected="" />,
|
||||
);
|
||||
for (const group of mockGroups) {
|
||||
expect(await findByText(group.name)).toBeInTheDocument();
|
||||
}
|
||||
});
|
||||
|
||||
it('should render the different items and their names', async () => {
|
||||
const mockGroups: CatalogFilterGroup[] = [
|
||||
const mockGroups: ButtonGroup[] = [
|
||||
{
|
||||
name: 'Test Group 1',
|
||||
items: [
|
||||
{
|
||||
id: EntityGroup.ALL,
|
||||
id: 'all',
|
||||
label: 'First Label',
|
||||
filterFn: () => true,
|
||||
},
|
||||
{
|
||||
id: EntityGroup.STARRED,
|
||||
id: 'starred',
|
||||
label: 'Second Label',
|
||||
filterFn: () => false,
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const { findByText } = render(
|
||||
wrapInTestApp(
|
||||
<CatalogFilter {...defaultFilterProps} groups={mockGroups} />,
|
||||
),
|
||||
const { findByText } = renderWrapped(
|
||||
<CatalogFilter buttonGroups={mockGroups} initiallySelected="all" />,
|
||||
);
|
||||
|
||||
const [group] = mockGroups;
|
||||
for (const item of group.items) {
|
||||
for (const item of mockGroups[0].items) {
|
||||
expect(await findByText(item.label)).toBeInTheDocument();
|
||||
}
|
||||
});
|
||||
|
||||
it('should render the count in each item', async () => {
|
||||
const mockGroups: CatalogFilterGroup[] = [
|
||||
it('selects the first item if no desired initial one is set', async () => {
|
||||
const mockGroups: ButtonGroup[] = [
|
||||
{
|
||||
name: 'Test Group 1',
|
||||
items: [
|
||||
{
|
||||
id: EntityGroup.ALL,
|
||||
id: 'all',
|
||||
label: 'First Label',
|
||||
count: 3,
|
||||
filterFn: () => true,
|
||||
},
|
||||
{
|
||||
id: EntityGroup.STARRED,
|
||||
id: 'starred',
|
||||
label: 'Second Label',
|
||||
count: 1,
|
||||
filterFn: () => false,
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const { getAllByText } = render(
|
||||
wrapInTestApp(
|
||||
<CatalogFilter {...defaultFilterProps} groups={mockGroups} />,
|
||||
),
|
||||
const onChange = jest.fn();
|
||||
|
||||
renderWrapped(
|
||||
<CatalogFilter
|
||||
buttonGroups={mockGroups}
|
||||
initiallySelected="all"
|
||||
onChange={onChange}
|
||||
/>,
|
||||
);
|
||||
|
||||
for (const key of Object.keys(defaultFilterProps.entitiesByFilter)) {
|
||||
const matcher = new RegExp(
|
||||
`(${defaultFilterProps.entitiesByFilter[key as EntityGroup].length})`,
|
||||
);
|
||||
const items = await getAllByText(matcher);
|
||||
items.forEach(el => expect(el).toBeInTheDocument());
|
||||
}
|
||||
await waitFor(() => {
|
||||
expect(onChange).toHaveBeenLastCalledWith({
|
||||
id: 'all',
|
||||
label: 'First Label',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('should fire the callback when an item is clicked', async () => {
|
||||
const mockGroups: CatalogFilterGroup[] = [
|
||||
it('selects the initial item', async () => {
|
||||
const mockGroups: ButtonGroup[] = [
|
||||
{
|
||||
name: 'Test Group 1',
|
||||
items: [
|
||||
{
|
||||
id: EntityGroup.ALL,
|
||||
id: 'all',
|
||||
label: 'First Label',
|
||||
count: 100,
|
||||
filterFn: () => true,
|
||||
},
|
||||
{
|
||||
id: EntityGroup.STARRED,
|
||||
id: 'starred',
|
||||
label: 'Second Label',
|
||||
count: 400,
|
||||
filterFn: () => false,
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const onSelectedChangeHandler = jest.fn();
|
||||
const onChange = jest.fn();
|
||||
|
||||
const { findByText } = render(
|
||||
wrapInTestApp(
|
||||
<CatalogFilter
|
||||
{...defaultFilterProps}
|
||||
groups={mockGroups}
|
||||
onFilterChange={onSelectedChangeHandler}
|
||||
/>,
|
||||
),
|
||||
renderWrapped(
|
||||
<CatalogFilter
|
||||
buttonGroups={mockGroups}
|
||||
onChange={onChange}
|
||||
initiallySelected="starred"
|
||||
/>,
|
||||
);
|
||||
|
||||
const item = mockGroups[0].items[0];
|
||||
|
||||
const element = await findByText(item.label);
|
||||
|
||||
fireEvent.click(element);
|
||||
|
||||
expect(onSelectedChangeHandler).toHaveBeenCalledWith(item.id);
|
||||
await waitFor(() => {
|
||||
expect(onChange).toHaveBeenLastCalledWith({
|
||||
id: 'starred',
|
||||
label: 'Second Label',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('should render a component when a function is passed to the count component', async () => {
|
||||
const mockGroups: CatalogFilterGroup[] = [
|
||||
it('can change the selected item', async () => {
|
||||
const mockGroups: ButtonGroup[] = [
|
||||
{
|
||||
name: 'Test Group 1',
|
||||
items: [
|
||||
{
|
||||
id: EntityGroup.ALL,
|
||||
id: 'all',
|
||||
label: 'First Label',
|
||||
count: () => <b>BACKSTAGE!</b>,
|
||||
filterFn: () => true,
|
||||
},
|
||||
{
|
||||
id: EntityGroup.STARRED,
|
||||
id: 'starred',
|
||||
label: 'Second Label',
|
||||
count: 400,
|
||||
filterFn: () => false,
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
const { findByText } = render(
|
||||
wrapInTestApp(
|
||||
<CatalogFilter {...defaultFilterProps} groups={mockGroups} />,
|
||||
),
|
||||
|
||||
const onChange = jest.fn();
|
||||
|
||||
const { findByText } = renderWrapped(
|
||||
<CatalogFilter
|
||||
buttonGroups={mockGroups}
|
||||
initiallySelected="all"
|
||||
onChange={onChange}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(await findByText('Test Group 1')).toBeInTheDocument();
|
||||
await waitFor(() => {
|
||||
expect(onChange).toHaveBeenLastCalledWith({
|
||||
id: 'all',
|
||||
label: 'First Label',
|
||||
});
|
||||
});
|
||||
|
||||
fireEvent.click(await findByText('Second Label'));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(onChange).toHaveBeenLastCalledWith({
|
||||
id: 'starred',
|
||||
label: 'Second Label',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('displays match counts properly', async () => {
|
||||
const mockGroups: ButtonGroup[] = [
|
||||
{
|
||||
name: 'Test Group 1',
|
||||
items: [
|
||||
{
|
||||
id: 'owned',
|
||||
label: 'First Label',
|
||||
filterFn: entity => entity.spec?.owner === 'tools@example.com',
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const { findByText } = renderWrapped(
|
||||
<CatalogFilter buttonGroups={mockGroups} initiallySelected="owned" />,
|
||||
);
|
||||
|
||||
expect(await findByText('1')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -14,31 +14,36 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import React, { FC } from 'react';
|
||||
import { Entity } from '@backstage/catalog-model';
|
||||
import { IconComponent } from '@backstage/core';
|
||||
import {
|
||||
Card,
|
||||
List,
|
||||
ListItemIcon,
|
||||
ListItemSecondaryAction,
|
||||
ListItemText,
|
||||
MenuItem,
|
||||
Typography,
|
||||
Theme,
|
||||
makeStyles,
|
||||
MenuItem,
|
||||
Theme,
|
||||
Typography,
|
||||
} from '@material-ui/core';
|
||||
import type { IconComponent } from '@backstage/core';
|
||||
import { EntityGroup } from '../../data/filters';
|
||||
import { EntitiesByFilter } from '../../hooks/useEntities';
|
||||
import React, {
|
||||
useCallback,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
} from 'react';
|
||||
import { FilterGroup, useEntityFilterGroup } from '../../filter';
|
||||
|
||||
export type CatalogFilterItem = {
|
||||
id: EntityGroup;
|
||||
label: string;
|
||||
icon?: IconComponent;
|
||||
count?: number | FC;
|
||||
};
|
||||
|
||||
export type CatalogFilterGroup = {
|
||||
export type ButtonGroup = {
|
||||
name: string;
|
||||
items: CatalogFilterItem[];
|
||||
items: {
|
||||
id: string;
|
||||
label: string;
|
||||
icon?: IconComponent;
|
||||
filterFn: (entity: Entity) => boolean;
|
||||
}[];
|
||||
};
|
||||
|
||||
const useStyles = makeStyles<Theme>(theme => ({
|
||||
@@ -67,21 +72,56 @@ const useStyles = makeStyles<Theme>(theme => ({
|
||||
},
|
||||
}));
|
||||
|
||||
export const CatalogFilter: FC<{
|
||||
selectedFilter: EntityGroup;
|
||||
onFilterChange: (type: EntityGroup) => void;
|
||||
entitiesByFilter: EntitiesByFilter;
|
||||
groups: CatalogFilterGroup[];
|
||||
}> = ({
|
||||
selectedFilter: selectedId,
|
||||
onFilterChange: setSelectedFilter,
|
||||
entitiesByFilter,
|
||||
groups,
|
||||
}) => {
|
||||
type OnChangeCallback = (item: { id: string; label: string }) => void;
|
||||
|
||||
type Props = {
|
||||
buttonGroups: ButtonGroup[];
|
||||
initiallySelected: string;
|
||||
onChange?: OnChangeCallback;
|
||||
};
|
||||
|
||||
/**
|
||||
* The main filter group in the sidebar, toggling owned/starred/all.
|
||||
*/
|
||||
export const CatalogFilter = ({
|
||||
buttonGroups,
|
||||
onChange,
|
||||
initiallySelected,
|
||||
}: Props) => {
|
||||
const classes = useStyles();
|
||||
const { currentFilter, setCurrentFilter, getFilterCount } = useFilter(
|
||||
buttonGroups,
|
||||
initiallySelected,
|
||||
);
|
||||
|
||||
const onChangeRef = useRef<OnChangeCallback>();
|
||||
useEffect(() => {
|
||||
onChangeRef.current = onChange;
|
||||
}, [onChange]);
|
||||
|
||||
const setCurrent = useCallback(
|
||||
(item: { id: string; label: string }) => {
|
||||
setCurrentFilter(item.id);
|
||||
onChangeRef.current?.({ id: item.id, label: item.label });
|
||||
},
|
||||
[setCurrentFilter],
|
||||
);
|
||||
|
||||
// Make one initial onChange to inform the surroundings about the selected
|
||||
// item
|
||||
useEffect(() => {
|
||||
const items = buttonGroups.flatMap(g => g.items);
|
||||
const item = items.find(i => i.id === initiallySelected) || items[0];
|
||||
if (item) {
|
||||
onChangeRef.current?.({ id: item.id, label: item.label });
|
||||
}
|
||||
// intentionally only happens on startup
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<Card className={classes.root}>
|
||||
{groups.map(group => (
|
||||
{buttonGroups.map(group => (
|
||||
<React.Fragment key={group.name}>
|
||||
<Typography variant="subtitle2" className={classes.title}>
|
||||
{group.name}
|
||||
@@ -93,10 +133,8 @@ export const CatalogFilter: FC<{
|
||||
key={item.id}
|
||||
button
|
||||
divider
|
||||
onClick={() => {
|
||||
setSelectedFilter(item.id);
|
||||
}}
|
||||
selected={item.id === selectedId}
|
||||
onClick={() => setCurrent(item)}
|
||||
selected={item.id === currentFilter}
|
||||
className={classes.menuItem}
|
||||
>
|
||||
{item.icon && (
|
||||
@@ -109,7 +147,9 @@ export const CatalogFilter: FC<{
|
||||
{item.label}
|
||||
</Typography>
|
||||
</ListItemText>
|
||||
{entitiesByFilter[item.id]?.length ?? '-'}
|
||||
<ListItemSecondaryAction>
|
||||
{getFilterCount(item.id) ?? '-'}
|
||||
</ListItemSecondaryAction>
|
||||
</MenuItem>
|
||||
))}
|
||||
</List>
|
||||
@@ -119,3 +159,53 @@ export const CatalogFilter: FC<{
|
||||
</Card>
|
||||
);
|
||||
};
|
||||
|
||||
function useFilter(
|
||||
buttonGroups: ButtonGroup[],
|
||||
initiallySelected: string,
|
||||
): {
|
||||
currentFilter: string;
|
||||
setCurrentFilter: (filterId: string) => void;
|
||||
getFilterCount: (filterId: string) => number | undefined;
|
||||
} {
|
||||
const [currentFilter, setCurrentFilter] = useState(initiallySelected);
|
||||
|
||||
const filterGroup = useMemo<FilterGroup>(
|
||||
() => ({
|
||||
filters: Object.fromEntries(
|
||||
buttonGroups.flatMap(g => g.items).map(i => [i.id, i.filterFn]),
|
||||
),
|
||||
}),
|
||||
[buttonGroups],
|
||||
);
|
||||
|
||||
const { setSelectedFilters, state } = useEntityFilterGroup(
|
||||
'primary-sidebar',
|
||||
filterGroup,
|
||||
[initiallySelected],
|
||||
);
|
||||
|
||||
const setCurrent = useCallback(
|
||||
(filterId: string) => {
|
||||
setCurrentFilter(filterId);
|
||||
setSelectedFilters([filterId]);
|
||||
},
|
||||
[setCurrentFilter, setSelectedFilters],
|
||||
);
|
||||
|
||||
const getFilterCount = useCallback(
|
||||
(filterId: string) => {
|
||||
if (state.type !== 'ready') {
|
||||
return undefined;
|
||||
}
|
||||
return state.state.filters[filterId].matchCount;
|
||||
},
|
||||
[state],
|
||||
);
|
||||
|
||||
return {
|
||||
currentFilter,
|
||||
setCurrentFilter: setCurrent,
|
||||
getFilterCount,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -14,26 +14,29 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import React, { FC } from 'react';
|
||||
import {
|
||||
Header,
|
||||
HomepageTimer,
|
||||
identityApiRef,
|
||||
Page,
|
||||
pageTheme,
|
||||
identityApiRef,
|
||||
useApi,
|
||||
} from '@backstage/core';
|
||||
import React from 'react';
|
||||
import { getTimeBasedGreeting } from './utils/timeUtil';
|
||||
|
||||
const CatalogLayout: FC<{}> = props => {
|
||||
const { children } = props;
|
||||
type Props = {
|
||||
children?: React.ReactNode;
|
||||
};
|
||||
|
||||
const CatalogLayout = ({ children }: Props) => {
|
||||
const greeting = getTimeBasedGreeting();
|
||||
const identityApi = useApi(identityApiRef);
|
||||
const userId = useApi(identityApiRef).getUserId();
|
||||
|
||||
return (
|
||||
<Page theme={pageTheme.home}>
|
||||
<Header
|
||||
title={`${greeting.greeting}, ${identityApi.getUserId()}!`}
|
||||
title={`${greeting.greeting}, ${userId}!`}
|
||||
subtitle="Backstage Service Catalog"
|
||||
tooltip={greeting.language}
|
||||
pageTitleOverride="Home"
|
||||
|
||||
@@ -14,45 +14,43 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import { Entity } from '@backstage/catalog-model';
|
||||
import {
|
||||
ApiProvider,
|
||||
ApiRegistry,
|
||||
errorApiRef,
|
||||
storageApiRef,
|
||||
WebStorage,
|
||||
IdentityApi,
|
||||
identityApiRef,
|
||||
storageApiRef,
|
||||
} from '@backstage/core';
|
||||
import { MockErrorApi, wrapInTestApp } from '@backstage/test-utils';
|
||||
import { render, fireEvent } from '@testing-library/react';
|
||||
import { MockStorageApi, wrapInTestApp } from '@backstage/test-utils';
|
||||
import { fireEvent, render } from '@testing-library/react';
|
||||
import React from 'react';
|
||||
import { catalogApiRef } from '../..';
|
||||
import { CatalogApi } from '../../api/types';
|
||||
import { EntityFilterGroupsProvider } from '../../filter';
|
||||
import { CatalogPage } from './CatalogPage';
|
||||
import { Entity } from '@backstage/catalog-model';
|
||||
|
||||
describe('CatalogPage', () => {
|
||||
const mockErrorApi = new MockErrorApi();
|
||||
const catalogApi: Partial<CatalogApi> = {
|
||||
getEntities: () =>
|
||||
Promise.resolve([
|
||||
{
|
||||
apiVersion: 'backstage.io/v1alpha1',
|
||||
kind: 'Component',
|
||||
metadata: {
|
||||
name: 'Entity1',
|
||||
},
|
||||
apiVersion: 'backstage.io/v1alpha1',
|
||||
kind: 'Component',
|
||||
spec: {
|
||||
owner: 'tools@example.com',
|
||||
type: 'service',
|
||||
},
|
||||
},
|
||||
{
|
||||
apiVersion: 'backstage.io/v1alpha1',
|
||||
kind: 'Component',
|
||||
metadata: {
|
||||
name: 'Entity2',
|
||||
},
|
||||
apiVersion: 'backstage.io/v1alpha1',
|
||||
kind: 'Component',
|
||||
spec: {
|
||||
owner: 'not-tools@example.com',
|
||||
type: 'service',
|
||||
@@ -62,49 +60,32 @@ describe('CatalogPage', () => {
|
||||
getLocationByEntity: () =>
|
||||
Promise.resolve({ id: 'id', type: 'github', target: 'url' }),
|
||||
};
|
||||
const mockIndentityApi: Partial<IdentityApi> = {
|
||||
const indentityApi: Partial<IdentityApi> = {
|
||||
getUserId: () => 'tools@example.com',
|
||||
};
|
||||
|
||||
const renderWrapped = (children: React.ReactNode) =>
|
||||
render(
|
||||
wrapInTestApp(
|
||||
<ApiProvider
|
||||
apis={ApiRegistry.from([
|
||||
[catalogApiRef, catalogApi],
|
||||
[identityApiRef, indentityApi],
|
||||
[storageApiRef, MockStorageApi.create()],
|
||||
])}
|
||||
>
|
||||
<EntityFilterGroupsProvider>{children}</EntityFilterGroupsProvider>,
|
||||
</ApiProvider>,
|
||||
),
|
||||
);
|
||||
|
||||
// this test right now causes some red lines in the log output when running tests
|
||||
// related to some theme issues in mui-table
|
||||
// https://github.com/mbrn/material-table/issues/1293
|
||||
it('should render', async () => {
|
||||
const { findByText } = render(
|
||||
wrapInTestApp(
|
||||
<ApiProvider
|
||||
apis={ApiRegistry.from([
|
||||
[errorApiRef, mockErrorApi],
|
||||
[catalogApiRef, catalogApi],
|
||||
[storageApiRef, new WebStorage('@mock', mockErrorApi)],
|
||||
[identityApiRef, mockIndentityApi],
|
||||
])}
|
||||
>
|
||||
<CatalogPage />
|
||||
</ApiProvider>,
|
||||
),
|
||||
);
|
||||
|
||||
const items = await findByText(/All Services \(2\)/);
|
||||
expect(items).toBeInTheDocument();
|
||||
});
|
||||
it('should filter by owner', async () => {
|
||||
const { findByText, getByText } = render(
|
||||
wrapInTestApp(
|
||||
<ApiProvider
|
||||
apis={ApiRegistry.from([
|
||||
[errorApiRef, mockErrorApi],
|
||||
[catalogApiRef, catalogApi],
|
||||
[storageApiRef, new WebStorage('@mock', mockErrorApi)],
|
||||
[identityApiRef, mockIndentityApi],
|
||||
])}
|
||||
>
|
||||
<CatalogPage />
|
||||
</ApiProvider>,
|
||||
),
|
||||
);
|
||||
fireEvent.click(getByText(/Owned/));
|
||||
const items = await findByText(/Owned \(1\)/);
|
||||
expect(items).toBeInTheDocument();
|
||||
const { findByText, getByText } = renderWrapped(<CatalogPage />);
|
||||
expect(await findByText(/Owned \(1\)/)).toBeInTheDocument();
|
||||
fireEvent.click(getByText(/All/));
|
||||
expect(await findByText(/All \(2\)/)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -14,39 +14,26 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import { Entity, LocationSpec } from '@backstage/catalog-model';
|
||||
import {
|
||||
Content,
|
||||
ContentHeader,
|
||||
DismissableBanner,
|
||||
HeaderTabs,
|
||||
identityApiRef,
|
||||
SupportButton,
|
||||
useApi,
|
||||
} from '@backstage/core';
|
||||
import CatalogLayout from './CatalogLayout';
|
||||
import { rootRoute as scaffolderRootRoute } from '@backstage/plugin-scaffolder';
|
||||
import {
|
||||
Button,
|
||||
Link,
|
||||
makeStyles,
|
||||
Typography,
|
||||
withStyles,
|
||||
} from '@material-ui/core';
|
||||
import Edit from '@material-ui/icons/Edit';
|
||||
import GitHub from '@material-ui/icons/GitHub';
|
||||
import Star from '@material-ui/icons/Star';
|
||||
import StarOutline from '@material-ui/icons/StarBorder';
|
||||
import React, { FC } from 'react';
|
||||
import { Button, makeStyles } from '@material-ui/core';
|
||||
import SettingsIcon from '@material-ui/icons/Settings';
|
||||
import StarIcon from '@material-ui/icons/Star';
|
||||
import React, { useMemo, useState } from 'react';
|
||||
import { Link as RouterLink } from 'react-router-dom';
|
||||
import { CatalogFilter } from '../CatalogFilter/CatalogFilter';
|
||||
import { EntityFilterGroupsProvider, useFilteredEntities } from '../../filter';
|
||||
import { useStarredEntities } from '../../hooks/useStarredEntites';
|
||||
import { CatalogFilter, ButtonGroup } from '../CatalogFilter/CatalogFilter';
|
||||
import { CatalogTable } from '../CatalogTable/CatalogTable';
|
||||
import { useEntities } from '../../hooks/useEntities';
|
||||
import { findLocationForEntityMeta } from '../../data/utils';
|
||||
import {
|
||||
getCatalogFilterItemByType,
|
||||
EntityGroup,
|
||||
filterGroups,
|
||||
labeledEntityTypes,
|
||||
} from '../../data/filters';
|
||||
import CatalogLayout from './CatalogLayout';
|
||||
import { CatalogTabs, LabeledComponentType } from './CatalogTabs';
|
||||
import { WelcomeBanner } from './WelcomeBanner';
|
||||
|
||||
const useStyles = makeStyles(theme => ({
|
||||
contentWrapper: {
|
||||
@@ -55,138 +42,116 @@ const useStyles = makeStyles(theme => ({
|
||||
gridTemplateColumns: '250px 1fr',
|
||||
gridColumnGap: theme.spacing(2),
|
||||
},
|
||||
emoji: {
|
||||
fontSize: '125%',
|
||||
marginRight: theme.spacing(2),
|
||||
},
|
||||
}));
|
||||
|
||||
export const CatalogPage: FC<{}> = () => {
|
||||
const {
|
||||
entitiesByFilter,
|
||||
error,
|
||||
loading,
|
||||
selectedFilter,
|
||||
setSelectedFilter,
|
||||
toggleStarredEntity,
|
||||
isStarredEntity,
|
||||
selectTypeFilter,
|
||||
} = useEntities();
|
||||
|
||||
const filteredEntities = entitiesByFilter[selectedFilter ?? EntityGroup.ALL];
|
||||
|
||||
const CatalogPageContents = () => {
|
||||
const styles = useStyles();
|
||||
const { loading, error, matchingEntities } = useFilteredEntities();
|
||||
const { isStarredEntity } = useStarredEntities();
|
||||
const userId = useApi(identityApiRef).getUserId();
|
||||
const [selectedTab, setSelectedTab] = useState<string>();
|
||||
const [selectedSidebarItem, setSelectedSidebarItem] = useState<string>();
|
||||
|
||||
const YellowStar = withStyles({
|
||||
root: {
|
||||
color: '#f3ba37',
|
||||
},
|
||||
})(Star);
|
||||
const tabs = useMemo<LabeledComponentType[]>(
|
||||
() => [
|
||||
{
|
||||
id: 'service',
|
||||
label: 'Services',
|
||||
},
|
||||
{
|
||||
id: 'website',
|
||||
label: 'Websites',
|
||||
},
|
||||
{
|
||||
id: 'library',
|
||||
label: 'Libraries',
|
||||
},
|
||||
{
|
||||
id: 'documentation',
|
||||
label: 'Documentation',
|
||||
},
|
||||
{
|
||||
id: 'other',
|
||||
label: 'Other',
|
||||
},
|
||||
],
|
||||
[],
|
||||
);
|
||||
|
||||
const actions = [
|
||||
(rowData: Entity) => {
|
||||
const location = findLocationForEntityMeta(rowData.metadata);
|
||||
return {
|
||||
icon: GitHub,
|
||||
tooltip: 'View on GitHub',
|
||||
onClick: () => {
|
||||
if (!location) return;
|
||||
window.open(location.target, '_blank');
|
||||
},
|
||||
hidden: location?.type !== 'github',
|
||||
};
|
||||
},
|
||||
(rowData: Entity) => {
|
||||
const createEditLink = (location: LocationSpec): string => {
|
||||
switch (location.type) {
|
||||
case 'github':
|
||||
return location.target.replace('/blob/', '/edit/');
|
||||
default:
|
||||
return location.target;
|
||||
}
|
||||
};
|
||||
|
||||
const location = findLocationForEntityMeta(rowData.metadata);
|
||||
|
||||
return {
|
||||
icon: Edit,
|
||||
tooltip: 'Edit',
|
||||
iconProps: { size: 'small' },
|
||||
onClick: () => {
|
||||
if (!location) return;
|
||||
window.open(createEditLink(location), '_blank');
|
||||
},
|
||||
hidden: location?.type !== 'github',
|
||||
};
|
||||
},
|
||||
(rowData: Entity) => {
|
||||
const isStarred = isStarredEntity(rowData);
|
||||
return {
|
||||
icon: isStarred ? YellowStar : StarOutline,
|
||||
tooltip: isStarred ? 'Remove from favorites' : 'Add to favorites',
|
||||
onClick: () => toggleStarredEntity(rowData),
|
||||
};
|
||||
},
|
||||
];
|
||||
const filterGroups = useMemo<ButtonGroup[]>(
|
||||
() => [
|
||||
{
|
||||
name: 'Personal',
|
||||
items: [
|
||||
{
|
||||
id: 'owned',
|
||||
label: 'Owned',
|
||||
icon: SettingsIcon,
|
||||
filterFn: entity => entity.spec?.owner === userId,
|
||||
},
|
||||
{
|
||||
id: 'starred',
|
||||
label: 'Starred',
|
||||
icon: StarIcon,
|
||||
filterFn: isStarredEntity,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'Company', // TODO: Replace with Company name, read from app config.
|
||||
items: [
|
||||
{
|
||||
id: 'all',
|
||||
label: 'All',
|
||||
filterFn: () => true,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
[isStarredEntity, userId],
|
||||
);
|
||||
|
||||
return (
|
||||
<CatalogLayout>
|
||||
<HeaderTabs
|
||||
tabs={labeledEntityTypes}
|
||||
onChange={(index: Number) => {
|
||||
selectTypeFilter(labeledEntityTypes[index as number].id);
|
||||
}}
|
||||
<CatalogTabs
|
||||
tabs={tabs}
|
||||
onChange={({ label }) => setSelectedTab(label)}
|
||||
/>
|
||||
<Content>
|
||||
<DismissableBanner
|
||||
variant="info"
|
||||
message={
|
||||
<Typography>
|
||||
<span role="img" aria-label="wave" className={styles.emoji}>
|
||||
👋🏼
|
||||
</span>
|
||||
Welcome to Backstage, we are happy to have you. Start by checking
|
||||
out our{' '}
|
||||
<Link href="/welcome" color="textSecondary">
|
||||
getting started
|
||||
</Link>{' '}
|
||||
page.
|
||||
</Typography>
|
||||
}
|
||||
id="catalog_page_welcome_banner"
|
||||
/>
|
||||
<ContentHeader title="Services">
|
||||
<WelcomeBanner />
|
||||
<ContentHeader title={selectedTab ?? ''}>
|
||||
<Button
|
||||
component={RouterLink}
|
||||
variant="contained"
|
||||
color="primary"
|
||||
to={scaffolderRootRoute.path}
|
||||
>
|
||||
Create Service
|
||||
Create Component
|
||||
</Button>
|
||||
<SupportButton>All your software catalog entities</SupportButton>
|
||||
</ContentHeader>
|
||||
<div className={styles.contentWrapper}>
|
||||
<div>
|
||||
<CatalogFilter
|
||||
groups={filterGroups}
|
||||
selectedFilter={selectedFilter ?? EntityGroup.ALL}
|
||||
onFilterChange={setSelectedFilter}
|
||||
entitiesByFilter={entitiesByFilter}
|
||||
buttonGroups={filterGroups}
|
||||
onChange={({ label }) => setSelectedSidebarItem(label)}
|
||||
initiallySelected="owned"
|
||||
/>
|
||||
</div>
|
||||
<CatalogTable
|
||||
titlePreamble={
|
||||
getCatalogFilterItemByType(selectedFilter ?? EntityGroup.ALL)
|
||||
?.label ?? ''
|
||||
}
|
||||
entities={filteredEntities || []}
|
||||
loading={loading && !error}
|
||||
titlePreamble={selectedSidebarItem ?? ''}
|
||||
entities={matchingEntities}
|
||||
loading={loading}
|
||||
error={error}
|
||||
actions={actions}
|
||||
/>
|
||||
</div>
|
||||
</Content>
|
||||
</CatalogLayout>
|
||||
);
|
||||
};
|
||||
|
||||
export const CatalogPage = () => (
|
||||
<EntityFilterGroupsProvider>
|
||||
<CatalogPageContents />
|
||||
</EntityFilterGroupsProvider>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
/*
|
||||
* 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 { Entity } from '@backstage/catalog-model';
|
||||
import { HeaderTabs } from '@backstage/core';
|
||||
import React, {
|
||||
useCallback,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
} from 'react';
|
||||
import { FilterGroup, useEntityFilterGroup } from '../../filter';
|
||||
|
||||
/**
|
||||
* A component type, and a human readable label for it.
|
||||
*/
|
||||
export type LabeledComponentType = {
|
||||
id: string;
|
||||
label: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Called on mount, and when the selected tab changes.
|
||||
*/
|
||||
export type OnChangeCallback = (tab: LabeledComponentType) => void;
|
||||
|
||||
type Props = {
|
||||
tabs: LabeledComponentType[];
|
||||
onChange?: OnChangeCallback;
|
||||
};
|
||||
|
||||
/**
|
||||
* The tabs at the top of the catalog list page, for component type filtering.
|
||||
*/
|
||||
export const CatalogTabs = ({ tabs, onChange }: Props) => {
|
||||
const filterGroup = useMemo<FilterGroup>(() => {
|
||||
return {
|
||||
filters: Object.fromEntries(
|
||||
tabs.map(t => [t.id, (entity: Entity) => entity.spec?.type === t.id]),
|
||||
),
|
||||
};
|
||||
}, [tabs]);
|
||||
|
||||
const { setSelectedFilters } = useEntityFilterGroup('type', filterGroup, [
|
||||
tabs[0].id,
|
||||
]);
|
||||
|
||||
const [currentTabIndex, setCurrentTabIndex] = useState<number>(0);
|
||||
|
||||
// Hold a reference to the callback
|
||||
const onChangeRef = useRef<OnChangeCallback>();
|
||||
useEffect(() => {
|
||||
onChangeRef.current = onChange;
|
||||
}, [onChange]);
|
||||
|
||||
useEffect(() => {
|
||||
onChangeRef.current?.(tabs[currentTabIndex]);
|
||||
}, [tabs, currentTabIndex]);
|
||||
|
||||
const switchTab = useCallback(
|
||||
(index: number) => {
|
||||
const tab = tabs[index];
|
||||
setSelectedFilters([tab.id]);
|
||||
setCurrentTabIndex(index);
|
||||
onChangeRef.current?.(tab);
|
||||
},
|
||||
[tabs, setSelectedFilters],
|
||||
);
|
||||
|
||||
return <HeaderTabs tabs={tabs} onChange={switchTab} />;
|
||||
};
|
||||
@@ -0,0 +1,55 @@
|
||||
/*
|
||||
* 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 { DismissableBanner } from '@backstage/core';
|
||||
import { Link, makeStyles, Typography } from '@material-ui/core';
|
||||
import React from 'react';
|
||||
|
||||
const useStyles = makeStyles(theme => ({
|
||||
contentWrapper: {
|
||||
display: 'grid',
|
||||
gridTemplateAreas: "'filters' 'table'",
|
||||
gridTemplateColumns: '250px 1fr',
|
||||
gridColumnGap: theme.spacing(2),
|
||||
},
|
||||
emoji: {
|
||||
fontSize: '125%',
|
||||
marginRight: theme.spacing(2),
|
||||
},
|
||||
}));
|
||||
|
||||
export const WelcomeBanner = () => {
|
||||
const classes = useStyles();
|
||||
return (
|
||||
<DismissableBanner
|
||||
variant="info"
|
||||
message={
|
||||
<Typography>
|
||||
<span role="img" aria-label="wave" className={classes.emoji}>
|
||||
👋🏼
|
||||
</span>
|
||||
Welcome to Backstage, we are happy to have you. Start by checking out
|
||||
our{' '}
|
||||
<Link href="/welcome" color="textSecondary">
|
||||
getting started
|
||||
</Link>{' '}
|
||||
page.
|
||||
</Typography>
|
||||
}
|
||||
id="catalog_page_welcome_banner"
|
||||
/>
|
||||
);
|
||||
};
|
||||
@@ -66,11 +66,9 @@ describe('CatalogTable component', () => {
|
||||
/>,
|
||||
),
|
||||
);
|
||||
expect(
|
||||
await rendered.findByText(`Owned (${entites.length})`),
|
||||
).toBeInTheDocument();
|
||||
expect(await rendered.findByText('component1')).toBeInTheDocument();
|
||||
expect(await rendered.findByText('component2')).toBeInTheDocument();
|
||||
expect(await rendered.findByText('component3')).toBeInTheDocument();
|
||||
expect(rendered.getByText(/Owned \(3\)/)).toBeInTheDocument();
|
||||
expect(rendered.getByText(/component1/)).toBeInTheDocument();
|
||||
expect(rendered.getByText(/component2/)).toBeInTheDocument();
|
||||
expect(rendered.getByText(/component3/)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -13,16 +13,21 @@
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import { Entity } from '@backstage/catalog-model';
|
||||
import { Table, TableColumn } from '@backstage/core';
|
||||
import { Entity, LocationSpec } from '@backstage/catalog-model';
|
||||
import { Table, TableColumn, TableProps } from '@backstage/core';
|
||||
import { Link } from '@material-ui/core';
|
||||
import Edit from '@material-ui/icons/Edit';
|
||||
import GitHub from '@material-ui/icons/GitHub';
|
||||
import Star from '@material-ui/icons/Star';
|
||||
import StarOutline from '@material-ui/icons/StarBorder';
|
||||
import { Alert } from '@material-ui/lab';
|
||||
import React, { FC } from 'react';
|
||||
import React from 'react';
|
||||
import { generatePath, Link as RouterLink } from 'react-router-dom';
|
||||
import { findLocationForEntityMeta } from '../../data/utils';
|
||||
import { useStarredEntities } from '../../hooks/useStarredEntites';
|
||||
import { entityRoute } from '../../routes';
|
||||
|
||||
const columns: TableColumn[] = [
|
||||
const columns: TableColumn<Entity>[] = [
|
||||
{
|
||||
title: 'Name',
|
||||
field: 'metadata.name',
|
||||
@@ -63,16 +68,16 @@ type CatalogTableProps = {
|
||||
titlePreamble: string;
|
||||
loading: boolean;
|
||||
error?: any;
|
||||
actions?: any;
|
||||
};
|
||||
|
||||
export const CatalogTable: FC<CatalogTableProps> = ({
|
||||
export const CatalogTable = ({
|
||||
entities,
|
||||
loading,
|
||||
error,
|
||||
titlePreamble,
|
||||
actions,
|
||||
}) => {
|
||||
}: CatalogTableProps) => {
|
||||
const { isStarredEntity, toggleStarredEntity } = useStarredEntities();
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div>
|
||||
@@ -83,8 +88,57 @@ export const CatalogTable: FC<CatalogTableProps> = ({
|
||||
);
|
||||
}
|
||||
|
||||
const actions: TableProps<Entity>['actions'] = [
|
||||
(rowData: Entity) => {
|
||||
const location = findLocationForEntityMeta(rowData.metadata);
|
||||
return {
|
||||
icon: () => <GitHub fontSize="small" />,
|
||||
tooltip: 'View on GitHub',
|
||||
onClick: () => {
|
||||
if (!location) return;
|
||||
window.open(location.target, '_blank');
|
||||
},
|
||||
hidden: location?.type !== 'github',
|
||||
};
|
||||
},
|
||||
(rowData: Entity) => {
|
||||
const createEditLink = (location: LocationSpec): string => {
|
||||
switch (location.type) {
|
||||
case 'github':
|
||||
return location.target.replace('/blob/', '/edit/');
|
||||
default:
|
||||
return location.target;
|
||||
}
|
||||
};
|
||||
const location = findLocationForEntityMeta(rowData.metadata);
|
||||
return {
|
||||
icon: () => <Edit fontSize="small" />,
|
||||
tooltip: 'Edit',
|
||||
onClick: () => {
|
||||
if (!location) return;
|
||||
window.open(createEditLink(location), '_blank');
|
||||
},
|
||||
hidden: location?.type !== 'github',
|
||||
};
|
||||
},
|
||||
(rowData: Entity) => {
|
||||
const isStarred = isStarredEntity(rowData);
|
||||
return {
|
||||
cellStyle: { paddingLeft: '1em' },
|
||||
icon: () =>
|
||||
isStarred ? (
|
||||
<Star htmlColor="#f3ba37" fontSize="small" />
|
||||
) : (
|
||||
<StarOutline fontSize="small" />
|
||||
),
|
||||
tooltip: isStarred ? 'Remove from favorites' : 'Add to favorites',
|
||||
onClick: () => toggleStarredEntity(rowData),
|
||||
};
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<Table
|
||||
<Table<Entity>
|
||||
isLoading={loading}
|
||||
columns={columns}
|
||||
options={{
|
||||
|
||||
@@ -27,7 +27,7 @@ jest.mock('react-router-dom', () => {
|
||||
import { ApiProvider, ApiRegistry, errorApiRef } from '@backstage/core';
|
||||
import { Entity } from '@backstage/catalog-model';
|
||||
import { wrapInTestApp } from '@backstage/test-utils';
|
||||
import { render, wait } from '@testing-library/react';
|
||||
import { render, waitFor } from '@testing-library/react';
|
||||
import * as React from 'react';
|
||||
import { CatalogApi, catalogApiRef } from '../../api/types';
|
||||
import { EntityPage, getPageTheme } from './EntityPage';
|
||||
@@ -66,7 +66,7 @@ describe('EntityPage', () => {
|
||||
),
|
||||
);
|
||||
|
||||
await wait(() => expect(useNavigate()).toHaveBeenCalledWith('/catalog'));
|
||||
await waitFor(() => expect(useNavigate()).toHaveBeenCalledWith('/catalog'));
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -1,123 +0,0 @@
|
||||
/*
|
||||
* 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 { Entity } from '@backstage/catalog-model';
|
||||
import SettingsIcon from '@material-ui/icons/Settings';
|
||||
import StarIcon from '@material-ui/icons/Star';
|
||||
import {
|
||||
CatalogFilterGroup,
|
||||
CatalogFilterItem,
|
||||
} from '../components/CatalogFilter/CatalogFilter';
|
||||
|
||||
export enum EntityGroup {
|
||||
ALL = 'ALL',
|
||||
STARRED = 'STARRED',
|
||||
OWNED = 'OWNED',
|
||||
}
|
||||
|
||||
export const filterGroups: CatalogFilterGroup[] = [
|
||||
{
|
||||
name: 'Personal',
|
||||
items: [
|
||||
{
|
||||
id: EntityGroup.OWNED,
|
||||
label: 'Owned',
|
||||
icon: SettingsIcon,
|
||||
},
|
||||
{
|
||||
id: EntityGroup.STARRED,
|
||||
label: 'Starred',
|
||||
icon: StarIcon,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
// TODO: Replace with Company name, read from app config.
|
||||
name: 'Company',
|
||||
items: [
|
||||
{
|
||||
id: EntityGroup.ALL,
|
||||
label: 'All Services',
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
export const getCatalogFilterItemByType = (filterType: EntityGroup) => {
|
||||
for (const group of filterGroups) {
|
||||
for (const filter of group.items) {
|
||||
if (filter.id === filterType) {
|
||||
return filter;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
type EntityFilter = (entity: Entity, options: EntityFilterOptions) => boolean;
|
||||
|
||||
type EntityFilterOptions = Partial<{
|
||||
isStarred: boolean;
|
||||
userId: string;
|
||||
}>;
|
||||
|
||||
type Owned = {
|
||||
owner: string;
|
||||
};
|
||||
|
||||
export const entityFilters: Record<string, EntityFilter> = {
|
||||
[EntityGroup.OWNED]: (e, { userId }) => {
|
||||
const owner = (e.spec! as Owned).owner;
|
||||
return owner === userId;
|
||||
},
|
||||
[EntityGroup.ALL]: () => true,
|
||||
[EntityGroup.STARRED]: (_, { isStarred }) => !!isStarred,
|
||||
};
|
||||
|
||||
export const entityTypeFilter = (e: Entity, type: string) =>
|
||||
(e.spec as any)?.type === type;
|
||||
|
||||
type EntityType = 'service' | 'website' | 'library' | 'documentation' | 'other';
|
||||
|
||||
type LabeledEntityType = {
|
||||
id: EntityType;
|
||||
label: string;
|
||||
};
|
||||
|
||||
export const labeledEntityTypes: LabeledEntityType[] = [
|
||||
{
|
||||
id: 'service',
|
||||
label: 'Services',
|
||||
},
|
||||
{
|
||||
id: 'website',
|
||||
label: 'Websites',
|
||||
},
|
||||
{
|
||||
id: 'library',
|
||||
label: 'Libraries',
|
||||
},
|
||||
{
|
||||
id: 'documentation',
|
||||
label: 'Documentation',
|
||||
},
|
||||
{
|
||||
id: 'other',
|
||||
label: 'Other',
|
||||
},
|
||||
];
|
||||
|
||||
export const defaultFilter: CatalogFilterItem = filterGroups[0].items[0];
|
||||
@@ -0,0 +1,207 @@
|
||||
/*
|
||||
* 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 { Entity } from '@backstage/catalog-model';
|
||||
import { useApi } from '@backstage/core';
|
||||
import React, { useCallback, useRef, useState } from 'react';
|
||||
import { useAsync } from 'react-use';
|
||||
import { catalogApiRef } from '../api/types';
|
||||
import { filterGroupsContext, FilterGroupsContext } from './context';
|
||||
import {
|
||||
EntityFilterFn,
|
||||
FilterGroup,
|
||||
FilterGroupState,
|
||||
FilterGroupStates,
|
||||
} from './types';
|
||||
|
||||
/**
|
||||
* Implementation of the shared filter groups state.
|
||||
*/
|
||||
export const EntityFilterGroupsProvider = ({
|
||||
children,
|
||||
}: {
|
||||
children?: React.ReactNode;
|
||||
}) => {
|
||||
const state = useProvideEntityFilters();
|
||||
return (
|
||||
<filterGroupsContext.Provider value={state}>
|
||||
{children}
|
||||
</filterGroupsContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
// The hook that implements the actual context building
|
||||
function useProvideEntityFilters(): FilterGroupsContext {
|
||||
const catalogApi = useApi(catalogApiRef);
|
||||
const { value: entities, error } = useAsync(() => catalogApi.getEntities());
|
||||
|
||||
const filterGroups = useRef<{
|
||||
[filterGroupId: string]: FilterGroup;
|
||||
}>({});
|
||||
const selectedFilterKeys = useRef<{
|
||||
[filterGroupId: string]: Set<string>;
|
||||
}>({});
|
||||
const [filterGroupStates, setFilterGroupStates] = useState<{
|
||||
[filterGroupId: string]: FilterGroupStates;
|
||||
}>({});
|
||||
const [matchingEntities, setMatchingEntities] = useState<Entity[]>([]);
|
||||
|
||||
const rebuild = useCallback(() => {
|
||||
setFilterGroupStates(
|
||||
buildStates(
|
||||
filterGroups.current,
|
||||
selectedFilterKeys.current,
|
||||
entities,
|
||||
error,
|
||||
),
|
||||
);
|
||||
setMatchingEntities(
|
||||
buildMatchingEntities(
|
||||
filterGroups.current,
|
||||
selectedFilterKeys.current,
|
||||
entities,
|
||||
),
|
||||
);
|
||||
}, [entities, error]);
|
||||
|
||||
const register = useCallback(
|
||||
(
|
||||
filterGroupId: string,
|
||||
filterGroup: FilterGroup,
|
||||
initialSelectedFilterIds?: string[],
|
||||
) => {
|
||||
filterGroups.current[filterGroupId] = filterGroup;
|
||||
selectedFilterKeys.current[filterGroupId] = new Set(
|
||||
initialSelectedFilterIds ?? [],
|
||||
);
|
||||
rebuild();
|
||||
},
|
||||
[rebuild],
|
||||
);
|
||||
|
||||
const unregister = useCallback(
|
||||
(filterGroupId: string) => {
|
||||
delete filterGroups.current[filterGroupId];
|
||||
delete selectedFilterKeys.current[filterGroupId];
|
||||
rebuild();
|
||||
},
|
||||
[rebuild],
|
||||
);
|
||||
|
||||
const setGroupSelectedFilters = useCallback(
|
||||
(filterGroupId: string, filters: string[]) => {
|
||||
selectedFilterKeys.current[filterGroupId] = new Set(filters);
|
||||
rebuild();
|
||||
},
|
||||
[rebuild],
|
||||
);
|
||||
|
||||
return {
|
||||
register,
|
||||
unregister,
|
||||
setGroupSelectedFilters,
|
||||
loading: !error && !entities,
|
||||
error,
|
||||
filterGroupStates,
|
||||
matchingEntities,
|
||||
};
|
||||
}
|
||||
|
||||
// Given all filter groups and what filters are actually selected, along with
|
||||
// the loading state for entities, generate the state of each individual filter
|
||||
function buildStates(
|
||||
filterGroups: { [filterGroupId: string]: FilterGroup },
|
||||
selectedFilterKeys: { [filterGroupId: string]: Set<string> },
|
||||
entities?: Entity[],
|
||||
error?: Error,
|
||||
): { [filterGroupId: string]: FilterGroupStates } {
|
||||
// On error - all entries are an error state
|
||||
if (error) {
|
||||
return Object.fromEntries(
|
||||
Object.keys(filterGroups).map(filterGroupId => [
|
||||
filterGroupId,
|
||||
{ type: 'error', error },
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
// On startup - all entries are a loading state
|
||||
if (!entities) {
|
||||
return Object.fromEntries(
|
||||
Object.keys(filterGroups).map(filterGroupId => [
|
||||
filterGroupId,
|
||||
{ type: 'loading' },
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
const result: { [filterGroupId: string]: FilterGroupStates } = {};
|
||||
for (const [filterGroupId, filterGroup] of Object.entries(filterGroups)) {
|
||||
const otherMatchingEntities = buildMatchingEntities(
|
||||
filterGroups,
|
||||
selectedFilterKeys,
|
||||
entities,
|
||||
filterGroupId,
|
||||
);
|
||||
const groupState: FilterGroupState = { filters: {} };
|
||||
for (const [filterId, filterFn] of Object.entries(filterGroup.filters)) {
|
||||
const isSelected = !!selectedFilterKeys[filterGroupId]?.has(filterId);
|
||||
const matchCount = otherMatchingEntities.filter(entity =>
|
||||
filterFn(entity),
|
||||
).length;
|
||||
groupState.filters[filterId] = { isSelected, matchCount };
|
||||
}
|
||||
result[filterGroupId] = { type: 'ready', state: groupState };
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// Given all filter groups and what filters are actually selected, extract all
|
||||
// entities that match all those filter groups.
|
||||
function buildMatchingEntities(
|
||||
filterGroups: { [filterGroupId: string]: FilterGroup },
|
||||
selectedFilterKeys: { [filterGroupId: string]: Set<string> },
|
||||
entities?: Entity[],
|
||||
excludeFilterGroupId?: string,
|
||||
): Entity[] {
|
||||
// Build one filter fn per filter group
|
||||
const allFilters: EntityFilterFn[] = [];
|
||||
for (const [filterGroupId, filterGroup] of Object.entries(filterGroups)) {
|
||||
if (excludeFilterGroupId === filterGroupId) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Pick out all of the filter functions in the group that are actually
|
||||
// selected
|
||||
const groupFilters: EntityFilterFn[] = [];
|
||||
for (const [filterId, filterFn] of Object.entries(filterGroup.filters)) {
|
||||
if (!!selectedFilterKeys[filterGroupId]?.has(filterId)) {
|
||||
groupFilters.push(filterFn);
|
||||
}
|
||||
}
|
||||
|
||||
// Need to match any of the selected filters in the group - if there is
|
||||
// any at all
|
||||
if (groupFilters.length) {
|
||||
allFilters.push(entity => groupFilters.some(fn => fn(entity)));
|
||||
}
|
||||
}
|
||||
|
||||
// All filter groups that had any checked filters need to match. Note that
|
||||
// every() always returns true for an empty array.
|
||||
return entities?.filter(entity => allFilters.every(fn => fn(entity))) ?? [];
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
/*
|
||||
* 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 { Entity } from '@backstage/catalog-model';
|
||||
import { createContext } from 'react';
|
||||
import { FilterGroup, FilterGroupStates } from './types';
|
||||
|
||||
export type FilterGroupsContext = {
|
||||
register: (
|
||||
filterGroupId: string,
|
||||
filterGroup: FilterGroup,
|
||||
initialSelectedFilterIds?: string[],
|
||||
) => void;
|
||||
unregister: (filterGroupId: string) => void;
|
||||
setGroupSelectedFilters: (filterGroupId: string, filterIds: string[]) => void;
|
||||
loading: boolean;
|
||||
error?: Error;
|
||||
filterGroupStates: { [filterGroupId: string]: FilterGroupStates };
|
||||
matchingEntities: Entity[];
|
||||
};
|
||||
|
||||
/**
|
||||
* The context that maintains shared state for all visible filter groups.
|
||||
*/
|
||||
export const filterGroupsContext = createContext<
|
||||
FilterGroupsContext | undefined
|
||||
>(undefined);
|
||||
@@ -0,0 +1,28 @@
|
||||
/*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
export { EntityFilterGroupsProvider } from './EntityFilterGroupsProvider';
|
||||
export type {
|
||||
EntityFilterFn,
|
||||
FilterGroup,
|
||||
FilterGroupState,
|
||||
FilterGroupStates,
|
||||
FilterGroupStatesError,
|
||||
FilterGroupStatesLoading,
|
||||
FilterGroupStatesReady,
|
||||
} from './types';
|
||||
export { useEntityFilterGroup } from './useEntityFilterGroup';
|
||||
export { useFilteredEntities } from './useFilteredEntities';
|
||||
@@ -0,0 +1,53 @@
|
||||
/*
|
||||
* 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 { Entity } from '@backstage/catalog-model';
|
||||
|
||||
export type EntityFilterFn = (entity: Entity) => boolean;
|
||||
|
||||
export type FilterGroup = {
|
||||
filters: {
|
||||
[filterId: string]: EntityFilterFn;
|
||||
};
|
||||
};
|
||||
|
||||
export type FilterGroupState = {
|
||||
filters: {
|
||||
[filterId: string]: {
|
||||
isSelected: boolean;
|
||||
matchCount: number;
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
export type FilterGroupStatesReady = {
|
||||
type: 'ready';
|
||||
state: FilterGroupState;
|
||||
};
|
||||
|
||||
export type FilterGroupStatesError = {
|
||||
type: 'error';
|
||||
error: Error;
|
||||
};
|
||||
|
||||
export type FilterGroupStatesLoading = {
|
||||
type: 'loading';
|
||||
};
|
||||
|
||||
export type FilterGroupStates =
|
||||
| FilterGroupStatesReady
|
||||
| FilterGroupStatesError
|
||||
| FilterGroupStatesLoading;
|
||||
@@ -0,0 +1,118 @@
|
||||
/*
|
||||
* 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 { ApiProvider, ApiRegistry, storageApiRef } from '@backstage/core';
|
||||
import { act, renderHook } from '@testing-library/react-hooks';
|
||||
import React from 'react';
|
||||
import { catalogApiRef } from '../api/types';
|
||||
import { EntityFilterGroupsProvider } from './EntityFilterGroupsProvider';
|
||||
import { FilterGroupStatesReady, FilterGroup } from './types';
|
||||
import { useEntityFilterGroup } from './useEntityFilterGroup';
|
||||
import { MockStorageApi } from '@backstage/test-utils';
|
||||
|
||||
describe('useEntityFilterGroup', () => {
|
||||
let catalogApi: jest.Mocked<typeof catalogApiRef.T>;
|
||||
let wrapper: ({ children }: { children?: React.ReactNode }) => JSX.Element;
|
||||
|
||||
beforeEach(() => {
|
||||
catalogApi = {
|
||||
/* eslint-disable-next-line @typescript-eslint/no-unused-vars */
|
||||
addLocation: jest.fn((_a, _b) => new Promise(() => {})),
|
||||
getEntities: jest.fn(),
|
||||
getLocationByEntity: jest.fn(),
|
||||
getLocationById: jest.fn(),
|
||||
removeEntityByUid: jest.fn(),
|
||||
getEntityByName: jest.fn(),
|
||||
};
|
||||
const apis = ApiRegistry.with(catalogApiRef, catalogApi).with(
|
||||
storageApiRef,
|
||||
MockStorageApi.create(),
|
||||
);
|
||||
wrapper = ({ children }: { children?: React.ReactNode }) => (
|
||||
<ApiProvider apis={apis}>
|
||||
<EntityFilterGroupsProvider>{children}</EntityFilterGroupsProvider>
|
||||
</ApiProvider>
|
||||
);
|
||||
});
|
||||
|
||||
it('works for an empty set of filters', async () => {
|
||||
catalogApi.getEntities.mockResolvedValue([]);
|
||||
const group: FilterGroup = { filters: {} };
|
||||
const { result, wait } = renderHook(
|
||||
() => useEntityFilterGroup('g1', group),
|
||||
{ wrapper },
|
||||
);
|
||||
|
||||
await wait(() => expect(result.current.state.type).toBe('ready'));
|
||||
});
|
||||
|
||||
it('works for a single group', async () => {
|
||||
catalogApi.getEntities.mockResolvedValue([
|
||||
{
|
||||
apiVersion: 'backstage.io/v1alpha1',
|
||||
kind: 'Component',
|
||||
metadata: { name: 'n' },
|
||||
},
|
||||
]);
|
||||
const group: FilterGroup = {
|
||||
filters: {
|
||||
f1: e => e.metadata.name === 'n',
|
||||
f2: e => e.metadata.name !== 'n',
|
||||
},
|
||||
};
|
||||
const { result, wait } = renderHook(
|
||||
() => useEntityFilterGroup('g1', group),
|
||||
{ wrapper },
|
||||
);
|
||||
|
||||
await wait(() => expect(result.current.state.type).toEqual('ready'));
|
||||
let state = result.current.state as FilterGroupStatesReady;
|
||||
expect(state.state.filters.f1).toEqual({
|
||||
isSelected: false,
|
||||
matchCount: 1,
|
||||
});
|
||||
expect(state.state.filters.f2).toEqual({
|
||||
isSelected: false,
|
||||
matchCount: 0,
|
||||
});
|
||||
|
||||
act(() => result.current.setSelectedFilters(['f1']));
|
||||
|
||||
await wait(() => expect(result.current.state.type).toEqual('ready'));
|
||||
state = result.current.state as FilterGroupStatesReady;
|
||||
expect(state.state.filters.f1).toEqual({
|
||||
isSelected: true,
|
||||
matchCount: 1,
|
||||
});
|
||||
expect(state.state.filters.f2).toEqual({
|
||||
isSelected: false,
|
||||
matchCount: 0,
|
||||
});
|
||||
|
||||
act(() => result.current.setSelectedFilters(['f2']));
|
||||
|
||||
await wait(() => expect(result.current.state.type).toEqual('ready'));
|
||||
state = result.current.state as FilterGroupStatesReady;
|
||||
expect(state.state.filters.f1).toEqual({
|
||||
isSelected: false,
|
||||
matchCount: 1,
|
||||
});
|
||||
expect(state.state.filters.f2).toEqual({
|
||||
isSelected: true,
|
||||
matchCount: 0,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,69 @@
|
||||
/*
|
||||
* 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 { useCallback, useContext, useEffect, useMemo } from 'react';
|
||||
import { filterGroupsContext } from './context';
|
||||
import { FilterGroup, FilterGroupStates } from './types';
|
||||
|
||||
export type EntityFilterGroupOutput = {
|
||||
state: FilterGroupStates;
|
||||
setSelectedFilters: (filterIds: string[]) => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* Hook that exposes the relevant data and operations for a single filter
|
||||
* group.
|
||||
*/
|
||||
export const useEntityFilterGroup = (
|
||||
filterGroupId: string,
|
||||
filterGroup: FilterGroup,
|
||||
initialSelectedFilters?: string[],
|
||||
): EntityFilterGroupOutput => {
|
||||
const context = useContext(filterGroupsContext);
|
||||
if (!context) {
|
||||
throw new Error(`Must be used inside an EntityFilterGroupsProvider`);
|
||||
}
|
||||
const {
|
||||
register,
|
||||
unregister,
|
||||
setGroupSelectedFilters,
|
||||
filterGroupStates,
|
||||
} = context;
|
||||
|
||||
// Intentionally consider initial set only at mount time
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
const initialMemo = useMemo(() => initialSelectedFilters?.slice(), []);
|
||||
|
||||
// Register the group on mount, and unregister on unmount
|
||||
useEffect(() => {
|
||||
register(filterGroupId, filterGroup, initialMemo);
|
||||
return () => unregister(filterGroupId);
|
||||
}, [register, unregister, filterGroupId, filterGroup, initialMemo]);
|
||||
|
||||
const setSelectedFilters = useCallback(
|
||||
(filters: string[]) => {
|
||||
setGroupSelectedFilters(filterGroupId, filters);
|
||||
},
|
||||
[setGroupSelectedFilters, filterGroupId],
|
||||
);
|
||||
|
||||
let state = filterGroupStates[filterGroupId];
|
||||
if (!state) {
|
||||
state = { type: 'loading' };
|
||||
}
|
||||
|
||||
return { state, setSelectedFilters };
|
||||
};
|
||||
@@ -0,0 +1,34 @@
|
||||
/*
|
||||
* 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 { useContext } from 'react';
|
||||
import { filterGroupsContext } from './context';
|
||||
|
||||
/**
|
||||
* Hook that exposes the result of applying a set of filter groups.
|
||||
*/
|
||||
export function useFilteredEntities() {
|
||||
const context = useContext(filterGroupsContext);
|
||||
if (!context) {
|
||||
throw new Error(`Must be used inside an EntityFilterGroupsProvider`);
|
||||
}
|
||||
|
||||
return {
|
||||
loading: context.loading,
|
||||
error: context.error,
|
||||
matchingEntities: context.matchingEntities,
|
||||
};
|
||||
}
|
||||
@@ -1,103 +0,0 @@
|
||||
/*
|
||||
* 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 { useState, useMemo } from 'react';
|
||||
import {
|
||||
EntityGroup,
|
||||
entityFilters,
|
||||
entityTypeFilter,
|
||||
labeledEntityTypes,
|
||||
} from '../data/filters';
|
||||
import { useApi, identityApiRef } from '@backstage/core';
|
||||
import { catalogApiRef } from '..';
|
||||
import { useStarredEntities } from './useStarredEntites';
|
||||
import { Entity } from '@backstage/catalog-model';
|
||||
import useStaleWhileRevalidate from 'swr';
|
||||
|
||||
export type EntitiesByFilter = Record<EntityGroup, Entity[] | undefined>;
|
||||
|
||||
type UseEntities = {
|
||||
selectedFilter: EntityGroup | undefined;
|
||||
setSelectedFilter: (f: EntityGroup) => void;
|
||||
error: Error | null;
|
||||
toggleStarredEntity: any;
|
||||
isStarredEntity: (e: Entity) => boolean;
|
||||
entitiesByFilter: EntitiesByFilter;
|
||||
loading: boolean;
|
||||
selectedTypeFilter: string;
|
||||
selectTypeFilter: (id: string) => void;
|
||||
};
|
||||
|
||||
export const useEntities = (): UseEntities => {
|
||||
const [selectedFilter, setSelectedFilter] = useState<
|
||||
EntityGroup | undefined
|
||||
>();
|
||||
const catalogApi = useApi(catalogApiRef);
|
||||
const { toggleStarredEntity, isStarredEntity } = useStarredEntities();
|
||||
const { data: entities, error } = useStaleWhileRevalidate(
|
||||
['catalog/all', entityFilters[selectedFilter ?? EntityGroup.ALL]],
|
||||
async () => catalogApi.getEntities(),
|
||||
);
|
||||
|
||||
const indentityApi = useApi(identityApiRef);
|
||||
const userId = indentityApi.getUserId();
|
||||
|
||||
const [selectedTypeFilter, selectTypeFilter] = useState<string>(
|
||||
labeledEntityTypes[0].id,
|
||||
);
|
||||
|
||||
const entitiesByFilter = useMemo(() => {
|
||||
const filterEntities = (
|
||||
ents: Entity[] | undefined,
|
||||
filterId: EntityGroup,
|
||||
isStarred: (e: Entity) => boolean,
|
||||
user: string,
|
||||
) => {
|
||||
return ents
|
||||
?.filter((e: Entity) =>
|
||||
entityFilters[filterId](e, {
|
||||
isStarred: isStarred(e),
|
||||
userId: user,
|
||||
}),
|
||||
)
|
||||
.filter(e => entityTypeFilter(e, selectedTypeFilter));
|
||||
};
|
||||
const data = Object.keys(EntityGroup).reduce(
|
||||
(res, key) => ({
|
||||
...res,
|
||||
[key]: filterEntities(
|
||||
entities,
|
||||
key as EntityGroup,
|
||||
isStarredEntity,
|
||||
userId,
|
||||
),
|
||||
}),
|
||||
{} as EntitiesByFilter,
|
||||
);
|
||||
return data;
|
||||
}, [entities, isStarredEntity, userId, selectedTypeFilter]);
|
||||
|
||||
return {
|
||||
selectedFilter,
|
||||
setSelectedFilter,
|
||||
error,
|
||||
toggleStarredEntity,
|
||||
isStarredEntity,
|
||||
entitiesByFilter,
|
||||
loading: entities === undefined,
|
||||
selectedTypeFilter,
|
||||
selectTypeFilter,
|
||||
};
|
||||
};
|
||||
@@ -4,6 +4,10 @@ metadata:
|
||||
name: react-ssr-template
|
||||
title: React SSR Template
|
||||
description: Next.js application skeleton for creating isomorphic web applications.
|
||||
tags:
|
||||
- Recommended
|
||||
- React
|
||||
spec:
|
||||
type: cookiecutter
|
||||
processor: cookiecutter
|
||||
type: website
|
||||
path: '.'
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
apiVersion: backstage.io/v1alpha1
|
||||
kind: Template
|
||||
metadata:
|
||||
name: springboot-template
|
||||
title: Spring Boot Service
|
||||
description: Standard Spring Boot (Java) microservice with recommended configuration.
|
||||
tags:
|
||||
- Recommended
|
||||
- Java
|
||||
spec:
|
||||
processor: cookiecutter
|
||||
type: service
|
||||
path: '.'
|
||||
@@ -1,8 +1,13 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
curl \
|
||||
--location \
|
||||
--request POST 'localhost:7000/catalog/locations' \
|
||||
--header 'Content-Type: application/json' \
|
||||
--data-raw "{\"type\": \"file\", \"target\": \"$(pwd)/sample-templates/react-ssr-template/template.yaml\"}"
|
||||
|
||||
for URL in \
|
||||
'react-ssr-template' \
|
||||
'springboot-template' \
|
||||
; do \
|
||||
curl \
|
||||
--location \
|
||||
--request POST 'localhost:7000/catalog/locations' \
|
||||
--header 'Content-Type: application/json' \
|
||||
--data-raw "{\"type\": \"file\", \"target\": \"$(pwd)/sample-templates/${URL}/template.yaml\"}"
|
||||
echo
|
||||
done
|
||||
|
||||
@@ -21,6 +21,8 @@
|
||||
"clean": "backstage-cli clean"
|
||||
},
|
||||
"dependencies": {
|
||||
"@backstage/catalog-model": "^0.1.1-alpha.12",
|
||||
"@backstage/plugin-catalog": "^0.1.1-alpha.12",
|
||||
"@backstage/core": "^0.1.1-alpha.12",
|
||||
"@backstage/theme": "^0.1.1-alpha.12",
|
||||
"@material-ui/core": "^4.9.1",
|
||||
@@ -29,7 +31,8 @@
|
||||
"react": "^16.13.1",
|
||||
"react-dom": "^16.13.1",
|
||||
"react-router-dom": "6.0.0-alpha.5",
|
||||
"react-use": "^14.2.0"
|
||||
"react-use": "^14.2.0",
|
||||
"swr": "^0.2.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@backstage/cli": "^0.1.1-alpha.12",
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import React, { useEffect } from 'react';
|
||||
import {
|
||||
Lifecycle,
|
||||
Content,
|
||||
@@ -23,33 +23,39 @@ import {
|
||||
SupportButton,
|
||||
Page,
|
||||
pageTheme,
|
||||
useApi,
|
||||
errorApiRef,
|
||||
} from '@backstage/core';
|
||||
import { Button, Grid, Link, Typography } from '@material-ui/core';
|
||||
import { catalogApiRef } from '@backstage/plugin-catalog';
|
||||
import {
|
||||
Typography,
|
||||
Link,
|
||||
Button,
|
||||
Grid,
|
||||
LinearProgress,
|
||||
} from '@material-ui/core';
|
||||
import { Link as RouterLink } from 'react-router-dom';
|
||||
import TemplateCard from '../TemplateCard';
|
||||
import useStaleWhileRevalidate from 'swr';
|
||||
import { TemplateEntityV1alpha1 } from '@backstage/catalog-model';
|
||||
|
||||
// TODO(blam): Connect to backend
|
||||
const STATIC_DATA = [
|
||||
{
|
||||
id: 'springboot-template',
|
||||
type: 'service',
|
||||
name: 'Spring Boot Service',
|
||||
tags: ['Recommended', 'Java'],
|
||||
description:
|
||||
'Standard Spring Boot (Java) microservice with recommended configuration.',
|
||||
ownerId: 'spotify',
|
||||
},
|
||||
{
|
||||
id: 'react-ssr-template',
|
||||
type: 'website',
|
||||
name: 'SSR React Website',
|
||||
tags: ['Recommended', 'React'],
|
||||
description:
|
||||
'Next.js application skeleton for creating isomorphic web applications.',
|
||||
ownerId: 'spotify',
|
||||
},
|
||||
];
|
||||
const ScaffolderPage: React.FC<{}> = () => {
|
||||
const catalogApi = useApi(catalogApiRef);
|
||||
const errorApi = useApi(errorApiRef);
|
||||
|
||||
const { data: templates, isValidating, error } = useStaleWhileRevalidate(
|
||||
'templates/all',
|
||||
async () =>
|
||||
catalogApi.getEntities({ kind: 'Template' }) as Promise<
|
||||
TemplateEntityV1alpha1[]
|
||||
>,
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!error) return;
|
||||
errorApi.post(error);
|
||||
}, [error, errorApi]);
|
||||
|
||||
return (
|
||||
<Page theme={pageTheme.home}>
|
||||
<Header
|
||||
@@ -84,18 +90,24 @@ const ScaffolderPage: React.FC<{}> = () => {
|
||||
</Link>
|
||||
.
|
||||
</Typography>
|
||||
{!templates && isValidating && <LinearProgress />}
|
||||
<Grid container>
|
||||
{STATIC_DATA.map(item => {
|
||||
return (
|
||||
<TemplateCard
|
||||
key={item.id}
|
||||
title={item.name}
|
||||
type={item.type}
|
||||
description={item.description}
|
||||
tags={item.tags}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
{templates &&
|
||||
templates.map(template => {
|
||||
return (
|
||||
<Grid item xs={12} sm={6} md={3}>
|
||||
<TemplateCard
|
||||
key={template.metadata.uid}
|
||||
title={`${
|
||||
(template.metadata.title || template.metadata.name) ?? ''
|
||||
}`}
|
||||
type={template.spec.type ?? ''}
|
||||
description={template.metadata.description ?? '-'}
|
||||
tags={(template.metadata?.tags as string[]) ?? []}
|
||||
/>
|
||||
</Grid>
|
||||
);
|
||||
})}
|
||||
</Grid>
|
||||
</Content>
|
||||
</Page>
|
||||
|
||||
@@ -14,14 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
import React, { FC } from 'react';
|
||||
import {
|
||||
Button,
|
||||
Card,
|
||||
Chip,
|
||||
Grid,
|
||||
Typography,
|
||||
makeStyles,
|
||||
} from '@material-ui/core';
|
||||
import { Button, Card, Chip, Typography, makeStyles } from '@material-ui/core';
|
||||
|
||||
const useStyles = makeStyles(theme => ({
|
||||
header: {
|
||||
@@ -59,25 +52,23 @@ const TemplateCard: FC<TemplateCardProps> = ({
|
||||
const classes = useStyles();
|
||||
|
||||
return (
|
||||
<Grid item xs={12} sm={6} md={3}>
|
||||
<Card>
|
||||
<div className={classes.header}>
|
||||
<Typography variant="subtitle2">{type}</Typography>
|
||||
<Typography variant="h6">{title}</Typography>
|
||||
<Card>
|
||||
<div className={classes.header}>
|
||||
<Typography variant="subtitle2">{type}</Typography>
|
||||
<Typography variant="h6">{title}</Typography>
|
||||
</div>
|
||||
<div className={classes.content}>
|
||||
{tags?.map(tag => (
|
||||
<Chip label={tag} key={tag} />
|
||||
))}
|
||||
<Typography variant="body2" paragraph className={classes.description}>
|
||||
{description}
|
||||
</Typography>
|
||||
<div className={classes.footer}>
|
||||
<Button color="primary">Choose</Button>
|
||||
</div>
|
||||
<div className={classes.content}>
|
||||
{tags?.map(tag => (
|
||||
<Chip label={tag} />
|
||||
))}
|
||||
<Typography variant="body2" paragraph className={classes.description}>
|
||||
{description}
|
||||
</Typography>
|
||||
<div className={classes.footer}>
|
||||
<Button color="primary">Choose</Button>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
</Grid>
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
@@ -27,7 +27,6 @@
|
||||
"@material-ui/core": "^4.9.1",
|
||||
"@material-ui/icons": "^4.9.1",
|
||||
"@material-ui/lab": "4.0.0-alpha.45",
|
||||
"@types/react": "^16.9",
|
||||
"color": "^3.1.2",
|
||||
"d3-force": "^2.0.1",
|
||||
"prop-types": "^15.7.2",
|
||||
@@ -43,6 +42,7 @@
|
||||
"@testing-library/user-event": "^12.0.7",
|
||||
"@types/color": "^3.0.1",
|
||||
"@types/d3-force": "^1.2.1",
|
||||
"@types/react": "^16.9",
|
||||
"@types/jest": "^25.2.2",
|
||||
"@types/node": "^12.0.0",
|
||||
"jest-fetch-mock": "^3.0.3"
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
*/
|
||||
|
||||
import { createApiRef } from '@backstage/core';
|
||||
import { MovedState } from './utils/types';
|
||||
|
||||
/**
|
||||
* Types related to the Radar's visualization.
|
||||
@@ -34,7 +35,7 @@ export interface RadarQuadrant {
|
||||
export interface RadarEntry {
|
||||
key: string; // react key
|
||||
id: string;
|
||||
moved: number;
|
||||
moved: MovedState;
|
||||
quadrant: RadarQuadrant;
|
||||
ring: RadarRing;
|
||||
title: string;
|
||||
|
||||
@@ -20,9 +20,9 @@ import { ThemeProvider } from '@material-ui/core';
|
||||
import { lightTheme } from '@backstage/theme';
|
||||
import GetBBoxPolyfill from '../../utils/polyfills/getBBox';
|
||||
|
||||
import Radar from './Radar';
|
||||
import Radar, { Props } from './Radar';
|
||||
|
||||
const minProps = {
|
||||
const minProps: Props = {
|
||||
width: 500,
|
||||
height: 200,
|
||||
quadrants: [{ id: 'languages', name: 'Languages' }],
|
||||
|
||||
@@ -14,12 +14,12 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import React, { FC, useState, useRef } from 'react';
|
||||
import React, { useState, useRef } from 'react';
|
||||
import RadarPlot from '../RadarPlot';
|
||||
import { Ring, Quadrant, Entry } from '../../utils/types';
|
||||
import type { Ring, Quadrant, Entry } from '../../utils/types';
|
||||
import { adjustQuadrants, adjustRings, adjustEntries } from './utils';
|
||||
|
||||
type Props = {
|
||||
export type Props = {
|
||||
width: number;
|
||||
height: number;
|
||||
quadrants: Quadrant[];
|
||||
@@ -28,17 +28,17 @@ type Props = {
|
||||
svgProps?: object;
|
||||
};
|
||||
|
||||
const Radar: FC<Props> = props => {
|
||||
const Radar = (props: Props): JSX.Element => {
|
||||
const { width, height, quadrants, rings, entries } = props;
|
||||
const radius = Math.min(width, height) / 2;
|
||||
|
||||
const [activeEntry, setActiveEntry] = useState<Entry | null>();
|
||||
const [activeEntry, setActiveEntry] = useState<Entry>();
|
||||
const node = useRef<SVGSVGElement>(null);
|
||||
|
||||
// TODO(dflemstr): most of this can be heavily memoized if performance becomes a problem
|
||||
adjustQuadrants(quadrants, radius, width, height);
|
||||
adjustRings(rings, radius);
|
||||
adjustEntries(entries, activeEntry, quadrants, rings, radius);
|
||||
adjustEntries(entries, quadrants, rings, radius, activeEntry);
|
||||
|
||||
return (
|
||||
<svg ref={node} width={width} height={height} {...props.svgProps}>
|
||||
@@ -49,9 +49,9 @@ const Radar: FC<Props> = props => {
|
||||
entries={entries}
|
||||
quadrants={quadrants}
|
||||
rings={rings}
|
||||
activeEntry={activeEntry || undefined}
|
||||
activeEntry={activeEntry}
|
||||
onEntryMouseEnter={entry => setActiveEntry(entry)}
|
||||
onEntryMouseLeave={() => setActiveEntry(null)}
|
||||
onEntryMouseLeave={() => setActiveEntry(undefined)}
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
import color from 'color';
|
||||
import { forceCollide, forceSimulation } from 'd3-force';
|
||||
import Segment from '../../utils/segment';
|
||||
import { Ring, Quadrant, Entry } from '../../utils/types';
|
||||
import type { Ring, Quadrant, Entry } from '../../utils/types';
|
||||
|
||||
export const adjustQuadrants = (
|
||||
quadrants: Quadrant[],
|
||||
@@ -81,14 +81,14 @@ export const adjustQuadrants = (
|
||||
},
|
||||
];
|
||||
|
||||
quadrants.forEach((quadrant, idx) => {
|
||||
const legendParam = legendParams[idx % 4];
|
||||
quadrants.forEach((quadrant, index) => {
|
||||
const legendParam = legendParams[index % 4];
|
||||
|
||||
quadrant.idx = idx;
|
||||
quadrant.radialMin = (idx * Math.PI) / 2;
|
||||
quadrant.radialMax = ((idx + 1) * Math.PI) / 2;
|
||||
quadrant.offsetX = idx % 4 === 0 || idx % 4 === 3 ? 1 : -1;
|
||||
quadrant.offsetY = idx % 4 === 0 || idx % 4 === 1 ? 1 : -1;
|
||||
quadrant.index = index;
|
||||
quadrant.radialMin = (index * Math.PI) / 2;
|
||||
quadrant.radialMax = ((index + 1) * Math.PI) / 2;
|
||||
quadrant.offsetX = index % 4 === 0 || index % 4 === 3 ? 1 : -1;
|
||||
quadrant.offsetY = index % 4 === 0 || index % 4 === 1 ? 1 : -1;
|
||||
quadrant.legendX = legendParam.x;
|
||||
quadrant.legendY = legendParam.y;
|
||||
quadrant.legendWidth = legendParam.width;
|
||||
@@ -98,13 +98,13 @@ export const adjustQuadrants = (
|
||||
|
||||
export const adjustEntries = (
|
||||
entries: Entry[],
|
||||
activeEntry: Entry | null | undefined,
|
||||
quadrants: Quadrant[],
|
||||
rings: Ring[],
|
||||
radius: number,
|
||||
activeEntry?: Entry,
|
||||
) => {
|
||||
let seed = 42;
|
||||
entries.forEach((entry, idx) => {
|
||||
entries.forEach((entry, index) => {
|
||||
const quadrant = quadrants.find(q => {
|
||||
const match =
|
||||
typeof entry.quadrant === 'object' ? entry.quadrant.id : entry.quadrant;
|
||||
@@ -124,7 +124,7 @@ export const adjustEntries = (
|
||||
throw new Error(`Unknown ring ${entry.ring} for entry ${entry.id}!`);
|
||||
}
|
||||
|
||||
entry.idx = idx;
|
||||
entry.index = index;
|
||||
entry.quadrant = quadrant;
|
||||
entry.ring = ring;
|
||||
entry.segment = new Segment(quadrant, ring, radius, () => seed++);
|
||||
@@ -163,10 +163,10 @@ export const adjustEntries = (
|
||||
};
|
||||
|
||||
export const adjustRings = (rings: Ring[], radius: number) => {
|
||||
rings.forEach((ring, idx) => {
|
||||
ring.idx = idx;
|
||||
ring.outerRadius = ((idx + 2) / (rings.length + 1)) * radius;
|
||||
rings.forEach((ring, index) => {
|
||||
ring.index = index;
|
||||
ring.outerRadius = ((index + 2) / (rings.length + 1)) * radius;
|
||||
ring.innerRadius =
|
||||
((idx === 0 ? 0 : idx + 1) / (rings.length + 1)) * radius;
|
||||
((index === 0 ? 0 : index + 1) / (rings.length + 1)) * radius;
|
||||
});
|
||||
};
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
/*
|
||||
* 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 from 'react';
|
||||
import { render } from '@testing-library/react';
|
||||
import { ThemeProvider } from '@material-ui/core';
|
||||
import { lightTheme } from '@backstage/theme';
|
||||
import GetBBoxPolyfill from '../../utils/polyfills/getBBox';
|
||||
|
||||
import RadarBubble, { Props } from './RadarBubble';
|
||||
|
||||
const minProps: Props = {
|
||||
visible: true,
|
||||
text: 'RadarBubble',
|
||||
x: 2,
|
||||
y: 2,
|
||||
};
|
||||
|
||||
describe('RadarBubble', () => {
|
||||
beforeAll(() => {
|
||||
GetBBoxPolyfill.create(0, 0, 1000, 500);
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
GetBBoxPolyfill.remove();
|
||||
});
|
||||
|
||||
it('should render', () => {
|
||||
const rendered = render(
|
||||
<ThemeProvider theme={lightTheme}>
|
||||
<svg>
|
||||
<RadarBubble {...minProps} />
|
||||
</svg>
|
||||
</ThemeProvider>,
|
||||
);
|
||||
|
||||
expect(rendered.getByText(minProps.text)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -14,10 +14,10 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import React, { FC, useRef, useLayoutEffect } from 'react';
|
||||
import React, { useRef, useLayoutEffect } from 'react';
|
||||
import { makeStyles, Theme } from '@material-ui/core';
|
||||
|
||||
type Props = {
|
||||
export type Props = {
|
||||
visible: boolean;
|
||||
text: string;
|
||||
x: number;
|
||||
@@ -46,7 +46,7 @@ const useStyles = makeStyles<Theme>(() => ({
|
||||
},
|
||||
}));
|
||||
|
||||
const RadarBubble: FC<Props> = props => {
|
||||
const RadarBubble = (props: Props): JSX.Element => {
|
||||
const classes = useStyles(props);
|
||||
const { visible, text } = props;
|
||||
|
||||
@@ -98,6 +98,7 @@ const RadarBubble: FC<Props> = props => {
|
||||
x={0}
|
||||
y={0}
|
||||
className={visible ? classes.visibleBubble : classes.bubble}
|
||||
data-testid="radar-bubble"
|
||||
>
|
||||
<rect ref={rectElem} rx={4} ry={4} className={classes.background} />
|
||||
<text ref={textElem} className={classes.text}>
|
||||
|
||||
@@ -14,50 +14,38 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import React, { useEffect, useState, FC } from 'react';
|
||||
import React, { useEffect } from 'react';
|
||||
import { Progress, useApi, errorApiRef, ErrorApi } from '@backstage/core';
|
||||
import { useAsync } from 'react-use';
|
||||
import Radar from '../components/Radar';
|
||||
import { TechRadarComponentProps, TechRadarLoaderResponse } from '../api';
|
||||
import getSampleData from '../sampleData';
|
||||
|
||||
const useTechRadarLoader = (props: TechRadarComponentProps) => {
|
||||
const errorApi = useApi<ErrorApi>(errorApiRef);
|
||||
const [state, setState] = useState<{
|
||||
loading: boolean;
|
||||
error?: Error;
|
||||
data?: TechRadarLoaderResponse;
|
||||
}>({
|
||||
loading: true,
|
||||
error: undefined,
|
||||
data: undefined,
|
||||
});
|
||||
|
||||
const { getData } = props;
|
||||
|
||||
useEffect(() => {
|
||||
if (!getData) {
|
||||
return;
|
||||
const state = useAsync(async () => {
|
||||
if (getData) {
|
||||
const response: TechRadarLoaderResponse = await getData();
|
||||
return response;
|
||||
}
|
||||
|
||||
getData()
|
||||
.then((payload: TechRadarLoaderResponse) => {
|
||||
setState({ loading: false, error: undefined, data: payload });
|
||||
})
|
||||
.catch((err: Error) => {
|
||||
errorApi.post(err);
|
||||
setState({
|
||||
loading: false,
|
||||
error: err,
|
||||
data: undefined,
|
||||
});
|
||||
});
|
||||
return undefined;
|
||||
}, [getData, errorApi]);
|
||||
|
||||
useEffect(() => {
|
||||
const { error } = state;
|
||||
if (error) {
|
||||
errorApi.post(error);
|
||||
}
|
||||
}, [errorApi, state]);
|
||||
|
||||
return state;
|
||||
};
|
||||
|
||||
const RadarComponent: FC<TechRadarComponentProps> = props => {
|
||||
const { loading, error, data } = useTechRadarLoader(props);
|
||||
const RadarComponent = (props: TechRadarComponentProps): JSX.Element => {
|
||||
const { loading, error, value: data } = useTechRadarLoader(props);
|
||||
|
||||
return (
|
||||
<>
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
/*
|
||||
* 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 from 'react';
|
||||
import { render } from '@testing-library/react';
|
||||
import { ThemeProvider } from '@material-ui/core';
|
||||
import { lightTheme } from '@backstage/theme';
|
||||
import GetBBoxPolyfill from '../../utils/polyfills/getBBox';
|
||||
|
||||
import RadarEntry, { Props } from './RadarEntry';
|
||||
|
||||
const minProps: Props = {
|
||||
x: 2,
|
||||
y: 2,
|
||||
value: 2,
|
||||
color: 'red',
|
||||
};
|
||||
|
||||
describe('RadarEntry', () => {
|
||||
beforeAll(() => {
|
||||
GetBBoxPolyfill.create(0, 0, 1000, 500);
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
GetBBoxPolyfill.remove();
|
||||
});
|
||||
|
||||
it('should render', () => {
|
||||
const rendered = render(
|
||||
<ThemeProvider theme={lightTheme}>
|
||||
<svg>
|
||||
<RadarEntry {...minProps} />
|
||||
</svg>
|
||||
</ThemeProvider>,
|
||||
);
|
||||
|
||||
const radarEntry = rendered.getByTestId('radar-entry');
|
||||
const { x, y } = minProps;
|
||||
expect(radarEntry).toBeInTheDocument();
|
||||
expect(radarEntry.getAttribute('transform')).toBe(`translate(${x}, ${y})`);
|
||||
expect(rendered.getByText(String(minProps.value))).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -14,13 +14,14 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import React, { FC } from 'react';
|
||||
import React from 'react';
|
||||
import { makeStyles, Theme } from '@material-ui/core';
|
||||
import { WithLink } from '../../utils/components';
|
||||
|
||||
type Props = {
|
||||
export type Props = {
|
||||
x: number;
|
||||
y: number;
|
||||
number: number;
|
||||
value: number;
|
||||
color: string;
|
||||
url?: string;
|
||||
moved?: number;
|
||||
@@ -43,14 +44,27 @@ const useStyles = makeStyles<Theme>(() => ({
|
||||
},
|
||||
}));
|
||||
|
||||
const RadarEntry: FC<Props> = props => {
|
||||
const makeBlip = (color: string, moved?: number) => {
|
||||
const style = { fill: color };
|
||||
|
||||
let blip = <circle r={9} style={style} />;
|
||||
if (moved && moved > 0) {
|
||||
blip = <path d="M -11,5 11,5 0,-13 z" style={style} />; // triangle pointing up
|
||||
} else if (moved && moved < 0) {
|
||||
blip = <path d="M -11,-5 11,-5 0,13 z" style={style} />; // triangle pointing down
|
||||
}
|
||||
|
||||
return blip;
|
||||
};
|
||||
|
||||
const RadarEntry = (props: Props): JSX.Element => {
|
||||
const classes = useStyles(props);
|
||||
|
||||
const {
|
||||
moved,
|
||||
color,
|
||||
url,
|
||||
number,
|
||||
value,
|
||||
x,
|
||||
y,
|
||||
onMouseEnter,
|
||||
@@ -58,24 +72,7 @@ const RadarEntry: FC<Props> = props => {
|
||||
onClick,
|
||||
} = props;
|
||||
|
||||
const style = { fill: color };
|
||||
|
||||
let blip;
|
||||
if (moved && moved > 0) {
|
||||
blip = <path d="M -11,5 11,5 0,-13 z" style={style} />; // triangle pointing up
|
||||
} else if (moved && moved < 0) {
|
||||
blip = <path d="M -11,-5 11,-5 0,13 z" style={style} />; // triangle pointing down
|
||||
} else {
|
||||
blip = <circle r={9} style={style} />;
|
||||
}
|
||||
|
||||
if (url) {
|
||||
blip = (
|
||||
<a href={url} className={classes.link}>
|
||||
{blip}
|
||||
</a>
|
||||
);
|
||||
}
|
||||
const blip = makeBlip(color, moved);
|
||||
|
||||
return (
|
||||
<g
|
||||
@@ -83,10 +80,13 @@ const RadarEntry: FC<Props> = props => {
|
||||
onMouseEnter={onMouseEnter}
|
||||
onMouseLeave={onMouseLeave}
|
||||
onClick={onClick}
|
||||
data-testid="radar-entry"
|
||||
>
|
||||
{blip}
|
||||
<WithLink url={url} className={classes.link}>
|
||||
{blip}
|
||||
</WithLink>
|
||||
<text y={3} className={classes.text}>
|
||||
{number}
|
||||
{value}
|
||||
</text>
|
||||
</g>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
/*
|
||||
* 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 from 'react';
|
||||
import { render } from '@testing-library/react';
|
||||
import { ThemeProvider } from '@material-ui/core';
|
||||
import { lightTheme } from '@backstage/theme';
|
||||
import GetBBoxPolyfill from '../../utils/polyfills/getBBox';
|
||||
|
||||
import RadarFooter, { Props } from './RadarFooter';
|
||||
|
||||
const minProps: Props = {
|
||||
x: 2,
|
||||
y: 2,
|
||||
};
|
||||
|
||||
describe('RadarFooter', () => {
|
||||
beforeAll(() => {
|
||||
GetBBoxPolyfill.create(0, 0, 1000, 500);
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
GetBBoxPolyfill.remove();
|
||||
});
|
||||
|
||||
it('should render', () => {
|
||||
const rendered = render(
|
||||
<ThemeProvider theme={lightTheme}>
|
||||
<svg>
|
||||
<RadarFooter {...minProps} />
|
||||
</svg>
|
||||
</ThemeProvider>,
|
||||
);
|
||||
const radarFooter = rendered.getByTestId('radar-footer');
|
||||
const { x, y } = minProps;
|
||||
expect(radarFooter).toBeInTheDocument();
|
||||
expect(radarFooter.getAttribute('transform')).toBe(`translate(${x}, ${y})`);
|
||||
});
|
||||
});
|
||||
@@ -14,10 +14,10 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import React, { FC } from 'react';
|
||||
import React from 'react';
|
||||
import { makeStyles, Theme } from '@material-ui/core';
|
||||
|
||||
type Props = {
|
||||
export type Props = {
|
||||
x: number;
|
||||
y: number;
|
||||
};
|
||||
@@ -31,12 +31,16 @@ const useStyles = makeStyles<Theme>(() => ({
|
||||
},
|
||||
}));
|
||||
|
||||
const RadarFooter: FC<Props> = props => {
|
||||
const RadarFooter = (props: Props): JSX.Element => {
|
||||
const { x, y } = props;
|
||||
const classes = useStyles(props);
|
||||
|
||||
return (
|
||||
<text transform={`translate(${x}, ${y})`} className={classes.text}>
|
||||
<text
|
||||
data-testid="radar-footer"
|
||||
transform={`translate(${x}, ${y})`}
|
||||
className={classes.text}
|
||||
>
|
||||
{'▲ moved up\u00a0\u00a0\u00a0\u00a0\u00a0▼ moved down'}
|
||||
</text>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
/*
|
||||
* 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 from 'react';
|
||||
import { render } from '@testing-library/react';
|
||||
import { ThemeProvider } from '@material-ui/core';
|
||||
import { lightTheme } from '@backstage/theme';
|
||||
import GetBBoxPolyfill from '../../utils/polyfills/getBBox';
|
||||
|
||||
import RadarGrid, { Props } from './RadarGrid';
|
||||
|
||||
const minProps: Props = {
|
||||
radius: 5,
|
||||
rings: [{ id: 'use', name: 'USE', color: '#93c47d' }],
|
||||
};
|
||||
|
||||
describe('RadarGrid', () => {
|
||||
beforeAll(() => {
|
||||
GetBBoxPolyfill.create(0, 0, 1000, 500);
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
GetBBoxPolyfill.remove();
|
||||
});
|
||||
|
||||
it('should render', () => {
|
||||
const rendered = render(
|
||||
<ThemeProvider theme={lightTheme}>
|
||||
<svg>
|
||||
<RadarGrid {...minProps} />
|
||||
</svg>
|
||||
</ThemeProvider>,
|
||||
);
|
||||
|
||||
expect(rendered.getByTestId('radar-grid-x-line')).toBeInTheDocument();
|
||||
expect(rendered.getByTestId('radar-grid-y-line')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -16,9 +16,9 @@
|
||||
|
||||
import React from 'react';
|
||||
import { makeStyles, Theme } from '@material-ui/core';
|
||||
import { Ring } from '../../utils/types';
|
||||
import type { Ring } from '../../utils/types';
|
||||
|
||||
type Props = {
|
||||
export type Props = {
|
||||
radius: number;
|
||||
rings: Ring[];
|
||||
};
|
||||
@@ -49,7 +49,7 @@ const RadarGrid = (props: Props) => {
|
||||
const { radius, rings } = props;
|
||||
const classes = useStyles(props);
|
||||
|
||||
const makeRingNode = (ringRadius: number | undefined, ringIndex: number) => [
|
||||
const makeRingNode = (ringIndex: number, ringRadius?: number) => [
|
||||
<circle
|
||||
key={`c${ringIndex}`}
|
||||
cx={0}
|
||||
@@ -76,6 +76,7 @@ const RadarGrid = (props: Props) => {
|
||||
x2={0}
|
||||
y2={radius}
|
||||
className={classes.axis}
|
||||
data-testid="radar-grid-x-line"
|
||||
/>,
|
||||
// Y axis
|
||||
<line
|
||||
@@ -85,10 +86,13 @@ const RadarGrid = (props: Props) => {
|
||||
x2={radius}
|
||||
y2={0}
|
||||
className={classes.axis}
|
||||
data-testid="radar-grid-y-line"
|
||||
/>,
|
||||
];
|
||||
|
||||
const ringNodes = rings.map(r => r.outerRadius).map(makeRingNode);
|
||||
const ringNodes = rings
|
||||
.map(r => r.outerRadius)
|
||||
.map((ringRadius, ringIndex) => makeRingNode(ringIndex, ringRadius));
|
||||
|
||||
return <>{axisNodes.concat(...ringNodes)}</>;
|
||||
};
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
/*
|
||||
* 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 from 'react';
|
||||
import { render } from '@testing-library/react';
|
||||
import { ThemeProvider } from '@material-ui/core';
|
||||
import { lightTheme } from '@backstage/theme';
|
||||
import GetBBoxPolyfill from '../../utils/polyfills/getBBox';
|
||||
|
||||
import RadarLegend, { Props } from './RadarLegend';
|
||||
|
||||
const minProps: Props = {
|
||||
quadrants: [{ id: 'languages', name: 'Languages' }],
|
||||
rings: [{ id: 'use', name: 'USE', color: '#93c47d' }],
|
||||
entries: [
|
||||
{
|
||||
id: 'typescript',
|
||||
title: 'TypeScript',
|
||||
quadrant: { id: 'languages', name: 'Languages' },
|
||||
moved: 0,
|
||||
ring: { id: 'use', name: 'USE', color: '#93c47d' },
|
||||
url: '#',
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
describe('RadarLegend', () => {
|
||||
beforeAll(() => {
|
||||
GetBBoxPolyfill.create(0, 0, 1000, 500);
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
GetBBoxPolyfill.remove();
|
||||
});
|
||||
|
||||
it('should render', () => {
|
||||
const rendered = render(
|
||||
<ThemeProvider theme={lightTheme}>
|
||||
<svg>
|
||||
<RadarLegend {...minProps} />
|
||||
</svg>
|
||||
</ThemeProvider>,
|
||||
);
|
||||
|
||||
expect(rendered.getByTestId('radar-legend')).toBeInTheDocument();
|
||||
expect(rendered.getAllByTestId('radar-quadrant')).toHaveLength(1);
|
||||
expect(rendered.getAllByTestId('radar-ring')).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
@@ -13,15 +13,16 @@
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
import React, { FC } from 'react';
|
||||
import React from 'react';
|
||||
import { makeStyles, Theme } from '@material-ui/core';
|
||||
import { Quadrant, Ring, Entry } from '../../utils/types';
|
||||
import type { Quadrant, Ring, Entry } from '../../utils/types';
|
||||
import { WithLink } from '../../utils/components';
|
||||
|
||||
type Segments = {
|
||||
[k: number]: { [k: number]: Entry[] };
|
||||
};
|
||||
|
||||
type Props = {
|
||||
export type Props = {
|
||||
quadrants: Quadrant[];
|
||||
rings: Ring[];
|
||||
entries: Entry[];
|
||||
@@ -29,7 +30,7 @@ type Props = {
|
||||
onEntryMouseLeave?: (entry: Entry) => void;
|
||||
};
|
||||
|
||||
const useStyles = makeStyles<Theme>(() => ({
|
||||
const useStyles = makeStyles<Theme>(theme => ({
|
||||
quadrant: {
|
||||
height: '100%',
|
||||
width: '100%',
|
||||
@@ -40,7 +41,7 @@ const useStyles = makeStyles<Theme>(() => ({
|
||||
pointerEvents: 'none',
|
||||
userSelect: 'none',
|
||||
marginTop: 0,
|
||||
marginBottom: 'calc(18px * 0.375)',
|
||||
marginBottom: theme.spacing(8 / (18 * 0.375)),
|
||||
fontSize: '18px',
|
||||
},
|
||||
rings: {
|
||||
@@ -56,7 +57,7 @@ const useStyles = makeStyles<Theme>(() => ({
|
||||
pointerEvents: 'none',
|
||||
userSelect: 'none',
|
||||
marginTop: 0,
|
||||
marginBottom: 'calc(12px * 0.375)',
|
||||
marginBottom: theme.spacing(8 / (12 * 0.375)),
|
||||
fontSize: '12px',
|
||||
fontWeight: 800,
|
||||
},
|
||||
@@ -79,73 +80,81 @@ const useStyles = makeStyles<Theme>(() => ({
|
||||
},
|
||||
}));
|
||||
|
||||
const RadarLegend: FC<Props> = props => {
|
||||
const RadarLegend = (props: Props): JSX.Element => {
|
||||
const classes = useStyles(props);
|
||||
|
||||
const _getSegment = (
|
||||
const getSegment = (
|
||||
segmented: Segments,
|
||||
quadrant: Quadrant,
|
||||
ring: Ring,
|
||||
ringOffset = 0,
|
||||
) => {
|
||||
const qidx = quadrant.idx;
|
||||
const ridx = ring.idx;
|
||||
const segmentedData = qidx === undefined ? {} : segmented[qidx] || {};
|
||||
return ridx === undefined ? [] : segmentedData[ridx + ringOffset] || [];
|
||||
const quadrantIndex = quadrant.index;
|
||||
const ringIndex = ring.index;
|
||||
const segmentedData =
|
||||
quadrantIndex === undefined ? {} : segmented[quadrantIndex] || {};
|
||||
return ringIndex === undefined
|
||||
? []
|
||||
: segmentedData[ringIndex + ringOffset] || [];
|
||||
};
|
||||
|
||||
const _renderRing = (
|
||||
ring: Ring,
|
||||
entries: Entry[],
|
||||
onEntryMouseEnter?: Props['onEntryMouseEnter'],
|
||||
onEntryMouseLeave?: Props['onEntryMouseEnter'],
|
||||
) => {
|
||||
type RadarLegendRingProps = {
|
||||
ring: Ring;
|
||||
entries: Entry[];
|
||||
onEntryMouseEnter?: Props['onEntryMouseEnter'];
|
||||
onEntryMouseLeave?: Props['onEntryMouseEnter'];
|
||||
};
|
||||
|
||||
const RadarLegendRing = ({
|
||||
ring,
|
||||
entries,
|
||||
onEntryMouseEnter,
|
||||
onEntryMouseLeave,
|
||||
}: RadarLegendRingProps) => {
|
||||
return (
|
||||
<div key={ring.id} className={classes.ring}>
|
||||
<div data-testid="radar-ring" key={ring.id} className={classes.ring}>
|
||||
<h3 className={classes.ringHeading}>{ring.name}</h3>
|
||||
{entries.length === 0 ? (
|
||||
<p>(empty)</p>
|
||||
) : (
|
||||
<ol className={classes.ringList}>
|
||||
{entries.map(entry => {
|
||||
let node = <span className={classes.entry}>{entry.title}</span>;
|
||||
|
||||
if (entry.url) {
|
||||
node = (
|
||||
<a className={classes.entryLink} href={entry.url}>
|
||||
{node}
|
||||
</a>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<li
|
||||
key={entry.id}
|
||||
value={(entry.idx || 0) + 1}
|
||||
onMouseEnter={
|
||||
onEntryMouseEnter && (() => onEntryMouseEnter(entry))
|
||||
}
|
||||
onMouseLeave={
|
||||
onEntryMouseLeave && (() => onEntryMouseLeave(entry))
|
||||
}
|
||||
>
|
||||
{node}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
{entries.map(entry => (
|
||||
<li
|
||||
key={entry.id}
|
||||
value={(entry.index || 0) + 1}
|
||||
onMouseEnter={
|
||||
onEntryMouseEnter && (() => onEntryMouseEnter(entry))
|
||||
}
|
||||
onMouseLeave={
|
||||
onEntryMouseLeave && (() => onEntryMouseLeave(entry))
|
||||
}
|
||||
>
|
||||
<WithLink url={entry.url} className={classes.entryLink}>
|
||||
<span className={classes.entry}>{entry.title}</span>
|
||||
</WithLink>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const _renderQuadrant = (
|
||||
segments: Segments,
|
||||
quadrant: Quadrant,
|
||||
rings: Ring[],
|
||||
onEntryMouseEnter: Props['onEntryMouseEnter'],
|
||||
onEntryMouseLeave: Props['onEntryMouseLeave'],
|
||||
) => {
|
||||
type RadarLegendQuadrantProps = {
|
||||
segments: Segments;
|
||||
quadrant: Quadrant;
|
||||
rings: Ring[];
|
||||
onEntryMouseEnter: Props['onEntryMouseEnter'];
|
||||
onEntryMouseLeave: Props['onEntryMouseLeave'];
|
||||
};
|
||||
|
||||
const RadarLegendQuadrant = ({
|
||||
segments,
|
||||
quadrant,
|
||||
rings,
|
||||
onEntryMouseEnter,
|
||||
onEntryMouseLeave,
|
||||
}: RadarLegendQuadrantProps) => {
|
||||
return (
|
||||
<foreignObject
|
||||
key={quadrant.id}
|
||||
@@ -153,46 +162,48 @@ const RadarLegend: FC<Props> = props => {
|
||||
y={quadrant.legendY}
|
||||
width={quadrant.legendWidth}
|
||||
height={quadrant.legendHeight}
|
||||
data-testid="radar-quadrant"
|
||||
>
|
||||
<div className={classes.quadrant}>
|
||||
<h2 className={classes.quadrantHeading}>{quadrant.name}</h2>
|
||||
<div className={classes.rings}>
|
||||
{rings.map(ring =>
|
||||
_renderRing(
|
||||
ring,
|
||||
_getSegment(segments, quadrant, ring),
|
||||
onEntryMouseEnter,
|
||||
onEntryMouseLeave,
|
||||
),
|
||||
)}
|
||||
{rings.map(ring => (
|
||||
<RadarLegendRing
|
||||
key={ring.id}
|
||||
ring={ring}
|
||||
entries={getSegment(segments, quadrant, ring)}
|
||||
onEntryMouseEnter={onEntryMouseEnter}
|
||||
onEntryMouseLeave={onEntryMouseLeave}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</foreignObject>
|
||||
);
|
||||
};
|
||||
|
||||
const _setupSegments = (entries: Entry[]) => {
|
||||
const setupSegments = (entries: Entry[]) => {
|
||||
const segments: Segments = {};
|
||||
|
||||
for (const entry of entries) {
|
||||
const qidx = entry.quadrant.idx;
|
||||
const ridx = entry.ring.idx;
|
||||
const quadrantIndex = entry.quadrant.index;
|
||||
const ringIndex = entry.ring.index;
|
||||
let quadrantData: { [k: number]: Entry[] } = {};
|
||||
if (qidx !== undefined) {
|
||||
if (segments[qidx] === undefined) {
|
||||
segments[qidx] = {};
|
||||
if (quadrantIndex !== undefined) {
|
||||
if (segments[quadrantIndex] === undefined) {
|
||||
segments[quadrantIndex] = {};
|
||||
}
|
||||
|
||||
quadrantData = segments[qidx];
|
||||
quadrantData = segments[quadrantIndex];
|
||||
}
|
||||
|
||||
let ringData = [];
|
||||
if (ridx !== undefined) {
|
||||
if (quadrantData[ridx] === undefined) {
|
||||
quadrantData[ridx] = [];
|
||||
if (ringIndex !== undefined) {
|
||||
if (quadrantData[ringIndex] === undefined) {
|
||||
quadrantData[ringIndex] = [];
|
||||
}
|
||||
|
||||
ringData = quadrantData[ridx];
|
||||
ringData = quadrantData[ringIndex];
|
||||
}
|
||||
|
||||
ringData.push(entry);
|
||||
@@ -209,19 +220,20 @@ const RadarLegend: FC<Props> = props => {
|
||||
onEntryMouseLeave,
|
||||
} = props;
|
||||
|
||||
const segments: Segments = _setupSegments(entries);
|
||||
const segments: Segments = setupSegments(entries);
|
||||
|
||||
return (
|
||||
<g>
|
||||
{quadrants.map(quadrant =>
|
||||
_renderQuadrant(
|
||||
segments,
|
||||
quadrant,
|
||||
rings,
|
||||
onEntryMouseEnter,
|
||||
onEntryMouseLeave,
|
||||
),
|
||||
)}
|
||||
<g data-testid="radar-legend">
|
||||
{quadrants.map(quadrant => (
|
||||
<RadarLegendQuadrant
|
||||
key={quadrant.id}
|
||||
segments={segments}
|
||||
quadrant={quadrant}
|
||||
rings={rings}
|
||||
onEntryMouseEnter={onEntryMouseEnter}
|
||||
onEntryMouseLeave={onEntryMouseLeave}
|
||||
/>
|
||||
))}
|
||||
</g>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import React, { FC } from 'react';
|
||||
import React from 'react';
|
||||
import { Grid } from '@material-ui/core';
|
||||
import {
|
||||
Content,
|
||||
@@ -29,7 +29,7 @@ import {
|
||||
import RadarComponent from '../components/RadarComponent';
|
||||
import { techRadarApiRef, TechRadarApi } from '../api';
|
||||
|
||||
const RadarPage: FC<{}> = () => {
|
||||
const RadarPage = (): JSX.Element => {
|
||||
const techRadarApi = useApi<TechRadarApi>(techRadarApiRef);
|
||||
|
||||
return (
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
/*
|
||||
* 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 from 'react';
|
||||
import { render } from '@testing-library/react';
|
||||
import { ThemeProvider } from '@material-ui/core';
|
||||
import { lightTheme } from '@backstage/theme';
|
||||
import GetBBoxPolyfill from '../../utils/polyfills/getBBox';
|
||||
|
||||
import RadarPlot, { Props } from './RadarPlot';
|
||||
|
||||
const minProps: Props = {
|
||||
width: 500,
|
||||
height: 200,
|
||||
radius: 50,
|
||||
quadrants: [{ id: 'languages', name: 'Languages' }],
|
||||
rings: [{ id: 'use', name: 'USE', color: '#93c47d' }],
|
||||
entries: [
|
||||
{
|
||||
id: 'typescript',
|
||||
title: 'TypeScript',
|
||||
quadrant: { id: 'languages', name: 'Languages' },
|
||||
moved: 0,
|
||||
ring: { id: 'use', name: 'USE', color: '#93c47d' },
|
||||
url: '#',
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
describe('RadarPlot', () => {
|
||||
beforeAll(() => {
|
||||
GetBBoxPolyfill.create(0, 0, 1000, 500);
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
GetBBoxPolyfill.remove();
|
||||
});
|
||||
|
||||
it('should render', () => {
|
||||
const rendered = render(
|
||||
<ThemeProvider theme={lightTheme}>
|
||||
<svg>
|
||||
<RadarPlot {...minProps} />
|
||||
</svg>
|
||||
</ThemeProvider>,
|
||||
);
|
||||
|
||||
expect(rendered.getByTestId('radar-plot')).toBeInTheDocument();
|
||||
expect(rendered.getByTestId('radar-legend')).toBeInTheDocument();
|
||||
expect(rendered.getByTestId('radar-footer')).toBeInTheDocument();
|
||||
expect(rendered.getByTestId('radar-bubble')).toBeInTheDocument();
|
||||
expect(rendered.getAllByTestId('radar-entry')).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
@@ -14,8 +14,8 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import React, { FC } from 'react';
|
||||
import { Quadrant, Ring, Entry } from '../../utils/types';
|
||||
import React from 'react';
|
||||
import type { Quadrant, Ring, Entry } from '../../utils/types';
|
||||
|
||||
import RadarGrid from '../RadarGrid';
|
||||
import RadarEntry from '../RadarEntry';
|
||||
@@ -23,7 +23,7 @@ import RadarBubble from '../RadarBubble';
|
||||
import RadarFooter from '../RadarFooter';
|
||||
import RadarLegend from '../RadarLegend';
|
||||
|
||||
type Props = {
|
||||
export type Props = {
|
||||
width: number;
|
||||
height: number;
|
||||
radius: number;
|
||||
@@ -36,7 +36,7 @@ type Props = {
|
||||
};
|
||||
|
||||
// A component that draws the radar circle.
|
||||
const RadarPlot: FC<Props> = props => {
|
||||
const RadarPlot = (props: Props): JSX.Element => {
|
||||
const {
|
||||
width,
|
||||
height,
|
||||
@@ -50,7 +50,7 @@ const RadarPlot: FC<Props> = props => {
|
||||
} = props;
|
||||
|
||||
return (
|
||||
<g>
|
||||
<g data-testid="radar-plot">
|
||||
<RadarLegend
|
||||
quadrants={quadrants}
|
||||
rings={rings}
|
||||
@@ -71,7 +71,7 @@ const RadarPlot: FC<Props> = props => {
|
||||
x={entry.x || 0}
|
||||
y={entry.y || 0}
|
||||
color={entry.color || ''}
|
||||
number={((entry && entry.idx) || 0) + 1}
|
||||
value={(entry?.index || 0) + 1}
|
||||
url={entry.url}
|
||||
moved={entry.moved}
|
||||
onMouseEnter={onEntryMouseEnter && (() => onEntryMouseEnter(entry))}
|
||||
@@ -80,9 +80,9 @@ const RadarPlot: FC<Props> = props => {
|
||||
))}
|
||||
<RadarBubble
|
||||
visible={!!activeEntry}
|
||||
text={activeEntry ? activeEntry.title : ''}
|
||||
x={activeEntry ? activeEntry.x || 0 : 0}
|
||||
y={activeEntry ? activeEntry.y || 0 : 0}
|
||||
text={activeEntry?.title || ''}
|
||||
x={activeEntry?.x || 0}
|
||||
y={activeEntry?.y || 0}
|
||||
/>
|
||||
</g>
|
||||
</g>
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
/*
|
||||
* 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 from 'react';
|
||||
|
||||
type WithLinkProps = {
|
||||
url?: string;
|
||||
className: string;
|
||||
children: React.ReactNode;
|
||||
};
|
||||
|
||||
export const WithLink = ({
|
||||
url,
|
||||
className,
|
||||
children,
|
||||
}: WithLinkProps): JSX.Element =>
|
||||
url ? (
|
||||
<a href={url} className={className}>
|
||||
{children}
|
||||
</a>
|
||||
) : (
|
||||
<>{children}</>
|
||||
);
|
||||
@@ -17,7 +17,7 @@
|
||||
// Parameters for a ring; its index in an array determines how close to the center this ring is.
|
||||
export type Ring = {
|
||||
id: string;
|
||||
idx?: number;
|
||||
index?: number;
|
||||
name: string;
|
||||
color: string;
|
||||
outerRadius?: number;
|
||||
@@ -27,7 +27,7 @@ export type Ring = {
|
||||
// Parameters for a quadrant (there should be exactly 4 of course)
|
||||
export type Quadrant = {
|
||||
id: string;
|
||||
idx?: number;
|
||||
index?: number;
|
||||
name: string;
|
||||
legendX?: number;
|
||||
legendY?: number;
|
||||
@@ -45,9 +45,15 @@ export type Segment = {
|
||||
random: Function;
|
||||
};
|
||||
|
||||
export enum MovedState {
|
||||
Down = -1,
|
||||
NoChange = 0,
|
||||
Up = 1,
|
||||
}
|
||||
|
||||
export type Entry = {
|
||||
id: string;
|
||||
idx?: number;
|
||||
index?: number;
|
||||
x?: number;
|
||||
y?: number;
|
||||
color?: string;
|
||||
@@ -61,7 +67,7 @@ export type Entry = {
|
||||
// An URL to a longer description as to why this entry is where it is
|
||||
url?: string;
|
||||
// How this entry has recently moved; -1 for "down", +1 for "up", 0 for not moved
|
||||
moved?: number;
|
||||
moved?: MovedState;
|
||||
active?: boolean;
|
||||
};
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ Welcome to the TechDocs plugin - Spotify's docs-like-code approach built directl
|
||||
|
||||
## Getting started
|
||||
|
||||
Your plugin has been added to the example app in this repository, meaning you'll be able to access it by running `yarn start` in the root directory, and then navigating to [/techdocs](http://localhost:3000/techdocs).
|
||||
Your plugin has been added to the example app in this repository, meaning you'll be able to access it by running `yarn start` in the root directory, and then navigating to [/docs](http://localhost:3000/docs).
|
||||
|
||||
You can also serve the plugin in isolation by running `yarn start` in the plugin directory.
|
||||
This method of serving the plugin provides quicker iteration speed and a faster startup and hot reloads.
|
||||
|
||||
@@ -29,6 +29,8 @@
|
||||
"@material-ui/lab": "4.0.0-alpha.45",
|
||||
"react": "^16.13.1",
|
||||
"react-dom": "^16.13.1",
|
||||
"react-router": "^6.0.0-alpha.5",
|
||||
"react-router-dom": "^6.0.0-alpha.5",
|
||||
"react-use": "^14.2.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
/*
|
||||
* 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.
|
||||
*/
|
||||
export const docStorageURL =
|
||||
'https://techdocs-mock-sites.storage.googleapis.com';
|
||||
@@ -34,6 +34,11 @@ import { Reader } from './reader/components/Reader';
|
||||
|
||||
export const rootRouteRef = createRouteRef({
|
||||
path: '/docs',
|
||||
title: 'TechDocs Landing Page',
|
||||
});
|
||||
|
||||
export const rootDocsRouteRef = createRouteRef({
|
||||
path: '/docs/:componentId/*',
|
||||
title: 'Docs',
|
||||
});
|
||||
|
||||
@@ -41,5 +46,6 @@ export const plugin = createPlugin({
|
||||
id: 'techdocs',
|
||||
register({ router }) {
|
||||
router.addRoute(rootRouteRef, Reader);
|
||||
router.addRoute(rootDocsRouteRef, Reader);
|
||||
},
|
||||
});
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
/*
|
||||
* 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, { FC } from 'react';
|
||||
import { Button, Card, Chip, Typography, makeStyles } from '@material-ui/core';
|
||||
|
||||
const useStyles = makeStyles(theme => ({
|
||||
header: {
|
||||
color: theme.palette.common.white,
|
||||
padding: theme.spacing(2, 2, 6),
|
||||
backgroundImage:
|
||||
'linear-gradient(-137deg, rgb(25, 230, 140) 0%, rgb(29, 127, 110) 100%)',
|
||||
},
|
||||
content: {
|
||||
padding: theme.spacing(2),
|
||||
},
|
||||
description: {
|
||||
height: 175,
|
||||
overflow: 'hidden',
|
||||
textOverflow: 'ellipsis',
|
||||
},
|
||||
footer: {
|
||||
display: 'flex',
|
||||
flexDirection: 'row-reverse',
|
||||
},
|
||||
}));
|
||||
|
||||
type DocsCardProps = {
|
||||
description: string;
|
||||
tags?: string[];
|
||||
title: string;
|
||||
type?: string;
|
||||
label: string;
|
||||
onClick?: () => void;
|
||||
};
|
||||
export const DocsCard: FC<DocsCardProps> = ({
|
||||
description,
|
||||
tags,
|
||||
title,
|
||||
type,
|
||||
label,
|
||||
onClick,
|
||||
}) => {
|
||||
const classes = useStyles();
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<div className={classes.header}>
|
||||
{type ?? <Typography variant="subtitle2">{type}</Typography>}
|
||||
<Typography variant="h6">{title}</Typography>
|
||||
</div>
|
||||
<div className={classes.content}>
|
||||
{tags?.map(tag => (
|
||||
<Chip label={tag} key={tag} />
|
||||
))}
|
||||
<Typography variant="body2" paragraph className={classes.description}>
|
||||
{description}
|
||||
</Typography>
|
||||
<div className={classes.footer}>
|
||||
<Button onClick={onClick} color="primary">
|
||||
{label}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
};
|
||||
@@ -16,801 +16,116 @@
|
||||
|
||||
import React from 'react';
|
||||
import { useShadowDom } from '..';
|
||||
|
||||
const mockHtml: string = `
|
||||
|
||||
|
||||
|
||||
|
||||
<!doctype html>
|
||||
<html lang="en" class="no-js">
|
||||
<head>
|
||||
<base href="https://mkdocs.peaceiris.com/getting-started/download-boilerplate/" />
|
||||
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
|
||||
<meta name="description" content="MkDocs Material Boilerplate (Starter Kit) - Deploy documentation to hosting platforms (Netlify, GitHub Pages, GitLab Pages, and AWS Amplify Console) with GitHub Actions, CircleCI, Docker, pipenv, and CI/CD">
|
||||
|
||||
|
||||
<link rel="canonical" href="https://mkdocs.peaceiris.com/getting-started/download-boilerplate/">
|
||||
|
||||
|
||||
<meta name="author" content="peaceiris">
|
||||
|
||||
<link rel="shortcut icon" href="../../assets/images/favicon.png">
|
||||
<meta name="generator" content="mkdocs-1.1.2, mkdocs-material-5.3.2">
|
||||
|
||||
|
||||
|
||||
<title>Download boilerplate - MkDocs Material Boilerplate</title>
|
||||
|
||||
|
||||
|
||||
<link rel="stylesheet" href="https://mkdocs.peaceiris.com/assets/stylesheets/main.fe0cca5b.min.css">
|
||||
|
||||
<link rel="stylesheet" href="https://mkdocs.peaceiris.com/assets/stylesheets/palette.a46bcfb3.min.css">
|
||||
|
||||
|
||||
|
||||
|
||||
<meta name="theme-color" content="#2196f3">
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<link href="https://fonts.gstatic.com" rel="preconnect" crossorigin>
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,400i,700%7CRoboto+Mono&display=fallback">
|
||||
<style>body,input{font-family:"Roboto",-apple-system,BlinkMacSystemFont,Helvetica,Arial,sans-serif}code,kbd,pre{font-family:"Roboto Mono",SFMono-Regular,Consolas,Menlo,monospace}</style>
|
||||
|
||||
|
||||
|
||||
<link rel="manifest" href="../../manifest.json" crossorigin="use-credentials">
|
||||
|
||||
|
||||
<link rel="stylesheet" href="../../assets/css/custom.css">
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
</head>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<body dir="ltr" data-md-color-scheme="" data-md-color-primary="blue" data-md-color-accent="blue">
|
||||
|
||||
|
||||
<input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer" autocomplete="off">
|
||||
<input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search" autocomplete="off">
|
||||
<label class="md-overlay" for="__drawer"></label>
|
||||
<div data-md-component="skip">
|
||||
|
||||
|
||||
<a href="#download_boilerplate" class="md-skip">
|
||||
Skip to content
|
||||
</a>
|
||||
|
||||
</div>
|
||||
<div data-md-component="announce">
|
||||
|
||||
</div>
|
||||
|
||||
<header class="md-header" data-md-component="header">
|
||||
<nav class="md-header-nav md-grid" aria-label="Header">
|
||||
<a href="https://mkdocs.peaceiris.com/" title="MkDocs Material Boilerplate" class="md-header-nav__button md-logo" aria-label="MkDocs Material Boilerplate">
|
||||
|
||||
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M12 8a3 3 0 003-3 3 3 0 00-3-3 3 3 0 00-3 3 3 3 0 003 3m0 3.54C9.64 9.35 6.5 8 3 8v11c3.5 0 6.64 1.35 9 3.54 2.36-2.19 5.5-3.54 9-3.54V8c-3.5 0-6.64 1.35-9 3.54z"/></svg>
|
||||
|
||||
</a>
|
||||
<label class="md-header-nav__button md-icon" for="__drawer">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M3 6h18v2H3V6m0 5h18v2H3v-2m0 5h18v2H3v-2z"/></svg>
|
||||
</label>
|
||||
<div class="md-header-nav__title" data-md-component="header-title">
|
||||
|
||||
<div class="md-header-nav__ellipsis">
|
||||
<span class="md-header-nav__topic md-ellipsis">
|
||||
MkDocs Material Boilerplate
|
||||
</span>
|
||||
<span class="md-header-nav__topic md-ellipsis">
|
||||
|
||||
Download boilerplate
|
||||
|
||||
</span>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<label class="md-header-nav__button md-icon" for="__search">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M9.5 3A6.5 6.5 0 0116 9.5c0 1.61-.59 3.09-1.56 4.23l.27.27h.79l5 5-1.5 1.5-5-5v-.79l-.27-.27A6.516 6.516 0 019.5 16 6.5 6.5 0 013 9.5 6.5 6.5 0 019.5 3m0 2C7 5 5 7 5 9.5S7 14 9.5 14 14 12 14 9.5 12 5 9.5 5z"/></svg>
|
||||
</label>
|
||||
|
||||
<div class="md-search" data-md-component="search" role="dialog">
|
||||
<label class="md-search__overlay" for="__search"></label>
|
||||
<div class="md-search__inner" role="search">
|
||||
<form class="md-search__form" name="search">
|
||||
<input type="text" class="md-search__input" name="query" aria-label="Search" placeholder="Search" autocapitalize="off" autocorrect="off" autocomplete="off" spellcheck="false" data-md-component="search-query" data-md-state="active">
|
||||
<label class="md-search__icon md-icon" for="__search">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M9.5 3A6.5 6.5 0 0116 9.5c0 1.61-.59 3.09-1.56 4.23l.27.27h.79l5 5-1.5 1.5-5-5v-.79l-.27-.27A6.516 6.516 0 019.5 16 6.5 6.5 0 013 9.5 6.5 6.5 0 019.5 3m0 2C7 5 5 7 5 9.5S7 14 9.5 14 14 12 14 9.5 12 5 9.5 5z"/></svg>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M20 11v2H8l5.5 5.5-1.42 1.42L4.16 12l7.92-7.92L13.5 5.5 8 11h12z"/></svg>
|
||||
</label>
|
||||
<button type="reset" class="md-search__icon md-icon" aria-label="Clear" data-md-component="search-reset" tabindex="-1">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12 19 6.41z"/></svg>
|
||||
</button>
|
||||
</form>
|
||||
<div class="md-search__output">
|
||||
<div class="md-search__scrollwrap" data-md-scrollfix>
|
||||
<div class="md-search-result" data-md-component="search-result">
|
||||
<div class="md-search-result__meta">
|
||||
Initializing search
|
||||
</div>
|
||||
<ol class="md-search-result__list"></ol>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<div class="md-header-nav__source">
|
||||
|
||||
<a href="https://github.com/peaceiris/mkdocs-material-boilerplate/" title="Go to repository" class="md-source">
|
||||
<div class="md-source__icon md-icon">
|
||||
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><path d="M439.55 236.05L244 40.45a28.87 28.87 0 00-40.81 0l-40.66 40.63 51.52 51.52c27.06-9.14 52.68 16.77 43.39 43.68l49.66 49.66c34.23-11.8 61.18 31 35.47 56.69-26.49 26.49-70.21-2.87-56-37.34L240.22 199v121.85c25.3 12.54 22.26 41.85 9.08 55a34.34 34.34 0 01-48.55 0c-17.57-17.6-11.07-46.91 11.25-56v-123c-20.8-8.51-24.6-30.74-18.64-45L142.57 101 8.45 235.14a28.86 28.86 0 000 40.81l195.61 195.6a28.86 28.86 0 0040.8 0l194.69-194.69a28.86 28.86 0 000-40.81z"/></svg>
|
||||
</div>
|
||||
<div class="md-source__repository">
|
||||
GitHub
|
||||
</div>
|
||||
</a>
|
||||
</div>
|
||||
|
||||
</nav>
|
||||
</header>
|
||||
|
||||
<div class="md-container" data-md-component="container">
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<nav class="md-tabs md-tabs--active" aria-label="Tabs" data-md-component="tabs">
|
||||
<div class="md-tabs__inner md-grid">
|
||||
<ul class="md-tabs__list">
|
||||
|
||||
|
||||
<li class="md-tabs__item">
|
||||
|
||||
<a href="../.." class="md-tabs__link">
|
||||
Home
|
||||
</a>
|
||||
|
||||
</li>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<li class="md-tabs__item">
|
||||
|
||||
<a href="./" class="md-tabs__link md-tabs__link--active">
|
||||
Getting started
|
||||
</a>
|
||||
|
||||
</li>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<li class="md-tabs__item">
|
||||
|
||||
<a href="../../hosting-and-deployment/combinations/" class="md-tabs__link">
|
||||
Hosting and Deployment
|
||||
</a>
|
||||
|
||||
</li>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<li class="md-tabs__item">
|
||||
|
||||
<a href="../../extensions/mathjax/" class="md-tabs__link">
|
||||
Extensions
|
||||
</a>
|
||||
|
||||
</li>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
</ul>
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
|
||||
<main class="md-main" data-md-component="main">
|
||||
<div class="md-main__inner md-grid">
|
||||
|
||||
|
||||
<div class="md-sidebar md-sidebar--primary" data-md-component="navigation">
|
||||
<div class="md-sidebar__scrollwrap">
|
||||
<div class="md-sidebar__inner">
|
||||
<nav class="md-nav md-nav--primary" aria-label="Navigation" data-md-level="0">
|
||||
<label class="md-nav__title" for="__drawer">
|
||||
<a href="https://mkdocs.peaceiris.com/" title="MkDocs Material Boilerplate" class="md-nav__button md-logo" aria-label="MkDocs Material Boilerplate">
|
||||
|
||||
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M12 8a3 3 0 003-3 3 3 0 00-3-3 3 3 0 00-3 3 3 3 0 003 3m0 3.54C9.64 9.35 6.5 8 3 8v11c3.5 0 6.64 1.35 9 3.54 2.36-2.19 5.5-3.54 9-3.54V8c-3.5 0-6.64 1.35-9 3.54z"/></svg>
|
||||
|
||||
</a>
|
||||
MkDocs Material Boilerplate
|
||||
</label>
|
||||
|
||||
<div class="md-nav__source">
|
||||
|
||||
<a href="https://github.com/peaceiris/mkdocs-material-boilerplate/" title="Go to repository" class="md-source">
|
||||
<div class="md-source__icon md-icon">
|
||||
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><path d="M439.55 236.05L244 40.45a28.87 28.87 0 00-40.81 0l-40.66 40.63 51.52 51.52c27.06-9.14 52.68 16.77 43.39 43.68l49.66 49.66c34.23-11.8 61.18 31 35.47 56.69-26.49 26.49-70.21-2.87-56-37.34L240.22 199v121.85c25.3 12.54 22.26 41.85 9.08 55a34.34 34.34 0 01-48.55 0c-17.57-17.6-11.07-46.91 11.25-56v-123c-20.8-8.51-24.6-30.74-18.64-45L142.57 101 8.45 235.14a28.86 28.86 0 000 40.81l195.61 195.6a28.86 28.86 0 0040.8 0l194.69-194.69a28.86 28.86 0 000-40.81z"/></svg>
|
||||
</div>
|
||||
<div class="md-source__repository">
|
||||
GitHub
|
||||
</div>
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<ul class="md-nav__list" data-md-scrollfix>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<li class="md-nav__item">
|
||||
<a href="../.." title="Home" class="md-nav__link">
|
||||
Home
|
||||
</a>
|
||||
</li>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<li class="md-nav__item">
|
||||
<a href="../../material-for-mkdocs/" title="Material for MkDocs" class="md-nav__link">
|
||||
Material for MkDocs
|
||||
</a>
|
||||
</li>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<li class="md-nav__item md-nav__item--active md-nav__item--nested">
|
||||
|
||||
<input class="md-nav__toggle md-toggle" data-md-toggle="nav-3" type="checkbox" id="nav-3" checked>
|
||||
|
||||
<label class="md-nav__link" for="nav-3">
|
||||
Getting started
|
||||
<span class="md-nav__icon md-icon">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M8.59 16.58L13.17 12 8.59 7.41 10 6l6 6-6 6-1.41-1.42z"/></svg>
|
||||
</span>
|
||||
</label>
|
||||
<nav class="md-nav" aria-label="Getting started" data-md-level="1">
|
||||
<label class="md-nav__title" for="nav-3">
|
||||
<span class="md-nav__icon md-icon">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M20 11v2H8l5.5 5.5-1.42 1.42L4.16 12l7.92-7.92L13.5 5.5 8 11h12z"/></svg>
|
||||
</span>
|
||||
Getting started
|
||||
</label>
|
||||
<ul class="md-nav__list" data-md-scrollfix>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<li class="md-nav__item md-nav__item--active">
|
||||
|
||||
<input class="md-nav__toggle md-toggle" data-md-toggle="toc" type="checkbox" id="__toc">
|
||||
|
||||
|
||||
|
||||
|
||||
<label class="md-nav__link md-nav__link--active" for="__toc">
|
||||
Download boilerplate
|
||||
<span class="md-nav__icon md-icon">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M3 9h14V7H3v2m0 4h14v-2H3v2m0 4h14v-2H3v2m16 0h2v-2h-2v2m0-10v2h2V7h-2m0 6h2v-2h-2v2z"/></svg>
|
||||
</span>
|
||||
</label>
|
||||
|
||||
<a href="./" title="Download boilerplate" class="md-nav__link md-nav__link--active">
|
||||
Download boilerplate
|
||||
</a>
|
||||
|
||||
|
||||
<nav class="md-nav md-nav--secondary" aria-label="Table of contents">
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<label class="md-nav__title" for="__toc">
|
||||
<span class="md-nav__icon md-icon">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M20 11v2H8l5.5 5.5-1.42 1.42L4.16 12l7.92-7.92L13.5 5.5 8 11h12z"/></svg>
|
||||
</span>
|
||||
Table of contents
|
||||
</label>
|
||||
<ul class="md-nav__list" data-md-scrollfix>
|
||||
|
||||
<li class="md-nav__item">
|
||||
<a href="#git_clone" class="md-nav__link">
|
||||
Git clone
|
||||
</a>
|
||||
|
||||
</li>
|
||||
|
||||
<li class="md-nav__item">
|
||||
<a href="#download_zip" class="md-nav__link">
|
||||
Download zip
|
||||
</a>
|
||||
|
||||
</li>
|
||||
|
||||
</ul>
|
||||
|
||||
</nav>
|
||||
|
||||
</li>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<li class="md-nav__item">
|
||||
<a href="../pipenv/" title="pipenv" class="md-nav__link">
|
||||
pipenv
|
||||
</a>
|
||||
</li>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<li class="md-nav__item">
|
||||
<a href="../invoke/" title="invoke" class="md-nav__link">
|
||||
invoke
|
||||
</a>
|
||||
</li>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<li class="md-nav__item">
|
||||
<a href="../docker/" title="Docker" class="md-nav__link">
|
||||
Docker
|
||||
</a>
|
||||
</li>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<li class="md-nav__item">
|
||||
<a href="../pip/" title="pip" class="md-nav__link">
|
||||
pip
|
||||
</a>
|
||||
</li>
|
||||
|
||||
|
||||
</ul>
|
||||
</nav>
|
||||
</li>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<li class="md-nav__item md-nav__item--nested">
|
||||
|
||||
<input class="md-nav__toggle md-toggle" data-md-toggle="nav-4" type="checkbox" id="nav-4">
|
||||
|
||||
<label class="md-nav__link" for="nav-4">
|
||||
Hosting and Deployment
|
||||
<span class="md-nav__icon md-icon">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M8.59 16.58L13.17 12 8.59 7.41 10 6l6 6-6 6-1.41-1.42z"/></svg>
|
||||
</span>
|
||||
</label>
|
||||
<nav class="md-nav" aria-label="Hosting and Deployment" data-md-level="1">
|
||||
<label class="md-nav__title" for="nav-4">
|
||||
<span class="md-nav__icon md-icon">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M20 11v2H8l5.5 5.5-1.42 1.42L4.16 12l7.92-7.92L13.5 5.5 8 11h12z"/></svg>
|
||||
</span>
|
||||
Hosting and Deployment
|
||||
</label>
|
||||
<ul class="md-nav__list" data-md-scrollfix>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<li class="md-nav__item">
|
||||
<a href="../../hosting-and-deployment/combinations/" title="Combinations" class="md-nav__link">
|
||||
Combinations
|
||||
</a>
|
||||
</li>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<li class="md-nav__item">
|
||||
<a href="../../hosting-and-deployment/netlify/" title="Netlify" class="md-nav__link">
|
||||
Netlify
|
||||
</a>
|
||||
</li>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<li class="md-nav__item">
|
||||
<a href="../../hosting-and-deployment/github-pages/" title="GitHub Pages" class="md-nav__link">
|
||||
GitHub Pages
|
||||
</a>
|
||||
</li>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<li class="md-nav__item">
|
||||
<a href="../../hosting-and-deployment/gitlab-pages/" title="GitLab Pages" class="md-nav__link">
|
||||
GitLab Pages
|
||||
</a>
|
||||
</li>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<li class="md-nav__item">
|
||||
<a href="../../hosting-and-deployment/aws-amplify-console/" title="AWS Amplify Console" class="md-nav__link">
|
||||
AWS Amplify Console
|
||||
</a>
|
||||
</li>
|
||||
|
||||
|
||||
</ul>
|
||||
</nav>
|
||||
</li>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<li class="md-nav__item md-nav__item--nested">
|
||||
|
||||
<input class="md-nav__toggle md-toggle" data-md-toggle="nav-5" type="checkbox" id="nav-5">
|
||||
|
||||
<label class="md-nav__link" for="nav-5">
|
||||
Extensions
|
||||
<span class="md-nav__icon md-icon">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M8.59 16.58L13.17 12 8.59 7.41 10 6l6 6-6 6-1.41-1.42z"/></svg>
|
||||
</span>
|
||||
</label>
|
||||
<nav class="md-nav" aria-label="Extensions" data-md-level="1">
|
||||
<label class="md-nav__title" for="nav-5">
|
||||
<span class="md-nav__icon md-icon">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M20 11v2H8l5.5 5.5-1.42 1.42L4.16 12l7.92-7.92L13.5 5.5 8 11h12z"/></svg>
|
||||
</span>
|
||||
Extensions
|
||||
</label>
|
||||
<ul class="md-nav__list" data-md-scrollfix>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<li class="md-nav__item">
|
||||
<a href="../../extensions/mathjax/" title="MathJax" class="md-nav__link">
|
||||
MathJax
|
||||
</a>
|
||||
</li>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<li class="md-nav__item">
|
||||
<a href="../../extensions/code-hilite/" title="Code Hilite" class="md-nav__link">
|
||||
Code Hilite
|
||||
</a>
|
||||
</li>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<li class="md-nav__item">
|
||||
<a href="../../extensions/footnote/" title="Footnote" class="md-nav__link">
|
||||
Footnote
|
||||
</a>
|
||||
</li>
|
||||
|
||||
|
||||
</ul>
|
||||
</nav>
|
||||
</li>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<li class="md-nav__item">
|
||||
<a href="../../license/" title="License" class="md-nav__link">
|
||||
License
|
||||
</a>
|
||||
</li>
|
||||
|
||||
|
||||
</ul>
|
||||
</nav>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<div class="md-sidebar md-sidebar--secondary" data-md-component="toc">
|
||||
<div class="md-sidebar__scrollwrap">
|
||||
<div class="md-sidebar__inner">
|
||||
|
||||
<nav class="md-nav md-nav--secondary" aria-label="Table of contents">
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<label class="md-nav__title" for="__toc">
|
||||
<span class="md-nav__icon md-icon">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M20 11v2H8l5.5 5.5-1.42 1.42L4.16 12l7.92-7.92L13.5 5.5 8 11h12z"/></svg>
|
||||
</span>
|
||||
Table of contents
|
||||
</label>
|
||||
<ul class="md-nav__list" data-md-scrollfix>
|
||||
|
||||
<li class="md-nav__item">
|
||||
<a href="#git_clone" class="md-nav__link">
|
||||
Git clone
|
||||
</a>
|
||||
|
||||
</li>
|
||||
|
||||
<li class="md-nav__item">
|
||||
<a href="#download_zip" class="md-nav__link">
|
||||
Download zip
|
||||
</a>
|
||||
|
||||
</li>
|
||||
|
||||
</ul>
|
||||
|
||||
</nav>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<div class="md-content">
|
||||
<article class="md-content__inner md-typeset">
|
||||
|
||||
|
||||
<a href="https://github.com/peaceiris/mkdocs-material-boilerplate/edit/master/docs_sample/getting-started/download-boilerplate.md" title="Edit this page" class="md-content__button md-icon">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M20.71 7.04c.39-.39.39-1.04 0-1.41l-2.34-2.34c-.37-.39-1.02-.39-1.41 0l-1.84 1.83 3.75 3.75M3 17.25V21h3.75L17.81 9.93l-3.75-3.75L3 17.25z"/></svg>
|
||||
</a>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<h1 id="download_boilerplate">Download boilerplate<a class="headerlink" href="#download_boilerplate" title="Permanent link">¶</a></h1>
|
||||
<h2 id="git_clone">Git clone<a class="headerlink" href="#git_clone" title="Permanent link">¶</a></h2>
|
||||
<div class="codehilite"><pre><span></span><code>git clone https://github.com/peaceiris/mkdocs-material-boilerplate.git
|
||||
<span class="nb">cd</span> mkdocs-material-boilerplate
|
||||
</code></pre></div>
|
||||
|
||||
|
||||
<h2 id="download_zip">Download zip<a class="headerlink" href="#download_zip" title="Permanent link">¶</a></h2>
|
||||
<div class="codehilite"><pre><span></span><code>wget <span class="s1">'https://github.com/peaceiris/mkdocs-material-boilerplate/archive/master.zip'</span>
|
||||
unzip master.zip
|
||||
<span class="nb">cd</span> mkdocs-material-boilerplate-master
|
||||
</code></pre></div>
|
||||
|
||||
|
||||
<p>👉 <a href="https://github.com/peaceiris/mkdocs-material-boilerplate/archive/master.zip">Click me to download zip</a></p>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
</article>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
|
||||
<footer class="md-footer">
|
||||
|
||||
<div class="md-footer-nav">
|
||||
<nav class="md-footer-nav__inner md-grid" aria-label="Footer">
|
||||
|
||||
<a href="../../material-for-mkdocs/" title="Material for MkDocs" class="md-footer-nav__link md-footer-nav__link--prev" rel="prev">
|
||||
<div class="md-footer-nav__button md-icon">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M20 11v2H8l5.5 5.5-1.42 1.42L4.16 12l7.92-7.92L13.5 5.5 8 11h12z"/></svg>
|
||||
</div>
|
||||
<div class="md-footer-nav__title">
|
||||
<div class="md-ellipsis">
|
||||
<span class="md-footer-nav__direction">
|
||||
Previous
|
||||
</span>
|
||||
Material for MkDocs
|
||||
</div>
|
||||
</div>
|
||||
</a>
|
||||
|
||||
|
||||
<a href="../pipenv/" title="pipenv" class="md-footer-nav__link md-footer-nav__link--next" rel="next">
|
||||
<div class="md-footer-nav__title">
|
||||
<div class="md-ellipsis">
|
||||
<span class="md-footer-nav__direction">
|
||||
Next
|
||||
</span>
|
||||
pipenv
|
||||
</div>
|
||||
</div>
|
||||
<div class="md-footer-nav__button md-icon">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M4 11v2h12l-5.5 5.5 1.42 1.42L19.84 12l-7.92-7.92L10.5 5.5 16 11H4z"/></svg>
|
||||
</div>
|
||||
</a>
|
||||
|
||||
</nav>
|
||||
</div>
|
||||
|
||||
<div class="md-footer-meta md-typeset">
|
||||
<div class="md-footer-meta__inner md-grid">
|
||||
<div class="md-footer-copyright">
|
||||
|
||||
<div class="md-footer-copyright__highlight">
|
||||
© 2019 peaceiris
|
||||
</div>
|
||||
|
||||
Made with
|
||||
<a href="https://squidfunk.github.io/mkdocs-material/" target="_blank" rel="noopener">
|
||||
Material for MkDocs
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<div class="md-footer-social">
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<a href="https://github.com/peaceiris" target="_blank" rel="noopener" title="github.com" class="md-footer-social__link">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 480 512"><path d="M186.1 328.7c0 20.9-10.9 55.1-36.7 55.1s-36.7-34.2-36.7-55.1 10.9-55.1 36.7-55.1 36.7 34.2 36.7 55.1zM480 278.2c0 31.9-3.2 65.7-17.5 95-37.9 76.6-142.1 74.8-216.7 74.8-75.8 0-186.2 2.7-225.6-74.8-14.6-29-20.2-63.1-20.2-95 0-41.9 13.9-81.5 41.5-113.6-5.2-15.8-7.7-32.4-7.7-48.8 0-21.5 4.9-32.3 14.6-51.8 45.3 0 74.3 9 108.8 36 29-6.9 58.8-10 88.7-10 27 0 54.2 2.9 80.4 9.2 34-26.7 63-35.2 107.8-35.2 9.8 19.5 14.6 30.3 14.6 51.8 0 16.4-2.6 32.7-7.7 48.2 27.5 32.4 39 72.3 39 114.2zm-64.3 50.5c0-43.9-26.7-82.6-73.5-82.6-18.9 0-37 3.4-56 6-14.9 2.3-29.8 3.2-45.1 3.2-15.2 0-30.1-.9-45.1-3.2-18.7-2.6-37-6-56-6-46.8 0-73.5 38.7-73.5 82.6 0 87.8 80.4 101.3 150.4 101.3h48.2c70.3 0 150.6-13.4 150.6-101.3zm-82.6-55.1c-25.8 0-36.7 34.2-36.7 55.1s10.9 55.1 36.7 55.1 36.7-34.2 36.7-55.1-10.9-55.1-36.7-55.1z"/></svg>
|
||||
</a>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<a href="https://twitter.com/piris314en" target="_blank" rel="noopener" title="twitter.com" class="md-footer-social__link">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path d="M459.37 151.716c.325 4.548.325 9.097.325 13.645 0 138.72-105.583 298.558-298.558 298.558-59.452 0-114.68-17.219-161.137-47.106 8.447.974 16.568 1.299 25.34 1.299 49.055 0 94.213-16.568 130.274-44.832-46.132-.975-84.792-31.188-98.112-72.772 6.498.974 12.995 1.624 19.818 1.624 9.421 0 18.843-1.3 27.614-3.573-48.081-9.747-84.143-51.98-84.143-102.985v-1.299c13.969 7.797 30.214 12.67 47.431 13.319-28.264-18.843-46.781-51.005-46.781-87.391 0-19.492 5.197-37.36 14.294-52.954 51.655 63.675 129.3 105.258 216.365 109.807-1.624-7.797-2.599-15.918-2.599-24.04 0-57.828 46.782-104.934 104.934-104.934 30.213 0 57.502 12.67 76.67 33.137 23.715-4.548 46.456-13.32 66.599-25.34-7.798 24.366-24.366 44.833-46.132 57.827 21.117-2.273 41.584-8.122 60.426-16.243-14.292 20.791-32.161 39.308-52.628 54.253z"/></svg>
|
||||
</a>
|
||||
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
</div>
|
||||
|
||||
<script src="../../assets/javascripts/vendor.d710d30a.min.js"></script>
|
||||
<script src="../../assets/javascripts/bundle.7f4f3c92.min.js"></script><script id="__lang" type="application/json">{"clipboard.copy": "Copy to clipboard", "clipboard.copied": "Copied to clipboard", "search.config.lang": "en", "search.config.pipeline": "trimmer, stopWordFilter", "search.config.separator": "[\\s\\-]+", "search.result.placeholder": "Type to start searching", "search.result.none": "No matching documents", "search.result.one": "1 matching document", "search.result.other": "# matching documents"}</script>
|
||||
|
||||
<script>
|
||||
app = initialize({
|
||||
base: "../..",
|
||||
features: ["tabs"],
|
||||
search: Object.assign({
|
||||
worker: "../../assets/javascripts/worker/search.9b3611bd.min.js"
|
||||
}, typeof search !== "undefined" && search)
|
||||
})
|
||||
</script>
|
||||
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.6/MathJax.js?config=TeX-MML-AM_CHTML"></script>
|
||||
|
||||
|
||||
</body>
|
||||
</html>
|
||||
`;
|
||||
import { useAsync } from 'react-use';
|
||||
import { useLocation, useParams, useNavigate } from 'react-router-dom';
|
||||
|
||||
import { Grid } from '@material-ui/core';
|
||||
import { Header, Content } from '@backstage/core';
|
||||
|
||||
import transformer, {
|
||||
addBaseUrl,
|
||||
rewriteDocLinks,
|
||||
addEventListener,
|
||||
} from '../transformers';
|
||||
import { docStorageURL } from '../../config';
|
||||
import URLParser from '../urlParser';
|
||||
import { DocsCard } from './DocsCard';
|
||||
|
||||
const useFetch = (url: string) => {
|
||||
const state = useAsync(async () => {
|
||||
const response = await fetch(url);
|
||||
const raw = await response.text();
|
||||
return raw;
|
||||
}, [url]);
|
||||
|
||||
return state;
|
||||
};
|
||||
|
||||
const useEnforcedTrailingSlash = (): void => {
|
||||
React.useEffect(() => {
|
||||
const actualUrl = window.location.href;
|
||||
const expectedUrl = new URLParser(window.location.href, '.').parse();
|
||||
|
||||
if (actualUrl !== expectedUrl) {
|
||||
window.history.replaceState({}, document.title, expectedUrl);
|
||||
}
|
||||
}, []);
|
||||
};
|
||||
|
||||
export const Reader = () => {
|
||||
const location = useLocation();
|
||||
const { componentId, '*': path } = useParams();
|
||||
const shadowDomRef = useShadowDom();
|
||||
const navigate = useNavigate();
|
||||
const normalizedUrl = new URLParser(
|
||||
`${docStorageURL}${location.pathname.replace('/docs', '')}`,
|
||||
'.',
|
||||
).parse();
|
||||
const state = useFetch(`${normalizedUrl}index.html`);
|
||||
|
||||
useEnforcedTrailingSlash();
|
||||
|
||||
React.useEffect(() => {
|
||||
const divElement = shadowDomRef.current;
|
||||
if (!divElement?.shadowRoot) {
|
||||
return;
|
||||
if (divElement?.shadowRoot && state.value) {
|
||||
const transformedElement = transformer(state.value, [
|
||||
addBaseUrl({
|
||||
docStorageURL,
|
||||
componentId,
|
||||
path,
|
||||
}),
|
||||
rewriteDocLinks({
|
||||
componentId,
|
||||
}),
|
||||
]);
|
||||
|
||||
divElement.shadowRoot.innerHTML = '';
|
||||
if (transformedElement) {
|
||||
divElement.shadowRoot.appendChild(transformedElement);
|
||||
transformer(divElement.shadowRoot.children[0], [
|
||||
addEventListener({
|
||||
onClick: navigate,
|
||||
}),
|
||||
]);
|
||||
}
|
||||
}
|
||||
divElement.shadowRoot.innerHTML = mockHtml;
|
||||
}, [shadowDomRef]);
|
||||
}, [shadowDomRef, state, componentId, path, navigate]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<h3>Shadow DOM should be underneath</h3>
|
||||
<div ref={shadowDomRef} />
|
||||
{componentId ? (
|
||||
<div ref={shadowDomRef} />
|
||||
) : (
|
||||
<>
|
||||
<Header
|
||||
title="Documentation"
|
||||
subtitle="Documentation available in Backstage"
|
||||
/>
|
||||
|
||||
<Content>
|
||||
<Grid container>
|
||||
<Grid item xs={12} sm={6} md={3}>
|
||||
<DocsCard
|
||||
onClick={() => navigate('/docs/mkdocs')}
|
||||
tags={['Developer Tool']}
|
||||
title="MkDocs"
|
||||
label="Read Docs"
|
||||
description="MkDocs is a fast, simple and downright gorgeous static site generator that's geared towards building project documentation. "
|
||||
/>
|
||||
</Grid>
|
||||
<Grid item xs={12} sm={6} md={3}>
|
||||
<DocsCard
|
||||
onClick={() => navigate('/docs/backstage-microsite')}
|
||||
tags={['Service']}
|
||||
title="Backstage"
|
||||
label="Read Docs"
|
||||
description="Getting started guides, API Overview, documentation around how to Create a Plugin and more. "
|
||||
/>
|
||||
</Grid>
|
||||
</Grid>
|
||||
</Content>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user