Browse Source

grafana app boilerplate

pull/2/head
rozetko 2 years ago
commit
e939222efa
  1. 12
      .config/.eslintrc
  2. 16
      .config/.prettierrc.js
  3. 15
      .config/Dockerfile
  4. 120
      .config/README.md
  5. 24
      .config/jest-setup.js
  6. 31
      .config/jest.config.js
  7. 17
      .config/tsconfig.json
  8. 37
      .config/types/custom.d.ts
  9. 2
      .config/webpack/constants.ts
  10. 9
      .config/webpack/tsconfig.webpack.json
  11. 42
      .config/webpack/utils.ts
  12. 185
      .config/webpack/webpack.config.ts
  13. 3
      .eslintrc
  14. 1
      .gitignore
  15. 1
      .nvmrc
  16. 4
      .prettierrc.js
  17. 5
      CHANGELOG.md
  18. 201
      LICENSE
  19. 79
      README.md
  20. 10
      cypress/integration/01-smoke.spec.ts
  21. 14
      docker-compose.yaml
  22. 2
      jest-setup.js
  23. 4
      jest.config.js
  24. 68
      package.json
  25. 5
      src/README.md
  26. 32
      src/components/App/App.test.tsx
  27. 8
      src/components/App/App.tsx
  28. 1
      src/components/App/index.tsx
  29. 51
      src/components/AppConfig/AppConfig.test.tsx
  30. 92
      src/components/AppConfig/AppConfig.tsx
  31. 1
      src/components/AppConfig/index.tsx
  32. 1
      src/img/logo.svg
  33. 12
      src/module.ts
  34. 34
      src/plugin.json
  35. 3
      tsconfig.json
  36. 9802
      yarn.lock

12
.config/.eslintrc

@ -0,0 +1,12 @@
/*
* ⚠ THIS FILE WAS SCAFFOLDED BY `@grafana/create-plugin`. DO NOT EDIT THIS FILE DIRECTLY. ⚠
*
* In order to extend the configuration follow the steps in .config/README.md
*/
{
"extends": ["@grafana/eslint-config"],
"root": true,
"rules": {
"react/prop-types": "off"
}
}

16
.config/.prettierrc.js

@ -0,0 +1,16 @@
/*
* THIS FILE WAS SCAFFOLDED BY `@grafana/create-plugin`. DO NOT EDIT THIS FILE DIRECTLY.
*
* In order to extend the configuration follow the steps in .config/README.md
*/
module.exports = {
"endOfLine": "auto",
"printWidth": 120,
"trailingComma": "es5",
"semi": true,
"jsxSingleQuote": false,
"singleQuote": true,
"useTabs": false,
"tabWidth": 2
};

15
.config/Dockerfile

@ -0,0 +1,15 @@
ARG grafana_version=latest
FROM grafana/grafana:${grafana_version}
# Make it as simple as possible to access the grafana instance for development purposes
# Do NOT enable these settings in a public facing / production grafana instance
ENV GF_AUTH_ANONYMOUS_ORG_ROLE "Admin"
ENV GF_AUTH_ANONYMOUS_ENABLED "true"
ENV GF_AUTH_BASIC_ENABLED "false"
# Set development mode so plugins can be loaded without the need to sign
ENV GF_DEFAULT_APP_MODE "development"
# Inject livereload script into grafana index.html
USER root
RUN sed -i 's/<\/body><\/html>/<script src=\"http:\/\/localhost:35729\/livereload.js\"><\/script><\/body><\/html>/g' /usr/share/grafana/public/views/index.html

120
.config/README.md

