├── .DS_Store ├── .config ├── .cprc.json ├── .eslintrc ├── .prettierrc.js ├── Dockerfile ├── README.md ├── entrypoint.sh ├── jest-setup.js ├── jest.config.js ├── jest │ ├── mocks │ │ └── react-inlinesvg.tsx │ └── utils.js ├── supervisord │ └── supervisord.conf ├── tsconfig.json ├── types │ └── custom.d.ts └── webpack │ ├── constants.ts │ ├── utils.ts │ └── webpack.config.ts ├── .eslintrc ├── .github └── workflows │ ├── ci.yml │ └── release.yml ├── .gitignore ├── .nvmrc ├── .prettierrc.js ├── CHANGELOG.md ├── LICENSE ├── README.md ├── appveyor.yml ├── docker-compose.yaml ├── docs └── README.md ├── examples ├── ckeditor.html ├── echarts-gl.html ├── leaflet-strava.html └── threejs-little-tokyo.html ├── jest-setup.js ├── jest.config.js ├── package.json ├── src ├── .DS_Store ├── changeHandler.ts ├── divPanelChild.tsx ├── divPanelEditChild.tsx ├── divPanelParent.tsx ├── editor.tsx ├── img │ ├── echarts-gl-gps.png │ ├── logo.png │ └── screenshot1.png ├── module.test.ts ├── module.tsx ├── plugin.json ├── types.ts └── utils │ ├── functions.ts │ ├── handlebars.ts │ └── postscribe.d.ts ├── tsconfig.json ├── validator-config.yaml └── yarn.lock /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/srclosson/div-panel/a9165855699722fe67a3e9ef506801705942fe90/.DS_Store -------------------------------------------------------------------------------- /.config/.cprc.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "5.5.1" 3 | } 4 | -------------------------------------------------------------------------------- /.config/.eslintrc: -------------------------------------------------------------------------------- 1 | /* 2 | * ⚠️⚠️⚠️ THIS FILE WAS SCAFFOLDED BY `@grafana/create-plugin`. DO NOT EDIT THIS FILE DIRECTLY. ⚠️⚠️⚠️ 3 | * 4 | * In order to extend the configuration follow the steps in 5 | * https://grafana.com/developers/plugin-tools/get-started/set-up-development-environment#extend-the-eslint-config 6 | */ 7 | { 8 | "extends": ["@grafana/eslint-config"], 9 | "root": true, 10 | "rules": { 11 | "react/prop-types": "off" 12 | }, 13 | "overrides": [ 14 | { 15 | "plugins": ["deprecation"], 16 | "files": ["src/**/*.{ts,tsx}"], 17 | "rules": { 18 | "deprecation/deprecation": "warn" 19 | }, 20 | "parserOptions": { 21 | "project": "./tsconfig.json" 22 | } 23 | } 24 | ] 25 | } 26 | -------------------------------------------------------------------------------- /.config/.prettierrc.js: -------------------------------------------------------------------------------- 1 | /* 2 | * ⚠️⚠️⚠️ THIS FILE WAS SCAFFOLDED BY `@grafana/create-plugin`. DO NOT EDIT THIS FILE DIRECTLY. ⚠️⚠️⚠️ 3 | * 4 | * In order to extend the configuration follow the steps in .config/README.md 5 | */ 6 | 7 | module.exports = { 8 | endOfLine: 'auto', 9 | printWidth: 120, 10 | trailingComma: 'es5', 11 | semi: true, 12 | jsxSingleQuote: false, 13 | singleQuote: true, 14 | useTabs: false, 15 | tabWidth: 2, 16 | }; 17 | -------------------------------------------------------------------------------- /.config/Dockerfile: -------------------------------------------------------------------------------- 1 | ARG grafana_version=latest 2 | ARG grafana_image=grafana-enterprise 3 | 4 | FROM grafana/${grafana_image}:${grafana_version} 5 | 6 | ARG development=false 7 | ARG TARGETARCH 8 | 9 | 10 | ENV DEV "${development}" 11 | 12 | # Make it as simple as possible to access the grafana instance for development purposes 13 | # Do NOT enable these settings in a public facing / production grafana instance 14 | ENV GF_AUTH_ANONYMOUS_ORG_ROLE "Admin" 15 | ENV GF_AUTH_ANONYMOUS_ENABLED "true" 16 | ENV GF_AUTH_BASIC_ENABLED "false" 17 | # Set development mode so plugins can be loaded without the need to sign 18 | ENV GF_DEFAULT_APP_MODE "development" 19 | 20 | 21 | LABEL maintainer="Grafana Labs " 22 | 23 | ENV GF_PATHS_HOME="/usr/share/grafana" 24 | WORKDIR $GF_PATHS_HOME 25 | 26 | USER root 27 | 28 | # Installing supervisor and inotify-tools 29 | RUN if [ "${development}" = "true" ]; then \ 30 | if grep -i -q alpine /etc/issue; then \ 31 | apk add supervisor inotify-tools git; \ 32 | elif grep -i -q ubuntu /etc/issue; then \ 33 | DEBIAN_FRONTEND=noninteractive && \ 34 | apt-get update && \ 35 | apt-get install -y supervisor inotify-tools git && \ 36 | rm -rf /var/lib/apt/lists/*; \ 37 | else \ 38 | echo 'ERROR: Unsupported base image' && /bin/false; \ 39 | fi \ 40 | fi 41 | 42 | COPY supervisord/supervisord.conf /etc/supervisor.d/supervisord.ini 43 | COPY supervisord/supervisord.conf /etc/supervisor/conf.d/supervisord.conf 44 | 45 | 46 | 47 | # Inject livereload script into grafana index.html 48 | RUN sed -i 's|||g' /usr/share/grafana/public/views/index.html 49 | 50 | 51 | COPY entrypoint.sh /entrypoint.sh 52 | RUN chmod +x /entrypoint.sh 53 | ENTRYPOINT ["/entrypoint.sh"] 54 | -------------------------------------------------------------------------------- /.config/README.md: -------------------------------------------------------------------------------- 1 | # Default build configuration by Grafana 2 | 3 | **This is an auto-generated directory and is not intended to be changed! ⚠️** 4 | 5 | The `.config/` directory holds basic configuration for the different tools 6 | that are used to develop, test and build the project. In order to make it updates easier we ask you to 7 | not edit files in this folder to extend configuration. 8 | 9 | ## How to extend the basic configs? 10 | 11 | Bear in mind that you are doing it at your own risk, and that extending any of the basic configuration can lead 12 | to issues around working with the project. 13 | 14 | ### Extending the ESLint config 15 | 16 | Edit the `.eslintrc` file in the project root in order to extend the ESLint configuration. 17 | 18 | **Example:** 19 | 20 | ```json 21 | { 22 | "extends": "./.config/.eslintrc", 23 | "rules": { 24 | "react/prop-types": "off" 25 | } 26 | } 27 | ``` 28 | 29 | --- 30 | 31 | ### Extending the Prettier config 32 | 33 | Edit the `.prettierrc.js` file in the project root in order to extend the Prettier configuration. 34 | 35 | **Example:** 36 | 37 | ```javascript 38 | module.exports = { 39 | // Prettier configuration provided by Grafana scaffolding 40 | ...require('./.config/.prettierrc.js'), 41 | 42 | semi: false, 43 | }; 44 | ``` 45 | 46 | --- 47 | 48 | ### Extending the Jest config 49 | 50 | There are two configuration in the project root that belong to Jest: `jest-setup.js` and `jest.config.js`. 51 | 52 | **`jest-setup.js`:** A file that is run before each test file in the suite is executed. We are using it to 53 | 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)) 54 | 55 | **`jest.config.js`:** The main Jest configuration file that extends the Grafana recommended setup. ([link to Jest docs](https://jestjs.io/docs/configuration)) 56 | 57 | #### ESM errors with Jest 58 | 59 | A common issue with the current jest config involves importing an npm package that only offers an ESM build. These packages cause jest to error with `SyntaxError: Cannot use import statement outside a module`. To work around this, we provide a list of known packages to pass to the `[transformIgnorePatterns](https://jestjs.io/docs/configuration#transformignorepatterns-arraystring)` jest configuration property. If need be, this can be extended in the following way: 60 | 61 | ```javascript 62 | process.env.TZ = 'UTC'; 63 | const { grafanaESModules, nodeModulesToTransform } = require('./config/jest/utils'); 64 | 65 | module.exports = { 66 | // Jest configuration provided by Grafana 67 | ...require('./.config/jest.config'), 68 | // Inform jest to only transform specific node_module packages. 69 | transformIgnorePatterns: [nodeModulesToTransform([...grafanaESModules, 'packageName'])], 70 | }; 71 | ``` 72 | 73 | --- 74 | 75 | ### Extending the TypeScript config 76 | 77 | Edit the `tsconfig.json` file in the project root in order to extend the TypeScript configuration. 78 | 79 | **Example:** 80 | 81 | ```json 82 | { 83 | "extends": "./.config/tsconfig.json", 84 | "compilerOptions": { 85 | "preserveConstEnums": true 86 | } 87 | } 88 | ``` 89 | 90 | --- 91 | 92 | ### Extending the Webpack config 93 | 94 | Follow these steps to extend the basic Webpack configuration that lives under `.config/`: 95 | 96 | #### 1. Create a new Webpack configuration file 97 | 98 | Create a new config file that is going to extend the basic one provided by Grafana. 99 | It can live in the project root, e.g. `webpack.config.ts`. 100 | 101 | #### 2. Merge the basic config provided by Grafana and your custom setup 102 | 103 | We are going to use [`webpack-merge`](https://github.com/survivejs/webpack-merge) for this. 104 | 105 | ```typescript 106 | // webpack.config.ts 107 | import type { Configuration } from 'webpack'; 108 | import { merge } from 'webpack-merge'; 109 | import grafanaConfig from './.config/webpack/webpack.config'; 110 | 111 | const config = async (env): Promise => { 112 | const baseConfig = await grafanaConfig(env); 113 | 114 | return merge(baseConfig, { 115 | // Add custom config here... 116 | output: { 117 | asyncChunks: true, 118 | }, 119 | }); 120 | }; 121 | 122 | export default config; 123 | ``` 124 | 125 | #### 3. Update the `package.json` to use the new Webpack config 126 | 127 | We need to update the `scripts` in the `package.json` to use the extended Webpack configuration. 128 | 129 | **Update for `build`:** 130 | 131 | ```diff 132 | -"build": "webpack -c ./.config/webpack/webpack.config.ts --env production", 133 | +"build": "webpack -c ./webpack.config.ts --env production", 134 | ``` 135 | 136 | **Update for `dev`:** 137 | 138 | ```diff 139 | -"dev": "webpack -w -c ./.config/webpack/webpack.config.ts --env development", 140 | +"dev": "webpack -w -c ./webpack.config.ts --env development", 141 | ``` 142 | 143 | ### Configure grafana image to use when running docker 144 | 145 | By default, `grafana-enterprise` will be used as the docker image for all docker related commands. If you want to override this behavior, simply alter the `docker-compose.yaml` by adding the following build arg `grafana_image`. 146 | 147 | **Example:** 148 | 149 | ```yaml 150 | version: '3.7' 151 | 152 | services: 153 | grafana: 154 | container_name: 'myorg-basic-app' 155 | build: 156 | context: ./.config 157 | args: 158 | grafana_version: ${GRAFANA_VERSION:-9.1.2} 159 | grafana_image: ${GRAFANA_IMAGE:-grafana} 160 | ``` 161 | 162 | In this example, we assign the environment variable `GRAFANA_IMAGE` to the build arg `grafana_image` with a default value of `grafana`. This will allow you to set the value while running the docker compose commands, which might be convenient in some scenarios. 163 | 164 | --- 165 | -------------------------------------------------------------------------------- /.config/entrypoint.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | if [ "${DEV}" = "false" ]; then 4 | echo "Starting test mode" 5 | exec /run.sh 6 | fi 7 | 8 | echo "Starting development mode" 9 | 10 | if grep -i -q alpine /etc/issue; then 11 | exec /usr/bin/supervisord -c /etc/supervisord.conf 12 | elif grep -i -q ubuntu /etc/issue; then 13 | exec /usr/bin/supervisord -c /etc/supervisor/supervisord.conf 14 | else 15 | echo 'ERROR: Unsupported base image' 16 | exit 1 17 | fi 18 | 19 | -------------------------------------------------------------------------------- /.config/jest-setup.js: -------------------------------------------------------------------------------- 1 | /* 2 | * ⚠️⚠️⚠️ THIS FILE WAS SCAFFOLDED BY `@grafana/create-plugin`. DO NOT EDIT THIS FILE DIRECTLY. ⚠️⚠️⚠️ 3 | * 4 | * In order to extend the configuration follow the steps in 5 | * https://grafana.com/developers/plugin-tools/get-started/set-up-development-environment#extend-the-jest-config 6 | */ 7 | 8 | import '@testing-library/jest-dom'; 9 | import { TextEncoder, TextDecoder } from 'util'; 10 | 11 | Object.assign(global, { TextDecoder, TextEncoder }); 12 | 13 | // https://jestjs.io/docs/manual-mocks#mocking-methods-which-are-not-implemented-in-jsdom 14 | Object.defineProperty(global, 'matchMedia', { 15 | writable: true, 16 | value: (query) => ({ 17 | matches: false, 18 | media: query, 19 | onchange: null, 20 | addListener: jest.fn(), // deprecated 21 | removeListener: jest.fn(), // deprecated 22 | addEventListener: jest.fn(), 23 | removeEventListener: jest.fn(), 24 | dispatchEvent: jest.fn(), 25 | }), 26 | }); 27 | 28 | HTMLCanvasElement.prototype.getContext = () => {}; 29 | -------------------------------------------------------------------------------- /.config/jest.config.js: -------------------------------------------------------------------------------- 1 | /* 2 | * ⚠️⚠️⚠️ THIS FILE WAS SCAFFOLDED BY `@grafana/create-plugin`. DO NOT EDIT THIS FILE DIRECTLY. ⚠️⚠️⚠️ 3 | * 4 | * In order to extend the configuration follow the steps in 5 | * https://grafana.com/developers/plugin-tools/get-started/set-up-development-environment#extend-the-jest-config 6 | */ 7 | 8 | const path = require('path'); 9 | const { grafanaESModules, nodeModulesToTransform } = require('./jest/utils'); 10 | 11 | module.exports = { 12 | moduleNameMapper: { 13 | '\\.(css|scss|sass)$': 'identity-obj-proxy', 14 | 'react-inlinesvg': path.resolve(__dirname, 'jest', 'mocks', 'react-inlinesvg.tsx'), 15 | }, 16 | modulePaths: ['/src'], 17 | setupFilesAfterEnv: ['/jest-setup.js'], 18 | testEnvironment: 'jest-environment-jsdom', 19 | testMatch: [ 20 | '/src/**/__tests__/**/*.{js,jsx,ts,tsx}', 21 | '/src/**/*.{spec,test,jest}.{js,jsx,ts,tsx}', 22 | '/src/**/*.{spec,test,jest}.{js,jsx,ts,tsx}', 23 | ], 24 | transform: { 25 | '^.+\\.(t|j)sx?$': [ 26 | '@swc/jest', 27 | { 28 | sourceMaps: 'inline', 29 | jsc: { 30 | parser: { 31 | syntax: 'typescript', 32 | tsx: true, 33 | decorators: false, 34 | dynamicImport: true, 35 | }, 36 | }, 37 | }, 38 | ], 39 | }, 40 | // Jest will throw `Cannot use import statement outside module` if it tries to load an 41 | // ES module without it being transformed first. ./config/README.md#esm-errors-with-jest 42 | transformIgnorePatterns: [nodeModulesToTransform(grafanaESModules)], 43 | }; 44 | -------------------------------------------------------------------------------- /.config/jest/mocks/react-inlinesvg.tsx: -------------------------------------------------------------------------------- 1 | // Due to the grafana/ui Icon component making fetch requests to 2 | // `/public/img/icon/.svg` we need to mock react-inlinesvg to prevent 3 | // the failed fetch requests from displaying errors in console. 4 | 5 | import React from 'react'; 6 | 7 | type Callback = (...args: any[]) => void; 8 | 9 | export interface StorageItem { 10 | content: string; 11 | queue: Callback[]; 12 | status: string; 13 | } 14 | 15 | export const cacheStore: { [key: string]: StorageItem } = Object.create(null); 16 | 17 | const SVG_FILE_NAME_REGEX = /(.+)\/(.+)\.svg$/; 18 | 19 | const InlineSVG = ({ src }: { src: string }) => { 20 | // testId will be the file name without extension (e.g. `public/img/icons/angle-double-down.svg` -> `angle-double-down`) 21 | const testId = src.replace(SVG_FILE_NAME_REGEX, '$2'); 22 | return ; 23 | }; 24 | 25 | export default InlineSVG; 26 | -------------------------------------------------------------------------------- /.config/jest/utils.js: -------------------------------------------------------------------------------- 1 | /* 2 | * ⚠️⚠️⚠️ THIS FILE WAS SCAFFOLDED BY `@grafana/create-plugin`. DO NOT EDIT THIS FILE DIRECTLY. ⚠️⚠️⚠️ 3 | * 4 | * In order to extend the configuration follow the steps in .config/README.md 5 | */ 6 | 7 | /* 8 | * This utility function is useful in combination with jest `transformIgnorePatterns` config 9 | * to transform specific packages (e.g.ES modules) in a projects node_modules folder. 10 | */ 11 | const nodeModulesToTransform = (moduleNames) => `node_modules\/(?!.*(${moduleNames.join('|')})\/.*)`; 12 | 13 | // Array of known nested grafana package dependencies that only bundle an ESM version 14 | const grafanaESModules = [ 15 | '.pnpm', // Support using pnpm symlinked packages 16 | '@grafana/schema', 17 | 'd3', 18 | 'd3-color', 19 | 'd3-force', 20 | 'd3-interpolate', 21 | 'd3-scale-chromatic', 22 | 'ol', 23 | 'react-colorful', 24 | 'rxjs', 25 | 'uuid', 26 | ]; 27 | 28 | module.exports = { 29 | nodeModulesToTransform, 30 | grafanaESModules, 31 | }; 32 | -------------------------------------------------------------------------------- /.config/supervisord/supervisord.conf: -------------------------------------------------------------------------------- 1 | [supervisord] 2 | nodaemon=true 3 | user=root 4 | 5 | [program:grafana] 6 | user=root 7 | directory=/var/lib/grafana 8 | command=/run.sh 9 | stdout_logfile=/dev/fd/1 10 | stdout_logfile_maxbytes=0 11 | redirect_stderr=true 12 | killasgroup=true 13 | stopasgroup=true 14 | autostart=true 15 | 16 | -------------------------------------------------------------------------------- /.config/tsconfig.json: -------------------------------------------------------------------------------- 1 | /* 2 | * ⚠️⚠️⚠️ THIS FILE WAS SCAFFOLDED BY `@grafana/create-plugin`. DO NOT EDIT THIS FILE DIRECTLY. ⚠️⚠️⚠️ 3 | * 4 | * In order to extend the configuration follow the steps in 5 | * https://grafana.com/developers/plugin-tools/get-started/set-up-development-environment#extend-the-typescript-config 6 | */ 7 | { 8 | "compilerOptions": { 9 | "alwaysStrict": true, 10 | "declaration": false, 11 | "rootDir": "../src", 12 | "baseUrl": "../src", 13 | "typeRoots": ["../node_modules/@types"], 14 | "resolveJsonModule": true 15 | }, 16 | "ts-node": { 17 | "compilerOptions": { 18 | "module": "commonjs", 19 | "target": "es5", 20 | "esModuleInterop": true 21 | }, 22 | "transpileOnly": true 23 | }, 24 | "include": ["../src", "./types"], 25 | "extends": "@grafana/tsconfig" 26 | } 27 | -------------------------------------------------------------------------------- /.config/types/custom.d.ts: -------------------------------------------------------------------------------- 1 | // Image declarations 2 | declare module '*.gif' { 3 | const src: string; 4 | export default src; 5 | } 6 | 7 | declare module '*.jpg' { 8 | const src: string; 9 | export default src; 10 | } 11 | 12 | declare module '*.jpeg' { 13 | const src: string; 14 | export default src; 15 | } 16 | 17 | declare module '*.png' { 18 | const src: string; 19 | export default src; 20 | } 21 | 22 | declare module '*.webp' { 23 | const src: string; 24 | export default src; 25 | } 26 | 27 | declare module '*.svg' { 28 | const content: string; 29 | export default content; 30 | } 31 | 32 | // Font declarations 33 | declare module '*.woff'; 34 | declare module '*.woff2'; 35 | declare module '*.eot'; 36 | declare module '*.ttf'; 37 | declare module '*.otf'; 38 | -------------------------------------------------------------------------------- /.config/webpack/constants.ts: -------------------------------------------------------------------------------- 1 | export const SOURCE_DIR = 'src'; 2 | export const DIST_DIR = 'dist'; 3 | -------------------------------------------------------------------------------- /.config/webpack/utils.ts: -------------------------------------------------------------------------------- 1 | import fs from 'fs'; 2 | import process from 'process'; 3 | import os from 'os'; 4 | import path from 'path'; 5 | import { glob } from 'glob'; 6 | import { SOURCE_DIR } from './constants'; 7 | 8 | export function isWSL() { 9 | if (process.platform !== 'linux') { 10 | return false; 11 | } 12 | 13 | if (os.release().toLowerCase().includes('microsoft')) { 14 | return true; 15 | } 16 | 17 | try { 18 | return fs.readFileSync('/proc/version', 'utf8').toLowerCase().includes('microsoft'); 19 | } catch { 20 | return false; 21 | } 22 | } 23 | 24 | export function getPackageJson() { 25 | return require(path.resolve(process.cwd(), 'package.json')); 26 | } 27 | 28 | export function getPluginJson() { 29 | return require(path.resolve(process.cwd(), `${SOURCE_DIR}/plugin.json`)); 30 | } 31 | 32 | export function getCPConfigVersion() { 33 | const cprcJson = path.resolve(__dirname, '../', '.cprc.json'); 34 | return fs.existsSync(cprcJson) ? require(cprcJson).version : { version: 'unknown' }; 35 | } 36 | 37 | export function hasReadme() { 38 | return fs.existsSync(path.resolve(process.cwd(), SOURCE_DIR, 'README.md')); 39 | } 40 | 41 | // Support bundling nested plugins by finding all plugin.json files in src directory 42 | // then checking for a sibling module.[jt]sx? file. 43 | export async function getEntries(): Promise> { 44 | const pluginsJson = await glob('**/src/**/plugin.json', { absolute: true }); 45 | 46 | const plugins = await Promise.all( 47 | pluginsJson.map((pluginJson) => { 48 | const folder = path.dirname(pluginJson); 49 | return glob(`${folder}/module.{ts,tsx,js,jsx}`, { absolute: true }); 50 | }) 51 | ); 52 | 53 | return plugins.reduce((result, modules) => { 54 | return modules.reduce((result, module) => { 55 | const pluginPath = path.dirname(module); 56 | const pluginName = path.relative(process.cwd(), pluginPath).replace(/src\/?/i, ''); 57 | const entryName = pluginName === '' ? 'module' : `${pluginName}/module`; 58 | 59 | result[entryName] = module; 60 | return result; 61 | }, result); 62 | }, {}); 63 | } 64 | -------------------------------------------------------------------------------- /.config/webpack/webpack.config.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * ⚠️⚠️⚠️ THIS FILE WAS SCAFFOLDED BY `@grafana/create-plugin`. DO NOT EDIT THIS FILE DIRECTLY. ⚠️⚠️⚠️ 3 | * 4 | * In order to extend the configuration follow the steps in 5 | * https://grafana.com/developers/plugin-tools/get-started/set-up-development-environment#extend-the-webpack-config 6 | */ 7 | 8 | import CopyWebpackPlugin from 'copy-webpack-plugin'; 9 | import ESLintPlugin from 'eslint-webpack-plugin'; 10 | import ForkTsCheckerWebpackPlugin from 'fork-ts-checker-webpack-plugin'; 11 | import path from 'path'; 12 | import ReplaceInFileWebpackPlugin from 'replace-in-file-webpack-plugin'; 13 | import TerserPlugin from 'terser-webpack-plugin'; 14 | import { SubresourceIntegrityPlugin } from "webpack-subresource-integrity"; 15 | import { type Configuration, BannerPlugin } from 'webpack'; 16 | import LiveReloadPlugin from 'webpack-livereload-plugin'; 17 | import VirtualModulesPlugin from 'webpack-virtual-modules'; 18 | 19 | import { DIST_DIR, SOURCE_DIR } from './constants'; 20 | import { getCPConfigVersion, getEntries, getPackageJson, getPluginJson, hasReadme, isWSL } from './utils'; 21 | 22 | const pluginJson = getPluginJson(); 23 | const cpVersion = getCPConfigVersion(); 24 | 25 | const virtualPublicPath = new VirtualModulesPlugin({ 26 | 'node_modules/grafana-public-path.js': ` 27 | import amdMetaModule from 'amd-module'; 28 | 29 | __webpack_public_path__ = 30 | amdMetaModule && amdMetaModule.uri 31 | ? amdMetaModule.uri.slice(0, amdMetaModule.uri.lastIndexOf('/') + 1) 32 | : 'public/plugins/${pluginJson.id}/'; 33 | `, 34 | }); 35 | 36 | const config = async (env): Promise => { 37 | const baseConfig: Configuration = { 38 | cache: { 39 | type: 'filesystem', 40 | buildDependencies: { 41 | config: [__filename], 42 | }, 43 | }, 44 | 45 | context: path.join(process.cwd(), SOURCE_DIR), 46 | 47 | devtool: env.production ? 'source-map' : 'eval-source-map', 48 | 49 | entry: await getEntries(), 50 | 51 | externals: [ 52 | // Required for dynamic publicPath resolution 53 | { 'amd-module': 'module' }, 54 | 'lodash', 55 | 'jquery', 56 | 'moment', 57 | 'slate', 58 | 'emotion', 59 | '@emotion/react', 60 | '@emotion/css', 61 | 'prismjs', 62 | 'slate-plain-serializer', 63 | '@grafana/slate-react', 64 | 'react', 65 | 'react-dom', 66 | 'react-redux', 67 | 'redux', 68 | 'rxjs', 69 | 'react-router', 70 | 'react-router-dom', 71 | 'd3', 72 | 'angular', 73 | '@grafana/ui', 74 | '@grafana/runtime', 75 | '@grafana/data', 76 | 77 | // Mark legacy SDK imports as external if their name starts with the "grafana/" prefix 78 | ({ request }, callback) => { 79 | const prefix = 'grafana/'; 80 | const hasPrefix = (request) => request.indexOf(prefix) === 0; 81 | const stripPrefix = (request) => request.substr(prefix.length); 82 | 83 | if (hasPrefix(request)) { 84 | return callback(undefined, stripPrefix(request)); 85 | } 86 | 87 | callback(); 88 | }, 89 | ], 90 | 91 | // Support WebAssembly according to latest spec - makes WebAssembly module async 92 | experiments: { 93 | asyncWebAssembly: true, 94 | }, 95 | 96 | mode: env.production ? 'production' : 'development', 97 | 98 | module: { 99 | rules: [ 100 | // This must come first in the rules array otherwise it breaks sourcemaps. 101 | { 102 | test: /src\/(?:.*\/)?module\.tsx?$/, 103 | use: [ 104 | { 105 | loader: 'imports-loader', 106 | options: { 107 | imports: `side-effects grafana-public-path`, 108 | }, 109 | }, 110 | ], 111 | }, 112 | { 113 | exclude: /(node_modules)/, 114 | test: /\.[tj]sx?$/, 115 | use: { 116 | loader: 'swc-loader', 117 | options: { 118 | jsc: { 119 | baseUrl: path.resolve(process.cwd(), SOURCE_DIR), 120 | target: 'es2015', 121 | loose: false, 122 | parser: { 123 | syntax: 'typescript', 124 | tsx: true, 125 | decorators: false, 126 | dynamicImport: true, 127 | }, 128 | }, 129 | }, 130 | }, 131 | }, 132 | { 133 | test: /\.css$/, 134 | use: ['style-loader', 'css-loader'], 135 | }, 136 | { 137 | test: /\.s[ac]ss$/, 138 | use: ['style-loader', 'css-loader', 'sass-loader'], 139 | }, 140 | { 141 | test: /\.(png|jpe?g|gif|svg)$/, 142 | type: 'asset/resource', 143 | generator: { 144 | filename: Boolean(env.production) ? '[hash][ext]' : '[file]', 145 | }, 146 | }, 147 | { 148 | test: /\.(woff|woff2|eot|ttf|otf)(\?v=\d+\.\d+\.\d+)?$/, 149 | type: 'asset/resource', 150 | generator: { 151 | filename: Boolean(env.production) ? '[hash][ext]' : '[file]', 152 | }, 153 | }, 154 | ], 155 | }, 156 | 157 | optimization: { 158 | minimize: Boolean(env.production), 159 | minimizer: [ 160 | new TerserPlugin({ 161 | terserOptions: { 162 | format: { 163 | comments: (_, { type, value }) => type === 'comment2' && value.trim().startsWith('[create-plugin]'), 164 | }, 165 | compress: { 166 | drop_console: ['log', 'info'] 167 | } 168 | }, 169 | }), 170 | ], 171 | }, 172 | 173 | output: { 174 | clean: { 175 | keep: new RegExp(`(.*?_(amd64|arm(64)?)(.exe)?|go_plugin_build_manifest)`), 176 | }, 177 | filename: '[name].js', 178 | library: { 179 | type: 'amd', 180 | }, 181 | path: path.resolve(process.cwd(), DIST_DIR), 182 | publicPath: `public/plugins/${pluginJson.id}/`, 183 | uniqueName: pluginJson.id, 184 | crossOriginLoading: 'anonymous', 185 | }, 186 | 187 | plugins: [ 188 | virtualPublicPath, 189 | // Insert create plugin version information into the bundle 190 | new BannerPlugin({ 191 | banner: "/* [create-plugin] version: " + cpVersion + " */", 192 | raw: true, 193 | entryOnly: true, 194 | }), 195 | new CopyWebpackPlugin({ 196 | patterns: [ 197 | // If src/README.md exists use it; otherwise the root README 198 | // To `compiler.options.output` 199 | { from: hasReadme() ? 'README.md' : '../README.md', to: '.', force: true }, 200 | { from: 'plugin.json', to: '.' }, 201 | { from: '../LICENSE', to: '.' }, 202 | { from: '../CHANGELOG.md', to: '.', force: true }, 203 | { from: '**/*.json', to: '.' }, // TODO 204 | { from: '**/*.svg', to: '.', noErrorOnMissing: true }, // Optional 205 | { from: '**/*.png', to: '.', noErrorOnMissing: true }, // Optional 206 | { from: '**/*.html', to: '.', noErrorOnMissing: true }, // Optional 207 | { from: 'img/**/*', to: '.', noErrorOnMissing: true }, // Optional 208 | { from: 'libs/**/*', to: '.', noErrorOnMissing: true }, // Optional 209 | { from: 'static/**/*', to: '.', noErrorOnMissing: true }, // Optional 210 | { from: '**/query_help.md', to: '.', noErrorOnMissing: true }, // Optional 211 | ], 212 | }), 213 | // Replace certain template-variables in the README and plugin.json 214 | new ReplaceInFileWebpackPlugin([ 215 | { 216 | dir: DIST_DIR, 217 | files: ['plugin.json', 'README.md'], 218 | rules: [ 219 | { 220 | search: /\%VERSION\%/g, 221 | replace: getPackageJson().version, 222 | }, 223 | { 224 | search: /\%TODAY\%/g, 225 | replace: new Date().toISOString().substring(0, 10), 226 | }, 227 | { 228 | search: /\%PLUGIN_ID\%/g, 229 | replace: pluginJson.id, 230 | }, 231 | ], 232 | }, 233 | ]), 234 | new SubresourceIntegrityPlugin({ 235 | hashFuncNames: ["sha256"], 236 | }), 237 | ...(env.development ? [ 238 | new LiveReloadPlugin(), 239 | new ForkTsCheckerWebpackPlugin({ 240 | async: Boolean(env.development), 241 | issue: { 242 | include: [{ file: '**/*.{ts,tsx}' }], 243 | }, 244 | typescript: { configFile: path.join(process.cwd(), 'tsconfig.json') }, 245 | }), 246 | new ESLintPlugin({ 247 | extensions: ['.ts', '.tsx'], 248 | lintDirtyModulesOnly: Boolean(env.development), // don't lint on start, only lint changed files 249 | }), 250 | ] : []), 251 | ], 252 | 253 | resolve: { 254 | extensions: ['.js', '.jsx', '.ts', '.tsx'], 255 | // handle resolving "rootDir" paths 256 | modules: [path.resolve(process.cwd(), 'src'), 'node_modules'], 257 | unsafeCache: true, 258 | }, 259 | }; 260 | 261 | if (isWSL()) { 262 | baseConfig.watchOptions = { 263 | poll: 3000, 264 | ignored: /node_modules/, 265 | }; 266 | } 267 | 268 | return baseConfig; 269 | }; 270 | 271 | export default config; 272 | -------------------------------------------------------------------------------- /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./.config/.eslintrc" 3 | } 4 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | pull_request: 8 | branches: 9 | - main 10 | jobs: 11 | build: 12 | runs-on: ubuntu-latest 13 | steps: 14 | - uses: actions/checkout@v2 15 | 16 | - name: Setup Node.js environment 17 | uses: actions/setup-node@v2.1.2 18 | with: 19 | node-version: "20.x" 20 | 21 | - name: Get yarn cache directory path 22 | id: yarn-cache-dir-path 23 | run: echo "::set-output name=dir::$(yarn cache dir)" 24 | 25 | - name: Cache yarn cache 26 | uses: actions/cache@v2 27 | id: cache-yarn-cache 28 | with: 29 | path: ${{ steps.yarn-cache-dir-path.outputs.dir }} 30 | key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }} 31 | restore-keys: | 32 | ${{ runner.os }}-yarn- 33 | 34 | - name: Cache node_modules 35 | id: cache-node-modules 36 | uses: actions/cache@v2 37 | with: 38 | path: node_modules 39 | key: ${{ runner.os }}-${{ matrix.node-version }}-nodemodules-${{ hashFiles('**/yarn.lock') }} 40 | restore-keys: | 41 | ${{ runner.os }}-${{ matrix.node-version }}-nodemodules- 42 | 43 | - name: Install dependencies 44 | run: yarn install --frozen-lockfile 45 | 46 | - name: Build and test frontend 47 | run: yarn build 48 | 49 | - name: Check for backend 50 | id: check-for-backend 51 | run: | 52 | if [ -f "Magefile.go" ] 53 | then 54 | echo "::set-output name=has-backend::true" 55 | fi 56 | 57 | - name: Setup Go environment 58 | if: steps.check-for-backend.outputs.has-backend == 'true' 59 | uses: actions/setup-go@v2 60 | with: 61 | go-version: "1.22.6" 62 | 63 | - name: Test backend 64 | if: steps.check-for-backend.outputs.has-backend == 'true' 65 | uses: magefile/mage-action@v1 66 | with: 67 | version: latest 68 | args: coverage 69 | 70 | - name: Build backend 71 | if: steps.check-for-backend.outputs.has-backend == 'true' 72 | uses: magefile/mage-action@v1 73 | with: 74 | version: latest 75 | args: buildAll 76 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | {{!-- /* 🚨 The `$\{{ }}` Github workflow expressions need to be escaped so they are not being interpreted by Handlebars. (this comment is going to be removed after scaffolding) 🚨 */ --}} 2 | # This GitHub Action automates the process of building Grafana plugins. 3 | # (For more information, see https://github.com/grafana/plugin-actions/blob/main/build-plugin/README.md) 4 | name: Release 5 | 6 | on: 7 | push: 8 | tags: 9 | - 'v*' # Run workflow on version tags, e.g. v1.0.0. 10 | 11 | permissions: read-all 12 | 13 | jobs: 14 | release: 15 | permissions: 16 | contents: write 17 | runs-on: ubuntu-latest 18 | steps: 19 | - uses: actions/checkout@v4 20 | - uses: grafana/plugin-actions/build-plugin@release 21 | # Uncomment to enable plugin signing 22 | # (For more info on how to generate the access policy token see https://grafana.com/developers/plugin-tools/publish-a-plugin/sign-a-plugin#generate-an-access-policy-token) 23 | #with: 24 | # Make sure to save the token in your repository secrets 25 | #policy_token: ${{ secrets.GRAFANA_ACCESS_POLICY_TOKEN }} 26 | # Usage of GRAFANA_API_KEY is deprecated, prefer `policy_token` option above 27 | #grafana_token: ${{ secrets.GRAFANA_API_KEY }} -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | 8 | node_modules/ 9 | 10 | # Runtime data 11 | pids 12 | *.pid 13 | *.seed 14 | *.pid.lock 15 | 16 | # Directory for instrumented libs generated by jscoverage/JSCover 17 | lib-cov 18 | 19 | # Coverage directory used by tools like istanbul 20 | coverage 21 | 22 | # Compiled binary addons (https://nodejs.org/api/addons.html) 23 | dist/ 24 | artifacts/ 25 | work/ 26 | ci/ 27 | e2e-results/ 28 | 29 | -------------------------------------------------------------------------------- /.nvmrc: -------------------------------------------------------------------------------- 1 | 20 2 | -------------------------------------------------------------------------------- /.prettierrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | // Prettier configuration provided by Grafana scaffolding 3 | ...require('./.config/.prettierrc.js'), 4 | }; 5 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/srclosson/div-panel/a9165855699722fe67a3e9ef506801705942fe90/CHANGELOG.md -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Grafana DIV Panel 2 | 3 | ![](https://raw.githubusercontent.com/srclosson/grafana-div-panel/master/src/img/screenshot1.png) 4 | ![](https://raw.githubusercontent.com/srclosson/grafana-div-panel/master/src/img/echarts-gl-gps.png) 5 | 6 | The div panel is a generic panel allowing you to specify your own html and javascript 7 | Just write your html the same way you normally would: 8 | 9 | ``` 10 | 11 | 12 | 16 | 17 | 18 |
19 | Hello Div Panel 20 |
21 | 22 | 57 | 58 | 59 | ``` 60 | 61 | Alternatively, you can use `script` tags and specify a `run` type. The same script above then would be: 62 | ``` 63 | 64 | 65 | 69 | 70 | 71 |
72 | Hello Div Panel 73 |
74 | 75 | 78 | 79 | 80 | console.log("I entered edit mode", elem, content); 81 | 82 | 83 | 92 | 93 | 96 | 97 | 98 | ``` 99 | 100 | It differs from other "DIY" panels in that it tries to allow as close as possible, the ability to load and use javascript 101 | libraries exactly as you would if you were developing an html page without grafana. Just open the embedded code editor (monaco) 102 | and write your code. 103 | 104 | ## Features 105 | 1. Builtin monaco code editor 106 | 2. Support for handlebars templates. If you log your data from the `onDivPanelDataUpdate` callback, you can use handlebars addressing to reference the data. Your templates will be resolved when the panel renders. 107 | 3. Support for script type="module". 108 | 109 | ## Development workflow 110 | 1. Write the code in the code editor. 111 | 2. Hit `run` to run a data update 112 | 3. Hit `clear` to clear the the rendered HTML+Javascript. When you hit run the next time, you will also get your `onDivPanelInit` callback. 113 | *Important* You must hit `` in the editor to save. When saving, your control will be re-rendered. 114 | 115 | ## Callbacks 116 | There are four callbacks provided. 117 | 1. `onDivPanelInit`: Called when your panel is contructed and your html is available. 118 | 2. `onDivPanelDataUpdate`: Called with the data retrieved from the datasource. 119 | 3. `onDivPanelEnterEditMode`: Called whenever you enter edit mode. 120 | 4. `onDivPanelExitEditMode`: Called whenever you exit edit mode. 121 | 122 | ## Building 123 | To build: 124 | 1. Clone this repo 125 | 2. `yarn install` 126 | 3. `yarn dev` (for a dev build) or `yarn build` (for a prod build that is minified) 127 | 4. Restart grafana 128 | 129 | ## Examples 130 | See the examples in the examples folder 131 | 132 | 133 | -------------------------------------------------------------------------------- /appveyor.yml: -------------------------------------------------------------------------------- 1 | # Test against the latest version of this Node.js version 2 | environment: 3 | nodejs_version: "10" 4 | 5 | # Local NPM Modules 6 | cache: 7 | - node_modules 8 | 9 | # Install scripts. (runs after repo cloning) 10 | install: 11 | # Get the latest stable version of Node.js or io.js 12 | - ps: Install-Product node $env:nodejs_version 13 | # install modules 14 | - npm install -g yarn --quiet 15 | - yarn install --pure-lockfile 16 | 17 | # Post-install test scripts. 18 | test_script: 19 | # Output useful info for debugging. 20 | - node --version 21 | - npm --version 22 | 23 | # Run the build 24 | build_script: 25 | - yarn dev # This will also run prettier! 26 | - yarn build # make sure both scripts work 27 | -------------------------------------------------------------------------------- /docker-compose.yaml: -------------------------------------------------------------------------------- 1 | services: 2 | grafana: 3 | user: root 4 | container_name: 'stephanieclosson-div-panel' 5 | 6 | build: 7 | context: ./.config 8 | args: 9 | grafana_image: ${GRAFANA_IMAGE:-grafana-enterprise} 10 | grafana_version: ${GRAFANA_VERSION:-11.2.2} 11 | development: ${DEVELOPMENT:-false} 12 | ports: 13 | - 3000:3000/tcp 14 | volumes: 15 | - ./dist:/var/lib/grafana/plugins/stephanieclosson-div-panel 16 | - ./provisioning:/etc/grafana/provisioning 17 | - .:/root/stephanieclosson-div-panel 18 | 19 | environment: 20 | NODE_ENV: development 21 | GF_LOG_FILTERS: plugin.stephanieclosson-div-panel:debug 22 | GF_LOG_LEVEL: debug 23 | GF_DATAPROXY_LOGGING: 1 24 | GF_PLUGINS_ALLOW_LOADING_UNSIGNED_PLUGINS: stephanieclosson-div-panel 25 | -------------------------------------------------------------------------------- /docs/README.md: -------------------------------------------------------------------------------- 1 | TODO: add example docs structure 2 | -------------------------------------------------------------------------------- /examples/ckeditor.html: -------------------------------------------------------------------------------- 1 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 44 | 45 | -------------------------------------------------------------------------------- /examples/echarts-gl.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 134 | 135 | -------------------------------------------------------------------------------- /examples/leaflet-strava.html: -------------------------------------------------------------------------------- 1 | 4 | 5 | 6 | 7 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 54 | 55 | -------------------------------------------------------------------------------- /examples/threejs-little-tokyo.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | three.js webgl - animation - keyframes 5 | 6 | 7 | 8 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 25 | 99 | 100 | -------------------------------------------------------------------------------- /jest-setup.js: -------------------------------------------------------------------------------- 1 | // Jest setup provided by Grafana scaffolding 2 | import './.config/jest-setup'; 3 | -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | // force timezone to UTC to allow tests to work regardless of local timezone 2 | // generally used by snapshots, but can affect specific tests 3 | process.env.TZ = 'UTC'; 4 | 5 | module.exports = { 6 | // Jest configuration provided by Grafana scaffolding 7 | ...require('./.config/jest.config'), 8 | }; 9 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "stephanieclosson-div-panel", 3 | "version": "1.2.3", 4 | "description": "Create your own panel with html + css and javascript", 5 | "scripts": { 6 | "build": "webpack -c ./.config/webpack/webpack.config.ts --env production", 7 | "dev": "webpack -w -c ./.config/webpack/webpack.config.ts --env development", 8 | "e2e": "yarn exec cypress install && yarn exec grafana-e2e run", 9 | "e2e:update": "yarn exec cypress install && yarn exec grafana-e2e run --update-screenshots", 10 | "lint": "eslint --cache --ignore-path ./.gitignore --ext .js,.jsx,.ts,.tsx .", 11 | "lint:fix": "yarn run lint --fix", 12 | "server": "docker compose up --build", 13 | "sign": "npx --yes @grafana/sign-plugin@latest", 14 | "test": "jest --watch --onlyChanged", 15 | "test:ci": "jest --passWithNoTests --maxWorkers 4", 16 | "typecheck": "tsc --noEmit" 17 | }, 18 | "author": "srclosson@gmail.com", 19 | "license": "Apache-2.0", 20 | "devDependencies": { 21 | "@babel/core": "^7.21.4", 22 | "@cypress/request": "3.0.5", 23 | "@grafana/e2e": "11.0.6", 24 | "@grafana/e2e-selectors": "11.2.2", 25 | "@grafana/eslint-config": "^7.0.0", 26 | "@grafana/tsconfig": "^2.0.0", 27 | "@swc/core": "^1.3.90", 28 | "@swc/helpers": "^0.5.0", 29 | "@swc/jest": "^0.2.26", 30 | "@testing-library/jest-dom": "6.1.4", 31 | "@testing-library/react": "14.0.0", 32 | "@types/jest": "^29.5.0", 33 | "@types/lodash": "4.17.10", 34 | "@types/node": "^20.8.7", 35 | "@types/prop-types": "15.7.13", 36 | "@types/react": "18.3.11", 37 | "@types/react-router-dom": "^5.2.0", 38 | "@types/testing-library__jest-dom": "5.14.8", 39 | "@types/underscore": "1.11.15", 40 | "acorn": "8.12.1", 41 | "console-feed": "3.6.0", 42 | "copy-webpack-plugin": "^11.0.0", 43 | "css-loader": "^6.7.3", 44 | "debug": "4.3.7", 45 | "eslint-plugin-deprecation": "^2.0.0", 46 | "eslint-webpack-plugin": "^4.0.1", 47 | "fork-ts-checker-webpack-plugin": "^8.0.0", 48 | "glob": "^10.2.7", 49 | "handlebars": "4.7.8", 50 | "identity-obj-proxy": "3.0.0", 51 | "imports-loader": "^5.0.0", 52 | "jest": "^29.5.0", 53 | "jest-environment-jsdom": "^29.5.0", 54 | "jquery": "3.7.1", 55 | "kind-of": "6.0.3", 56 | "lodash": "4.17.21", 57 | "log4js": "6.9.1", 58 | "minimist": "1.2.8", 59 | "postscribe": "2.0.8", 60 | "prettier": "^2.8.7", 61 | "prop-types": "15.8.1", 62 | "react": "18.3.1", 63 | "replace-in-file-webpack-plugin": "^1.0.6", 64 | "sass": "1.63.2", 65 | "sass-loader": "13.3.1", 66 | "style-loader": "3.3.3", 67 | "swc-loader": "^0.2.3", 68 | "terser-webpack-plugin": "^5.3.10", 69 | "ts-node": "^10.9.2", 70 | "tsconfig-paths": "^4.2.0", 71 | "typescript": "5.5.4", 72 | "underscore": "1.13.7", 73 | "webpack": "^5.94.0", 74 | "webpack-cli": "^5.1.4", 75 | "webpack-livereload-plugin": "^3.0.2", 76 | "webpack-subresource-integrity": "^5.1.0", 77 | "webpack-virtual-modules": "^0.6.2" 78 | }, 79 | "dependencies": { 80 | "@emotion/css": "11.10.6", 81 | "@grafana/data": "11.2.2", 82 | "@grafana/runtime": "11.2.2", 83 | "@grafana/schema": "^10.4.0", 84 | "@grafana/ui": "11.2.2", 85 | "@types/jquery": "3.5.31", 86 | "@types/uuid": "10.0.0", 87 | "react": "18.2.0", 88 | "react-dom": "18.2.0", 89 | "tslib": "2.5.3", 90 | "uuid": "10.0.0" 91 | }, 92 | "packageManager": "yarn@1.22.19" 93 | } 94 | -------------------------------------------------------------------------------- /src/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/srclosson/div-panel/a9165855699722fe67a3e9ef506801705942fe90/src/.DS_Store -------------------------------------------------------------------------------- /src/changeHandler.ts: -------------------------------------------------------------------------------- 1 | import { PanelModel } from '@grafana/data'; 2 | import { DivPanelOptions } from './types'; 3 | 4 | export const divPanelChangedHandler = ( 5 | panel: PanelModel> | any, 6 | prevPluginId: string, 7 | prevOptions: any 8 | ): Partial => { 9 | return prevOptions; 10 | }; 11 | 12 | export const divPanelMigrationHandler = ( 13 | panel: PanelModel> | any 14 | ): Partial => { 15 | return panel.options; 16 | }; 17 | -------------------------------------------------------------------------------- /src/divPanelChild.tsx: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react'; 2 | import * as functions from 'utils/functions'; 3 | import { DivPanelChildProps, divStyle } from './types'; 4 | import { register, compile } from 'utils/handlebars'; 5 | import { isEqual } from 'underscore'; 6 | 7 | interface State { 8 | ref: HTMLDivElement | null; 9 | } 10 | 11 | export class DivPanelChild extends Component { 12 | constructor(props: DivPanelChildProps) { 13 | super(props); 14 | this.state = { 15 | ref: null, 16 | }; 17 | 18 | register(this.props.data); 19 | } 20 | 21 | shouldComponentUpdate = (prevProps: DivPanelChildProps, prevState: State): boolean => { 22 | const truth = 23 | isEqual(prevProps, this.props) || 24 | prevProps.data.state === 'Done' || 25 | prevProps.data.state === 'Streaming'; 26 | return truth; 27 | }; 28 | 29 | componentDidUpdate = async () => { 30 | const { ref } = this.state; 31 | this.panelUpdate(ref!); 32 | }; 33 | 34 | panelUpdate = async (elem: HTMLDivElement) => { 35 | const { data } = this.props; 36 | const { scripts } = this.props.parsed; 37 | const { series } = data; 38 | 39 | scripts.forEach((s: HTMLScriptElement) => { 40 | try { 41 | functions.run({ 42 | code: s, 43 | elem, 44 | data: series, 45 | }); 46 | } catch (err) { 47 | //const error = typeof err === 'object' ? err.stack : err; 48 | // onChange({ 49 | // ...options, 50 | // error, 51 | // }); 52 | } 53 | }); 54 | }; 55 | 56 | loadDependencies = async (elem: HTMLDivElement) => { 57 | const { imports, meta, modules, scripts } = this.props.parsed; 58 | const { data } = this.props; 59 | await functions.loadDependencies(elem, imports, meta); 60 | await Promise.all(modules.map((i) => functions.loadModule(i, data, elem))); 61 | await Promise.all(scripts.map((i) => functions.init(elem.children?.item(0)!, i))); 62 | await this.panelUpdate(elem); 63 | }; 64 | 65 | setRef = (element: HTMLDivElement | null) => { 66 | this.setState({ 67 | ref: element, 68 | }); 69 | if (element) { 70 | this.loadDependencies(element); 71 | } 72 | }; 73 | 74 | render() { 75 | const { html } = this.props.parsed; 76 | const { series } = this.props.data; 77 | 78 | return ( 79 | <> 80 |
85 | 86 | ); 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /src/divPanelEditChild.tsx: -------------------------------------------------------------------------------- 1 | import React, { useEffect, useCallback } from 'react'; 2 | import { DivPanelChildProps, divStyle } from './types'; 3 | import { register, compile } from 'utils/handlebars'; 4 | import * as functions from 'utils/functions'; 5 | 6 | interface Props extends DivPanelChildProps { 7 | editMode: boolean; 8 | changeEditContent: (html: string[]) => void; 9 | } 10 | 11 | export const DivPanelEditChild: React.FC = (props: Props) => { 12 | let element: HTMLDivElement | null = null; 13 | const { parsed, data, changeEditContent } = props; 14 | const { html } = parsed; 15 | const { series } = data; 16 | 17 | // const onOptionsChange = (key: string, value: boolean) => { 18 | // onChange({ 19 | // ...options, 20 | // [key]: value, 21 | // }); 22 | // }; 23 | 24 | const mount = useCallback(() => { 25 | register(data); 26 | }, [data]); 27 | 28 | const panelShutdown = (elem: HTMLDivElement) => { 29 | const { scripts } = parsed; 30 | const childElement: Element = elem.children.item(0)!; 31 | const editContent: string[] = scripts.map((i) => functions.runExitEditMode(childElement, i)); 32 | changeEditContent(editContent); 33 | }; 34 | 35 | const unmount = () => { 36 | panelShutdown(element!); 37 | }; 38 | 39 | const panelUpdate = useCallback((elem: HTMLDivElement) => { 40 | const { scripts } = parsed; 41 | const { series } = data; 42 | 43 | scripts.forEach((s: HTMLScriptElement) => { 44 | try { 45 | functions.run({ 46 | code: s, 47 | elem, 48 | data: series, 49 | }); 50 | } catch (err) { 51 | console.log("scripts.forEach error", err); 52 | } 53 | }); 54 | }, [data, parsed]); 55 | 56 | const loadDependencies = async (elem: HTMLDivElement) => { 57 | const { imports, meta, scripts } = parsed; 58 | const childElement: Element = elem.children.item(0)!; 59 | await functions.loadDependencies(elem, imports, meta); 60 | scripts.map((i) => functions.init(childElement, i)); 61 | scripts.map((i) => functions.runEnterEditMode(childElement, i)); 62 | await panelUpdate(elem); 63 | }; 64 | 65 | const setRef = (elem: HTMLDivElement | null) => { 66 | if (elem) { 67 | element = elem; 68 | loadDependencies(elem); 69 | } 70 | }; 71 | 72 | useEffect(() => { 73 | mount(); 74 | return () => { 75 | unmount(); 76 | }; 77 | }); 78 | 79 | return ( 80 | <> 81 |
82 | 83 | ); 84 | }; 85 | -------------------------------------------------------------------------------- /src/divPanelParent.tsx: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react'; 2 | import { DivPanelChild } from './divPanelChild'; 3 | import { DivPanelEditChild } from './divPanelEditChild'; 4 | import { DivPanelType, getDivPanelState, DivPanelOptions, defaults } from './types'; 5 | import { hasEditModeFunctions } from './utils/functions'; 6 | import { PanelProps } from '@grafana/data'; 7 | import { parseHtml } from 'utils/functions'; 8 | 9 | interface Props extends PanelProps {} 10 | 11 | export class DivPanelParent extends Component { 12 | constructor(props: Props) { 13 | super(props); 14 | } 15 | 16 | onChangeChild = (newOptions: DivPanelOptions) => { 17 | const { onOptionsChange, options } = this.props; 18 | 19 | onOptionsChange({ 20 | ...options, 21 | editor: newOptions, 22 | }); 23 | }; 24 | 25 | onChangeEditContent = (newEditContent: string[]) => { 26 | const { options } = this.props; 27 | 28 | this.onChangeChild({ 29 | ...options.editor, 30 | editContent: newEditContent, 31 | }); 32 | }; 33 | 34 | render() { 35 | const { data } = this.props; 36 | const { editor } = this.props.options; 37 | const { content, error } = editor || defaults; 38 | const { command, editMode } = getDivPanelState(); 39 | 40 | if (command === 'clear') { 41 | return
Clear and unmount complete
; 42 | } 43 | 44 | const parsed = parseHtml(content, error); 45 | if (editMode && hasEditModeFunctions(content)) { 46 | return ( 47 | 55 | ); 56 | } 57 | 58 | return ; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/editor.tsx: -------------------------------------------------------------------------------- 1 | import React, { useEffect, useCallback } from 'react'; 2 | import { StandardEditorProps } from '@grafana/data'; 3 | import { DivPanelOptions, defaultContent, getDivPanelState, setDivPanelState, defaults } from './types'; 4 | import { CodeEditor, Button } from '@grafana/ui'; 5 | //import { Console, Hook, Unhook } from 'console-feed'; 6 | 7 | export const DivMonacoEditor: React.FC> = ({ value, onChange }) => { 8 | const options = value || defaults; 9 | const content = options?.content || defaultContent; 10 | // const [logs, setLogs] = useState([]); 11 | // onChange({ 12 | // ...value, 13 | // editMode: true, 14 | // }); 15 | 16 | // run once! 17 | // useEffect((): any => { 18 | // const hookedConsole = Hook( 19 | // window.console, 20 | // (log: any) => setLogs((currLogs: Console[]): any => [...currLogs, log]), 21 | // false 22 | // ); 23 | // return () => Unhook(hookedConsole); 24 | // }, []); 25 | 26 | const commitContent = (content: string) => { 27 | onChange({ 28 | ...value, 29 | content, 30 | }); 31 | }; 32 | 33 | const onSave = (content: string) => { 34 | commitContent(content); 35 | }; 36 | 37 | const onClearClick = () => { 38 | setDivPanelState({ 39 | ...getDivPanelState(), 40 | command: 'clear', 41 | }); 42 | 43 | commitContent(content); 44 | }; 45 | 46 | const onRunClick = () => { 47 | setDivPanelState({ 48 | ...getDivPanelState(), 49 | command: 'render', 50 | }); 51 | commitContent(content); 52 | }; 53 | 54 | const onEditModeChange = useCallback((editMode: boolean) => { 55 | setDivPanelState({ 56 | ...getDivPanelState(), 57 | editMode, 58 | }); 59 | }, []); 60 | 61 | useEffect(() => { 62 | onEditModeChange(true); 63 | return () => { 64 | onEditModeChange(false); 65 | }; 66 | }); 67 | 68 | return ( 69 | <> 70 | 71 | 72 | 73 | {/* */} 74 | 75 | ); 76 | }; 77 | -------------------------------------------------------------------------------- /src/img/echarts-gl-gps.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/srclosson/div-panel/a9165855699722fe67a3e9ef506801705942fe90/src/img/echarts-gl-gps.png -------------------------------------------------------------------------------- /src/img/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/srclosson/div-panel/a9165855699722fe67a3e9ef506801705942fe90/src/img/logo.png -------------------------------------------------------------------------------- /src/img/screenshot1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/srclosson/div-panel/a9165855699722fe67a3e9ef506801705942fe90/src/img/screenshot1.png -------------------------------------------------------------------------------- /src/module.test.ts: -------------------------------------------------------------------------------- 1 | // Just a stub test 2 | describe('placeholder test', () => { 3 | it('should return true', () => { 4 | expect(true).toBeTruthy(); 5 | }); 6 | }); 7 | -------------------------------------------------------------------------------- /src/module.tsx: -------------------------------------------------------------------------------- 1 | /* eslint react/display-name: 0 */ 2 | import { PanelPlugin } from '@grafana/data'; 3 | import { DivPanelParent } from 'divPanelParent'; 4 | import { DivMonacoEditor } from 'editor'; 5 | import { DivPanelType, defaults } from './types'; 6 | //import { divPanelMigrationHandler } from './changeHandler'; 7 | 8 | export const plugin = new PanelPlugin(DivPanelParent).setPanelOptions((builder) => { 9 | builder.addCustomEditor({ 10 | id: 'divPanelEdit', 11 | path: 'editor', 12 | name: 'Div Panel Code Editor', 13 | editor: DivMonacoEditor, 14 | defaultValue: defaults, 15 | }); 16 | }); 17 | //.setMigrationHandler(divPanelMigrationHandler); 18 | -------------------------------------------------------------------------------- /src/plugin.json: -------------------------------------------------------------------------------- 1 | { 2 | "type": "panel", 3 | "name": "Div Panel", 4 | "id": "stephanieclosson-div-panel", 5 | "info": { 6 | "description": "Create your own panel with html + css and javascript", 7 | "author": { 8 | "name": "srclosson@gmail.com", 9 | "url": "http://grafana.com" 10 | }, 11 | "keywords": [ 12 | "div", 13 | "es6", 14 | "htmlnode", 15 | "d3" 16 | ], 17 | "logos": { 18 | "small": "img/logo.png", 19 | "large": "img/logo.png" 20 | }, 21 | "links": [ 22 | { 23 | "name": "Website", 24 | "url": "https://github.com/srclosson/div-panel" 25 | }, 26 | { 27 | "name": "License", 28 | "url": "https://github.com/srclosson/div-panel/blob/main/LICENSE" 29 | } 30 | ], 31 | "screenshots": [], 32 | "version": "%VERSION%", 33 | "updated": "%TODAY%" 34 | }, 35 | "dependencies": { 36 | "grafanaVersion": "6.3.x", 37 | "grafanaDependency": ">=6.3.0", 38 | "plugins": [] 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/types.ts: -------------------------------------------------------------------------------- 1 | import { PanelProps, PanelData } from '@grafana/data'; 2 | import { css } from '@emotion/css'; 3 | 4 | export const defaultEditContent = ` 5 | 6 |
7 | Hello Div Panel 8 |
9 | 10 | 45 | 46 | `; 47 | 48 | export const defaultContent = ` 49 | 50 |
51 | Hello Div Panel 52 |
53 | 54 | 71 | 72 | `; 73 | export interface DivPanelParsedHtml { 74 | html: string; 75 | meta: HTMLMetaElement[]; 76 | scripts: HTMLScriptElement[]; 77 | modules: HTMLScriptElement[]; 78 | imports: HTMLScriptElement[]; 79 | links: HTMLLinkElement[]; 80 | } 81 | 82 | export interface DivPanelOptions { 83 | content: string; 84 | editContent: string[]; 85 | editCss: string[]; 86 | error?: string; 87 | } 88 | 89 | export interface DivPanelType { 90 | editor: DivPanelOptions; 91 | } 92 | 93 | export const defaults: DivPanelOptions = { 94 | content: defaultContent, 95 | editContent: [], 96 | editCss: [], 97 | }; 98 | 99 | export interface DivPanelChildProps { 100 | onChange: (options: DivPanelOptions) => void; 101 | options: DivPanelOptions; 102 | parsed: DivPanelParsedHtml; 103 | data: PanelData; 104 | } 105 | 106 | export interface DivPanelProps extends PanelProps {} 107 | 108 | export interface DivPanelState { 109 | command: string; 110 | editMode: boolean; 111 | error?: string; 112 | } 113 | 114 | const defaultDivPanelState = { 115 | command: '', 116 | editMode: false, 117 | }; 118 | 119 | let divPanelState: DivPanelState = defaultDivPanelState; 120 | 121 | export const setDivPanelState = (state: DivPanelState) => { 122 | divPanelState = { ...state }; 123 | }; 124 | 125 | export const getDivPanelState = (): DivPanelState => { 126 | return divPanelState; 127 | }; 128 | 129 | export const clearDivPanelState = () => { 130 | divPanelState = { 131 | ...divPanelState, 132 | command: '', 133 | }; 134 | }; 135 | 136 | export const divStyle = { 137 | wrapper: css` 138 | display: grid; 139 | position: relative; 140 | width: 100%; 141 | height: 100%; 142 | `, 143 | }; 144 | -------------------------------------------------------------------------------- /src/utils/functions.ts: -------------------------------------------------------------------------------- 1 | import postscribe from 'postscribe'; 2 | import { DataFrame, PanelData } from '@grafana/data'; 3 | import { DivPanelParsedHtml } from 'types'; 4 | import { v4 as uuidv4 } from 'uuid'; 5 | 6 | interface ScriptArgs { 7 | data?: DataFrame[]; 8 | elem: HTMLDivElement; 9 | code: HTMLScriptElement; 10 | } 11 | 12 | let scriptsLoaded: Record = {}; 13 | let linksLoaded: Record = {}; 14 | let divGlobals: any = {}; 15 | 16 | export const init = (elem: Element, code: HTMLScriptElement): any => { 17 | try { 18 | const f = new Function( 19 | 'divGlobals', 20 | 'elem', 21 | ` 22 | ${code.textContent} 23 | if (typeof onDivPanelInit === 'function') { 24 | onDivPanelInit(elem); 25 | } 26 | ` 27 | ); 28 | f(divGlobals, elem); 29 | } catch (ex) { 30 | throw ex; 31 | } 32 | }; 33 | 34 | export const loadMeta = (elem: HTMLMetaElement): Promise => { 35 | return new Promise((resolve) => { 36 | postscribe(document.head, elem.outerHTML, { 37 | done: () => resolve(elem), 38 | }); 39 | }); 40 | }; 41 | 42 | export const loadCSS = (elem: HTMLLinkElement): Promise => { 43 | return new Promise((resolve) => { 44 | const href = elem.getAttribute('href'); 45 | if (href && !linksLoaded[href]) { 46 | postscribe(document.head, elem.outerHTML, { 47 | done: () => { 48 | linksLoaded[href] = true; 49 | resolve(elem); 50 | }, 51 | }); 52 | } else { 53 | resolve(elem); 54 | } 55 | }); 56 | }; 57 | 58 | export const load = async (elem: HTMLScriptElement, container?: HTMLElement): Promise => { 59 | return new Promise((resolve, reject) => { 60 | try { 61 | const url = elem.getAttribute('src'); 62 | if (url && scriptsLoaded && !scriptsLoaded[url]) { 63 | postscribe(container || document.head, elem.outerHTML, { 64 | done: () => { 65 | fetch(url, { mode: 'no-cors' }) 66 | .then((response: Response) => response.text()) 67 | .then((code) => { 68 | let res = new Function(code)(); 69 | scriptsLoaded[url] = true; 70 | resolve(res); 71 | }) 72 | .catch((err) => { 73 | console.error("here's an error", err); 74 | reject(err); 75 | }); 76 | }, 77 | error: (err: any) => { 78 | console.error('rejecting', err); 79 | reject(err); 80 | }, 81 | }); 82 | } else { 83 | resolve('scripts already loaded'); 84 | } 85 | } catch (ex) { 86 | reject(ex); 87 | } 88 | }); 89 | }; 90 | 91 | export const loadModule = async ( 92 | elem: HTMLScriptElement, 93 | panelData: PanelData, 94 | container?: HTMLElement 95 | ): Promise => { 96 | return new Promise((resolve, reject) => { 97 | try { 98 | if (container) { 99 | const uuid = uuidv4(); 100 | container.id = uuid; 101 | elem.innerHTML = ` 102 | var divPanelElementUUID = "${uuid}"; 103 | var divPanelContainer = document.getElementById("${uuid}"); 104 | ${elem.innerHTML}; 105 | `; 106 | postscribe(container || document.head, elem.outerHTML, { 107 | done: (result: any) => { 108 | resolve(result); 109 | }, 110 | error: (err: any) => { 111 | reject(err); 112 | }, 113 | }); 114 | } 115 | } catch (ex) { 116 | reject(ex); 117 | } 118 | }); 119 | }; 120 | 121 | export const run = (args: ScriptArgs): string => { 122 | try { 123 | const f = new Function( 124 | 'divGlobals', 125 | 'data', 126 | 'elem', 127 | ` 128 | ${args.code.textContent} 129 | 130 | if (data && typeof onDivPanelDataUpdate === 'function') { 131 | onDivPanelDataUpdate(data, elem); 132 | } 133 | ` 134 | ); 135 | return f(divGlobals, args.data, args.elem); 136 | } catch (ex) { 137 | throw ex; 138 | } 139 | }; 140 | 141 | export const runEnterEditMode = (elem: Element, script: HTMLScriptElement) => { 142 | try { 143 | const f = new Function( 144 | 'divGlobals', 145 | 'elem', 146 | ` 147 | ${script.textContent} 148 | 149 | if (typeof onDivPanelEnterEditMode === 'function') { 150 | onDivPanelEnterEditMode(elem); 151 | } 152 | ` 153 | ); 154 | return f(divGlobals, elem); 155 | } catch (ex) { 156 | throw ex; 157 | } 158 | }; 159 | 160 | export const runExitEditMode = (elem: Element, script: HTMLScriptElement): string => { 161 | try { 162 | const f = new Function( 163 | 'divGlobals', 164 | 'elem', 165 | ` 166 | ${script.textContent} 167 | 168 | if (typeof onDivPanelExitEditMode === 'function') { 169 | return onDivPanelExitEditMode(elem); 170 | } 171 | ` 172 | ); 173 | return f(divGlobals, elem); 174 | } catch (ex) { 175 | throw ex; 176 | } 177 | }; 178 | 179 | export const hasEditModeFunctions = (text: string): boolean => { 180 | return text.includes('onDivPanelEnterEditMode') && text.includes('onDivPanelExitEditMode'); 181 | }; 182 | 183 | export const parseHtml = (content: string, error?: string): DivPanelParsedHtml => { 184 | const scripts: HTMLScriptElement[] = []; 185 | const imports: HTMLScriptElement[] = []; 186 | const links: HTMLLinkElement[] = []; 187 | const meta: HTMLMetaElement[] = []; 188 | const modules: HTMLScriptElement[] = []; 189 | const divElement: HTMLDivElement = document.createElement('div'); 190 | 191 | const parser = new DOMParser(); 192 | const newDoc = parser.parseFromString(content, 'text/html'); 193 | const head: HTMLHeadElement = newDoc.documentElement.children[0] as HTMLHeadElement; 194 | const body: HTMLBodyElement = newDoc.documentElement.children[1] as HTMLBodyElement; 195 | 196 | for (let i = 0; i < head.children.length; i++) { 197 | switch (head.children[i].nodeName) { 198 | case 'META': 199 | document.head.appendChild(head.children[i].cloneNode(true) as HTMLMetaElement); 200 | break; 201 | case 'LINK': 202 | document.head.appendChild(head.children[i].cloneNode(true) as HTMLLinkElement); 203 | break; 204 | case 'STYLE': 205 | document.head.appendChild(head.children[i].cloneNode(true)); 206 | break; 207 | case 'SCRIPT': 208 | imports.push(head.children[i].cloneNode(true) as HTMLScriptElement); 209 | document.head.appendChild(head.children[i].cloneNode(true)); 210 | break; 211 | default: 212 | break; 213 | } 214 | } 215 | 216 | for (let i = 0; i < body.children.length; i++) { 217 | switch (body.children[i].nodeName) { 218 | case 'SCRIPT': 219 | if (body.children[i].getAttribute('src')) { 220 | document.body.appendChild(body.children[i].cloneNode(true) as HTMLScriptElement); 221 | } else if (body.children[i].getAttribute('type') === 'module') { 222 | let temp: HTMLScriptElement = body.children[i].cloneNode(true) as HTMLScriptElement; 223 | modules.push(temp); 224 | } else { 225 | switch (body.children[i].getAttribute('run')?.toLowerCase()) { 226 | case 'oninit': 227 | { 228 | let temp: HTMLScriptElement = body.children[i].cloneNode(true) as HTMLScriptElement; 229 | temp.textContent = `function onDivPanelInit(elem) { 230 | ${temp.textContent} 231 | } 232 | `; 233 | scripts.push(temp); 234 | } 235 | break; 236 | case 'onentereditmode': 237 | { 238 | let temp: HTMLScriptElement = body.children[i].cloneNode(true) as HTMLScriptElement; 239 | temp.textContent = `function onDivPanelEnterEditMode(elem) { 240 | ${temp.textContent} 241 | } 242 | `; 243 | scripts.push(temp); 244 | } 245 | break; 246 | case 'onexiteditmode': 247 | { 248 | let temp: HTMLScriptElement = body.children[i].cloneNode(true) as HTMLScriptElement; 249 | temp.textContent = `function onDivPanelExitEditMode(elem) { 250 | ${temp.textContent} 251 | } 252 | `; 253 | scripts.push(temp); 254 | } 255 | break; 256 | case 'ondata': 257 | { 258 | let temp: HTMLScriptElement = body.children[i].cloneNode(true) as HTMLScriptElement; 259 | temp.textContent = `function onDivPanelDataUpdate(data, elem) { 260 | ${temp.textContent} 261 | } 262 | `; 263 | scripts.push(temp); 264 | } 265 | break; 266 | default: 267 | scripts.push(body.children[i].cloneNode(true) as HTMLScriptElement); 268 | break; 269 | } 270 | } 271 | 272 | break; 273 | case 'STYLE': 274 | divElement.appendChild(body.children[i].cloneNode(true)); 275 | break; 276 | default: 277 | divElement.appendChild(body.children[i].cloneNode(true)); 278 | break; 279 | } 280 | } 281 | 282 | let html = divElement.innerHTML; 283 | if (error) { 284 | html = error; 285 | } 286 | 287 | return { 288 | html, 289 | meta, 290 | scripts, 291 | modules, 292 | imports, 293 | links, 294 | }; 295 | }; 296 | 297 | export const parseScripts = (content: string) => { 298 | const scripts: HTMLScriptElement[] = []; 299 | const parser = new DOMParser(); 300 | const newDoc = parser.parseFromString(content, 'text/html'); 301 | const body: HTMLBodyElement = newDoc.documentElement.children[1] as HTMLBodyElement; 302 | 303 | for (let i = 0; i < body.children.length; i++) { 304 | switch (body.children[i].nodeName) { 305 | case 'SCRIPT': 306 | scripts.push(body.children[i].cloneNode(true) as HTMLScriptElement); 307 | break; 308 | } 309 | } 310 | 311 | return scripts; 312 | }; 313 | 314 | export const loadDependencies = async ( 315 | elem: Element, 316 | imports: HTMLScriptElement[], 317 | meta: HTMLMetaElement[] 318 | ): Promise => { 319 | let promises: Array> = []; 320 | 321 | let container: HTMLElement | null | undefined = elem?.parentElement; 322 | if (container) { 323 | container = container.parentElement?.parentElement?.parentElement; 324 | } 325 | if (container) { 326 | for (const i of imports) { 327 | promises.push(load(i, container)); 328 | } 329 | for (const i of meta) { 330 | promises.push(loadMeta(i)); 331 | } 332 | } else { 333 | throw "We didn't have a container, so we didn't load dependencies"; 334 | } 335 | 336 | return Promise.all(promises); 337 | }; 338 | -------------------------------------------------------------------------------- /src/utils/handlebars.ts: -------------------------------------------------------------------------------- 1 | import { PanelData, DataFrame } from '@grafana/data'; 2 | const Handlebars = require('handlebars'); 3 | 4 | export const register = (data: PanelData) => { 5 | Handlebars.registerHelper('last', () => 6 | data.series[0].fields[1].values.get(data.series[0].fields[1].values.length - 1) 7 | ); 8 | }; 9 | 10 | export const compile = (html: string, series: DataFrame[]): string => { 11 | try { 12 | const template = Handlebars.compile(html); 13 | return template(series); 14 | } catch (ex) { 15 | return html; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /src/utils/postscribe.d.ts: -------------------------------------------------------------------------------- 1 | declare module 'postscribe'; 2 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./.config/tsconfig.json" 3 | } 4 | -------------------------------------------------------------------------------- /validator-config.yaml: -------------------------------------------------------------------------------- 1 | global: 2 | enabled: true 3 | jsonOutput: false 4 | reportAll: false 5 | 6 | analyzers: 7 | htmlreadme: 8 | enabled: false 9 | --------------------------------------------------------------------------------