@ -0,0 +1,120 @@
# Default build configuration by Grafana
**This is an auto-generated directory and is not intended to be changed! ⚠**
The `.config/` directory holds basic configuration for the different tools
that are used to develop, test and build the project. In order to make it updates easier we ask you to
not edit files in this folder to extend configuration.
## How to extend the basic configs?
Bear in mind that you are doing it at your own risk, and that extending any of the basic configuration can lead
to issues around working with the project.
### Extending the ESLint config
Edit the `.eslintrc` file in the project root in order to extend the ESLint configuration.
**Example:**
```json
{
"extends": "./.config/.eslintrc",
"rules": {
"react/prop-types": "off"
}
}
```
---
### Extending the Prettier config
Edit the `.prettierrc.js` file in the project root in order to extend the Prettier configuration.
**Example:**
```javascript
module.exports = {
// Prettier configuration provided by Grafana scaffolding
...require("./.config/.prettierrc.js"),
semi: false,
};
```
---
### Extending the Jest config
There are two configuration in the project root that belong to Jest: `jest-setup.js` and `jest.config.js`.
**`jest-setup.js`:** A file that is run before each test file in the suite is executed. We are using it to
set up the Jest DOM for the testing library and to apply some polyfills. ([link to Jest docs](https://jestjs.io/docs/configuration#setupfilesafterenv-array))
**`jest.config.js`:** The main Jest configuration file that is extending our basic Grafana-tailored setup. ([link to Jest docs](https://jestjs.io/docs/configuration))
---
### Extending the TypeScript config
Edit the `tsconfig.json` file in the project root in order to extend the TypeScript configuration.
**Example:**
```json
{
"extends": "./.config/tsconfig.json",
"compilerOptions": {
"preserveConstEnums": true
}
}
```
---
### Extending the Webpack config
Follow these steps to extend the basic Webpack configuration that lives under `.config/`:
#### 1. Create a new Webpack configuration file
Create a new config file that is going to extend the basic one provided by Grafana.
It can live in the project root, e.g. `webpack.config.ts`.
#### 2. Merge the basic config provided by Grafana and your custom setup
We are going to use [`webpack-merge`](https://github.com/survivejs/webpack-merge) for this.
```typescript
// webpack.config.ts
import type { Configuration } from 'webpack';
import { merge } from 'webpack-merge';
import grafanaConfig from './.config/webpack/webpack.config';
const config = async (env): Promise<Configuration> => {
const baseConfig = await grafanaConfig(env);
return merge(baseConfig, {
// Add custom config here...
output: {
asyncChunks: true,
},
});
};
export default config;
```
#### 3. Update the `package.json` to use the new Webpack config
We need to update the `scripts` in the `package.json` to use the extended Webpack configuration.
**Update for `build`:**
```diff
-"build": "TS_NODE_PROJECT=\"./.config/webpack/tsconfig.webpack.json\" webpack -c ./.config/webpack/webpack.config.ts --env production",
+"build": "TS_NODE_PROJECT=\"./.config/webpack/tsconfig.webpack.json\" webpack -c ./webpack.config.ts --env production",
```
**Update for `dev`:**
```diff
-"dev": "TS_NODE_PROJECT=\"./.config/webpack/tsconfig.webpack.json\" webpack -w -c ./.config/webpack/webpack.config.ts --env development",
+"dev": "TS_NODE_PROJECT=\"./.config/webpack/tsconfig.webpack.json\" webpack -w -c ./webpack.config.ts --env development",
```

24
.config/jest-setup.js

@ -0,0 +1,24 @@
/*
* THIS FILE WAS SCAFFOLDED BY `@grafana/create-plugin`. DO NOT EDIT THIS FILE DIRECTLY.
*
* In order to extend the configuration follow the steps in .config/README.md
*/
import '@testing-library/jest-dom';
// https://jestjs.io/docs/manual-mocks#mocking-methods-which-are-not-implemented-in-jsdom
Object.defineProperty(global, 'matchMedia', {
writable: true,
value: jest.fn().mockImplementation((query) => ({
matches: false,
media: query,
onchange: null,
addListener: jest.fn(), // deprecated
removeListener: jest.fn(), // deprecated
addEventListener: jest.fn(),
removeEventListener: jest.fn(),
dispatchEvent: jest.fn(),
})),
});
HTMLCanvasElement.prototype.getContext = () => {};

31
.config/jest.config.js

@ -0,0 +1,31 @@
/*
* THIS FILE WAS SCAFFOLDED BY `@grafana/create-plugin`. DO NOT EDIT THIS FILE DIRECTLY.
*
* In order to extend the configuration follow the steps in .config/README.md
*/
module.exports = {
testEnvironment: 'jest-environment-jsdom',
testMatch: [
'<rootDir>/src/**/__tests__/**/*.{js,jsx,ts,tsx}',
'<rootDir>/src/**/*.{spec,test,jest}.{js,jsx,ts,tsx}',
'<rootDir>/src/**/*.{spec,test,jest}.{js,jsx,ts,tsx}',
],
transform: {
'^.+\\.(t|j)sx?$': [
'@swc/jest',
{
sourceMaps: true,
jsc: {
parser: {
syntax: 'typescript',
tsx: true,
decorators: false,
dynamicImport: true,
},
},
},
],
},
setupFilesAfterEnv: ['<rootDir>/jest-setup.js'],
};

17
.config/tsconfig.json

@ -0,0 +1,17 @@
/*
* THIS FILE WAS SCAFFOLDED BY `@grafana/create-plugin`. DO NOT EDIT THIS FILE DIRECTLY.
*
* In order to extend the configuration follow the steps in .config/README.md
*/
{
"compilerOptions": {
"alwaysStrict": true,
"declaration": false,
"rootDir": "../src",
"baseUrl": "../src",
"typeRoots": ["../node_modules/@types"],
"resolveJsonModule": true
},
"include": ["../src", "./types"],
"extends": "@grafana/tsconfig"
}

37
.config/types/custom.d.ts vendored

@ -0,0 +1,37 @@
// Image declarations
declare module '*.gif' {
const src: string;
export default src;
}
declare module '*.jpg' {
const src: string;
export default src;
}
declare module '*.jpeg' {
const src: string;
export default src;
}
declare module '*.png' {
const src: string;
export default src;
}
declare module '*.webp' {
const src: string;
export default src;
}
declare module '*.svg' {
const content: string;
export default content;
}
// Font declarations
declare module '*.woff';
declare module '*.woff2';
declare module '*.eot';
declare module '*.ttf';
declare module '*.otf';

2
.config/webpack/constants.ts

@ -0,0 +1,2 @@
export const SOURCE_DIR = 'src';
export const DIST_DIR = 'dist';

9
.config/webpack/tsconfig.webpack.json

@ -0,0 +1,9 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es5",
"esModuleInterop": true
},
"transpileOnly": true,
"transpiler": "ts-node/transpilers/swc-experimental"
}

42
.config/webpack/utils.ts

@ -0,0 +1,42 @@
import fs from 'fs';
import path from 'path';
import util from 'util';
import glob from 'glob';
import { SOURCE_DIR } from './constants';
const globAsync = util.promisify(glob);
export function getPackageJson() {
return require(path.resolve(process.cwd(), 'package.json'));
}
export function getPluginId() {
const { id } = require(path.resolve(process.cwd(), `${SOURCE_DIR}/plugin.json`));
return id;
}
export function hasReadme() {
return fs.existsSync(path.resolve(process.cwd(), SOURCE_DIR, 'README.md'));
}
export async function getEntries(): Promise<Record<string, string>> {
const parent = '..';
const pluginsJson = await globAsync('**/src/**/plugin.json');
const plugins = await Promise.all(pluginsJson.map(pluginJson => {
const folder = path.dirname(pluginJson);
return globAsync(`${folder}/module.{ts,tsx,js}`);
}));
return plugins.reduce((result, modules) => {
return modules.reduce((result, module) => {
const pluginPath = path.resolve(path.dirname(module), parent);
const pluginName = path.basename(pluginPath);
const entryName = plugins.length > 1 ? `${pluginName}/module` : 'module';
result[entryName] = path.join(parent, module);
return result;
}, result);
}, {});
}

185
.config/webpack/webpack.config.ts

@ -0,0 +1,185 @@
/*
* THIS FILE WAS SCAFFOLDED BY `@grafana/create-plugin`. DO NOT EDIT THIS FILE DIRECTLY.
*
* In order to extend the configuration follow the steps in .config/README.md
*/
import CopyWebpackPlugin from 'copy-webpack-plugin';
import ESLintPlugin from 'eslint-webpack-plugin';
import ForkTsCheckerWebpackPlugin from 'fork-ts-checker-webpack-plugin';
import LiveReloadPlugin from 'webpack-livereload-plugin';
import path from 'path';
import ReplaceInFileWebpackPlugin from 'replace-in-file-webpack-plugin';
import { Configuration } from 'webpack';
import { getPackageJson, getPluginId, hasReadme, getEntries } from './utils';
import { SOURCE_DIR, DIST_DIR } from './constants';
const config = async (env): Promise<Configuration> => ({
cache: {
type: 'filesystem',
buildDependencies: {
config: [__filename],
},
},
context: path.join(process.cwd(), SOURCE_DIR),
devtool: env.production ? 'source-map' : 'eval-source-map',
entry: await getEntries(),
externals: [
'lodash',
'jquery',
'moment',
'slate',
'emotion',
'@emotion/react',
'@emotion/css',
'prismjs',
'slate-plain-serializer',
'@grafana/slate-react',
'react',
'react-dom',
'react-redux',
'redux',
'rxjs',
'react-router-dom',
'd3',
'angular',
'@grafana/ui',
'@grafana/runtime',
'@grafana/data',
// Mark legacy SDK imports as external if their name starts with the "grafana/" prefix
({ request }, callback) => {
const prefix = 'grafana/';
const hasPrefix = (request) => request.indexOf(prefix) === 0;
const stripPrefix = (request) => request.substr(prefix.length);
if (hasPrefix(request)) {
return callback(null, stripPrefix(request));
}
callback();
},
],
mode: env.production ? 'production' : 'development',
module: {
rules: [
{
exclude: /(node_modules)/,
test: /\.[tj]sx?$/,
use: {
loader: 'swc-loader',
options: {
jsc: {
baseUrl: './src',
target: 'es2015',
loose: false,
parser: {
syntax: 'typescript',
tsx: true,
decorators: false,
dynamicImport: true,
},
},
},
},
},
{
test: /\.(png|jpe?g|gif|svg)$/,
use: [
{
loader: 'asset/resource',
options: {
outputPath: '/',
name: Boolean(env.production) ? '[path][hash].[ext]' : '[path][name].[ext]',
},
},
],
},
{
test: /\.(woff|woff2|eot|ttf|otf)(\?v=\d+\.\d+\.\d+)?$/,
loader: 'asset/resource',
options: {
// Keep publicPath relative for host.com/grafana/ deployments
publicPath: `public/plugins/${getPluginId()}/fonts`,
outputPath: 'fonts',
name: Boolean(env.production) ? '[hash].[ext]' : '[name].[ext]',
},
},
],
},
output: {
clean: true,
filename: '[name].js',
libraryTarget: 'amd',
path: path.resolve(process.cwd(), DIST_DIR),
publicPath: '/',
},
plugins: [
new CopyWebpackPlugin({
patterns: [
// If src/README.md exists use it; otherwise the root README
// To `compiler.options.output`
{ from: hasReadme() ? 'README.md' : '../README.md', to: '.', force: true },
{ from: 'plugin.json', to: '.' },
{ from: '../LICENSE', to: '.' },
{ from: '../CHANGELOG.md', to: '.', force: true },
{ from: '**/*.json', to: '.' }, // TODO<Add an error for checking the basic structure of the repo>
{ from: '**/*.svg', to: '.', noErrorOnMissing: true }, // Optional
{ from: '**/*.png', to: '.', noErrorOnMissing: true }, // Optional
{ from: '**/*.html', to: '.', noErrorOnMissing: true }, // Optional
{ from: 'img/**/*', to: '.', noErrorOnMissing: true }, // Optional
{ from: 'libs/**/*', to: '.', noErrorOnMissing: true }, // Optional
{ from: 'static/**/*', to: '.', noErrorOnMissing: true }, // Optional
],
}),
// Replace certain template-variables in the README and plugin.json
new ReplaceInFileWebpackPlugin([
{
dir: DIST_DIR,
files: ['plugin.json', 'README.md'],
rules: [
{
search: /\%VERSION\%/g,
replace: getPackageJson().version,
},
{
search: /\%TODAY\%/g,
replace: new Date().toISOString().substring(0, 10),
},
{
search: /\%PLUGIN_ID\%/g,
replace: getPluginId(),
},
],
},
]),
new ForkTsCheckerWebpackPlugin({
async: Boolean(env.development),
issue: {
include: [{ file: '**/*.{ts,tsx}' }],
},
typescript: { configFile: path.join(process.cwd(), 'tsconfig.json') },
}),
new ESLintPlugin({
extensions: ['.ts', '.tsx'],
lintDirtyModulesOnly: Boolean(env.development), // don't lint on start, only lint changed files
}),
...(env.development ? [new LiveReloadPlugin()] : []),
],
resolve: {
extensions: ['.js', '.jsx', '.ts', '.tsx'],
unsafeCache: true,
},
});
export default config;

3
.eslintrc

@ -0,0 +1,3 @@
{
"extends": "./.config/.eslintrc"
}

1
.gitignore vendored

@ -0,0 +1 @@
node_modules

1
.nvmrc

@ -0,0 +1 @@
14

4
.prettierrc.js

@ -0,0 +1,4 @@
module.exports = {
// Prettier configuration provided by Grafana scaffolding
...require("./.config/.prettierrc.js")
};

5
CHANGELOG.md

@ -0,0 +1,5 @@
# Changelog
## 1.0.0 (Unreleased)
Initial release.

201
LICENSE

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
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.

79
README.md

@ -0,0 +1,79 @@
# Grafana app plugin template
This template is a starting point for building an app plugin for Grafana.
## What are Grafana app plugins?
App plugins can let you create a custom out-of-the-box monitoring experience by custom pages, nested datasources and panel plugins.
## Getting started
### Frontend
1. Install dependencies
```bash
yarn install
```
2. Build plugin in development mode or run in watch mode
```bash
yarn dev
# or
yarn watch
```
3. Build plugin in production mode
```bash
yarn build
```
4. Run the tests (using Jest)
```bash
# Runs the tests and watches for changes
yarn test
# Exists after running all the tests
yarn lint:ci
```
5. Spin up a Grafana instance and run the plugin inside it (using Docker)
```bash
yarn server
```
6. Run the E2E tests (using Cypress)
```bash
# Spin up a Grafana instance first that we tests against
yarn server
# Start the tests
yarn e2e
```
7. Run the linter
```bash
yarn lint
# or
yarn lint:fix
```
## Learn more
Below you can find source code for existing app plugins and other related documentation.
- [Basic app plugin example](https://github.com/grafana/grafana-plugin-examples/tree/master/examples/app-basic#readme)
- [Plugin.json documentation](https://grafana.com/docs/grafana/latest/developers/plugins/metadata/)
- [How to sign a plugin?](https://grafana.com/docs/grafana/latest/developers/plugins/sign-a-plugin/)

10
cypress/integration/01-smoke.spec.ts

@ -0,0 +1,10 @@
import { e2e } from '@grafana/e2e';
e2e.scenario({
describeName: 'Smoke test',
itName: 'Smoke test',
scenario: () => {
e2e.pages.Home.visit();
e2e().contains('Welcome to Grafana').should('be.visible');
},
});

14
docker-compose.yaml

@ -0,0 +1,14 @@
version: '3.0'
services:
grafana:
container_name: 'data-exporter'
build:
context: ./.config
args:
grafana_version: ${GRAFANA_VERSION:-9.1.2}
ports:
- 3000:3000/tcp
volumes:
- ./dist:/var/lib/grafana/plugins/data-exporter,
- ./provisioning:/etc/grafana/provisioning

2
jest-setup.js

@ -0,0 +1,2 @@
// Jest setup provided by Grafana scaffolding
import './.config/jest-setup';

4
jest.config.js

@ -0,0 +1,4 @@
module.exports = {
// Jest configuration provided by Grafana scaffolding
...require('./.config/jest.config'),
};

68
package.json

@ -0,0 +1,68 @@
{
"name": "corpglory-dataexporter-app",
"version": "1.0.0",
"description": "",
"scripts": {
"build": "TS_NODE_PROJECT=\"./.config/webpack/tsconfig.webpack.json\" webpack -c ./.config/webpack/webpack.config.ts --env production",
"dev": "TS_NODE_PROJECT=\"./.config/webpack/tsconfig.webpack.json\" webpack -w -c ./.config/webpack/webpack.config.ts --env development",
"test": "jest --watch --onlyChanged",
"test:ci": "jest --maxWorkers 4",
"typecheck": "tsc --noEmit",
"lint": "eslint --cache --ignore-path ./.gitignore --ext .js,.jsx,.ts,.tsx .",
"lint:fix": "yarn lint --fix",
"e2e": "yarn cypress install && yarn grafana-e2e run",
"e2e:update": "yarn cypress install && yarn grafana-e2e run --update-screenshots",
"server": "docker-compose up --build"
},
"author": "CorpGlory Inc.",
"license": "Apache-2.0",
"devDependencies": {
"@babel/core": "^7.16.7",
"@grafana/e2e": "9.1.2",
"@grafana/e2e-selectors": "9.1.2",
"@grafana/eslint-config": "^2.5.0",
"@grafana/tsconfig": "^1.2.0-rc1",
"@swc/core": "^1.2.144",
"@swc/helpers": "^0.3.6",
"@swc/jest": "^0.2.20",
"@testing-library/jest-dom": "^5.16.2",
"@testing-library/react": "^12.1.3",
"@types/glob": "^8.0.0",
"@types/jest": "^27.4.1",
"@types/react-router-dom": "^5.3.3",
"@types/node": "^17.0.19",
"@typescript-eslint/eslint-plugin": "^4.33.0",
"@typescript-eslint/parser": "^4.33.0",
"copy-webpack-plugin": "^10.0.0",
"eslint": "^7.32.0",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-jsdoc": "^36.1.0",
"eslint-plugin-prettier": "^4.0.0",
"eslint-plugin-react": "^7.26.1",
"eslint-plugin-react-hooks": "^4.2.0",
"eslint-webpack-plugin": "^3.1.1",
"glob": "^8.0.3",
"jest": "27.5.0",
"fork-ts-checker-webpack-plugin": "^7.2.0",
"prettier": "^2.5.0",
"replace-in-file-webpack-plugin": "^1.0.6",
"swc-loader": "^0.1.15",
"tsconfig-paths": "^3.12.0",
"ts-node": "^10.5.0",
"typescript": "^4.4.0",
"webpack": "^5.69.1",
"webpack-cli": "^4.9.2",
"webpack-livereload-plugin": "^3.0.2"
},
"engines": {
"node": ">=14"
},
"dependencies": {
"@emotion/css": "^11.1.3",
"@grafana/data": "9.1.2",
"@grafana/runtime": "9.1.2",
"@grafana/ui": "9.1.2",
"@types/lodash": "latest",
"react-router-dom": "^5.2.0"
}
}

5
src/README.md

@ -0,0 +1,5 @@
<!-- This README file is going to be the one displayed on the Grafana.com website for your plugin -->
# Data Exporter

32
src/components/App/App.test.tsx

@ -0,0 +1,32 @@
import React from 'react';
import { AppRootProps, PluginType } from '@grafana/data';
import { render, screen } from '@testing-library/react';
import { App } from './App';
describe('Components/App', () => {
let props: AppRootProps;
beforeEach(() => {
jest.resetAllMocks();
props = {
basename: 'a/sample-app',
meta: {
id: 'sample-app',
name: 'Sample App',
type: PluginType.app,
enabled: true,
jsonData: {},
},
query: {},
path: '',
onNavChanged: jest.fn(),
} as unknown as AppRootProps;
});
test('renders without an error"', () => {
render(<App {...props} />);
expect(screen.queryByText(/Hello Grafana!/i)).toBeInTheDocument();
});
});

8
src/components/App/App.tsx

@ -0,0 +1,8 @@
import * as React from 'react';
import { AppRootProps } from '@grafana/data';
export class App extends React.PureComponent<AppRootProps> {
render() {
return <div className="page-container">Hello Grafana!</div>;
}
}

1
src/components/App/index.tsx

@ -0,0 +1 @@
export * from './App';

51
src/components/AppConfig/AppConfig.test.tsx

@ -0,0 +1,51 @@
import React from 'react';
import { render, screen } from '@testing-library/react';
import { PluginType } from '@grafana/data';
import { AppConfig, AppConfigProps } from './AppConfig';
describe('Components/AppConfig', () => {
let props: AppConfigProps;
beforeEach(() => {
jest.resetAllMocks();
props = {
plugin: {
meta: {
id: 'sample-app',
name: 'Sample App',
type: PluginType.app,
enabled: true,
jsonData: {},
},
},
query: {},
} as unknown as AppConfigProps;
});
test('renders without an error"', () => {
render(<AppConfig plugin={props.plugin} query={props.query} />);
expect(screen.queryByText(/Enable \/ Disable/i)).toBeInTheDocument();
});
test('renders an "Enable" button if the plugin is disabled', () => {
const plugin = { meta: { ...props.plugin.meta, enabled: false } };
// @ts-ignore - We don't need to provide `addConfigPage()` and `setChannelSupport()` for these tests
render(<AppConfig plugin={plugin} query={props.query} />);
expect(screen.queryByText(/The plugin is currently not enabled./i)).toBeInTheDocument();
expect(screen.queryByText(/The plugin is currently enabled./i)).not.toBeInTheDocument();
});
test('renders a "Disable" button if the plugin is enabled', () => {
const plugin = { meta: { ...props.plugin.meta, enabled: true } };
// @ts-ignore - We don't need to provide `addConfigPage()` and `setChannelSupport()` for these tests
render(<AppConfig plugin={plugin} query={props.query} />);
expect(screen.queryByText(/The plugin is currently enabled./i)).toBeInTheDocument();
expect(screen.queryByText(/The plugin is currently not enabled./i)).not.toBeInTheDocument();
});
});

92
src/components/AppConfig/AppConfig.tsx

@ -0,0 +1,92 @@
import React from 'react';
import { Button, Legend, useStyles2 } from '@grafana/ui';
import { PluginConfigPageProps, AppPluginMeta, PluginMeta, GrafanaTheme2 } from '@grafana/data';
import { getBackendSrv } from '@grafana/runtime';
import { css } from '@emotion/css';
import { lastValueFrom } from 'rxjs';
export type AppPluginSettings = {};
export interface AppConfigProps extends PluginConfigPageProps<AppPluginMeta<AppPluginSettings>> {}
export const AppConfig = ({ plugin }: AppConfigProps) => {
const s = useStyles2(getStyles);
const { enabled, jsonData } = plugin.meta;
return (
<div className="gf-form-group">
<div>
{/* Enable the plugin */}
<Legend>Enable / Disable</Legend>
{!enabled && (
<>
<div className={s.colorWeak}>The plugin is currently not enabled.</div>
<Button
className={s.marginTop}
variant="primary"
onClick={() =>
updatePluginAndReload(plugin.meta.id, {
enabled: true,
pinned: true,
jsonData,
})
}
>
Enable plugin
</Button>
</>
)}
{/* Disable the plugin */}
{enabled && (
<>
<div className={s.colorWeak}>The plugin is currently enabled.</div>
<Button
className={s.marginTop}
variant="destructive"
onClick={() =>
updatePluginAndReload(plugin.meta.id, {
enabled: false,
pinned: false,
jsonData,
})
}
>
Disable plugin
</Button>
</>
)}
</div>
</div>
);
};
const getStyles = (theme: GrafanaTheme2) => ({
colorWeak: css`
color: ${theme.colors.text.secondary};
`,
marginTop: css`
margin-top: ${theme.spacing(3)};
`,
});
const updatePluginAndReload = async (pluginId: string, data: Partial<PluginMeta>) => {
try {
await updatePlugin(pluginId, data);
// Reloading the page as the changes made here wouldn't be propagated to the actual plugin otherwise.
// This is not ideal, however unfortunately currently there is no supported way for updating the plugin state.
window.location.reload();
} catch (e) {
console.error('Error while updating the plugin', e);
}
};
export const updatePlugin = async (pluginId: string, data: Partial<PluginMeta>) => {
const response = getBackendSrv().fetch({
url: `/api/plugins/${pluginId}/settings`,
method: 'POST',
data,
});
return lastValueFrom(response);
};

1
src/components/AppConfig/index.tsx

@ -0,0 +1 @@
export * from './AppConfig';

1
src/img/logo.svg

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 81.9 71.52"><defs><style>.cls-1{fill:#84aff1;}.cls-2{fill:#3865ab;}.cls-3{fill:url(#linear-gradient);}</style><linearGradient id="linear-gradient" x1="42.95" y1="16.88" x2="81.9" y2="16.88" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#f2cc0c"/><stop offset="1" stop-color="#ff9830"/></linearGradient></defs><g id="Layer_2" data-name="Layer 2"><g id="Layer_1-2" data-name="Layer 1"><path class="cls-1" d="M55.46,62.43A2,2,0,0,1,54.07,59l4.72-4.54a2,2,0,0,1,2.2-.39l3.65,1.63,3.68-3.64a2,2,0,1,1,2.81,2.84l-4.64,4.6a2,2,0,0,1-2.22.41L60.6,58.26l-3.76,3.61A2,2,0,0,1,55.46,62.43Z"/><path class="cls-2" d="M37,0H2A2,2,0,0,0,0,2V31.76a2,2,0,0,0,2,2H37a2,2,0,0,0,2-2V2A2,2,0,0,0,37,0ZM4,29.76V8.84H35V29.76Z"/><path class="cls-3" d="M79.9,0H45a2,2,0,0,0-2,2V31.76a2,2,0,0,0,2,2h35a2,2,0,0,0,2-2V2A2,2,0,0,0,79.9,0ZM47,29.76V8.84h31V29.76Z"/><path class="cls-2" d="M37,37.76H2a2,2,0,0,0-2,2V69.52a2,2,0,0,0,2,2H37a2,2,0,0,0,2-2V39.76A2,2,0,0,0,37,37.76ZM4,67.52V46.6H35V67.52Z"/><path class="cls-2" d="M79.9,37.76H45a2,2,0,0,0-2,2V69.52a2,2,0,0,0,2,2h35a2,2,0,0,0,2-2V39.76A2,2,0,0,0,79.9,37.76ZM47,67.52V46.6h31V67.52Z"/><rect class="cls-1" x="10.48" y="56.95" width="4" height="5.79"/><rect class="cls-1" x="17.43" y="53.95" width="4" height="8.79"/><rect class="cls-1" x="24.47" y="50.95" width="4" height="11.79"/><path class="cls-1" d="M19.47,25.8a6.93,6.93,0,1,1,6.93-6.92A6.93,6.93,0,0,1,19.47,25.8Zm0-9.85a2.93,2.93,0,1,0,2.93,2.93A2.93,2.93,0,0,0,19.47,16Z"/></g></g></svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

12
src/module.ts

@ -0,0 +1,12 @@
import { AppPlugin } from '@grafana/data';
import { App } from './components/App';
import { AppConfig } from './components/AppConfig';
export const plugin = new AppPlugin<{}>().setRootPage(App).addConfigPage({
title: 'Configuration',
icon: 'fa fa-cog',
// @ts-ignore - Would expect a Class component, however works absolutely fine with a functional one
// Implementation: https://github.com/grafana/grafana/blob/fd44c01675e54973370969dfb9e78f173aff7910/public/app/features/plugins/PluginPage.tsx#L157
body: AppConfig,
id: 'configuration',
});

34
src/plugin.json

@ -0,0 +1,34 @@
{
"$schema": "https://raw.githubusercontent.com/grafana/grafana/master/docs/sources/developers/plugins/plugin.schema.json",
"type": "app",
"name": "Data Exporter",
"id": "corpglory-dataexporter-app",
"info": {
"description": "",
"author": {
"name": "CorpGlory Inc."
},
"logos": {
"small": "img/logo.svg",
"large": "img/logo.svg"
},
"keywords": ["export", "csv"],
"screenshots": [],
"version": "%VERSION%",
"updated": "%TODAY%"
},
"includes": [
{
"type": "page",
"name": "Default",
"path": "/a/%PLUGIN_ID%",
"role": "Admin",
"addToNav": true,
"defaultNav": true
}
],
"dependencies": {
"grafanaDependency": ">=7.0.0",
"plugins": []
}
}

3
tsconfig.json

@ -0,0 +1,3 @@
{
"extends": "./.config/tsconfig.json"
}

9802
yarn.lock

File diff suppressed because it is too large Load Diff
Loading…
Cancel
Save