diff --git a/.eslintrc.js b/.eslintrc.js index 083a04d74d..fd6e8d7b53 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -17,7 +17,12 @@ * under the License. */ module.exports = { - extends: ['airbnb', 'prettier', 'prettier/react', 'plugin:react-hooks/recommended'], + extends: [ + 'airbnb', + 'prettier', + 'prettier/react', + 'plugin:react-hooks/recommended', + ], parser: '@babel/eslint-parser', parserOptions: { ecmaFeatures: { @@ -82,7 +87,8 @@ module.exports = { paths: [ { name: 'antd', - message: 'Please import Ant components from the index of common/components', + message: + 'Please import Ant components from the index of common/components', }, ], }, @@ -196,7 +202,10 @@ module.exports = { rules: { // this is to keep eslint from complaining about storybook addons, // since they are included as dev dependencies rather than direct dependencies. - 'import/no-extraneous-dependencies': ['error', { devDependencies: true }], + 'import/no-extraneous-dependencies': [ + 'error', + { devDependencies: true }, + ], }, }, { diff --git a/.prettierrc b/.prettierrc deleted file mode 100644 index 7c0954a887..0000000000 --- a/.prettierrc +++ /dev/null @@ -1,13 +0,0 @@ -{ - "arrowParens": "avoid", - "bracketSpacing": true, - "bracketSameLine": false, - "printWidth": 100, - "proseWrap": "always", - "requirePragma": false, - "semi": true, - "singleQuote": true, - "tabWidth": 2, - "trailingComma": "all", - "useTabs": false -} diff --git a/commitlint.config.js b/commitlint.config.js index 2c7251869a..00101d3f45 100644 --- a/commitlint.config.js +++ b/commitlint.config.js @@ -18,5 +18,8 @@ */ module.exports = { - extends: ['@commitlint/config-conventional', '@commitlint/config-lerna-scopes'], + extends: [ + '@commitlint/config-conventional', + '@commitlint/config-lerna-scopes', + ], }; diff --git a/jest.config.js b/jest.config.js index 21281f2bdf..732a8de696 100644 --- a/jest.config.js +++ b/jest.config.js @@ -19,7 +19,10 @@ module.exports = { bail: false, - collectCoverageFrom: ['**/src/**/*.{ts,tsx,js,jsx}', '**/test/**/*.{ts,tsx,js,jsx}'], + collectCoverageFrom: [ + '**/src/**/*.{ts,tsx,js,jsx}', + '**/test/**/*.{ts,tsx,js,jsx}', + ], coverageDirectory: './coverage', coveragePathIgnorePatterns: [ 'coverage/', diff --git a/packages/generator-superset/generators/app/index.js b/packages/generator-superset/generators/app/index.js index e5acb6ea90..1bf2f21b46 100644 --- a/packages/generator-superset/generators/app/index.js +++ b/packages/generator-superset/generators/app/index.js @@ -26,7 +26,9 @@ const yosay = require('yosay'); module.exports = class extends Generator { async prompting() { // Have Yeoman greet the user. - this.log(yosay(`Welcome to the rad ${chalk.red('generator-superset')} generator!`)); + this.log( + yosay(`Welcome to the rad ${chalk.red('generator-superset')} generator!`), + ); this.option('skipInstall'); diff --git a/packages/generator-superset/generators/package/index.js b/packages/generator-superset/generators/package/index.js index 02468a9183..314d41d050 100644 --- a/packages/generator-superset/generators/package/index.js +++ b/packages/generator-superset/generators/package/index.js @@ -66,7 +66,10 @@ module.exports = class extends Generator { this.answers, ); const ext = this.answers.language === 'typescript' ? 'ts' : 'js'; - this.fs.copy(this.templatePath('src/index.txt'), this.destinationPath(`src/index.${ext}`)); + this.fs.copy( + this.templatePath('src/index.txt'), + this.destinationPath(`src/index.${ext}`), + ); this.fs.copy( this.templatePath('test/index.txt'), this.destinationPath(`test/index.test.${ext}`), diff --git a/packages/generator-superset/generators/plugin-chart/index.js b/packages/generator-superset/generators/plugin-chart/index.js index db1592d638..58f94a8482 100644 --- a/packages/generator-superset/generators/plugin-chart/index.js +++ b/packages/generator-superset/generators/plugin-chart/index.js @@ -39,7 +39,9 @@ module.exports = class extends Generator { name: 'description', message: 'Description:', // Default to current folder name - default: _.upperFirst(_.startCase(this.appname.replace('plugin chart', '').trim())), + default: _.upperFirst( + _.startCase(this.appname.replace('plugin chart', '').trim()), + ), }, { type: 'list', @@ -106,9 +108,16 @@ module.exports = class extends Generator { ['src/MyChart.erb', `src/${packageLabel}.tsx`], ['test/index.erb', 'test/index.test.ts'], ['test/plugin/buildQuery.test.erb', 'test/plugin/buildQuery.test.ts'], - ['test/plugin/transformProps.test.erb', 'test/plugin/transformProps.test.ts'], + [ + 'test/plugin/transformProps.test.erb', + 'test/plugin/transformProps.test.ts', + ], ].forEach(([src, dest]) => { - this.fs.copyTpl(this.templatePath(src), this.destinationPath(dest), params); + this.fs.copyTpl( + this.templatePath(src), + this.destinationPath(dest), + params, + ); }); ['types/external.d.ts', 'src/images/thumbnail.png'].forEach(file => { diff --git a/packages/generator-superset/test/app.test.js b/packages/generator-superset/test/app.test.js index f3983b40f5..57900cdcd2 100644 --- a/packages/generator-superset/test/app.test.js +++ b/packages/generator-superset/test/app.test.js @@ -49,6 +49,11 @@ describe('generator-superset:app', () => { }); it('creates files', () => { - assert.file(['package.json', 'README.md', 'src/index.ts', 'test/index.test.ts']); + assert.file([ + 'package.json', + 'README.md', + 'src/index.ts', + 'test/index.test.ts', + ]); }); }); diff --git a/packages/generator-superset/test/package.test.js b/packages/generator-superset/test/package.test.js index 316cef174b..62a4f7a329 100644 --- a/packages/generator-superset/test/package.test.js +++ b/packages/generator-superset/test/package.test.js @@ -52,7 +52,12 @@ describe('generator-superset:package', () => { ); it('creates files', () => { - assert.file(['package.json', 'README.md', 'src/index.ts', 'test/index.test.ts']); + assert.file([ + 'package.json', + 'README.md', + 'src/index.ts', + 'test/index.test.ts', + ]); }); }); @@ -65,7 +70,12 @@ describe('generator-superset:package', () => { ); it('creates files', () => { - assert.file(['package.json', 'README.md', 'src/index.js', 'test/index.test.js']); + assert.file([ + 'package.json', + 'README.md', + 'src/index.js', + 'test/index.test.js', + ]); }); }); }); diff --git a/packages/superset-ui-chart-controls/src/components/CertifiedIconWithTooltip.tsx b/packages/superset-ui-chart-controls/src/components/CertifiedIconWithTooltip.tsx index ff7f98e9d6..194a415082 100644 --- a/packages/superset-ui-chart-controls/src/components/CertifiedIconWithTooltip.tsx +++ b/packages/superset-ui-chart-controls/src/components/CertifiedIconWithTooltip.tsx @@ -42,7 +42,9 @@ function CertifiedIconWithTooltip({ id={`${kebabCase(metricName)}-tooltip`} title={
- {certifiedBy && {t('Certified by %s', certifiedBy)}} + {certifiedBy && ( + {t('Certified by %s', certifiedBy)} + )}
{details}
} diff --git a/packages/superset-ui-chart-controls/src/components/ColumnOption.tsx b/packages/superset-ui-chart-controls/src/components/ColumnOption.tsx index 7fac985ebb..a42f0344ac 100644 --- a/packages/superset-ui-chart-controls/src/components/ColumnOption.tsx +++ b/packages/superset-ui-chart-controls/src/components/ColumnOption.tsx @@ -64,7 +64,10 @@ export function ColumnOption({ trigger={['hover']} placement="top" > - + {column.verbose_name || column.column_name} diff --git a/packages/superset-ui-chart-controls/src/components/ControlForm/ControlFormItem.tsx b/packages/superset-ui-chart-controls/src/components/ControlForm/ControlFormItem.tsx index 86a669770e..470972a81b 100644 --- a/packages/superset-ui-chart-controls/src/components/ControlForm/ControlFormItem.tsx +++ b/packages/superset-ui-chart-controls/src/components/ControlForm/ControlFormItem.tsx @@ -29,7 +29,8 @@ export type ControlFormItemProps = ControlFormItemSpec & { onChange?: (fieldValue: JsonValue) => void; }; -export type ControlFormItemNode = FunctionComponentElement; +export type ControlFormItemNode = + FunctionComponentElement; /** * Accept `false` or `0`, but not empty string. @@ -53,7 +54,9 @@ export function ControlFormItem({ }: ControlFormItemProps) { const { gridUnit } = useTheme(); const [hovered, setHovered] = useState(false); - const [value, setValue] = useState(initialValue === undefined ? defaultValue : initialValue); + const [value, setValue] = useState( + initialValue === undefined ? defaultValue : initialValue, + ); const [validationErrors, setValidationErrors] = useState(); @@ -66,7 +69,9 @@ export function ControlFormItem({ : e; const errors = (validators - ?.map(validator => (!required && isEmptyValue(fieldValue) ? false : validator(fieldValue))) + ?.map(validator => + !required && isEmptyValue(fieldValue) ? false : validator(fieldValue), + ) .filter(x => !!x) as string[]) || []; setValidationErrors(errors); setValue(fieldValue); @@ -87,8 +92,14 @@ export function ControlFormItem({ onMouseLeave={() => setHovered(false)} > {controlType === 'Checkbox' ? ( - - {label} {hovered && description && } + + {label}{' '} + {hovered && description && ( + + )} ) : ( <> diff --git a/packages/superset-ui-chart-controls/src/components/ControlForm/index.tsx b/packages/superset-ui-chart-controls/src/components/ControlForm/index.tsx index fb414ad57e..9dafb3c39f 100644 --- a/packages/superset-ui-chart-controls/src/components/ControlForm/index.tsx +++ b/packages/superset-ui-chart-controls/src/components/ControlForm/index.tsx @@ -17,7 +17,12 @@ * under the License. */ import React, { FunctionComponentElement, useMemo } from 'react'; -import { FAST_DEBOUNCE, JsonObject, JsonValue, useTheme } from '@superset-ui/core'; +import { + FAST_DEBOUNCE, + JsonObject, + JsonValue, + useTheme, +} from '@superset-ui/core'; import { debounce } from 'lodash'; import { ControlFormItemNode } from './ControlFormItem'; @@ -57,7 +62,11 @@ export type ControlFormProps = { /** * Light weight form for control panel. */ -export default function ControlForm({ onChange, value, children }: ControlFormProps) { +export default function ControlForm({ + onChange, + value, + children, +}: ControlFormProps) { const theme = useTheme(); const debouncedOnChange = useMemo( () => @@ -94,7 +103,10 @@ export default function ControlForm({ onChange, value, children }: ControlFormPr } // propagate to the form if (!(debounceDelay in debouncedOnChange)) { - debouncedOnChange[debounceDelay] = debounce(onChange, debounceDelay); + debouncedOnChange[debounceDelay] = debounce( + onChange, + debounceDelay, + ); } debouncedOnChange[debounceDelay]({ ...value, diff --git a/packages/superset-ui-chart-controls/src/components/ControlHeader.tsx b/packages/superset-ui-chart-controls/src/components/ControlHeader.tsx index b7370be474..c1b22494ef 100644 --- a/packages/superset-ui-chart-controls/src/components/ControlHeader.tsx +++ b/packages/superset-ui-chart-controls/src/components/ControlHeader.tsx @@ -118,7 +118,11 @@ export default function ControlHeader({ )} {validationErrors.length > 0 && ( - + {' '} diff --git a/packages/superset-ui-chart-controls/src/components/InfoTooltipWithTrigger.tsx b/packages/superset-ui-chart-controls/src/components/InfoTooltipWithTrigger.tsx index 1ac49381c7..747a6535fe 100644 --- a/packages/superset-ui-chart-controls/src/components/InfoTooltipWithTrigger.tsx +++ b/packages/superset-ui-chart-controls/src/components/InfoTooltipWithTrigger.tsx @@ -41,7 +41,9 @@ export function InfoTooltipWithTrigger({ className = 'text-muted', placement = 'right', }: InfoTooltipWithTriggerProps) { - const iconClass = `fa fa-${icon} ${className} ${bsStyle ? `text-${bsStyle}` : ''}`; + const iconClass = `fa fa-${icon} ${className} ${ + bsStyle ? `text-${bsStyle}` : '' + }`; const iconEl = ( + {iconEl} ); diff --git a/packages/superset-ui-chart-controls/src/components/MetricOption.tsx b/packages/superset-ui-chart-controls/src/components/MetricOption.tsx index 700159b101..b76f772b43 100644 --- a/packages/superset-ui-chart-controls/src/components/MetricOption.tsx +++ b/packages/superset-ui-chart-controls/src/components/MetricOption.tsx @@ -73,7 +73,12 @@ export function MetricOption({ /> )} {showTooltip ? ( - + {link} diff --git a/packages/superset-ui-chart-controls/src/components/Tooltip.tsx b/packages/superset-ui-chart-controls/src/components/Tooltip.tsx index a77e2b7b25..3b4aed17e4 100644 --- a/packages/superset-ui-chart-controls/src/components/Tooltip.tsx +++ b/packages/superset-ui-chart-controls/src/components/Tooltip.tsx @@ -43,7 +43,11 @@ export const Tooltip = ({ overlayStyle, color, ...props }: TooltipProps) => { `} /> diff --git a/packages/superset-ui-chart-controls/src/constants.ts b/packages/superset-ui-chart-controls/src/constants.ts index 0ba9d9eea3..5e16956c60 100644 --- a/packages/superset-ui-chart-controls/src/constants.ts +++ b/packages/superset-ui-chart-controls/src/constants.ts @@ -36,7 +36,9 @@ export const TIME_COLUMN_OPTION: ColumnMeta = { verbose_name: COLUMN_NAME_ALIASES[DTTM_ALIAS], column_name: DTTM_ALIAS, type_generic: GenericDataType.TEMPORAL, - description: t('A reference to the [Time] configuration, taking granularity into account'), + description: t( + 'A reference to the [Time] configuration, taking granularity into account', + ), }; export const QueryModeLabel = { diff --git a/packages/superset-ui-chart-controls/src/index.ts b/packages/superset-ui-chart-controls/src/index.ts index 2db39c83cc..6f19d0e468 100644 --- a/packages/superset-ui-chart-controls/src/index.ts +++ b/packages/superset-ui-chart-controls/src/index.ts @@ -31,7 +31,11 @@ export * from './components/ColumnTypeLabel'; export * from './components/MetricOption'; // React control components -export { sharedControls, dndEntity, dndColumnsControl } from './shared-controls'; +export { + sharedControls, + dndEntity, + dndColumnsControl, +} from './shared-controls'; export { default as sharedControlComponents } from './shared-controls/components'; export { legacySortBy } from './shared-controls/legacySortBy'; export * from './shared-controls/emitFilterControl'; diff --git a/packages/superset-ui-chart-controls/src/operators/boxplotOperator.ts b/packages/superset-ui-chart-controls/src/operators/boxplotOperator.ts index 8b551fc6d1..300bdcbc40 100644 --- a/packages/superset-ui-chart-controls/src/operators/boxplotOperator.ts +++ b/packages/superset-ui-chart-controls/src/operators/boxplotOperator.ts @@ -16,16 +16,20 @@ * specific language governing permissions and limitationsxw * under the License. */ -import { PostProcessingBoxplot, getMetricLabel, ensureIsArray } from '@superset-ui/core'; +import { + PostProcessingBoxplot, + getMetricLabel, + ensureIsArray, +} from '@superset-ui/core'; import { PostProcessingFactory } from './types'; -type BoxPlotQueryObjectWhiskerType = PostProcessingBoxplot['options']['whisker_type']; +type BoxPlotQueryObjectWhiskerType = + PostProcessingBoxplot['options']['whisker_type']; const PERCENTILE_REGEX = /(\d+)\/(\d+) percentiles/; -export const boxplotOperator: PostProcessingFactory = ( - formData, - queryObject, -) => { +export const boxplotOperator: PostProcessingFactory< + PostProcessingBoxplot | undefined +> = (formData, queryObject) => { const { groupby, whiskerOptions } = formData; if (whiskerOptions) { @@ -39,7 +43,10 @@ export const boxplotOperator: PostProcessingFactory = ( - formData, - queryObject, -) => { +export const contributionOperator: PostProcessingFactory< + PostProcessingContribution | undefined +> = (formData, queryObject) => { if (formData.contributionMode) { return { operation: 'contribution', diff --git a/packages/superset-ui-chart-controls/src/operators/pivotOperator.ts b/packages/superset-ui-chart-controls/src/operators/pivotOperator.ts index 45e5a1d173..e29e33bd0e 100644 --- a/packages/superset-ui-chart-controls/src/operators/pivotOperator.ts +++ b/packages/superset-ui-chart-controls/src/operators/pivotOperator.ts @@ -16,15 +16,18 @@ * specific language governing permissions and limitationsxw * under the License. */ -import { ensureIsArray, getMetricLabel, PostProcessingPivot } from '@superset-ui/core'; +import { + ensureIsArray, + getMetricLabel, + PostProcessingPivot, +} from '@superset-ui/core'; import { PostProcessingFactory } from './types'; import { TIME_COLUMN, isValidTimeCompare } from './utils'; import { timeComparePivotOperator } from './timeComparePivotOperator'; -export const pivotOperator: PostProcessingFactory = ( - formData, - queryObject, -) => { +export const pivotOperator: PostProcessingFactory< + PostProcessingPivot | undefined +> = (formData, queryObject) => { const metricLabels = ensureIsArray(queryObject.metrics).map(getMetricLabel); if (queryObject.is_timeseries && metricLabels.length) { if (isValidTimeCompare(formData, queryObject)) { @@ -38,7 +41,9 @@ export const pivotOperator: PostProcessingFactory [metric, { operator: 'mean' }])), + aggregates: Object.fromEntries( + metricLabels.map(metric => [metric, { operator: 'mean' }]), + ), drop_missing_columns: false, }, }; diff --git a/packages/superset-ui-chart-controls/src/operators/prophetOperator.ts b/packages/superset-ui-chart-controls/src/operators/prophetOperator.ts index 75fb609526..1b208034db 100644 --- a/packages/superset-ui-chart-controls/src/operators/prophetOperator.ts +++ b/packages/superset-ui-chart-controls/src/operators/prophetOperator.ts @@ -19,10 +19,9 @@ import { PostProcessingProphet } from '@superset-ui/core'; import { PostProcessingFactory } from './types'; -export const prophetOperator: PostProcessingFactory = ( - formData, - queryObject, -) => { +export const prophetOperator: PostProcessingFactory< + PostProcessingProphet | undefined +> = (formData, queryObject) => { if (formData.forecastEnabled) { return { operation: 'prophet', diff --git a/packages/superset-ui-chart-controls/src/operators/resampleOperator.ts b/packages/superset-ui-chart-controls/src/operators/resampleOperator.ts index 24dec524cd..a43838d710 100644 --- a/packages/superset-ui-chart-controls/src/operators/resampleOperator.ts +++ b/packages/superset-ui-chart-controls/src/operators/resampleOperator.ts @@ -21,10 +21,9 @@ import { PostProcessingResample } from '@superset-ui/core'; import { PostProcessingFactory } from './types'; import { TIME_COLUMN } from './utils'; -export const resampleOperator: PostProcessingFactory = ( - formData, - queryObject, -) => { +export const resampleOperator: PostProcessingFactory< + PostProcessingResample | undefined +> = (formData, queryObject) => { const resampleZeroFill = formData.resample_method === 'zerofill'; const resampleMethod = resampleZeroFill ? 'asfreq' : formData.resample_method; const resampleRule = formData.resample_rule; diff --git a/packages/superset-ui-chart-controls/src/operators/rollingWindowOperator.ts b/packages/superset-ui-chart-controls/src/operators/rollingWindowOperator.ts index 0d505d28f2..f8dd40137b 100644 --- a/packages/superset-ui-chart-controls/src/operators/rollingWindowOperator.ts +++ b/packages/superset-ui-chart-controls/src/operators/rollingWindowOperator.ts @@ -25,7 +25,11 @@ import { PostProcessingCum, ComparisionType, } from '@superset-ui/core'; -import { getMetricOffsetsMap, isValidTimeCompare, TIME_COMPARISON_SEPARATOR } from './utils'; +import { + getMetricOffsetsMap, + isValidTimeCompare, + TIME_COMPARISON_SEPARATOR, +} from './utils'; import { PostProcessingFactory } from './types'; export const rollingWindowOperator: PostProcessingFactory< @@ -37,7 +41,10 @@ export const rollingWindowOperator: PostProcessingFactory< const comparisonType = formData.comparison_type; if (comparisonType === ComparisionType.Values) { // time compare type: actual values - columns = [...Array.from(metricsMap.values()), ...Array.from(metricsMap.keys())]; + columns = [ + ...Array.from(metricsMap.values()), + ...Array.from(metricsMap.keys()), + ]; } else { // time compare type: difference / percentage / ratio columns = Array.from(metricsMap.entries()).map(([offset, metric]) => @@ -65,7 +72,11 @@ export const rollingWindowOperator: PostProcessingFactory< }; } - if ([RollingType.Sum, RollingType.Mean, RollingType.Std].includes(formData.rolling_type)) { + if ( + [RollingType.Sum, RollingType.Mean, RollingType.Std].includes( + formData.rolling_type, + ) + ) { return { operation: 'rolling', options: { diff --git a/packages/superset-ui-chart-controls/src/operators/sortOperator.ts b/packages/superset-ui-chart-controls/src/operators/sortOperator.ts index 3ab04faad5..9a86f4b371 100644 --- a/packages/superset-ui-chart-controls/src/operators/sortOperator.ts +++ b/packages/superset-ui-chart-controls/src/operators/sortOperator.ts @@ -21,11 +21,13 @@ import { PostProcessingSort, RollingType } from '@superset-ui/core'; import { PostProcessingFactory } from './types'; import { TIME_COLUMN } from './utils'; -export const sortOperator: PostProcessingFactory = ( - formData, - queryObject, -) => { - if (queryObject.is_timeseries && Object.values(RollingType).includes(formData.rolling_type)) { +export const sortOperator: PostProcessingFactory< + PostProcessingSort | undefined +> = (formData, queryObject) => { + if ( + queryObject.is_timeseries && + Object.values(RollingType).includes(formData.rolling_type) + ) { return { operation: 'sort', options: { diff --git a/packages/superset-ui-chart-controls/src/operators/timeCompareOperator.ts b/packages/superset-ui-chart-controls/src/operators/timeCompareOperator.ts index 1680f49783..55d8a82977 100644 --- a/packages/superset-ui-chart-controls/src/operators/timeCompareOperator.ts +++ b/packages/superset-ui-chart-controls/src/operators/timeCompareOperator.ts @@ -21,14 +21,16 @@ import { ComparisionType, PostProcessingCompare } from '@superset-ui/core'; import { getMetricOffsetsMap, isValidTimeCompare } from './utils'; import { PostProcessingFactory } from './types'; -export const timeCompareOperator: PostProcessingFactory = ( - formData, - queryObject, -) => { +export const timeCompareOperator: PostProcessingFactory< + PostProcessingCompare | undefined +> = (formData, queryObject) => { const comparisonType = formData.comparison_type; const metricOffsetMap = getMetricOffsetsMap(formData, queryObject); - if (isValidTimeCompare(formData, queryObject) && comparisonType !== ComparisionType.Values) { + if ( + isValidTimeCompare(formData, queryObject) && + comparisonType !== ComparisionType.Values + ) { return { operation: 'compare', options: { diff --git a/packages/superset-ui-chart-controls/src/operators/timeComparePivotOperator.ts b/packages/superset-ui-chart-controls/src/operators/timeComparePivotOperator.ts index 74c9c90207..51ae7a061c 100644 --- a/packages/superset-ui-chart-controls/src/operators/timeComparePivotOperator.ts +++ b/packages/superset-ui-chart-controls/src/operators/timeComparePivotOperator.ts @@ -17,14 +17,21 @@ * specific language governing permissions and limitationsxw * under the License. */ -import { ComparisionType, PostProcessingPivot, NumpyFunction } from '@superset-ui/core'; -import { getMetricOffsetsMap, isValidTimeCompare, TIME_COMPARISON_SEPARATOR } from './utils'; +import { + ComparisionType, + PostProcessingPivot, + NumpyFunction, +} from '@superset-ui/core'; +import { + getMetricOffsetsMap, + isValidTimeCompare, + TIME_COMPARISON_SEPARATOR, +} from './utils'; import { PostProcessingFactory } from './types'; -export const timeComparePivotOperator: PostProcessingFactory = ( - formData, - queryObject, -) => { +export const timeComparePivotOperator: PostProcessingFactory< + PostProcessingPivot | undefined +> = (formData, queryObject) => { const comparisonType = formData.comparison_type; const metricOffsetMap = getMetricOffsetsMap(formData, queryObject); @@ -38,7 +45,9 @@ export const timeComparePivotOperator: PostProcessingFactory [comparisonType, metric, offset].join(TIME_COMPARISON_SEPARATOR)) + .map(([offset, metric]) => + [comparisonType, metric, offset].join(TIME_COMPARISON_SEPARATOR), + ) // use the 'mean' aggregates to avoid drop NaN .map(metric => [metric, { operator: 'mean' as NumpyFunction }]), ); @@ -48,7 +57,8 @@ export const timeComparePivotOperator: PostProcessingFactory> = ( const metricOffsetMap = new Map(); metricLabels.forEach((metric: string) => { timeOffsets.forEach((offset: string) => { - metricOffsetMap.set([metric, offset].join(TIME_COMPARISON_SEPARATOR), metric); + metricOffsetMap.set( + [metric, offset].join(TIME_COMPARISON_SEPARATOR), + metric, + ); }); }); diff --git a/packages/superset-ui-chart-controls/src/operators/utils/isValidTimeCompare.ts b/packages/superset-ui-chart-controls/src/operators/utils/isValidTimeCompare.ts index a2a4afaa33..793bb39231 100644 --- a/packages/superset-ui-chart-controls/src/operators/utils/isValidTimeCompare.ts +++ b/packages/superset-ui-chart-controls/src/operators/utils/isValidTimeCompare.ts @@ -21,9 +21,15 @@ import { ComparisionType } from '@superset-ui/core'; import { getMetricOffsetsMap } from './getMetricOffsetsMap'; import { PostProcessingFactory } from '../types'; -export const isValidTimeCompare: PostProcessingFactory = (formData, queryObject) => { +export const isValidTimeCompare: PostProcessingFactory = ( + formData, + queryObject, +) => { const comparisonType = formData.comparison_type; const metricOffsetMap = getMetricOffsetsMap(formData, queryObject); - return Object.values(ComparisionType).includes(comparisonType) && metricOffsetMap.size > 0; + return ( + Object.values(ComparisionType).includes(comparisonType) && + metricOffsetMap.size > 0 + ); }; diff --git a/packages/superset-ui-chart-controls/src/sections/advancedAnalytics.tsx b/packages/superset-ui-chart-controls/src/sections/advancedAnalytics.tsx index 453a6c77d8..036670c4df 100644 --- a/packages/superset-ui-chart-controls/src/sections/advancedAnalytics.tsx +++ b/packages/superset-ui-chart-controls/src/sections/advancedAnalytics.tsx @@ -38,7 +38,9 @@ export const advancedAnalyticsControls: ControlPanelSectionConfig = { type: 'SelectControl', label: t('Rolling function'), default: null, - choices: [[null, t('None')]].concat(formatSelectOptions(Object.values(RollingType))), + choices: [[null, t('None')]].concat( + formatSelectOptions(Object.values(RollingType)), + ), description: t( 'Defines a rolling window function to apply, works along ' + 'with the [Periods] text box', diff --git a/packages/superset-ui-chart-controls/src/sections/forecastInterval.tsx b/packages/superset-ui-chart-controls/src/sections/forecastInterval.tsx index 6a9bdd9132..b65b52db76 100644 --- a/packages/superset-ui-chart-controls/src/sections/forecastInterval.tsx +++ b/packages/superset-ui-chart-controls/src/sections/forecastInterval.tsx @@ -16,7 +16,11 @@ * specific language governing permissions and limitations * under the License. */ -import { legacyValidateInteger, legacyValidateNumber, t } from '@superset-ui/core'; +import { + legacyValidateInteger, + legacyValidateNumber, + t, +} from '@superset-ui/core'; import { ControlPanelSectionConfig } from '../types'; export const FORECAST_DEFAULT_DATA = { @@ -52,7 +56,9 @@ export const forecastIntervalControls: ControlPanelSectionConfig = { label: t('Forecast periods'), validators: [legacyValidateInteger], default: FORECAST_DEFAULT_DATA.forecastPeriods, - description: t('How many periods into the future do we want to predict'), + description: t( + 'How many periods into the future do we want to predict', + ), }, }, ], @@ -64,7 +70,9 @@ export const forecastIntervalControls: ControlPanelSectionConfig = { label: t('Confidence interval'), validators: [legacyValidateNumber], default: FORECAST_DEFAULT_DATA.forecastInterval, - description: t('Width of the confidence interval. Should be between 0 and 1'), + description: t( + 'Width of the confidence interval. Should be between 0 and 1', + ), }, }, { diff --git a/packages/superset-ui-chart-controls/src/sections/sections.tsx b/packages/superset-ui-chart-controls/src/sections/sections.tsx index 53ac2ae2ff..1c99593ad8 100644 --- a/packages/superset-ui-chart-controls/src/sections/sections.tsx +++ b/packages/superset-ui-chart-controls/src/sections/sections.tsx @@ -75,7 +75,9 @@ export const datasourceAndVizType: ControlPanelSectionConfig = { type: 'HiddenControl', label: t('URL Parameters'), hidden: true, - description: t('Extra url parameters for use in Jinja templated queries'), + description: t( + 'Extra url parameters for use in Jinja templated queries', + ), }, }, { diff --git a/packages/superset-ui-chart-controls/src/shared-controls/components/ColumnConfigControl/ColumnConfigControl.tsx b/packages/superset-ui-chart-controls/src/shared-controls/components/ColumnConfigControl/ColumnConfigControl.tsx index 9021a34801..55c560cb79 100644 --- a/packages/superset-ui-chart-controls/src/shared-controls/components/ColumnConfigControl/ColumnConfigControl.tsx +++ b/packages/superset-ui-chart-controls/src/shared-controls/components/ColumnConfigControl/ColumnConfigControl.tsx @@ -17,23 +17,31 @@ * under the License. */ import React, { useMemo, useState } from 'react'; -import { ChartDataResponseResult, useTheme, t, GenericDataType } from '@superset-ui/core'; +import { + ChartDataResponseResult, + useTheme, + t, + GenericDataType, +} from '@superset-ui/core'; import ControlHeader from '../../../components/ControlHeader'; import { ControlComponentProps } from '../types'; import ColumnConfigItem from './ColumnConfigItem'; -import { ColumnConfigInfo, ColumnConfig, ColumnConfigFormLayout } from './types'; +import { + ColumnConfigInfo, + ColumnConfig, + ColumnConfigFormLayout, +} from './types'; import { DEFAULT_CONFIG_FORM_LAYOUT } from './constants'; import { COLUMN_NAME_ALIASES } from '../../../constants'; -export type ColumnConfigControlProps = ControlComponentProps< - Record -> & { - queryResponse?: ChartDataResponseResult; - configFormLayout?: ColumnConfigFormLayout; - appliedColumnNames?: string[]; - emitFilter: boolean; -}; +export type ColumnConfigControlProps = + ControlComponentProps> & { + queryResponse?: ChartDataResponseResult; + configFormLayout?: ColumnConfigFormLayout; + appliedColumnNames?: string[]; + emitFilter: boolean; + }; /** * Max number of columns to show by default. @@ -102,7 +110,9 @@ export default function ColumnConfigControl({ // Only keep configs for known columns const validConfigs: Record = colnames && value - ? Object.fromEntries(Object.entries(value).filter(([key]) => colnames.includes(key))) + ? Object.fromEntries( + Object.entries(value).filter(([key]) => colnames.includes(key)), + ) : { ...value }; onChange({ ...validConfigs, @@ -114,7 +124,10 @@ export default function ColumnConfigControl({ if (!colnames || colnames.length === 0) return null; const needShowMoreButton = colnames.length > MAX_NUM_COLS + 2; - const cols = needShowMoreButton && !showAllColumns ? colnames.slice(0, MAX_NUM_COLS) : colnames; + const cols = + needShowMoreButton && !showAllColumns + ? colnames.slice(0, MAX_NUM_COLS) + : colnames; return ( <> diff --git a/packages/superset-ui-chart-controls/src/shared-controls/components/ColumnConfigControl/ColumnConfigItem.tsx b/packages/superset-ui-chart-controls/src/shared-controls/components/ColumnConfigControl/ColumnConfigItem.tsx index b4851f5785..ee9c1ea17b 100644 --- a/packages/superset-ui-chart-controls/src/shared-controls/components/ColumnConfigControl/ColumnConfigItem.tsx +++ b/packages/superset-ui-chart-controls/src/shared-controls/components/ColumnConfigControl/ColumnConfigItem.tsx @@ -20,7 +20,9 @@ import React from 'react'; import { useTheme } from '@superset-ui/core'; import { Popover } from 'antd'; import ColumnTypeLabel from '../../../components/ColumnTypeLabel'; -import ColumnConfigPopover, { ColumnConfigPopoverProps } from './ColumnConfigPopover'; +import ColumnConfigPopover, { + ColumnConfigPopoverProps, +} from './ColumnConfigPopover'; export type ColumnConfigItemProps = ColumnConfigPopoverProps; diff --git a/packages/superset-ui-chart-controls/src/shared-controls/components/ColumnConfigControl/ColumnConfigPopover.tsx b/packages/superset-ui-chart-controls/src/shared-controls/components/ColumnConfigControl/ColumnConfigPopover.tsx index cb493609ec..dbc40b216e 100644 --- a/packages/superset-ui-chart-controls/src/shared-controls/components/ColumnConfigControl/ColumnConfigPopover.tsx +++ b/packages/superset-ui-chart-controls/src/shared-controls/components/ColumnConfigControl/ColumnConfigPopover.tsx @@ -23,8 +23,15 @@ import ControlForm, { ControlFormItem, ControlFormItemSpec, } from '../../../components/ControlForm'; -import { SHARED_COLUMN_CONFIG_PROPS, SharedColumnConfigProp } from './constants'; -import { ColumnConfig, ColumnConfigFormLayout, ColumnConfigInfo } from './types'; +import { + SHARED_COLUMN_CONFIG_PROPS, + SharedColumnConfigProp, +} from './constants'; +import { + ColumnConfig, + ColumnConfigFormLayout, + ColumnConfigInfo, +} from './types'; export type ColumnConfigPopoverProps = { column: ColumnConfigInfo; @@ -39,24 +46,28 @@ export default function ColumnConfigPopover({ }: ColumnConfigPopoverProps) { return ( - {configFormLayout[column.type === undefined ? GenericDataType.STRING : column.type].map( - (row, i) => ( - - {row.map(meta => { - const key = typeof meta === 'string' ? meta : meta.name; - const override = - typeof meta === 'string' ? {} : 'override' in meta ? meta.override : meta.config; - const props = { - ...(key in SHARED_COLUMN_CONFIG_PROPS - ? SHARED_COLUMN_CONFIG_PROPS[key as SharedColumnConfigProp] - : undefined), - ...override, - } as ControlFormItemSpec; - return ; - })} - - ), - )} + {configFormLayout[ + column.type === undefined ? GenericDataType.STRING : column.type + ].map((row, i) => ( + + {row.map(meta => { + const key = typeof meta === 'string' ? meta : meta.name; + const override = + typeof meta === 'string' + ? {} + : 'override' in meta + ? meta.override + : meta.config; + const props = { + ...(key in SHARED_COLUMN_CONFIG_PROPS + ? SHARED_COLUMN_CONFIG_PROPS[key as SharedColumnConfigProp] + : undefined), + ...override, + } as ControlFormItemSpec; + return ; + })} + + ))} ); } diff --git a/packages/superset-ui-chart-controls/src/shared-controls/components/ColumnConfigControl/constants.tsx b/packages/superset-ui-chart-controls/src/shared-controls/components/ColumnConfigControl/constants.tsx index b15ae51527..150f1e91f0 100644 --- a/packages/superset-ui-chart-controls/src/shared-controls/components/ColumnConfigControl/constants.tsx +++ b/packages/superset-ui-chart-controls/src/shared-controls/components/ColumnConfigControl/constants.tsx @@ -125,7 +125,9 @@ const showCellBars: ControlFormItemSpec<'Checkbox'> = { const alignPositiveNegative: ControlFormItemSpec<'Checkbox'> = { controlType: 'Checkbox', label: t('Align +/-'), - description: t('Whether to align positive and negative values in cell bar chart at 0'), + description: t( + 'Whether to align positive and negative values in cell bar chart at 0', + ), defaultValue: false, debounceDelay: 200, }; @@ -133,7 +135,9 @@ const alignPositiveNegative: ControlFormItemSpec<'Checkbox'> = { const colorPositiveNegative: ControlFormItemSpec<'Checkbox'> = { controlType: 'Checkbox', label: t('Color +/-'), - description: t('Whether to colorize numeric values by if they are positive or negative'), + description: t( + 'Whether to colorize numeric values by if they are positive or negative', + ), defaultValue: false, debounceDelay: 200, }; @@ -167,20 +171,32 @@ export type SharedColumnConfig = { export const DEFAULT_CONFIG_FORM_LAYOUT: ColumnConfigFormLayout = { [GenericDataType.STRING]: [ - ['columnWidth', { name: 'horizontalAlign', override: { defaultValue: 'left' } }], + [ + 'columnWidth', + { name: 'horizontalAlign', override: { defaultValue: 'left' } }, + ], ], [GenericDataType.NUMERIC]: [ - ['columnWidth', { name: 'horizontalAlign', override: { defaultValue: 'right' } }], + [ + 'columnWidth', + { name: 'horizontalAlign', override: { defaultValue: 'right' } }, + ], ['d3NumberFormat'], ['d3SmallNumberFormat'], ['alignPositiveNegative', 'colorPositiveNegative'], ['showCellBars'], ], [GenericDataType.TEMPORAL]: [ - ['columnWidth', { name: 'horizontalAlign', override: { defaultValue: 'left' } }], + [ + 'columnWidth', + { name: 'horizontalAlign', override: { defaultValue: 'left' } }, + ], ['d3TimeFormat'], ], [GenericDataType.BOOLEAN]: [ - ['columnWidth', { name: 'horizontalAlign', override: { defaultValue: 'left' } }], + [ + 'columnWidth', + { name: 'horizontalAlign', override: { defaultValue: 'left' } }, + ], ], }; diff --git a/packages/superset-ui-chart-controls/src/shared-controls/components/ColumnConfigControl/types.ts b/packages/superset-ui-chart-controls/src/shared-controls/components/ColumnConfigControl/types.ts index c9dcf85d9c..ef449ef8ed 100644 --- a/packages/superset-ui-chart-controls/src/shared-controls/components/ColumnConfigControl/types.ts +++ b/packages/superset-ui-chart-controls/src/shared-controls/components/ColumnConfigControl/types.ts @@ -16,9 +16,16 @@ * specific language governing permissions and limitations * under the License. */ -import { GenericDataType, JsonObject, StrictJsonValue } from '@superset-ui/core'; +import { + GenericDataType, + JsonObject, + StrictJsonValue, +} from '@superset-ui/core'; import { ControlFormItemSpec } from '../../../components/ControlForm'; -import { SHARED_COLUMN_CONFIG_PROPS, SharedColumnConfigProp } from './constants'; +import { + SHARED_COLUMN_CONFIG_PROPS, + SharedColumnConfigProp, +} from './constants'; /** * Column formatting configs. @@ -42,6 +49,9 @@ export type ColumnConfigFormItem = | { name: SharedColumnConfigProp; override: Partial } | { name: string; config: ControlFormItemSpec }; -export type ColumnConfigFormLayout = Record; +export type ColumnConfigFormLayout = Record< + GenericDataType, + ColumnConfigFormItem[][] +>; export default {}; diff --git a/packages/superset-ui-chart-controls/src/shared-controls/components/RadioButtonControl.tsx b/packages/superset-ui-chart-controls/src/shared-controls/components/RadioButtonControl.tsx index 9999956de0..e9f6a6f9bc 100644 --- a/packages/superset-ui-chart-controls/src/shared-controls/components/RadioButtonControl.tsx +++ b/packages/superset-ui-chart-controls/src/shared-controls/components/RadioButtonControl.tsx @@ -21,7 +21,10 @@ import { JsonValue, useTheme } from '@superset-ui/core'; import ControlHeader from '../../components/ControlHeader'; // [value, label] -export type RadioButtonOption = [JsonValue, Exclude]; +export type RadioButtonOption = [ + JsonValue, + Exclude, +]; export interface RadioButtonControlProps { label?: ReactNode; @@ -66,7 +69,9 @@ export default function RadioButtonControl({
diff --git a/packages/superset-ui-demo/storybook/shared/components/ResizableChartDemo.tsx b/packages/superset-ui-demo/storybook/shared/components/ResizableChartDemo.tsx index 4486295f0f..f48399b6d6 100644 --- a/packages/superset-ui-demo/storybook/shared/components/ResizableChartDemo.tsx +++ b/packages/superset-ui-demo/storybook/shared/components/ResizableChartDemo.tsx @@ -45,19 +45,31 @@ export default function ResizableChartDemo({ const [size, setSize] = useState(initialSize); return ( - setSize(data.size)}> - {children({ width: size.width - panelPadding, height: size.height - panelPadding })} + setSize(data.size)} + > + {children({ + width: size.width - panelPadding, + height: size.height - panelPadding, + })} ); } -export const withResizableChartDemo: DecoratorFunction = (storyFn, context) => { +export const withResizableChartDemo: DecoratorFunction = ( + storyFn, + context, +) => { const { parameters: { initialSize, panelPadding }, } = context; return ( - + {innerSize => storyFn({ ...context, ...innerSize })} ); diff --git a/packages/superset-ui-demo/storybook/shared/components/ResizablePanel.tsx b/packages/superset-ui-demo/storybook/shared/components/ResizablePanel.tsx index 94adddba14..f7cf2c2e5e 100644 --- a/packages/superset-ui-demo/storybook/shared/components/ResizablePanel.tsx +++ b/packages/superset-ui-demo/storybook/shared/components/ResizablePanel.tsx @@ -18,7 +18,11 @@ */ import React, { PropsWithChildren, ReactNode } from 'react'; -import { ResizableBox, ResizableBoxProps, ResizeCallbackData } from 'react-resizable'; +import { + ResizableBox, + ResizableBoxProps, + ResizeCallbackData, +} from 'react-resizable'; import 'react-resizable/css/styles.css'; diff --git a/packages/superset-ui-demo/storybook/shared/components/VerifyCORS.tsx b/packages/superset-ui-demo/storybook/shared/components/VerifyCORS.tsx index 3f8266f615..de0b2ef8ab 100644 --- a/packages/superset-ui-demo/storybook/shared/components/VerifyCORS.tsx +++ b/packages/superset-ui-demo/storybook/shared/components/VerifyCORS.tsx @@ -18,7 +18,12 @@ */ import React, { ReactNode } from 'react'; -import { SupersetClient, Method, makeApi, SupersetApiError } from '@superset-ui/core'; +import { + SupersetClient, + Method, + makeApi, + SupersetApiError, +} from '@superset-ui/core'; import ErrorMessage from './ErrorMessage'; export type Props = { @@ -87,7 +92,9 @@ export default class VerifyCORS extends React.Component { } return { error: 'Must provide valid endpoint and payload.' }; }) - .then(result => this.setState({ didVerify: true, error: undefined, payload: result })) + .then(result => + this.setState({ didVerify: true, error: undefined, payload: result }), + ) .catch(error => this.setState({ error })); } @@ -102,13 +109,18 @@ export default class VerifyCORS extends React.Component {
This example requires CORS requests from this domain.

- 1) enable CORS requests in your Superset App from {`${window.location.origin}`} + 1) enable CORS requests in your Superset App from{' '} + {`${window.location.origin}`}
2) configure your Superset App host name below
- 3) click below to verify authentication. You may debug CORS further using the - `@superset-ui/connection` story.
+ 3) click below to verify authentication. You may debug CORS further + using the `@superset-ui/connection` story.

-
diff --git a/packages/superset-ui-demo/storybook/shared/components/createQueryStory.tsx b/packages/superset-ui-demo/storybook/shared/components/createQueryStory.tsx index 5444d6a2bb..eb1d39e41a 100644 --- a/packages/superset-ui-demo/storybook/shared/components/createQueryStory.tsx +++ b/packages/superset-ui-demo/storybook/shared/components/createQueryStory.tsx @@ -19,7 +19,11 @@ import React from 'react'; import { text, select } from '@storybook/addon-knobs'; -import { SuperChart, ChartDataProvider, SupersetClient } from '@superset-ui/core'; +import { + SuperChart, + ChartDataProvider, + SupersetClient, +} from '@superset-ui/core'; import Expandable from './Expandable'; import VerifyCORS, { renderError } from './VerifyCORS'; @@ -37,12 +41,18 @@ export default function createQueryStory({ }) { const keys = Object.keys(choices); const story = () => { - const host = text('Set Superset App host for CORS request', 'localhost:8088'); + const host = text( + 'Set Superset App host for CORS request', + 'localhost:8088', + ); const mode = select('Choose mode:', keys, keys[0]); const { formData: presetFormData, chartType } = choices[mode]; const width = text('Vis width', '400'); const height = text('Vis height', '400'); - const formData = text('Override formData', JSON.stringify(presetFormData, null, 2)); + const formData = text( + 'Override formData', + JSON.stringify(presetFormData, null, 2), + ); return (
@@ -71,7 +81,9 @@ export default function createQueryStory({ />
-
{JSON.stringify(payload, null, 2)}
+
+                          {JSON.stringify(payload, null, 2)}
+                        
); diff --git a/packages/superset-ui-demo/storybook/stories/plugins/legacy-plugin-chart-chord/data.ts b/packages/superset-ui-demo/storybook/stories/plugins/legacy-plugin-chart-chord/data.ts index 58fb6ee03a..979029aa61 100644 --- a/packages/superset-ui-demo/storybook/stories/plugins/legacy-plugin-chart-chord/data.ts +++ b/packages/superset-ui-demo/storybook/stories/plugins/legacy-plugin-chart-chord/data.ts @@ -27,5 +27,13 @@ export default { [16, 32, 299, 123, 146, 1], [22, 83, 53, 21, 22, 6], ], - nodes: ['Hong Kong', 'Tokyo', 'Taipei', 'Beijing', 'Bangkok', 'Jakarta', 'Singapore'], + nodes: [ + 'Hong Kong', + 'Tokyo', + 'Taipei', + 'Beijing', + 'Bangkok', + 'Jakarta', + 'Singapore', + ], }; diff --git a/packages/superset-ui-demo/storybook/stories/plugins/legacy-plugin-chart-country-map/CountryMapStories.tsx b/packages/superset-ui-demo/storybook/stories/plugins/legacy-plugin-chart-country-map/CountryMapStories.tsx index 5924d91064..f4d6be31c9 100644 --- a/packages/superset-ui-demo/storybook/stories/plugins/legacy-plugin-chart-country-map/CountryMapStories.tsx +++ b/packages/superset-ui-demo/storybook/stories/plugins/legacy-plugin-chart-country-map/CountryMapStories.tsx @@ -17,7 +17,12 @@ * under the License. */ import React, { useEffect, useState } from 'react'; -import { JsonObject, seedRandom, SuperChart, SequentialD3 } from '@superset-ui/core'; +import { + JsonObject, + seedRandom, + SuperChart, + SequentialD3, +} from '@superset-ui/core'; import CountryMapChartPlugin from '@superset-ui/legacy-plugin-chart-country-map/src'; import countries from '@superset-ui/legacy-plugin-chart-country-map/src/countries'; import { withKnobs, select } from '@storybook/addon-knobs'; @@ -60,7 +65,11 @@ export const basic = function BasicCountryMapStory({ width, height }) { }, [country]); if (!data) { - return
Loading...
; + return ( +
+ Loading... +
+ ); } return ( diff --git a/packages/superset-ui-demo/storybook/stories/plugins/legacy-plugin-chart-event-flow/Stories.jsx b/packages/superset-ui-demo/storybook/stories/plugins/legacy-plugin-chart-event-flow/Stories.jsx index 4f80f555ff..a28df94a9d 100644 --- a/packages/superset-ui-demo/storybook/stories/plugins/legacy-plugin-chart-event-flow/Stories.jsx +++ b/packages/superset-ui-demo/storybook/stories/plugins/legacy-plugin-chart-event-flow/Stories.jsx @@ -28,11 +28,13 @@ export default { title: 'Legacy Chart Plugins/legacy-plugin-chart-event-flow', }; -const data = sampleEvents.twentyUsers.allEvents.map(({ ENTITY_ID, EVENT_NAME, TS }) => ({ - __timestamp: TS, - eventName: EVENT_NAME, - userId: ENTITY_ID, -})); +const data = sampleEvents.twentyUsers.allEvents.map( + ({ ENTITY_ID, EVENT_NAME, TS }) => ({ + __timestamp: TS, + eventName: EVENT_NAME, + userId: ENTITY_ID, + }), +); export const basic = () => ( ( - + ); diff --git a/packages/superset-ui-demo/storybook/stories/plugins/legacy-plugin-chart-histogram/data.ts b/packages/superset-ui-demo/storybook/stories/plugins/legacy-plugin-chart-histogram/data.ts index 073b9d7a46..21ac39d508 100644 --- a/packages/superset-ui-demo/storybook/stories/plugins/legacy-plugin-chart-histogram/data.ts +++ b/packages/superset-ui-demo/storybook/stories/plugins/legacy-plugin-chart-histogram/data.ts @@ -22,10 +22,11 @@ export default [ { key: 'Entrance exam', values: [ - 0.87, 0.944, 1.0, 0.879, 0.69, 0.667, 0.794, 0.838, 0.875, 0.385, 0.968, 0.804, 1.0, 0.943, - 0.96, 0.333, 0.5, 0.929, 0.863, 0.75, 0.957, 0.914, 1.0, 0.909, 0.742, 0.964, 0.25, 0.75, 0.5, - 0.867, 0.909, 0.333, 0.867, 0.952, 0.857, 0.949, 0.857, 0.333, 0.8, 0.707, 0.833, 0.75, 0.88, - 0.771, 1.0, 1.0, 0.769, 1.0, 0.769, 0.622, 0.909, 0.725, 0.951, 1.0, + 0.87, 0.944, 1.0, 0.879, 0.69, 0.667, 0.794, 0.838, 0.875, 0.385, 0.968, + 0.804, 1.0, 0.943, 0.96, 0.333, 0.5, 0.929, 0.863, 0.75, 0.957, 0.914, + 1.0, 0.909, 0.742, 0.964, 0.25, 0.75, 0.5, 0.867, 0.909, 0.333, 0.867, + 0.952, 0.857, 0.949, 0.857, 0.333, 0.8, 0.707, 0.833, 0.75, 0.88, 0.771, + 1.0, 1.0, 0.769, 1.0, 0.769, 0.622, 0.909, 0.725, 0.951, 1.0, ], }, ]; diff --git a/packages/superset-ui-demo/storybook/stories/plugins/legacy-plugin-chart-parallel-coordinates/Stories.tsx b/packages/superset-ui-demo/storybook/stories/plugins/legacy-plugin-chart-parallel-coordinates/Stories.tsx index 514db8e3ee..df907b8a61 100644 --- a/packages/superset-ui-demo/storybook/stories/plugins/legacy-plugin-chart-parallel-coordinates/Stories.tsx +++ b/packages/superset-ui-demo/storybook/stories/plugins/legacy-plugin-chart-parallel-coordinates/Stories.tsx @@ -22,7 +22,9 @@ import { SuperChart } from '@superset-ui/core'; import ParallelCoordinatesChartPlugin from '@superset-ui/legacy-plugin-chart-parallel-coordinates'; import data from './data'; -new ParallelCoordinatesChartPlugin().configure({ key: 'parallel-coordinates' }).register(); +new ParallelCoordinatesChartPlugin() + .configure({ key: 'parallel-coordinates' }) + .register(); export default { title: 'Legacy Chart Plugins/legacy-plugin-chart-parallel-coordinates', diff --git a/packages/superset-ui-demo/storybook/stories/plugins/legacy-preset-chart-big-number/BigNumberTotal/BigNumberTotalStories.tsx b/packages/superset-ui-demo/storybook/stories/plugins/legacy-preset-chart-big-number/BigNumberTotal/BigNumberTotalStories.tsx index 1dac150a3e..f99d4f2e03 100644 --- a/packages/superset-ui-demo/storybook/stories/plugins/legacy-preset-chart-big-number/BigNumberTotal/BigNumberTotalStories.tsx +++ b/packages/superset-ui-demo/storybook/stories/plugins/legacy-preset-chart-big-number/BigNumberTotal/BigNumberTotalStories.tsx @@ -21,7 +21,9 @@ import { SuperChart } from '@superset-ui/core'; import { BigNumberTotalChartPlugin } from '@superset-ui/legacy-preset-chart-big-number'; import data from './data'; -new BigNumberTotalChartPlugin().configure({ key: 'big-number-total' }).register(); +new BigNumberTotalChartPlugin() + .configure({ key: 'big-number-total' }) + .register(); export default { title: 'Legacy Chart Plugins/legacy-preset-big-number/BigNumberTotal', diff --git a/packages/superset-ui-demo/storybook/stories/plugins/legacy-preset-chart-nvd3/Area/Stories.tsx b/packages/superset-ui-demo/storybook/stories/plugins/legacy-preset-chart-nvd3/Area/Stories.tsx index ae92fb84de..86d2306125 100644 --- a/packages/superset-ui-demo/storybook/stories/plugins/legacy-preset-chart-nvd3/Area/Stories.tsx +++ b/packages/superset-ui-demo/storybook/stories/plugins/legacy-preset-chart-nvd3/Area/Stories.tsx @@ -26,6 +26,9 @@ export default { }; export { stacked } from './stories/stacked'; -export { stackedWithYAxisBounds, stackedWithYAxisBoundsMinOnly } from './stories/stackedWithBounds'; +export { + stackedWithYAxisBounds, + stackedWithYAxisBoundsMinOnly, +} from './stories/stackedWithBounds'; export { expanded } from './stories/expanded'; export { controlsShown } from './stories/controlsShown'; diff --git a/packages/superset-ui-demo/storybook/stories/plugins/legacy-preset-chart-nvd3/Bar/stories/barWithPositiveAndNegativeValues.tsx b/packages/superset-ui-demo/storybook/stories/plugins/legacy-preset-chart-nvd3/Bar/stories/barWithPositiveAndNegativeValues.tsx index a25a13264a..513278ab77 100644 --- a/packages/superset-ui-demo/storybook/stories/plugins/legacy-preset-chart-nvd3/Bar/stories/barWithPositiveAndNegativeValues.tsx +++ b/packages/superset-ui-demo/storybook/stories/plugins/legacy-preset-chart-nvd3/Bar/stories/barWithPositiveAndNegativeValues.tsx @@ -32,7 +32,10 @@ export const barWithPositiveAndNegativeValues = () => ( { data: data.map((group, i) => ({ ...group, - values: group.values.map(pair => ({ ...pair, y: (i % 2 === 0 ? 1 : -1) * pair.y })), + values: group.values.map(pair => ({ + ...pair, + y: (i % 2 === 0 ? 1 : -1) * pair.y, + })), })), }, ]} diff --git a/packages/superset-ui-demo/storybook/stories/plugins/legacy-preset-chart-nvd3/DistBar/stories/manyBars.tsx b/packages/superset-ui-demo/storybook/stories/plugins/legacy-preset-chart-nvd3/DistBar/stories/manyBars.tsx index fcb1117a93..a609b7c690 100644 --- a/packages/superset-ui-demo/storybook/stories/plugins/legacy-preset-chart-nvd3/DistBar/stories/manyBars.tsx +++ b/packages/superset-ui-demo/storybook/stories/plugins/legacy-preset-chart-nvd3/DistBar/stories/manyBars.tsx @@ -33,7 +33,10 @@ const LONG_LABEL = for (let i = 0; i < 50; i += 1) { data[0].values.push({ - x: `${LONG_LABEL.substring(0, Math.round(seedRandom() * LONG_LABEL.length))} ${i + 1}`, + x: `${LONG_LABEL.substring( + 0, + Math.round(seedRandom() * LONG_LABEL.length), + )} ${i + 1}`, y: Math.round(seedRandom() * 10000), }); } diff --git a/packages/superset-ui-demo/storybook/stories/plugins/plugin-chart-echarts/BoxPlot/Stories.tsx b/packages/superset-ui-demo/storybook/stories/plugins/plugin-chart-echarts/BoxPlot/Stories.tsx index 8d9073a20e..5a0724e416 100644 --- a/packages/superset-ui-demo/storybook/stories/plugins/plugin-chart-echarts/BoxPlot/Stories.tsx +++ b/packages/superset-ui-demo/storybook/stories/plugins/plugin-chart-echarts/BoxPlot/Stories.tsx @@ -25,9 +25,14 @@ import transformProps from '@superset-ui/plugin-chart-echarts/lib/BoxPlot/transf import data from './data'; import { withResizableChartDemo } from '../../../../shared/components/ResizableChartDemo'; -new EchartsBoxPlotChartPlugin().configure({ key: 'echarts-boxplot' }).register(); +new EchartsBoxPlotChartPlugin() + .configure({ key: 'echarts-boxplot' }) + .register(); -getChartTransformPropsRegistry().registerValue('echarts-boxplot', transformProps); +getChartTransformPropsRegistry().registerValue( + 'echarts-boxplot', + transformProps, +); export default { title: 'Chart Plugins/plugin-chart-echarts/BoxPlot', @@ -45,7 +50,11 @@ export const BoxPlot = ({ width, height }) => ( groupby: ['type', 'region'], metrics: ['AVG(averageprice)'], whiskerOptions: 'Tukey', - xTicksLayout: select('X Tick Layout', ['auto', 'flat', '45°', '90°', 'staggered'], '45°'), + xTicksLayout: select( + 'X Tick Layout', + ['auto', 'flat', '45°', '90°', 'staggered'], + '45°', + ), yAxisFormat: 'SMART_NUMBER', }} /> diff --git a/packages/superset-ui-demo/storybook/stories/plugins/plugin-chart-echarts/Funnel/Stories.tsx b/packages/superset-ui-demo/storybook/stories/plugins/plugin-chart-echarts/Funnel/Stories.tsx index 334465fb53..cca38ab38a 100644 --- a/packages/superset-ui-demo/storybook/stories/plugins/plugin-chart-echarts/Funnel/Stories.tsx +++ b/packages/superset-ui-demo/storybook/stories/plugins/plugin-chart-echarts/Funnel/Stories.tsx @@ -27,7 +27,10 @@ import { withResizableChartDemo } from '../../../../shared/components/ResizableC new EchartsFunnelChartPlugin().configure({ key: 'echarts-funnel' }).register(); -getChartTransformPropsRegistry().registerValue('echarts-funnel', transformProps); +getChartTransformPropsRegistry().registerValue( + 'echarts-funnel', + transformProps, +); export default { title: 'Chart Plugins/plugin-chart-echarts/Funnel', @@ -50,7 +53,14 @@ export const Funnel = ({ width, height }) => ( gap: number('gap', 0), labelType: select( 'label type', - ['key', 'value', 'percent', 'key_value', 'key_percent', 'key_value_percent'], + [ + 'key', + 'value', + 'percent', + 'key_value', + 'key_percent', + 'key_value_percent', + ], 'key', ), labelLine: boolean('Label line', true), diff --git a/packages/superset-ui-demo/storybook/stories/plugins/plugin-chart-echarts/MixedTimeseries/Stories.tsx b/packages/superset-ui-demo/storybook/stories/plugins/plugin-chart-echarts/MixedTimeseries/Stories.tsx index 101e0c0b98..45ce36c109 100644 --- a/packages/superset-ui-demo/storybook/stories/plugins/plugin-chart-echarts/MixedTimeseries/Stories.tsx +++ b/packages/superset-ui-demo/storybook/stories/plugins/plugin-chart-echarts/MixedTimeseries/Stories.tsx @@ -19,15 +19,26 @@ import React from 'react'; import { SuperChart, getChartTransformPropsRegistry } from '@superset-ui/core'; -import { boolean, number, text, select, withKnobs } from '@storybook/addon-knobs'; +import { + boolean, + number, + text, + select, + withKnobs, +} from '@storybook/addon-knobs'; import { EchartsTimeseriesChartPlugin } from '@superset-ui/plugin-chart-echarts'; import transformProps from '@superset-ui/plugin-chart-echarts/lib/MixedTimeseries/transformProps'; import data from '../Timeseries/data'; import { withResizableChartDemo } from '../../../../shared/components/ResizableChartDemo'; -new EchartsTimeseriesChartPlugin().configure({ key: 'mixed-timeseries' }).register(); +new EchartsTimeseriesChartPlugin() + .configure({ key: 'mixed-timeseries' }) + .register(); -getChartTransformPropsRegistry().registerValue('mixed-timeseries', transformProps); +getChartTransformPropsRegistry().registerValue( + 'mixed-timeseries', + transformProps, +); export default { title: 'Chart Plugins/plugin-chart-echarts/MixedTimeseries', diff --git a/packages/superset-ui-demo/storybook/stories/plugins/plugin-chart-echarts/Pie/Stories.tsx b/packages/superset-ui-demo/storybook/stories/plugins/plugin-chart-echarts/Pie/Stories.tsx index a5434332e8..a062f9ea09 100644 --- a/packages/superset-ui-demo/storybook/stories/plugins/plugin-chart-echarts/Pie/Stories.tsx +++ b/packages/superset-ui-demo/storybook/stories/plugins/plugin-chart-echarts/Pie/Stories.tsx @@ -54,7 +54,14 @@ export const WeekdayPie = ({ width, height }) => ( showLegend: boolean('Show legend', false), labelType: select( 'Pie label type', - ['key', 'value', 'percent', 'key_value', 'key_percent', 'key_value_percent'], + [ + 'key', + 'value', + 'percent', + 'key_value', + 'key_percent', + 'key_value_percent', + ], 'key', ), }} @@ -81,7 +88,14 @@ export const PopulationPie = ({ width, height }) => ( showLegend: boolean('Show legend', false), labelType: select( 'Pie label type', - ['key', 'value', 'percent', 'key_value', 'key_percent', 'key_value_percent'], + [ + 'key', + 'value', + 'percent', + 'key_value', + 'key_percent', + 'key_value_percent', + ], 'key', ), }} diff --git a/packages/superset-ui-demo/storybook/stories/plugins/plugin-chart-echarts/Timeseries/Stories.tsx b/packages/superset-ui-demo/storybook/stories/plugins/plugin-chart-echarts/Timeseries/Stories.tsx index 769290d195..468dc88dcb 100644 --- a/packages/superset-ui-demo/storybook/stories/plugins/plugin-chart-echarts/Timeseries/Stories.tsx +++ b/packages/superset-ui-demo/storybook/stories/plugins/plugin-chart-echarts/Timeseries/Stories.tsx @@ -25,9 +25,14 @@ import transformProps from '@superset-ui/plugin-chart-echarts/lib/Timeseries/tra import data from './data'; import { withResizableChartDemo } from '../../../../shared/components/ResizableChartDemo'; -new EchartsTimeseriesChartPlugin().configure({ key: 'echarts-timeseries' }).register(); +new EchartsTimeseriesChartPlugin() + .configure({ key: 'echarts-timeseries' }) + .register(); -getChartTransformPropsRegistry().registerValue('echarts-timeseries', transformProps); +getChartTransformPropsRegistry().registerValue( + 'echarts-timeseries', + transformProps, +); export default { title: 'Chart Plugins/plugin-chart-echarts/Timeseries', diff --git a/packages/superset-ui-demo/storybook/stories/plugins/plugin-chart-echarts/Tree/Stories.tsx b/packages/superset-ui-demo/storybook/stories/plugins/plugin-chart-echarts/Tree/Stories.tsx index bb2b4f9a48..99f004dcf6 100644 --- a/packages/superset-ui-demo/storybook/stories/plugins/plugin-chart-echarts/Tree/Stories.tsx +++ b/packages/superset-ui-demo/storybook/stories/plugins/plugin-chart-echarts/Tree/Stories.tsx @@ -45,17 +45,38 @@ export const Tree = ({ width, height }) => ( datasource: '3__table', granularity_sqla: 'ds', metric: 'count', - id: select('Id Column', ['id_column', 'name_column', 'parent_column'], 'id_column'), + id: select( + 'Id Column', + ['id_column', 'name_column', 'parent_column'], + 'id_column', + ), rootNodeId: text('Root Node', '1'), - parent: select('Parent Column', ['parent_column', 'id_column'], 'parent_column'), + parent: select( + 'Parent Column', + ['parent_column', 'id_column'], + 'parent_column', + ), name: select('Name Column', [null, 'name_column'], 'name_column'), - position: select('Label Position', ['top', 'right', 'left', 'bottom'], 'top'), + position: select( + 'Label Position', + ['top', 'right', 'left', 'bottom'], + 'top', + ), layout: select('Tree Layout', ['orthogonal', 'radial'], 'orthogonal'), orient: select('Orientation', ['LR', 'RL', 'TB', 'BT'], 'LR'), emphasis: select('Emphasis', ['ancestor', 'descendant'], 'descendant'), - symbol: select('Symbol', ['emptyCircle', 'circle', 'rect', 'triangle'], 'circle'), - symbol_size: number('[Symbol Size', 7, { range: true, min: 5, max: 30, step: 2 }), + symbol: select( + 'Symbol', + ['emptyCircle', 'circle', 'rect', 'triangle'], + 'circle', + ), + symbol_size: number('[Symbol Size', 7, { + range: true, + min: 5, + max: 30, + step: 2, + }), }} /> ); diff --git a/packages/superset-ui-demo/storybook/stories/plugins/plugin-chart-echarts/Treemap/Stories.tsx b/packages/superset-ui-demo/storybook/stories/plugins/plugin-chart-echarts/Treemap/Stories.tsx index b0b46f68b1..ec465aa030 100644 --- a/packages/superset-ui-demo/storybook/stories/plugins/plugin-chart-echarts/Treemap/Stories.tsx +++ b/packages/superset-ui-demo/storybook/stories/plugins/plugin-chart-echarts/Treemap/Stories.tsx @@ -25,9 +25,14 @@ import transformProps from '@superset-ui/plugin-chart-echarts/lib/Treemap/transf import data from './data'; import { withResizableChartDemo } from '../../../../shared/components/ResizableChartDemo'; -new EchartsTreemapChartPlugin().configure({ key: 'echarts-treemap' }).register(); +new EchartsTreemapChartPlugin() + .configure({ key: 'echarts-treemap' }) + .register(); -getChartTransformPropsRegistry().registerValue('echarts-treemap', transformProps); +getChartTransformPropsRegistry().registerValue( + 'echarts-treemap', + transformProps, +); export default { title: 'Chart Plugins/plugin-chart-echarts/Treemap', @@ -46,7 +51,11 @@ export const Treemap = ({ width, height }) => ( metric: 'count', showLabels: boolean('Show labels', true), showUpperLabels: boolean('Show upperLabels', true), - labelType: select('Treemap label type', ['key', 'value', 'key_value'], 'key_value'), + labelType: select( + 'Treemap label type', + ['key', 'value', 'key_value'], + 'key_value', + ), }} /> ); diff --git a/packages/superset-ui-demo/storybook/stories/plugins/plugin-chart-table/TableStories.tsx b/packages/superset-ui-demo/storybook/stories/plugins/plugin-chart-table/TableStories.tsx index fb786ecc59..c89dff86c5 100644 --- a/packages/superset-ui-demo/storybook/stories/plugins/plugin-chart-table/TableStories.tsx +++ b/packages/superset-ui-demo/storybook/stories/plugins/plugin-chart-table/TableStories.tsx @@ -21,7 +21,9 @@ import React from 'react'; import memoizeOne from 'memoize-one'; import { withKnobs, number, boolean } from '@storybook/addon-knobs'; import { SuperChart } from '@superset-ui/core'; -import TableChartPlugin, { TableChartProps } from '@superset-ui/plugin-chart-table/src'; +import TableChartPlugin, { + TableChartProps, +} from '@superset-ui/plugin-chart-table/src'; import { basicFormData, basicData, birthNames } from './testData'; import { withResizableChartDemo } from '../../../shared/components/ResizableChartDemo'; @@ -125,7 +127,14 @@ export const BigTable = ({ width, height }) => { showCellBars, includeSearch, }); - return ; + return ( + + ); }; BigTable.story = { parameters: { diff --git a/packages/superset-ui-demo/storybook/stories/plugins/plugin-chart-table/testData.ts b/packages/superset-ui-demo/storybook/stories/plugins/plugin-chart-table/testData.ts index 1be44ac7b2..75d6f5f09b 100644 --- a/packages/superset-ui-demo/storybook/stories/plugins/plugin-chart-table/testData.ts +++ b/packages/superset-ui-demo/storybook/stories/plugins/plugin-chart-table/testData.ts @@ -16,8 +16,14 @@ * specific language governing permissions and limitations * under the License. */ -import { ChartDataResponseResult, GenericDataType } from '@superset-ui/core/src'; -import { TableChartFormData, TableChartProps } from '@superset-ui/plugin-chart-table/src'; +import { + ChartDataResponseResult, + GenericDataType, +} from '@superset-ui/core/src'; +import { + TableChartFormData, + TableChartProps, +} from '@superset-ui/plugin-chart-table/src'; // @ts-ignore // eslint-disable-next-line import/extensions import birthNamesJson from './birthNames.json'; diff --git a/packages/superset-ui-demo/storybook/stories/plugins/plugin-chart-word-cloud/Stories.tsx b/packages/superset-ui-demo/storybook/stories/plugins/plugin-chart-word-cloud/Stories.tsx index cff36df1b9..25d28d40f2 100644 --- a/packages/superset-ui-demo/storybook/stories/plugins/plugin-chart-word-cloud/Stories.tsx +++ b/packages/superset-ui-demo/storybook/stories/plugins/plugin-chart-word-cloud/Stories.tsx @@ -29,7 +29,9 @@ import { withResizableChartDemo } from '../../../shared/components/ResizableChar import data from './data'; new WordCloudChartPlugin().configure({ key: 'word-cloud2' }).register(); -new LegacyWordCloudChartPlugin().configure({ key: 'legacy-word-cloud2' }).register(); +new LegacyWordCloudChartPlugin() + .configure({ key: 'legacy-word-cloud2' }) + .register(); // Enable the new WordCloud Props to show case its full features // if the control panel is updated to be able to pass formData in the new format. diff --git a/packages/superset-ui-demo/storybook/stories/plugins/preset-chart-xy/BoxPlot/Stories.tsx b/packages/superset-ui-demo/storybook/stories/plugins/preset-chart-xy/BoxPlot/Stories.tsx index 7772b0f53e..6fa4efb072 100644 --- a/packages/superset-ui-demo/storybook/stories/plugins/preset-chart-xy/BoxPlot/Stories.tsx +++ b/packages/superset-ui-demo/storybook/stories/plugins/preset-chart-xy/BoxPlot/Stories.tsx @@ -17,10 +17,15 @@ * under the License. */ -import { BoxPlotChartPlugin, LegacyBoxPlotChartPlugin } from '@superset-ui/preset-chart-xy'; +import { + BoxPlotChartPlugin, + LegacyBoxPlotChartPlugin, +} from '@superset-ui/preset-chart-xy'; import { BOX_PLOT_PLUGIN_LEGACY_TYPE, BOX_PLOT_PLUGIN_TYPE } from './constants'; -new LegacyBoxPlotChartPlugin().configure({ key: BOX_PLOT_PLUGIN_LEGACY_TYPE }).register(); +new LegacyBoxPlotChartPlugin() + .configure({ key: BOX_PLOT_PLUGIN_LEGACY_TYPE }) + .register(); new BoxPlotChartPlugin().configure({ key: BOX_PLOT_PLUGIN_TYPE }).register(); export default { diff --git a/packages/superset-ui-demo/storybook/stories/plugins/preset-chart-xy/Line/Stories.tsx b/packages/superset-ui-demo/storybook/stories/plugins/preset-chart-xy/Line/Stories.tsx index d5ad581a0a..8b20351c6b 100644 --- a/packages/superset-ui-demo/storybook/stories/plugins/preset-chart-xy/Line/Stories.tsx +++ b/packages/superset-ui-demo/storybook/stories/plugins/preset-chart-xy/Line/Stories.tsx @@ -17,11 +17,16 @@ * under the License. */ -import { LineChartPlugin, LegacyLineChartPlugin } from '@superset-ui/preset-chart-xy'; +import { + LineChartPlugin, + LegacyLineChartPlugin, +} from '@superset-ui/preset-chart-xy'; import { withKnobs } from '@storybook/addon-knobs'; import { LINE_PLUGIN_TYPE, LINE_PLUGIN_LEGACY_TYPE } from './constants'; -new LegacyLineChartPlugin().configure({ key: LINE_PLUGIN_LEGACY_TYPE }).register(); +new LegacyLineChartPlugin() + .configure({ key: LINE_PLUGIN_LEGACY_TYPE }) + .register(); new LineChartPlugin().configure({ key: LINE_PLUGIN_TYPE }).register(); export default { diff --git a/packages/superset-ui-demo/storybook/stories/plugins/preset-chart-xy/Line/stories/basic.tsx b/packages/superset-ui-demo/storybook/stories/plugins/preset-chart-xy/Line/stories/basic.tsx index f68da6082d..4659a5c887 100644 --- a/packages/superset-ui-demo/storybook/stories/plugins/preset-chart-xy/Line/stories/basic.tsx +++ b/packages/superset-ui-demo/storybook/stories/plugins/preset-chart-xy/Line/stories/basic.tsx @@ -39,8 +39,16 @@ export default () => ( type: 'time', }, axis: { - orient: radios('x.axis.orient', { top: 'top', bottom: 'bottom' }, 'bottom'), - title: radios('x.axis.title', { enable: 'Time', disable: '', '': undefined }, 'Time'), + orient: radios( + 'x.axis.orient', + { top: 'top', bottom: 'bottom' }, + 'bottom', + ), + title: radios( + 'x.axis.title', + { enable: 'Time', disable: '', '': undefined }, + 'Time', + ), }, }, y: { @@ -55,7 +63,11 @@ export default () => ( { left: 'left', right: 'right', '': undefined }, 'left', ), - title: radios('y.axis.title', { enable: 'Score', disable: '', '': undefined }, 'Score'), + title: radios( + 'y.axis.title', + { enable: 'Score', disable: '', '': undefined }, + 'Score', + ), }, }, stroke: { diff --git a/packages/superset-ui-demo/storybook/stories/plugins/preset-chart-xy/Line/stories/flush.tsx b/packages/superset-ui-demo/storybook/stories/plugins/preset-chart-xy/Line/stories/flush.tsx index 8cb0ce09cf..aff3f5cfa8 100644 --- a/packages/superset-ui-demo/storybook/stories/plugins/preset-chart-xy/Line/stories/flush.tsx +++ b/packages/superset-ui-demo/storybook/stories/plugins/preset-chart-xy/Line/stories/flush.tsx @@ -48,8 +48,16 @@ export default () => ( }, axis: { tickCount: 6, - orient: radios('x.axis.orient', { top: 'top', bottom: 'bottom' }, 'bottom'), - title: radios('x.axis.title', { enable: 'Time', disable: '', '': undefined }, 'Time'), + orient: radios( + 'x.axis.orient', + { top: 'top', bottom: 'bottom' }, + 'bottom', + ), + title: radios( + 'x.axis.title', + { enable: 'Time', disable: '', '': undefined }, + 'Time', + ), }, }, y: { @@ -100,8 +108,16 @@ export default () => ( axis: { labelFlush: 5, tickCount: 6, - orient: radios('x.axis.orient', { top: 'top', bottom: 'bottom' }, 'bottom'), - title: radios('x.axis.title', { enable: 'Time', disable: '', '': undefined }, 'Time'), + orient: radios( + 'x.axis.orient', + { top: 'top', bottom: 'bottom' }, + 'bottom', + ), + title: radios( + 'x.axis.title', + { enable: 'Time', disable: '', '': undefined }, + 'Time', + ), }, }, y: { diff --git a/packages/superset-ui-demo/storybook/stories/plugins/preset-chart-xy/ScatterPlot/Stories.tsx b/packages/superset-ui-demo/storybook/stories/plugins/preset-chart-xy/ScatterPlot/Stories.tsx index bb6a8640d8..ec3135e6d4 100644 --- a/packages/superset-ui-demo/storybook/stories/plugins/preset-chart-xy/ScatterPlot/Stories.tsx +++ b/packages/superset-ui-demo/storybook/stories/plugins/preset-chart-xy/ScatterPlot/Stories.tsx @@ -17,12 +17,22 @@ * under the License. */ -import { ScatterPlotChartPlugin, LegacyScatterPlotChartPlugin } from '@superset-ui/preset-chart-xy'; +import { + ScatterPlotChartPlugin, + LegacyScatterPlotChartPlugin, +} from '@superset-ui/preset-chart-xy'; import { withKnobs } from '@storybook/addon-knobs'; -import { SCATTER_PLOT_PLUGIN_TYPE, SCATTER_PLOT_PLUGIN_LEGACY_TYPE } from './constants'; +import { + SCATTER_PLOT_PLUGIN_TYPE, + SCATTER_PLOT_PLUGIN_LEGACY_TYPE, +} from './constants'; -new LegacyScatterPlotChartPlugin().configure({ key: SCATTER_PLOT_PLUGIN_LEGACY_TYPE }).register(); -new ScatterPlotChartPlugin().configure({ key: SCATTER_PLOT_PLUGIN_TYPE }).register(); +new LegacyScatterPlotChartPlugin() + .configure({ key: SCATTER_PLOT_PLUGIN_LEGACY_TYPE }) + .register(); +new ScatterPlotChartPlugin() + .configure({ key: SCATTER_PLOT_PLUGIN_TYPE }) + .register(); export default { title: 'Chart Plugins/preset-chart-xy/ScatterPlot', diff --git a/packages/superset-ui-demo/storybook/stories/plugins/preset-chart-xy/ScatterPlot/stories/basic.tsx b/packages/superset-ui-demo/storybook/stories/plugins/preset-chart-xy/ScatterPlot/stories/basic.tsx index 4e42d51a09..42bc331306 100644 --- a/packages/superset-ui-demo/storybook/stories/plugins/preset-chart-xy/ScatterPlot/stories/basic.tsx +++ b/packages/superset-ui-demo/storybook/stories/plugins/preset-chart-xy/ScatterPlot/stories/basic.tsx @@ -42,7 +42,11 @@ export default () => ( type: 'linear', }, axis: { - orient: radios('x.axis.orient', { top: 'top', bottom: 'bottom' }, 'bottom'), + orient: radios( + 'x.axis.orient', + { top: 'top', bottom: 'bottom' }, + 'bottom', + ), }, }, y: { @@ -52,7 +56,11 @@ export default () => ( type: 'linear', }, axis: { - orient: radios('y.axis.orient', { left: 'left', right: 'right' }, 'left'), + orient: radios( + 'y.axis.orient', + { left: 'left', right: 'right' }, + 'left', + ), }, }, fill: { diff --git a/packages/superset-ui-demo/storybook/stories/plugins/preset-chart-xy/ScatterPlot/stories/bubble.tsx b/packages/superset-ui-demo/storybook/stories/plugins/preset-chart-xy/ScatterPlot/stories/bubble.tsx index 21db17151e..6a782b2b4b 100644 --- a/packages/superset-ui-demo/storybook/stories/plugins/preset-chart-xy/ScatterPlot/stories/bubble.tsx +++ b/packages/superset-ui-demo/storybook/stories/plugins/preset-chart-xy/ScatterPlot/stories/bubble.tsx @@ -42,7 +42,11 @@ export default () => ( type: 'linear', }, axis: { - orient: radios('x.axis.orient', { top: 'top', bottom: 'bottom' }, 'bottom'), + orient: radios( + 'x.axis.orient', + { top: 'top', bottom: 'bottom' }, + 'bottom', + ), }, }, y: { @@ -52,7 +56,11 @@ export default () => ( type: 'linear', }, axis: { - orient: radios('y.axis.orient', { left: 'left', right: 'right' }, 'left'), + orient: radios( + 'y.axis.orient', + { left: 'left', right: 'right' }, + 'left', + ), }, }, size: { diff --git a/packages/superset-ui-demo/storybook/stories/superset-ui-chart/ChartDataProviderStories.tsx b/packages/superset-ui-demo/storybook/stories/superset-ui-chart/ChartDataProviderStories.tsx index 806722bb75..14d4d6d8bd 100644 --- a/packages/superset-ui-demo/storybook/stories/superset-ui-chart/ChartDataProviderStories.tsx +++ b/packages/superset-ui-demo/storybook/stories/superset-ui-chart/ChartDataProviderStories.tsx @@ -20,7 +20,11 @@ import React from 'react'; import { text, select, withKnobs } from '@storybook/addon-knobs'; -import { SuperChart, ChartDataProvider, SupersetClient } from '@superset-ui/core'; +import { + SuperChart, + ChartDataProvider, + SupersetClient, +} from '@superset-ui/core'; import { BigNumberChartPlugin as LegacyBigNumberPlugin } from '@superset-ui/legacy-preset-chart-big-number'; import LegacySankeyPlugin from '@superset-ui/legacy-plugin-chart-sankey'; import LegacySunburstPlugin from '@superset-ui/legacy-plugin-chart-sunburst'; @@ -73,13 +77,19 @@ export const dataProvider = () => { const visType = select('Chart Plugin Type', VIS_TYPES, VIS_TYPES[0]); const width = text('Vis width', '500'); const height = text('Vis height', '300'); - const formData = text('Override formData', JSON.stringify(FORM_DATA_LOOKUP[visType])); + const formData = text( + 'Override formData', + JSON.stringify(FORM_DATA_LOOKUP[visType]), + ); return (
{() => ( - + {({ loading, payload, error }) => { if (loading) return
Loading!
; @@ -99,7 +109,9 @@ export const dataProvider = () => { />
-
{JSON.stringify(payload, null, 2)}
+
+                        {JSON.stringify(payload, null, 2)}
+                      
); diff --git a/packages/superset-ui-demo/storybook/stories/superset-ui-chart/SuperChartStories.tsx b/packages/superset-ui-demo/storybook/stories/superset-ui-chart/SuperChartStories.tsx index 9e1a5e5e29..c46fb81626 100644 --- a/packages/superset-ui-demo/storybook/stories/superset-ui-chart/SuperChartStories.tsx +++ b/packages/superset-ui-demo/storybook/stories/superset-ui-chart/SuperChartStories.tsx @@ -147,17 +147,23 @@ export const withNoResults = () => { const width = text('Vis width', '100%'); const height = text('Vis height', '100%'); - return ; + return ( + + ); }; export const withNoResultsAndMedium = () => { const width = text('Vis width', '400'); const height = text('Vis height', '300'); - return ; + return ( + + ); }; export const withNoResultsAndSmall = () => { const width = text('Vis width', '150'); const height = text('Vis height', '200'); - return ; + return ( + + ); }; diff --git a/packages/superset-ui-demo/storybook/stories/superset-ui-connection/ConnectionStories.tsx b/packages/superset-ui-demo/storybook/stories/superset-ui-connection/ConnectionStories.tsx index 09a86baf6d..d73998784a 100644 --- a/packages/superset-ui-demo/storybook/stories/superset-ui-connection/ConnectionStories.tsx +++ b/packages/superset-ui-demo/storybook/stories/superset-ui-connection/ConnectionStories.tsx @@ -21,7 +21,9 @@ import React from 'react'; import { select, text, withKnobs } from '@storybook/addon-knobs'; import { bigNumberFormData } from '@superset-ui/core/test/chart/fixtures/formData'; -import VerifyCORS, { Props as VerifyCORSProps } from '../../shared/components/VerifyCORS'; +import VerifyCORS, { + Props as VerifyCORSProps, +} from '../../shared/components/VerifyCORS'; import Expandable from '../../shared/components/Expandable'; const REQUEST_METHODS = ['GET', 'POST']; @@ -44,7 +46,9 @@ export const configureCORS = () => { const selectEndpoint = select('Endpoint', ENDPOINTS, ''); const customEndpoint = text('Custom Endpoint (override above)', ''); const endpoint = customEndpoint || selectEndpoint; - const method = endpoint ? select('Request method', REQUEST_METHODS, 'POST') : undefined; + const method = endpoint + ? select('Request method', REQUEST_METHODS, 'POST') + : undefined; const postPayload = endpoint && method === 'POST' ? text('POST payload', JSON.stringify({ form_data: bigNumberFormData })) @@ -60,11 +64,15 @@ export const configureCORS = () => { > {({ payload }) => ( <> -
Success! Update knobs below to try again
+
+ Success! Update knobs below to try again +


-
{JSON.stringify(payload, null, 2)}
+
+                {JSON.stringify(payload, null, 2)}
+              
)} diff --git a/packages/superset-ui-demo/storybook/stories/superset-ui-number-format/BigNumberStories.jsx b/packages/superset-ui-demo/storybook/stories/superset-ui-number-format/BigNumberStories.jsx index b8f2ae8003..a09920a620 100644 --- a/packages/superset-ui-demo/storybook/stories/superset-ui-number-format/BigNumberStories.jsx +++ b/packages/superset-ui-demo/storybook/stories/superset-ui-number-format/BigNumberStories.jsx @@ -69,9 +69,11 @@ class NumberFormatValidator extends React.PureComponent {

- This @superset-ui/number-format package enriches d3-format - to handle invalid formats as well as edge case values. Use the validator below to - preview outputs from the specified format string. See + This @superset-ui/number-format package enriches{' '} + d3-format + to handle invalid formats as well as edge case values. Use the + validator below to preview outputs from the specified format + string. See

This @superset-ui/time-format package enriches - d3-time-format to handle invalid formats as well as edge case values. Use - the validator below to preview outputs from the specified format string. See + d3-time-format to handle invalid formats as well as + edge case values. Use the validator below to preview outputs from + the specified format string. See ( - {v instanceof Date ? v.toUTCString() : `${v}`} + + {v instanceof Date ? v.toUTCString() : `${v}`} + "{formatTime(formatString, v)}" diff --git a/plugins/legacy-plugin-chart-calendar/src/Calendar.js b/plugins/legacy-plugin-chart-calendar/src/Calendar.js index 2d651c3b61..6b701c231a 100644 --- a/plugins/legacy-plugin-chart-calendar/src/Calendar.js +++ b/plugins/legacy-plugin-chart-calendar/src/Calendar.js @@ -98,7 +98,9 @@ function Calendar(element, props) { container.selectAll('*').remove(); const div = container.append('div'); - const subDomainTextFormat = showValues ? (date, value) => valueFormatter(value) : null; + const subDomainTextFormat = showValues + ? (date, value) => valueFormatter(value) + : null; // Trick to convert all timestamps to UTC // TODO: Verify if this conversion is really necessary @@ -107,7 +109,8 @@ function Calendar(element, props) { Object.keys(data.data).forEach(metric => { metricsData[metric] = {}; Object.keys(data.data[metric]).forEach(ts => { - metricsData[metric][convertUTCTS(ts * 1000) / 1000] = data.data[metric][ts]; + metricsData[metric][convertUTCTS(ts * 1000) / 1000] = + data.data[metric][ts]; }); }); diff --git a/plugins/legacy-plugin-chart-calendar/src/controlPanel.ts b/plugins/legacy-plugin-chart-calendar/src/controlPanel.ts index 4b3208c5d8..2787687b06 100644 --- a/plugins/legacy-plugin-chart-calendar/src/controlPanel.ts +++ b/plugins/legacy-plugin-chart-calendar/src/controlPanel.ts @@ -39,7 +39,13 @@ const config: ControlPanelConfig = { type: 'SelectControl', label: t('Domain'), default: 'month', - choices: formatSelectOptions(['hour', 'day', 'week', 'month', 'year']), + choices: formatSelectOptions([ + 'hour', + 'day', + 'week', + 'month', + 'year', + ]), description: t('The time unit used for the grouping of blocks'), }, }, @@ -49,7 +55,13 @@ const config: ControlPanelConfig = { type: 'SelectControl', label: t('Subdomain'), default: 'day', - choices: formatSelectOptions(['min', 'hour', 'day', 'week', 'month']), + choices: formatSelectOptions([ + 'min', + 'hour', + 'day', + 'week', + 'month', + ]), description: t( 'The time unit for each block. Should be a smaller unit than ' + 'domain_granularity. Should be larger or equal to Time Grain', @@ -152,7 +164,9 @@ const config: ControlPanelConfig = { label: t('Show Values'), renderTrigger: true, default: false, - description: t('Whether to display the numerical values within the cells'), + description: t( + 'Whether to display the numerical values within the cells', + ), }, }, ], diff --git a/plugins/legacy-plugin-chart-calendar/src/index.js b/plugins/legacy-plugin-chart-calendar/src/index.js index f77849cf35..5c0a9425ef 100644 --- a/plugins/legacy-plugin-chart-calendar/src/index.js +++ b/plugins/legacy-plugin-chart-calendar/src/index.js @@ -28,7 +28,14 @@ const metadata = new ChartMetadata({ "Visualizes how a metric has changed over a time using a color scale and a calendar view. Gray values are used to indicate missing values and the linear color scheme is used to encode the magnitude of each day's value.", ), name: t('Calendar Heatmap'), - tags: [t('Business'), t('Comparison'), t('Intensity'), t('Pattern'), t('Report'), t('Trend')], + tags: [ + t('Business'), + t('Comparison'), + t('Intensity'), + t('Pattern'), + t('Report'), + t('Trend'), + ], thumbnail, useLegacyApi: true, }); diff --git a/plugins/legacy-plugin-chart-calendar/src/vendor/cal-heatmap.js b/plugins/legacy-plugin-chart-calendar/src/vendor/cal-heatmap.js index 980ac1c1ea..572070f614 100644 --- a/plugins/legacy-plugin-chart-calendar/src/vendor/cal-heatmap.js +++ b/plugins/legacy-plugin-chart-calendar/src/vendor/cal-heatmap.js @@ -26,7 +26,9 @@ var CalHeatMap = function () { .offset([-5, 0]) .html( d => ` - ${self.options.timeFormatter(d.t)}: ${self.options.valueFormatter(d.v)} + ${self.options.timeFormatter(d.t)}: ${self.options.valueFormatter( + d.v, + )} `, ); self.legendTip = d3tip() @@ -365,7 +367,12 @@ var CalHeatMap = function () { case 'week': return 24 * 7; case 'month': - return 24 * (self.options.domainDynamicDimension ? self.getDayCountInMonth(d) : 31); + return ( + 24 * + (self.options.domainDynamicDimension + ? self.getDayCountInMonth(d) + : 31) + ); } }, defaultRowNumber: 6, @@ -376,7 +383,9 @@ var CalHeatMap = function () { case 'week': return 28; case 'month': - return self.options.domainDynamicDimension ? self.getDayCountInMonth(d) : 31; + return self.options.domainDynamicDimension + ? self.getDayCountInMonth(d) + : 31; } }, row: function (d) { @@ -390,17 +399,25 @@ var CalHeatMap = function () { if (self.options.domain === 'month') { if (self.options.colLimit > 0 || self.options.rowLimit > 0) { return Math.floor( - (d.getHours() + (d.getDate() - 1) * 24) / self._domainType.hour.row(d), + (d.getHours() + (d.getDate() - 1) * 24) / + self._domainType.hour.row(d), ); } - return Math.floor(d.getHours() / self._domainType.hour.row(d)) + (d.getDate() - 1) * 4; + return ( + Math.floor(d.getHours() / self._domainType.hour.row(d)) + + (d.getDate() - 1) * 4 + ); } else if (self.options.domain === 'week') { if (self.options.colLimit > 0 || self.options.rowLimit > 0) { return Math.floor( - (d.getHours() + self.getWeekDay(d) * 24) / self._domainType.hour.row(d), + (d.getHours() + self.getWeekDay(d) * 24) / + self._domainType.hour.row(d), ); } - return Math.floor(d.getHours() / self._domainType.hour.row(d)) + self.getWeekDay(d) * 4; + return ( + Math.floor(d.getHours() / self._domainType.hour.row(d)) + + self.getWeekDay(d) * 4 + ); } return Math.floor(d.getHours() / self._domainType.hour.row(d)); }, @@ -425,7 +442,12 @@ var CalHeatMap = function () { connector: 'at', }, extractUnit: function (d) { - return new Date(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours()).getTime(); + return new Date( + d.getFullYear(), + d.getMonth(), + d.getDate(), + d.getHours(), + ).getTime(); }, }, day: { @@ -436,9 +458,13 @@ var CalHeatMap = function () { case 'week': return 7; case 'month': - return self.options.domainDynamicDimension ? self.getDayCountInMonth(d) : 31; + return self.options.domainDynamicDimension + ? self.getDayCountInMonth(d) + : 31; case 'year': - return self.options.domainDynamicDimension ? self.getDayCountInYear(d) : 366; + return self.options.domainDynamicDimension + ? self.getDayCountInYear(d) + : 366; } }, defaultColumnNumber: function (d) { @@ -447,8 +473,11 @@ var CalHeatMap = function () { case 'week': return 1; case 'month': - return self.options.domainDynamicDimension && !self.options.verticalOrientation - ? self.getWeekNumber(new Date(d.getFullYear(), d.getMonth() + 1, 0)) - + return self.options.domainDynamicDimension && + !self.options.verticalOrientation + ? self.getWeekNumber( + new Date(d.getFullYear(), d.getMonth() + 1, 0), + ) - self.getWeekNumber(d) + 1 : 6; @@ -471,17 +500,24 @@ var CalHeatMap = function () { x: function (d) { switch (self.options.domain) { case 'week': - return Math.floor(self.getWeekDay(d) / self._domainType.day.row(d)); + return Math.floor( + self.getWeekDay(d) / self._domainType.day.row(d), + ); case 'month': if (self.options.colLimit > 0 || self.options.rowLimit > 0) { - return Math.floor((d.getDate() - 1) / self._domainType.day.row(d)); + return Math.floor( + (d.getDate() - 1) / self._domainType.day.row(d), + ); } return ( - self.getWeekNumber(d) - self.getWeekNumber(new Date(d.getFullYear(), d.getMonth())) + self.getWeekNumber(d) - + self.getWeekNumber(new Date(d.getFullYear(), d.getMonth())) ); case 'year': if (self.options.colLimit > 0 || self.options.rowLimit > 0) { - return Math.floor((self.getDayOfYear(d) - 1) / self._domainType.day.row(d)); + return Math.floor( + (self.getDayOfYear(d) - 1) / self._domainType.day.row(d), + ); } return self.getWeekNumber(d); } @@ -524,8 +560,9 @@ var CalHeatMap = function () { return self._domainType.week.maxItemNumber; case 'month': return self.options.domainDynamicDimension - ? self.getWeekNumber(new Date(d.getFullYear(), d.getMonth() + 1, 0)) - - self.getWeekNumber(d) + ? self.getWeekNumber( + new Date(d.getFullYear(), d.getMonth() + 1, 0), + ) - self.getWeekNumber(d) : 5; } }, @@ -540,9 +577,13 @@ var CalHeatMap = function () { x: function (d) { switch (self.options.domain) { case 'year': - return Math.floor(self.getWeekNumber(d) / self._domainType.week.row(d)); + return Math.floor( + self.getWeekNumber(d) / self._domainType.week.row(d), + ); case 'month': - return Math.floor(self.getMonthWeekNumber(d) / self._domainType.week.row(d)); + return Math.floor( + self.getMonthWeekNumber(d) / self._domainType.week.row(d), + ); } }, y: function (d) { @@ -700,7 +741,10 @@ var CalHeatMap = function () { self._domains.set( d, self.getSubDomain(d).map(function (d) { - return { t: self._domainType[self.options.subDomain].extractUnit(d), v: null }; + return { + t: self._domainType[self.options.subDomain].extractUnit(d), + v: null, + }; }), ); }); @@ -725,7 +769,8 @@ var CalHeatMap = function () { function _initCalendar() { self.verticalDomainLabel = - self.options.label.position === 'top' || self.options.label.position === 'bottom'; + self.options.label.position === 'top' || + self.options.label.position === 'bottom'; self.domainVerticalLabelHeight = self.options.label.height === null @@ -733,7 +778,10 @@ var CalHeatMap = function () { : self.options.label.height; self.domainHorizontalLabelWidth = 0; - if (self.options.domainLabelFormat === '' && self.options.label.height === null) { + if ( + self.options.domainLabelFormat === '' && + self.options.label.height === null + ) { self.domainVerticalLabelHeight = 0; } @@ -748,10 +796,13 @@ var CalHeatMap = function () { // ATTACHING DOMAIN NAVIGATION EVENT // // =========================================================================// if (self.options.nextSelector !== false) { - d3.select(self.options.nextSelector).on('click.' + self.options.itemNamespace, function () { - d3.event.preventDefault(); - return self.loadNextDomain(1); - }); + d3.select(self.options.nextSelector).on( + 'click.' + self.options.itemNamespace, + function () { + d3.event.preventDefault(); + return self.loadNextDomain(1); + }, + ); } if (self.options.previousSelector !== false) { @@ -764,7 +815,11 @@ var CalHeatMap = function () { ); } - self.Legend.redraw(self.graphDim.width - self.options.domainGutter - self.options.cellPadding); + self.Legend.redraw( + self.graphDim.width - + self.options.domainGutter - + self.options.cellPadding, + ); self.afterLoad(); var domains = self.getDomainKeys(); @@ -792,8 +847,10 @@ var CalHeatMap = function () { // @param int d Domain start timestamp function w(d, outer) { var width = - self.options.cellSize * self._domainType[self.options.subDomain].column(d) + - self.options.cellPadding * self._domainType[self.options.subDomain].column(d); + self.options.cellSize * + self._domainType[self.options.subDomain].column(d) + + self.options.cellPadding * + self._domainType[self.options.subDomain].column(d); if (arguments.length === 2 && outer === true) { return (width += self.domainHorizontalLabelWidth + @@ -808,7 +865,8 @@ var CalHeatMap = function () { function h(d, outer) { var height = self.options.cellSize * self._domainType[self.options.subDomain].row(d) + - self.options.cellPadding * self._domainType[self.options.subDomain].row(d); + self.options.cellPadding * + self._domainType[self.options.subDomain].row(d); if (arguments.length === 2 && outer === true) { height += self.options.domainGutter + @@ -991,7 +1049,9 @@ var CalHeatMap = function () { }) .call(function (selection) { if (options.cellRadius > 0) { - selection.attr('rx', options.cellRadius).attr('ry', options.cellRadius); + selection + .attr('rx', options.cellRadius) + .attr('ry', options.cellRadius); } if ( @@ -1040,8 +1100,10 @@ var CalHeatMap = function () { return ( y + options.label.offset.y * - ((options.label.rotate === 'right' && options.label.position === 'right') || - (options.label.rotate === 'left' && options.label.position === 'left') + ((options.label.rotate === 'right' && + options.label.position === 'right') || + (options.label.rotate === 'left' && + options.label.position === 'left') ? -1 : 1) ); @@ -1061,7 +1123,8 @@ var CalHeatMap = function () { return ( x + self.domainHorizontalLabelWidth - - options.label.offset.x * (options.label.rotate === 'right' ? -1 : 1) + options.label.offset.x * + (options.label.rotate === 'right' ? -1 : 1) ); } return x + options.label.offset.x; @@ -1109,7 +1172,12 @@ var CalHeatMap = function () { var s = 'rotate(270), '; switch (options.label.position) { case 'right': - s += 'translate(-' + (w(d) + self.domainHorizontalLabelWidth) + ' , ' + w(d) + ')'; + s += + 'translate(-' + + (w(d) + self.domainHorizontalLabelWidth) + + ' , ' + + w(d) + + ')'; break; case 'left': s += @@ -1158,10 +1226,14 @@ var CalHeatMap = function () { .transition() .duration(options.animationDuration) .attr('x', function (d) { - return options.verticalOrientation ? 0 : self.domainPosition.getPosition(d); + return options.verticalOrientation + ? 0 + : self.domainPosition.getPosition(d); }) .attr('y', function (d) { - return options.verticalOrientation ? self.domainPosition.getPosition(d) : 0; + return options.verticalOrientation + ? self.domainPosition.getPosition(d) + : 0; }); } @@ -1231,12 +1303,16 @@ CalHeatMap.prototype = { validateSelector(options.itemSelector, false, 'itemSelector'); if (parent.allowedDataType.indexOf(options.dataType) === -1) { - throw new Error("The data type '" + options.dataType + "' is not valid data type"); + throw new Error( + "The data type '" + options.dataType + "' is not valid data type", + ); } if (d3.select(options.itemSelector)[0][0] === null) { throw new Error( - "The node '" + options.itemSelector + "' specified in itemSelector does not exists", + "The node '" + + options.itemSelector + + "' specified in itemSelector does not exists", ); } @@ -1254,8 +1330,13 @@ CalHeatMap.prototype = { this.options.subDomain = getOptimalSubDomain(settings.domain); } - if (typeof options.itemNamespace !== 'string' || options.itemNamespace === '') { - console.log('itemNamespace can not be empty, falling back to cal-heatmap'); + if ( + typeof options.itemNamespace !== 'string' || + options.itemNamespace === '' + ) { + console.log( + 'itemNamespace can not be empty, falling back to cal-heatmap', + ); options.itemNamespace = 'cal-heatmap'; } @@ -1288,7 +1369,8 @@ CalHeatMap.prototype = { ? options.domainLabelFormat : this._domainType[options.domain].format.legend; options.subDomainTextFormat = - (typeof options.subDomainTextFormat === 'string' && options.subDomainTextFormat !== '') || + (typeof options.subDomainTextFormat === 'string' && + options.subDomainTextFormat !== '') || typeof options.subDomainTextFormat === 'function' ? options.subDomainTextFormat : null; @@ -1360,13 +1442,25 @@ CalHeatMap.prototype = { throw new Error("The domain '" + options.domain + "' is not valid"); } - if (!parent._domainType.hasOwnProperty(options.subDomain) || options.subDomain === 'year') { - throw new Error("The subDomain '" + options.subDomain + "' is not valid"); + if ( + !parent._domainType.hasOwnProperty(options.subDomain) || + options.subDomain === 'year' + ) { + throw new Error( + "The subDomain '" + options.subDomain + "' is not valid", + ); } - if (parent._domainType[options.domain].level <= parent._domainType[options.subDomain].level) { + if ( + parent._domainType[options.domain].level <= + parent._domainType[options.subDomain].level + ) { throw new Error( - "'" + options.subDomain + "' is not a valid subDomain to '" + options.domain + "'", + "'" + + options.subDomain + + "' is not a valid subDomain to '" + + options.domain + + "'", ); } @@ -1382,7 +1476,8 @@ CalHeatMap.prototype = { // Auto-align label, depending on it's position if ( !settings.hasOwnProperty('label') || - (settings.hasOwnProperty('label') && !settings.label.hasOwnProperty('align')) + (settings.hasOwnProperty('label') && + !settings.label.hasOwnProperty('align')) ) { switch (options.label.position) { case 'left': @@ -1404,9 +1499,13 @@ CalHeatMap.prototype = { if ( !settings.hasOwnProperty('label') || - (settings.hasOwnProperty('label') && !settings.label.hasOwnProperty('offset')) + (settings.hasOwnProperty('label') && + !settings.label.hasOwnProperty('offset')) ) { - if (options.label.position === 'left' || options.label.position === 'right') { + if ( + options.label.position === 'left' || + options.label.position === 'right' + ) { options.label.offset = { x: 10, y: 15, @@ -1430,8 +1529,9 @@ CalHeatMap.prototype = { break; case 'middle': case 'center': - options.legendMargin[options.legendHorizontalPosition === 'right' ? 3 : 1] = - parent.DEFAULT_LEGEND_MARGIN; + options.legendMargin[ + options.legendHorizontalPosition === 'right' ? 3 : 1 + ] = parent.DEFAULT_LEGEND_MARGIN; } } @@ -1495,7 +1595,9 @@ CalHeatMap.prototype = { function parseRowLimit(value) { if (value > 0 && options.colLimit > 0) { - console.log('colLimit and rowLimit are mutually exclusive, rowLimit will be ignored'); + console.log( + 'colLimit and rowLimit are mutually exclusive, rowLimit will be ignored', + ); return null; } return value > 0 ? value : null; @@ -1594,7 +1696,9 @@ CalHeatMap.prototype = { return options.legendColors.overflow; } - return parent.legendScale(Math.min(d.v, options.legend[options.legend.length - 1])); + return parent.legendScale( + Math.min(d.v, options.legend[options.legend.length - 1]), + ); }); } @@ -1624,9 +1728,13 @@ CalHeatMap.prototype = { } if (d.v !== null) { - htmlClass.push(parent.Legend.getClass(d.v, parent.legendScale === null)); + htmlClass.push( + parent.Legend.getClass(d.v, parent.legendScale === null), + ); } else if (options.considerMissingDataAsZero && pastDate) { - htmlClass.push(parent.Legend.getClass(0, parent.legendScale === null)); + htmlClass.push( + parent.Legend.getClass(0, parent.legendScale === null), + ); } if (options.onClick !== null) { @@ -1668,7 +1776,9 @@ CalHeatMap.prototype = { .call(formatSubDomainText) .attr('fill', d => { if (!d.v) return '#000'; - const rgb = parent.legendScale(Math.min(d.v, options.legend[options.legend.length - 1])); + const rgb = parent.legendScale( + Math.min(d.v, options.legend[options.legend.length - 1]), + ); return getContrastingColor(rgb, 135); }); }, @@ -1870,9 +1980,15 @@ CalHeatMap.prototype = { 'use strict'; if (d.v === null && !this.options.considerMissingDataAsZero) { - return this.formatStringWithObject(this.options.subDomainTitleFormat.empty, { - date: this.formatDate(new Date(d.t), this.options.subDomainDateFormat), - }); + return this.formatStringWithObject( + this.options.subDomainTitleFormat.empty, + { + date: this.formatDate( + new Date(d.t), + this.options.subDomainDateFormat, + ), + }, + ); } else { var value = d.v; // Consider null as 0 @@ -1880,12 +1996,18 @@ CalHeatMap.prototype = { value = 0; } - return this.formatStringWithObject(this.options.subDomainTitleFormat.filled, { - count: this.formatNumber(value), - name: this.options.itemName[value !== 1 ? 1 : 0], - connector: this._domainType[this.options.subDomain].format.connector, - date: this.formatDate(new Date(d.t), this.options.subDomainDateFormat), - }); + return this.formatStringWithObject( + this.options.subDomainTitleFormat.filled, + { + count: this.formatNumber(value), + name: this.options.itemName[value !== 1 ? 1 : 0], + connector: this._domainType[this.options.subDomain].format.connector, + date: this.formatDate( + new Date(d.t), + this.options.subDomainDateFormat, + ), + }, + ); } }, @@ -1908,7 +2030,10 @@ CalHeatMap.prototype = { return false; } - var bound = this.loadNewDomains(this.NAVIGATE_RIGHT, this.getDomain(this.getNextDomain(), n)); + var bound = this.loadNewDomains( + this.NAVIGATE_RIGHT, + this.getDomain(this.getNextDomain(), n), + ); this.afterLoadNextDomain(bound.end); this.checkIfMaxDomainIsReached(this.getNextDomain().getTime(), bound.start); @@ -1952,7 +2077,10 @@ CalHeatMap.prototype = { var domains = this.getDomainKeys(); function buildSubDomain(d) { - return { t: parent._domainType[parent.options.subDomain].extractUnit(d), v: null }; + return { + t: parent._domainType[parent.options.subDomain].extractUnit(d), + v: null, + }; } // Remove out of bound domains from list of new domains to prepend @@ -2010,7 +2138,10 @@ CalHeatMap.prototype = { maxDomainIsReached: function (datetimestamp) { 'use strict'; - return this.options.maxDate !== null && this.options.maxDate.getTime() < datetimestamp; + return ( + this.options.maxDate !== null && + this.options.maxDate.getTime() < datetimestamp + ); }, /** @@ -2022,7 +2153,10 @@ CalHeatMap.prototype = { minDomainIsReached: function (datetimestamp) { 'use strict'; - return this.options.minDate !== null && this.options.minDate.getTime() >= datetimestamp; + return ( + this.options.minDate !== null && + this.options.minDate.getTime() >= datetimestamp + ); }, /** @@ -2050,14 +2184,18 @@ CalHeatMap.prototype = { positionSubDomainX: function (d) { 'use strict'; - var index = this._domainType[this.options.subDomain].position.x(new Date(d)); + var index = this._domainType[this.options.subDomain].position.x( + new Date(d), + ); return index * this.options.cellSize + index * this.options.cellPadding; }, positionSubDomainY: function (d) { 'use strict'; - var index = this._domainType[this.options.subDomain].position.y(new Date(d)); + var index = this._domainType[this.options.subDomain].position.y( + new Date(d), + ); return index * this.options.cellSize + index * this.options.cellPadding; }, @@ -2111,7 +2249,9 @@ CalHeatMap.prototype = { if (this.options.highlight.length > 0) { for (var i in this.options.highlight) { if (this.dateIsEqual(this.options.highlight[i], d)) { - return this.isNow(this.options.highlight[i]) ? ' highlight-now' : ' highlight'; + return this.isNow(this.options.highlight[i]) + ? ' highlight-now' + : ' highlight'; } } } @@ -2185,7 +2325,10 @@ CalHeatMap.prototype = { ); case 'x_month': case 'month': - return dateA.getFullYear() === dateB.getFullYear() && dateA.getMonth() === dateB.getMonth(); + return ( + dateA.getFullYear() === dateB.getFullYear() && + dateA.getMonth() === dateB.getMonth() + ); default: return false; } @@ -2230,7 +2373,11 @@ CalHeatMap.prototype = { ).getTime(); case 'x_day': case 'day': - return new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime(); + return new Date( + date.getFullYear(), + date.getMonth(), + date.getDate(), + ).getTime(); case 'x_week': case 'week': case 'x_month': @@ -2266,7 +2413,10 @@ CalHeatMap.prototype = { getWeekNumber: function (d) { 'use strict'; - var f = this.options.weekStartOnMonday === true ? d3.time.format('%W') : d3.time.format('%U'); + var f = + this.options.weekStartOnMonday === true + ? d3.time.format('%W') + : d3.time.format('%U'); return f(d); }, @@ -2283,7 +2433,9 @@ CalHeatMap.prototype = { d = new Date(d); } - var monthFirstWeekNumber = this.getWeekNumber(new Date(d.getFullYear(), d.getMonth())); + var monthFirstWeekNumber = this.getWeekNumber( + new Date(d.getFullYear(), d.getMonth()), + ); return this.getWeekNumber(d) - monthFirstWeekNumber - 1; }, @@ -2405,10 +2557,20 @@ CalHeatMap.prototype = { getMinuteDomain: function (d, range) { 'use strict'; - var start = new Date(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours()); + var start = new Date( + d.getFullYear(), + d.getMonth(), + d.getDate(), + d.getHours(), + ); var stop = null; if (range instanceof Date) { - stop = new Date(range.getFullYear(), range.getMonth(), range.getDate(), range.getHours()); + stop = new Date( + range.getFullYear(), + range.getMonth(), + range.getDate(), + range.getHours(), + ); } else { stop = new Date(+start + range * 1000 * 60); } @@ -2425,10 +2587,20 @@ CalHeatMap.prototype = { getHourDomain: function (d, range) { 'use strict'; - var start = new Date(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours()); + var start = new Date( + d.getFullYear(), + d.getMonth(), + d.getDate(), + d.getHours(), + ); var stop = null; if (range instanceof Date) { - stop = new Date(range.getFullYear(), range.getMonth(), range.getDate(), range.getHours()); + stop = new Date( + range.getFullYear(), + range.getMonth(), + range.getDate(), + range.getHours(), + ); } else { stop = new Date(start); stop.setHours(stop.getHours() + range); @@ -2493,7 +2665,11 @@ CalHeatMap.prototype = { var weekStart; if (this.options.weekStartOnMonday === false) { - weekStart = new Date(d.getFullYear(), d.getMonth(), d.getDate() - d.getDay()); + weekStart = new Date( + d.getFullYear(), + d.getMonth(), + d.getDate() - d.getDay(), + ); } else { if (d.getDay() === 1) { weekStart = new Date(d.getFullYear(), d.getMonth(), d.getDate()); @@ -2501,7 +2677,11 @@ CalHeatMap.prototype = { weekStart = new Date(d.getFullYear(), d.getMonth(), d.getDate()); weekStart.setDate(weekStart.getDate() - 6); } else { - weekStart = new Date(d.getFullYear(), d.getMonth(), d.getDate() - d.getDay() + 1); + weekStart = new Date( + d.getFullYear(), + d.getMonth(), + d.getDate() - d.getDay() + 1, + ); } } @@ -2662,7 +2842,9 @@ CalHeatMap.prototype = { if (domain === 'month') { var endOfMonth = new Date(date.getFullYear(), date.getMonth() + 1, 0); var endWeekNb = parent.getWeekNumber(endOfMonth); - var startWeekNb = parent.getWeekNumber(new Date(date.getFullYear(), date.getMonth())); + var startWeekNb = parent.getWeekNumber( + new Date(date.getFullYear(), date.getMonth()), + ); if (startWeekNb > endWeekNb) { startWeekNb = 0; @@ -2678,16 +2860,28 @@ CalHeatMap.prototype = { switch (this.options.subDomain) { case 'x_min': case 'min': - return this.getMinuteDomain(date, computeMinSubDomainSize(date, this.options.domain)); + return this.getMinuteDomain( + date, + computeMinSubDomainSize(date, this.options.domain), + ); case 'x_hour': case 'hour': - return this.getHourDomain(date, computeHourSubDomainSize(date, this.options.domain)); + return this.getHourDomain( + date, + computeHourSubDomainSize(date, this.options.domain), + ); case 'x_day': case 'day': - return this.getDayDomain(date, computeDaySubDomainSize(date, this.options.domain)); + return this.getDayDomain( + date, + computeDaySubDomainSize(date, this.options.domain), + ); case 'x_week': case 'week': - return this.getWeekDomain(date, computeWeekSubDomainSize(date, this.options.domain)); + return this.getWeekDomain( + date, + computeWeekSubDomainSize(date, this.options.domain), + ); case 'x_month': case 'month': return this.getMonthDomain(date, 12); @@ -2705,7 +2899,10 @@ CalHeatMap.prototype = { if (arguments.length === 0) { n = 1; } - return this.getDomain(this.jumpDate(this.getDomainKeys().pop(), n, this.options.domain), 1)[0]; + return this.getDomain( + this.jumpDate(this.getDomainKeys().pop(), n, this.options.domain), + 1, + )[0]; }, /** @@ -2743,7 +2940,14 @@ CalHeatMap.prototype = { * - True if there are no data to load * - False if data are loaded asynchronously */ - getDatas: function (source, startDate, endDate, callback, afterLoad, updateMode) { + getDatas: function ( + source, + startDate, + endDate, + callback, + afterLoad, + updateMode, + ) { 'use strict'; var self = this; @@ -2762,7 +2966,10 @@ CalHeatMap.prototype = { } else { console.log('Provided callback for afterLoadData is not a function.'); } - } else if (self.options.dataType === 'csv' || self.options.dataType === 'tsv') { + } else if ( + self.options.dataType === 'csv' || + self.options.dataType === 'tsv' + ) { data = this.interpretCSV(data); } self.parseDatas(data, updateMode, startDate, endDate); @@ -2784,7 +2991,11 @@ CalHeatMap.prototype = { } var payload = null; if (self.options.dataPostPayload !== null) { - payload = this.parseURI(self.options.dataPostPayload, startDate, endDate); + payload = this.parseURI( + self.options.dataPostPayload, + startDate, + endDate, + ); } var xhr = null; @@ -2941,14 +3152,20 @@ CalHeatMap.prototype = { var parent = this; var options = parent.options; var legendWidth = options.displayLegend - ? parent.Legend.getDim('width') + options.legendMargin[1] + options.legendMargin[3] + ? parent.Legend.getDim('width') + + options.legendMargin[1] + + options.legendMargin[3] : 0; var legendHeight = options.displayLegend - ? parent.Legend.getDim('height') + options.legendMargin[0] + options.legendMargin[2] + ? parent.Legend.getDim('height') + + options.legendMargin[0] + + options.legendMargin[2] : 0; - var graphWidth = parent.graphDim.width - options.domainGutter - options.cellPadding; - var graphHeight = parent.graphDim.height - options.domainGutter - options.cellPadding; + var graphWidth = + parent.graphDim.width - options.domainGutter - options.cellPadding; + var graphHeight = + parent.graphDim.height - options.domainGutter - options.cellPadding; this.root .transition() @@ -3134,7 +3351,11 @@ CalHeatMap.prototype = { this.fill(); } - this.Legend.redraw(this.graphDim.width - this.options.domainGutter - this.options.cellPadding); + this.Legend.redraw( + this.graphDim.width - + this.options.domainGutter - + this.options.cellPadding, + ); }, /** @@ -3165,7 +3386,11 @@ CalHeatMap.prototype = { return false; } this.options.displayLegend = true; - this.Legend.redraw(this.graphDim.width - this.options.domainGutter - this.options.cellPadding); + this.Legend.redraw( + this.graphDim.width - + this.options.domainGutter - + this.options.cellPadding, + ); return true; }, @@ -3237,7 +3462,11 @@ CalHeatMap.prototype = { '.qi': {}, }; - for (var j = 1, total = this.options.legend.length + 1; j <= total; j += 1) { + for ( + var j = 1, total = this.options.legend.length + 1; + j <= total; + j += 1 + ) { styles['.q' + j] = {}; } @@ -3591,7 +3820,13 @@ Legend.prototype.redraw = function (width) { .duration(options.animationDuration) .attr('transform', function () { if (options.legendOrientation === 'vertical') { - return 'rotate(90 ' + options.legendCellSize / 2 + ' ' + options.legendCellSize / 2 + ')'; + return ( + 'rotate(90 ' + + options.legendCellSize / 2 + + ' ' + + options.legendCellSize / 2 + + ')' + ); } return ''; }); @@ -3680,7 +3915,9 @@ Legend.prototype.buildColors = function () { _legend.unshift(0); } else if (_legend[0] <= 0) { // Let's guess the leftmost value, it we have to add one - _legend.unshift(_legend[0] - (_legend[_legend.length - 1] - _legend[0]) / _legend.length); + _legend.unshift( + _legend[0] - (_legend[_legend.length - 1] - _legend[0]) / _legend.length, + ); } var colorScale; if (options.legendColors.hasOwnProperty('colorScale')) { @@ -3696,7 +3933,10 @@ Legend.prototype.buildColors = function () { var legendColors = _legend.map(function (element) { return colorScale(element); }); - this.calendar.legendScale = d3.scale.threshold().domain(options.legend).range(legendColors); + this.calendar.legendScale = d3.scale + .threshold() + .domain(options.legend) + .range(legendColors); return true; }; @@ -3719,7 +3959,11 @@ Legend.prototype.getClass = function (n, withCssClass) { var index = [this.calendar.options.legend.length + 1]; - for (var i = 0, total = this.calendar.options.legend.length - 1; i <= total; i += 1) { + for ( + var i = 0, total = this.calendar.options.legend.length - 1; + i <= total; + i += 1 + ) { if (this.calendar.options.legend[0] > 0 && n < 0) { index = ['1', 'i']; break; diff --git a/plugins/legacy-plugin-chart-chord/src/Chord.js b/plugins/legacy-plugin-chart-chord/src/Chord.js index b1c7adb76c..d36083e6cb 100644 --- a/plugins/legacy-plugin-chart-chord/src/Chord.js +++ b/plugins/legacy-plugin-chart-chord/src/Chord.js @@ -19,7 +19,10 @@ /* eslint-disable no-param-reassign, react/sort-prop-types */ import d3 from 'd3'; import PropTypes from 'prop-types'; -import { getNumberFormatter, CategoricalColorNamespace } from '@superset-ui/core'; +import { + getNumberFormatter, + CategoricalColorNamespace, +} from '@superset-ui/core'; const propTypes = { data: PropTypes.shape({ @@ -102,7 +105,9 @@ function Chord(element, props) { // Remove the labels that don't fit. :( groupText .filter(function filter(d, i) { - return groupPath[0][i].getTotalLength() / 2 - 16 < this.getComputedTextLength(); + return ( + groupPath[0][i].getTotalLength() / 2 - 16 < this.getComputedTextLength() + ); }) .remove(); @@ -124,9 +129,11 @@ function Chord(element, props) { .append('title') .text( d => - `${nodes[d.source.index]} → ${nodes[d.target.index]}: ${f(d.source.value)}\n${ - nodes[d.target.index] - } → ${nodes[d.source.index]}: ${f(d.target.value)}`, + `${nodes[d.source.index]} → ${nodes[d.target.index]}: ${f( + d.source.value, + )}\n${nodes[d.target.index]} → ${nodes[d.source.index]}: ${f( + d.target.value, + )}`, ); } diff --git a/plugins/legacy-plugin-chart-chord/src/controlPanel.ts b/plugins/legacy-plugin-chart-chord/src/controlPanel.ts index 73ae97f225..c2559a7b0d 100644 --- a/plugins/legacy-plugin-chart-chord/src/controlPanel.ts +++ b/plugins/legacy-plugin-chart-chord/src/controlPanel.ts @@ -37,7 +37,9 @@ const config: ControlPanelConfig = { config: { type: 'CheckboxControl', label: t('Sort by metric'), - description: t('Whether to sort results by the selected metric in descending order.'), + description: t( + 'Whether to sort results by the selected metric in descending order.', + ), }, }, ], diff --git a/plugins/legacy-plugin-chart-chord/src/index.js b/plugins/legacy-plugin-chart-chord/src/index.js index cf147242de..4726a9aef2 100644 --- a/plugins/legacy-plugin-chart-chord/src/index.js +++ b/plugins/legacy-plugin-chart-chord/src/index.js @@ -28,9 +28,17 @@ const metadata = new ChartMetadata({ description: t( 'Showcases the flow or link between categories using thickness of chords. The value and corresponding thickness can be different for each side.', ), - exampleGallery: [{ url: example, caption: t('Relationships between community channels') }], + exampleGallery: [ + { url: example, caption: t('Relationships between community channels') }, + ], name: t('Chord Diagram'), - tags: [t('Aesthetic'), t('Circular'), t('Legacy'), t('Proportional'), t('Relational')], + tags: [ + t('Aesthetic'), + t('Circular'), + t('Legacy'), + t('Proportional'), + t('Relational'), + ], thumbnail, useLegacyApi: true, }); diff --git a/plugins/legacy-plugin-chart-country-map/src/CountryMap.js b/plugins/legacy-plugin-chart-country-map/src/CountryMap.js index f1b0d4659f..ef26569199 100644 --- a/plugins/legacy-plugin-chart-country-map/src/CountryMap.js +++ b/plugins/legacy-plugin-chart-country-map/src/CountryMap.js @@ -20,7 +20,10 @@ import d3 from 'd3'; import PropTypes from 'prop-types'; import { extent as d3Extent } from 'd3-array'; -import { getNumberFormatter, getSequentialSchemeRegistry } from '@superset-ui/core'; +import { + getNumberFormatter, + getSequentialSchemeRegistry, +} from '@superset-ui/core'; import countries, { countryOptions } from './countries'; import './CountryMap.css'; @@ -42,7 +45,8 @@ const propTypes = { const maps = {}; function CountryMap(element, props) { - const { data, width, height, country, linearColorScheme, numberFormat } = props; + const { data, width, height, country, linearColorScheme, numberFormat } = + props; const container = element; const format = getNumberFormatter(numberFormat); @@ -78,7 +82,10 @@ function CountryMap(element, props) { .classed('text-layer', true) .attr('transform', `translate(${width / 2}, 45)`); const bigText = textLayer.append('text').classed('big-text', true); - const resultText = textLayer.append('text').classed('result-text', true).attr('dy', '1em'); + const resultText = textLayer + .append('text') + .classed('result-text', true) + .attr('dy', '1em'); let centered; @@ -104,10 +111,16 @@ function CountryMap(element, props) { g.transition() .duration(750) - .attr('transform', `translate(${halfWidth},${halfHeight})scale(${k})translate(${-x},${-y})`); + .attr( + 'transform', + `translate(${halfWidth},${halfHeight})scale(${k})translate(${-x},${-y})`, + ); textLayer .style('opacity', 0) - .attr('transform', `translate(0,0)translate(${x},${hasCenter ? y - 5 : 45})`) + .attr( + 'transform', + `translate(0,0)translate(${x},${hasCenter ? y - 5 : 45})`, + ) .transition() .duration(750) .style('opacity', 1); @@ -123,7 +136,9 @@ function CountryMap(element, props) { backgroundRect.on('click', clicked); - const selectAndDisplayNameOfRegion = function selectAndDisplayNameOfRegion(feature) { + const selectAndDisplayNameOfRegion = function selectAndDisplayNameOfRegion( + feature, + ) { let name = ''; if (feature && feature.properties) { if (feature.properties.ID_2) { @@ -149,7 +164,9 @@ function CountryMap(element, props) { } d3.select(this).style('fill', c); selectAndDisplayNameOfRegion(d); - const result = data.filter(region => region.country_id === d.properties.ISO); + const result = data.filter( + region => region.country_id === d.properties.ISO, + ); updateMetrics(result); }; @@ -206,7 +223,8 @@ function CountryMap(element, props) { const url = countries[country]; d3.json(url, (error, mapData) => { if (error) { - const countryName = countryOptions.find(x => x[0] === country)?.[1] || country; + const countryName = + countryOptions.find(x => x[0] === country)?.[1] || country; d3.select(element).html( `

`, ); diff --git a/plugins/legacy-plugin-chart-country-map/src/index.js b/plugins/legacy-plugin-chart-country-map/src/index.js index 83570927e1..5ac3e398ef 100644 --- a/plugins/legacy-plugin-chart-country-map/src/index.js +++ b/plugins/legacy-plugin-chart-country-map/src/index.js @@ -28,7 +28,14 @@ const metadata = new ChartMetadata({ "Visualizes how a single metric varies across a country's principal subdivisions (states, provinces, etc) on a chloropleth map. Each subdivision's value is elevated when you hover over the corresponding geographic boundary.", ), name: t('Country Map'), - tags: [t('2D'), t('Comparison'), t('Geo'), t('Range'), t('Report'), t('Stacked')], + tags: [ + t('2D'), + t('Comparison'), + t('Geo'), + t('Range'), + t('Report'), + t('Stacked'), + ], thumbnail, useLegacyApi: true, }); diff --git a/plugins/legacy-plugin-chart-event-flow/src/controlPanel.tsx b/plugins/legacy-plugin-chart-event-flow/src/controlPanel.tsx index 325ec944bf..fd5ab5b5dd 100644 --- a/plugins/legacy-plugin-chart-event-flow/src/controlPanel.tsx +++ b/plugins/legacy-plugin-chart-event-flow/src/controlPanel.tsx @@ -47,7 +47,9 @@ const config: ControlPanelConfig = { }), // choices is from `mapStateToProps` default: (control: { choices?: string[] }) => - control.choices && control.choices.length > 0 ? control.choices[0][0] : null, + control.choices && control.choices.length > 0 + ? control.choices[0][0] + : null, validators: [validateNonEmpty], }, }, @@ -125,7 +127,9 @@ const config: ControlPanelConfig = { }, row_limit: { label: t('Max Events'), - description: t('The maximum number of events to return, equivalent to the number of rows'), + description: t( + 'The maximum number of events to return, equivalent to the number of rows', + ), }, }, }; diff --git a/plugins/legacy-plugin-chart-event-flow/src/transformProps.ts b/plugins/legacy-plugin-chart-event-flow/src/transformProps.ts index 7bb99903de..c738ca6ebb 100644 --- a/plugins/legacy-plugin-chart-event-flow/src/transformProps.ts +++ b/plugins/legacy-plugin-chart-event-flow/src/transformProps.ts @@ -33,7 +33,8 @@ export interface EventFlowChartProps extends ChartProps { } export default function transformProps(chartProps: ChartProps) { - const { formData, queriesData, width, height } = chartProps as EventFlowChartProps; + const { formData, queriesData, width, height } = + chartProps as EventFlowChartProps; const { allColumnsX, entity, minLeafNodeEventCount } = formData; const { data } = queriesData[0]; @@ -45,10 +46,14 @@ export default function transformProps(chartProps: ChartProps) { // map from the Superset form fields to 's expected data keys const accessorFunctions = { [ENTITY_ID]: (datum: TimeseriesDataRecord) => String(datum[userKey]), - [EVENT_NAME]: (datum: TimeseriesDataRecord) => datum[eventNameKey] as string, + [EVENT_NAME]: (datum: TimeseriesDataRecord) => + datum[eventNameKey] as string, [TS]: (datum: TimeseriesDataRecord): Date | null => // eslint-disable-next-line no-underscore-dangle - datum.__timestamp || datum.__timestamp === 0 ? new Date(datum.__timestamp) : null, + datum.__timestamp || datum.__timestamp === 0 + ? // eslint-disable-next-line no-underscore-dangle + new Date(datum.__timestamp) + : null, }; const cleanData = cleanEvents(data, accessorFunctions); diff --git a/plugins/legacy-plugin-chart-force-directed/src/controlPanel.ts b/plugins/legacy-plugin-chart-force-directed/src/controlPanel.ts index 1a1e21f834..575507ba46 100644 --- a/plugins/legacy-plugin-chart-force-directed/src/controlPanel.ts +++ b/plugins/legacy-plugin-chart-force-directed/src/controlPanel.ts @@ -36,7 +36,9 @@ export default { config: { type: 'CheckboxControl', label: t('Sort by metric'), - description: t('Whether to sort results by the selected metric in descending order.'), + description: t( + 'Whether to sort results by the selected metric in descending order.', + ), }, }, ], @@ -55,7 +57,16 @@ export default { freeForm: true, label: t('Link Length'), default: '200', - choices: formatSelectOptions(['10', '25', '50', '75', '100', '150', '200', '250']), + choices: formatSelectOptions([ + '10', + '25', + '50', + '75', + '100', + '150', + '200', + '250', + ]), description: t('Link length in the force layout'), }, }, diff --git a/plugins/legacy-plugin-chart-heatmap/src/Heatmap.js b/plugins/legacy-plugin-chart-heatmap/src/Heatmap.js index 83a1161493..4626116aa8 100644 --- a/plugins/legacy-plugin-chart-heatmap/src/Heatmap.js +++ b/plugins/legacy-plugin-chart-heatmap/src/Heatmap.js @@ -21,7 +21,11 @@ import d3 from 'd3'; import PropTypes from 'prop-types'; import 'd3-svg-legend'; import d3tip from 'd3-tip'; -import { getNumberFormatter, NumberFormats, getSequentialSchemeRegistry } from '@superset-ui/core'; +import { + getNumberFormatter, + NumberFormats, + getSequentialSchemeRegistry, +} from '@superset-ui/core'; import './vendor/d3tip.css'; import './Heatmap.css'; @@ -120,8 +124,14 @@ function Heatmap(element, props) { let longestY = 1; records.forEach(datum => { - longestX = Math.max(longestX, (datum.x && datum.x.toString().length) || 1); - longestY = Math.max(longestY, (datum.y && datum.y.toString().length) || 1); + longestX = Math.max( + longestX, + (datum.x && datum.x.toString().length) || 1, + ); + longestY = Math.max( + longestY, + (datum.y && datum.y.toString().length) || 1, + ); }); if (leftMargin === 'auto') { @@ -148,7 +158,10 @@ function Heatmap(element, props) { return; } - if (xAxisNode.getBoundingClientRect().x + 4 < container.node().getBoundingClientRect().x) { + if ( + xAxisNode.getBoundingClientRect().x + 4 < + container.node().getBoundingClientRect().x + ) { container .selectAll('.x.axis') .selectAll('text') @@ -173,9 +186,13 @@ function Heatmap(element, props) { } else if (sortMethod === 'alpha_desc') { domain = keys.sort(cmp).reverse(); } else if (sortMethod === 'value_desc') { - domain = Object.keys(domain).sort((a, b) => (domain[a] > domain[b] ? -1 : 1)); + domain = Object.keys(domain).sort((a, b) => + domain[a] > domain[b] ? -1 : 1, + ); } else if (sortMethod === 'value_asc') { - domain = Object.keys(domain).sort((a, b) => (domain[b] > domain[a] ? -1 : 1)); + domain = Object.keys(domain).sort((a, b) => + domain[b] > domain[a] ? -1 : 1, + ); } if (k === 'y' && rangeBands) { @@ -198,13 +215,15 @@ function Heatmap(element, props) { let hmWidth = width - (margin.left + margin.right); let hmHeight = height - (margin.bottom + margin.top); const hideYLabel = () => { - margin.left = leftMargin === 'auto' ? DEFAULT_PROPERTIES.marginLeft : leftMargin; + margin.left = + leftMargin === 'auto' ? DEFAULT_PROPERTIES.marginLeft : leftMargin; hmWidth = width - (margin.left + margin.right); showY = false; }; const hideXLabel = () => { - margin.bottom = bottomMargin === 'auto' ? DEFAULT_PROPERTIES.marginBottom : bottomMargin; + margin.bottom = + bottomMargin === 'auto' ? DEFAULT_PROPERTIES.marginBottom : bottomMargin; hmHeight = height - (margin.bottom + margin.top); showX = false; }; @@ -215,7 +234,10 @@ function Heatmap(element, props) { } // Hide X Labels - if (hmHeight < DEFAULT_PROPERTIES.minChartHeight || hmWidth < DEFAULT_PROPERTIES.minChartWidth) { + if ( + hmHeight < DEFAULT_PROPERTIES.minChartHeight || + hmWidth < DEFAULT_PROPERTIES.minChartWidth + ) { hideXLabel(); } @@ -281,7 +303,10 @@ function Heatmap(element, props) { .attr('text-anchor', 'middle') .attr('dy', '.35em') .text(d => valueFormatter(d.v)) - .attr('font-size', `${Math.min(yRbScale.rangeBand(), xRbScale.rangeBand()) / 3}px`) + .attr( + 'font-size', + `${Math.min(yRbScale.rangeBand(), xRbScale.rangeBand()) / 3}px`, + ) .attr('fill', d => (d.v >= extents[1] / 2 ? 'white' : 'black')); } diff --git a/plugins/legacy-plugin-chart-heatmap/src/controlPanel.ts b/plugins/legacy-plugin-chart-heatmap/src/controlPanel.ts index ce76cd7408..6fb5bfd085 100644 --- a/plugins/legacy-plugin-chart-heatmap/src/controlPanel.ts +++ b/plugins/legacy-plugin-chart-heatmap/src/controlPanel.ts @@ -16,7 +16,12 @@ * specific language governing permissions and limitations * under the License. */ -import { FeatureFlag, isFeatureEnabled, t, validateNonEmpty } from '@superset-ui/core'; +import { + FeatureFlag, + isFeatureEnabled, + t, + validateNonEmpty, +} from '@superset-ui/core'; import { columnChoices, ControlPanelConfig, @@ -87,7 +92,9 @@ const config: ControlPanelConfig = { config: { type: 'CheckboxControl', label: t('Sort by metric'), - description: t('Whether to sort results by the selected metric in descending order.'), + description: t( + 'Whether to sort results by the selected metric in descending order.', + ), }, }, ], @@ -109,7 +116,9 @@ const config: ControlPanelConfig = { choices: formatSelectOptionsForRange(1, 50), default: '1', clearable: false, - description: t('Number of steps to take between ticks when displaying the X scale'), + description: t( + 'Number of steps to take between ticks when displaying the X scale', + ), }, }, ], @@ -123,7 +132,9 @@ const config: ControlPanelConfig = { default: '1', clearable: false, renderTrigger: true, - description: t('Number of steps to take between ticks when displaying the Y scale'), + description: t( + 'Number of steps to take between ticks when displaying the Y scale', + ), }, }, ], @@ -174,10 +185,20 @@ const config: ControlPanelConfig = { freeForm: true, clearable: false, label: t('Left Margin'), - choices: formatSelectOptions(['auto', 50, 75, 100, 125, 150, 200]), + choices: formatSelectOptions([ + 'auto', + 50, + 75, + 100, + 125, + 150, + 200, + ]), default: 'auto', renderTrigger: true, - description: t('Left margin, in pixels, allowing for more room for axis labels'), + description: t( + 'Left margin, in pixels, allowing for more room for axis labels', + ), }, }, ], @@ -189,10 +210,20 @@ const config: ControlPanelConfig = { clearable: false, freeForm: true, label: t('Bottom Margin'), - choices: formatSelectOptions(['auto', 50, 75, 100, 125, 150, 200]), + choices: formatSelectOptions([ + 'auto', + 50, + 75, + 100, + 125, + 150, + 200, + ]), default: 'auto', renderTrigger: true, - description: t('Bottom margin, in pixels, allowing for more room for axis labels'), + description: t( + 'Bottom margin, in pixels, allowing for more room for axis labels', + ), }, }, ], @@ -255,7 +286,9 @@ const config: ControlPanelConfig = { type: 'CheckboxControl', label: t('Show percentage'), renderTrigger: true, - description: t('Whether to include the percentage in the tooltip'), + description: t( + 'Whether to include the percentage in the tooltip', + ), default: true, }, }, @@ -268,7 +301,9 @@ const config: ControlPanelConfig = { label: t('Show Values'), renderTrigger: true, default: false, - description: t('Whether to display the numerical values within the cells'), + description: t( + 'Whether to display the numerical values within the cells', + ), }, }, ], diff --git a/plugins/legacy-plugin-chart-histogram/src/WithLegend.jsx b/plugins/legacy-plugin-chart-histogram/src/WithLegend.jsx index 867dd52e3b..d70c20b124 100644 --- a/plugins/legacy-plugin-chart-histogram/src/WithLegend.jsx +++ b/plugins/legacy-plugin-chart-histogram/src/WithLegend.jsx @@ -89,7 +89,8 @@ class WithLegend extends React.Component { } render() { - const { className, width, height, position, renderChart, renderLegend } = this.props; + const { className, width, height, position, renderChart, renderLegend } = + this.props; const isHorizontal = position === 'left' || position === 'right'; diff --git a/plugins/legacy-plugin-chart-histogram/src/controlPanel.ts b/plugins/legacy-plugin-chart-histogram/src/controlPanel.ts index b2de53cbc8..b049cb7839 100644 --- a/plugins/legacy-plugin-chart-histogram/src/controlPanel.ts +++ b/plugins/legacy-plugin-chart-histogram/src/controlPanel.ts @@ -16,7 +16,12 @@ * specific language governing permissions and limitations * under the License. */ -import { FeatureFlag, isFeatureEnabled, t, validateNonEmpty } from '@superset-ui/core'; +import { + FeatureFlag, + isFeatureEnabled, + t, + validateNonEmpty, +} from '@superset-ui/core'; import { columnChoices, ControlPanelConfig, @@ -80,7 +85,16 @@ const config: ControlPanelConfig = { freeForm: true, label: t('No of Bins'), default: 5, - choices: formatSelectOptions(['10', '25', '50', '75', '100', '150', '200', '250']), + choices: formatSelectOptions([ + '10', + '25', + '50', + '75', + '100', + '150', + '200', + '250', + ]), description: t('Select the number of bins for the histogram'), }, }, diff --git a/plugins/legacy-plugin-chart-horizon/src/HorizonChart.jsx b/plugins/legacy-plugin-chart-horizon/src/HorizonChart.jsx index 0fbc8bb047..b71227b6cd 100644 --- a/plugins/legacy-plugin-chart-horizon/src/HorizonChart.jsx +++ b/plugins/legacy-plugin-chart-horizon/src/HorizonChart.jsx @@ -75,12 +75,18 @@ class HorizonChart extends React.PureComponent { let yDomain; if (colorScale === 'overall') { - const allValues = data.reduce((acc, current) => acc.concat(current.values), []); + const allValues = data.reduce( + (acc, current) => acc.concat(current.values), + [], + ); yDomain = d3Extent(allValues, d => d.y); } return ( -
+
{data.map(row => ( ({ ...d, y: d.y - rawData[0].y })) : rawData; + colorScale === 'change' + ? rawData.map(d => ({ ...d, y: d.y - rawData[0].y })) + : rawData; const context = this.canvas.getContext('2d'); context.imageSmoothingEnabled = false; @@ -106,7 +108,9 @@ class HorizonRow extends React.PureComponent { const step = width / data.length; // the data frame currently being shown: const startIndex = Math.floor(Math.max(0, -(offsetX / step))); - const endIndex = Math.floor(Math.min(data.length, startIndex + width / step)); + const endIndex = Math.floor( + Math.min(data.length, startIndex + width / step), + ); // skip drawing if there's no data to be drawn if (startIndex > data.length) { @@ -140,7 +144,12 @@ class HorizonRow extends React.PureComponent { continue; } if (value !== undefined) { - context.fillRect(offsetX + i * step, y(value), step + 1, y(0) - y(value)); + context.fillRect( + offsetX + i * step, + y(value), + step + 1, + y(0) - y(value), + ); } } } @@ -166,7 +175,12 @@ class HorizonRow extends React.PureComponent { if (value >= 0) { continue; } - context.fillRect(offsetX + ii * step, y(-value), step + 1, y(0) - y(-value)); + context.fillRect( + offsetX + ii * step, + y(-value), + step + 1, + y(0) - y(-value), + ); } } } diff --git a/plugins/legacy-plugin-chart-horizon/src/controlPanel.ts b/plugins/legacy-plugin-chart-horizon/src/controlPanel.ts index 9fe3cd940e..63571600d2 100644 --- a/plugins/legacy-plugin-chart-horizon/src/controlPanel.ts +++ b/plugins/legacy-plugin-chart-horizon/src/controlPanel.ts @@ -17,7 +17,11 @@ * under the License. */ import { t } from '@superset-ui/core'; -import { ControlPanelConfig, formatSelectOptions, sections } from '@superset-ui/chart-controls'; +import { + ControlPanelConfig, + formatSelectOptions, + sections, +} from '@superset-ui/chart-controls'; const config: ControlPanelConfig = { controlPanelSections: [ @@ -66,7 +70,16 @@ const config: ControlPanelConfig = { freeForm: true, label: t('Series Height'), default: '25', - choices: formatSelectOptions(['10', '25', '40', '50', '75', '100', '150', '200']), + choices: formatSelectOptions([ + '10', + '25', + '40', + '50', + '75', + '100', + '150', + '200', + ]), description: t('Pixel height of each series'), }, }, diff --git a/plugins/legacy-plugin-chart-map-box/src/MapBox.jsx b/plugins/legacy-plugin-chart-map-box/src/MapBox.jsx index 32e1854f01..6fe4a24eab 100644 --- a/plugins/legacy-plugin-chart-map-box/src/MapBox.jsx +++ b/plugins/legacy-plugin-chart-map-box/src/MapBox.jsx @@ -102,7 +102,8 @@ class MapBox extends React.Component { bounds, } = this.props; const { viewport } = this.state; - const isDragging = viewport.isDragging === undefined ? false : viewport.isDragging; + const isDragging = + viewport.isDragging === undefined ? false : viewport.isDragging; // Compute the clusters based on the original bounds and current zoom level. Note when zoom/pan // to an area outside of the original bounds, no additional queries are made to the backend to diff --git a/plugins/legacy-plugin-chart-map-box/src/ScatterPlotGlowOverlay.jsx b/plugins/legacy-plugin-chart-map-box/src/ScatterPlotGlowOverlay.jsx index fd3678bc5c..cfbd880f05 100644 --- a/plugins/legacy-plugin-chart-map-box/src/ScatterPlotGlowOverlay.jsx +++ b/plugins/legacy-plugin-chart-map-box/src/ScatterPlotGlowOverlay.jsx @@ -33,7 +33,9 @@ const propTypes = { locations: PropTypes.arrayOf(PropTypes.object).isRequired, pointRadiusUnit: PropTypes.string, renderWhileDragging: PropTypes.bool, - rgb: PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.string, PropTypes.number])), + rgb: PropTypes.arrayOf( + PropTypes.oneOfType([PropTypes.string, PropTypes.number]), + ), zoom: PropTypes.number, }; @@ -79,7 +81,13 @@ class ScatterPlotGlowOverlay extends React.PureComponent { drawText(ctx, pixel, options = {}) { const IS_DARK_THRESHOLD = 110; - const { fontHeight = 0, label = '', radius = 0, rgb = [0, 0, 0], shadow = false } = options; + const { + fontHeight = 0, + label = '', + radius = 0, + rgb = [0, 0, 0], + shadow = false, + } = options; const maxWidth = radius * 1.8; const luminance = luminanceFromRGB(rgb[1], rgb[2], rgb[3]); @@ -126,7 +134,10 @@ class ScatterPlotGlowOverlay extends React.PureComponent { locations.forEach((location, i) => { if (location.properties.cluster) { - clusterLabelMap[i] = computeClusterLabel(location.properties, aggregation); + clusterLabelMap[i] = computeClusterLabel( + location.properties, + aggregation, + ); } }, this); @@ -138,7 +149,10 @@ class ScatterPlotGlowOverlay extends React.PureComponent { if ((renderWhileDragging || !isDragging) && locations) { locations.forEach(function _forEach(location, i) { const pixel = project(lngLatAccessor(location)); - const pixelRounded = [roundDecimal(pixel[0], 1), roundDecimal(pixel[1], 1)]; + const pixelRounded = [ + roundDecimal(pixel[0], 1), + roundDecimal(pixel[1], 1), + ]; if ( pixelRounded[0] + radius >= 0 && @@ -149,14 +163,36 @@ class ScatterPlotGlowOverlay extends React.PureComponent { ctx.beginPath(); if (location.properties.cluster) { let clusterLabel = clusterLabelMap[i]; - const scaledRadius = roundDecimal((clusterLabel / maxLabel) ** 0.5 * radius, 1); + const scaledRadius = roundDecimal( + (clusterLabel / maxLabel) ** 0.5 * radius, + 1, + ); const fontHeight = roundDecimal(scaledRadius * 0.5, 1); const [x, y] = pixelRounded; - const gradient = ctx.createRadialGradient(x, y, scaledRadius, x, y, 0); + const gradient = ctx.createRadialGradient( + x, + y, + scaledRadius, + x, + y, + 0, + ); - gradient.addColorStop(1, `rgba(${rgb[1]}, ${rgb[2]}, ${rgb[3]}, 0.8)`); - gradient.addColorStop(0, `rgba(${rgb[1]}, ${rgb[2]}, ${rgb[3]}, 0)`); - ctx.arc(pixelRounded[0], pixelRounded[1], scaledRadius, 0, Math.PI * 2); + gradient.addColorStop( + 1, + `rgba(${rgb[1]}, ${rgb[2]}, ${rgb[3]}, 0.8)`, + ); + gradient.addColorStop( + 0, + `rgba(${rgb[1]}, ${rgb[2]}, ${rgb[3]}, 0)`, + ); + ctx.arc( + pixelRounded[0], + pixelRounded[1], + scaledRadius, + 0, + Math.PI * 2, + ); ctx.fillStyle = gradient; ctx.fill(); @@ -178,7 +214,8 @@ class ScatterPlotGlowOverlay extends React.PureComponent { const defaultRadius = radius / 6; const radiusProperty = location.properties.radius; const pointMetric = location.properties.metric; - let pointRadius = radiusProperty === null ? defaultRadius : radiusProperty; + let pointRadius = + radiusProperty === null ? defaultRadius : radiusProperty; let pointLabel; if (radiusProperty !== null) { @@ -188,7 +225,11 @@ class ScatterPlotGlowOverlay extends React.PureComponent { pointRadius = kmToPixels(pointRadius, pointLatitude, zoom); } else if (pointRadiusUnit === 'Miles') { pointLabel = `${roundDecimal(pointRadius, 2)}mi`; - pointRadius = kmToPixels(pointRadius * MILES_PER_KM, pointLatitude, zoom); + pointRadius = kmToPixels( + pointRadius * MILES_PER_KM, + pointLatitude, + zoom, + ); } } @@ -203,7 +244,13 @@ class ScatterPlotGlowOverlay extends React.PureComponent { pointRadius = defaultRadius; } - ctx.arc(pixelRounded[0], pixelRounded[1], roundDecimal(pointRadius, 1), 0, Math.PI * 2); + ctx.arc( + pixelRounded[0], + pixelRounded[1], + roundDecimal(pointRadius, 1), + 0, + Math.PI * 2, + ); ctx.fillStyle = `rgb(${rgb[1]}, ${rgb[2]}, ${rgb[3]})`; ctx.fill(); diff --git a/plugins/legacy-plugin-chart-map-box/src/controlPanel.ts b/plugins/legacy-plugin-chart-map-box/src/controlPanel.ts index 49dde5176d..1e0dbf3ff4 100644 --- a/plugins/legacy-plugin-chart-map-box/src/controlPanel.ts +++ b/plugins/legacy-plugin-chart-map-box/src/controlPanel.ts @@ -114,7 +114,9 @@ const config: ControlPanelConfig = { ), mapStateToProps: state => { const datasourceChoices = columnChoices(state.datasource); - const choices: [string, string][] = formatSelectOptions(['Auto']); + const choices: [string, string][] = formatSelectOptions([ + 'Auto', + ]); return { choices: choices.concat(datasourceChoices), }; @@ -130,7 +132,9 @@ const config: ControlPanelConfig = { label: t('Point Radius Unit'), default: 'Pixels', choices: formatSelectOptions(['Pixels', 'Miles', 'Kilometers']), - description: t('The unit of measure for the specified point radius'), + description: t( + 'The unit of measure for the specified point radius', + ), }, }, ], @@ -166,7 +170,14 @@ const config: ControlPanelConfig = { type: 'SelectControl', label: t('Cluster label aggregator'), clearable: false, - choices: formatSelectOptions(['sum', 'mean', 'min', 'max', 'std', 'var']), + choices: formatSelectOptions([ + 'sum', + 'mean', + 'min', + 'max', + 'std', + 'var', + ]), default: 'sum', description: t( 'Aggregate function applied to the list of points ' + @@ -187,7 +198,9 @@ const config: ControlPanelConfig = { type: 'CheckboxControl', label: t('Live render'), default: true, - description: t('Points and clusters will update as the viewport is being changed'), + description: t( + 'Points and clusters will update as the viewport is being changed', + ), }, }, ], @@ -203,7 +216,10 @@ const config: ControlPanelConfig = { ['mapbox://styles/mapbox/streets-v9', 'Streets'], ['mapbox://styles/mapbox/dark-v9', 'Dark'], ['mapbox://styles/mapbox/light-v9', 'Light'], - ['mapbox://styles/mapbox/satellite-streets-v9', 'Satellite Streets'], + [ + 'mapbox://styles/mapbox/satellite-streets-v9', + 'Satellite Streets', + ], ['mapbox://styles/mapbox/satellite-v9', 'Satellite'], ['mapbox://styles/mapbox/outdoors-v9', 'Outdoors'], ], @@ -220,7 +236,9 @@ const config: ControlPanelConfig = { label: t('Opacity'), default: 1, isFloat: true, - description: t('Opacity of all clusters, points, and labels. Between 0 and 1.'), + description: t( + 'Opacity of all clusters, points, and labels. Between 0 and 1.', + ), }, }, ], diff --git a/plugins/legacy-plugin-chart-map-box/src/transformProps.js b/plugins/legacy-plugin-chart-map-box/src/transformProps.js index 670ed45ba6..bf5fed5caf 100644 --- a/plugins/legacy-plugin-chart-map-box/src/transformProps.js +++ b/plugins/legacy-plugin-chart-map-box/src/transformProps.js @@ -24,7 +24,8 @@ const NOOP = () => {}; export default function transformProps(chartProps) { const { width, height, formData, hooks, queriesData } = chartProps; const { onError = NOOP, setControlValue = NOOP } = hooks; - const { bounds, geoJSON, hasCustomMetric, mapboxApiKey } = queriesData[0].data; + const { bounds, geoJSON, hasCustomMetric, mapboxApiKey } = + queriesData[0].data; const { clusteringRadius, globalOpacity, diff --git a/plugins/legacy-plugin-chart-map-box/src/utils/geo.js b/plugins/legacy-plugin-chart-map-box/src/utils/geo.js index 676b810193..d2e48a65f6 100644 --- a/plugins/legacy-plugin-chart-map-box/src/utils/geo.js +++ b/plugins/legacy-plugin-chart-map-box/src/utils/geo.js @@ -26,7 +26,8 @@ export function kmToPixels(kilometers, latitude, zoomLevel) { // Algorithm from: http://wiki.openstreetmap.org/wiki/Zoom_levels const latitudeRad = latitude * (Math.PI / 180); // Seems like the zoomLevel is off by one - const kmPerPixel = (EARTH_CIRCUMFERENCE_KM * Math.cos(latitudeRad)) / 2 ** (zoomLevel + 9); + const kmPerPixel = + (EARTH_CIRCUMFERENCE_KM * Math.cos(latitudeRad)) / 2 ** (zoomLevel + 9); return roundDecimal(kilometers / kmPerPixel, 2); } diff --git a/plugins/legacy-plugin-chart-map-box/src/utils/luminanceFromRGB.js b/plugins/legacy-plugin-chart-map-box/src/utils/luminanceFromRGB.js index 9e26e3214b..545d6b04ec 100644 --- a/plugins/legacy-plugin-chart-map-box/src/utils/luminanceFromRGB.js +++ b/plugins/legacy-plugin-chart-map-box/src/utils/luminanceFromRGB.js @@ -23,5 +23,9 @@ export const LUMINANCE_BLUE_WEIGHT = 0.0722; export default function luminanceFromRGB(r, g, b) { // Formula: https://en.wikipedia.org/wiki/Relative_luminance - return LUMINANCE_RED_WEIGHT * r + LUMINANCE_GREEN_WEIGHT * g + LUMINANCE_BLUE_WEIGHT * b; + return ( + LUMINANCE_RED_WEIGHT * r + + LUMINANCE_GREEN_WEIGHT * g + + LUMINANCE_BLUE_WEIGHT * b + ); } diff --git a/plugins/legacy-plugin-chart-paired-t-test/src/PairedTTest.jsx b/plugins/legacy-plugin-chart-paired-t-test/src/PairedTTest.jsx index 59efb796fd..4f20e92301 100644 --- a/plugins/legacy-plugin-chart-paired-t-test/src/PairedTTest.jsx +++ b/plugins/legacy-plugin-chart-paired-t-test/src/PairedTTest.jsx @@ -41,7 +41,8 @@ const defaultProps = { class PairedTTest extends React.PureComponent { render() { - const { className, metrics, groups, data, alpha, pValPrec, liftValPrec } = this.props; + const { className, metrics, groups, data, alpha, pValPrec, liftValPrec } = + this.props; return (
diff --git a/plugins/legacy-plugin-chart-paired-t-test/src/TTestTable.jsx b/plugins/legacy-plugin-chart-paired-t-test/src/TTestTable.jsx index 23d45222a1..e897e892ff 100644 --- a/plugins/legacy-plugin-chart-paired-t-test/src/TTestTable.jsx +++ b/plugins/legacy-plugin-chart-paired-t-test/src/TTestTable.jsx @@ -133,10 +133,15 @@ class TTestTable extends React.Component { } }); const tvalue = -Math.abs( - diffSum * Math.sqrt((finiteCount - 1) / (finiteCount * diffSqSum - diffSum * diffSum)), + diffSum * + Math.sqrt( + (finiteCount - 1) / (finiteCount * diffSqSum - diffSum * diffSum), + ), ); try { - return (2 * new dist.Studentt(finiteCount - 1).cdf(tvalue)).toFixed(pValPrec); // two-sided test + return (2 * new dist.Studentt(finiteCount - 1).cdf(tvalue)).toFixed( + pValPrec, + ); // two-sided test } catch (error) { return NaN; } diff --git a/plugins/legacy-plugin-chart-paired-t-test/src/controlPanel.ts b/plugins/legacy-plugin-chart-paired-t-test/src/controlPanel.ts index e3a0b3bda4..f3504ea649 100644 --- a/plugins/legacy-plugin-chart-paired-t-test/src/controlPanel.ts +++ b/plugins/legacy-plugin-chart-paired-t-test/src/controlPanel.ts @@ -71,7 +71,9 @@ const config: ControlPanelConfig = { type: 'TextControl', label: t('Significance Level'), default: 0.05, - description: t('Threshold alpha level for determining significance'), + description: t( + 'Threshold alpha level for determining significance', + ), }, }, ], @@ -82,7 +84,9 @@ const config: ControlPanelConfig = { type: 'TextControl', label: t('p-value precision'), default: 6, - description: t('Number of decimal places with which to display p-values'), + description: t( + 'Number of decimal places with which to display p-values', + ), }, }, ], @@ -93,7 +97,9 @@ const config: ControlPanelConfig = { type: 'TextControl', label: t('Lift percent precision'), default: 4, - description: t('Number of decimal places with which to display lift values'), + description: t( + 'Number of decimal places with which to display lift values', + ), }, }, ], diff --git a/plugins/legacy-plugin-chart-paired-t-test/src/transformProps.js b/plugins/legacy-plugin-chart-paired-t-test/src/transformProps.js index 1cd3d3bf77..73027a54a2 100644 --- a/plugins/legacy-plugin-chart-paired-t-test/src/transformProps.js +++ b/plugins/legacy-plugin-chart-paired-t-test/src/transformProps.js @@ -18,14 +18,22 @@ */ export default function transformProps(chartProps) { const { formData, queriesData } = chartProps; - const { groupby, liftvaluePrecision, metrics, pvaluePrecision, significanceLevel } = formData; + const { + groupby, + liftvaluePrecision, + metrics, + pvaluePrecision, + significanceLevel, + } = formData; return { alpha: significanceLevel, data: queriesData[0].data, groups: groupby, liftValPrec: parseInt(liftvaluePrecision, 10), - metrics: metrics.map(metric => (typeof metric === 'string' ? metric : metric.label)), + metrics: metrics.map(metric => + typeof metric === 'string' ? metric : metric.label, + ), pValPrec: parseInt(pvaluePrecision, 10), }; } diff --git a/plugins/legacy-plugin-chart-parallel-coordinates/README.md b/plugins/legacy-plugin-chart-parallel-coordinates/README.md index a983ecc065..67bcb1ebdb 100644 --- a/plugins/legacy-plugin-chart-parallel-coordinates/README.md +++ b/plugins/legacy-plugin-chart-parallel-coordinates/README.md @@ -13,7 +13,9 @@ lookup this chart throughout the app. ```js import ParallelCoordinatesChartPlugin from '@superset-ui/legacy-plugin-chart-parallel-coordinates'; -new ParallelCoordinatesChartPlugin().configure({ key: 'parallel-coordinates' }).register(); +new ParallelCoordinatesChartPlugin() + .configure({ key: 'parallel-coordinates' }) + .register(); ``` Then use it via `SuperChart`. See diff --git a/plugins/legacy-plugin-chart-parallel-coordinates/src/ParallelCoordinates.js b/plugins/legacy-plugin-chart-parallel-coordinates/src/ParallelCoordinates.js index 55c3428d04..61d151d1f3 100644 --- a/plugins/legacy-plugin-chart-parallel-coordinates/src/ParallelCoordinates.js +++ b/plugins/legacy-plugin-chart-parallel-coordinates/src/ParallelCoordinates.js @@ -65,11 +65,16 @@ function ParallelCoordinates(element, props) { .createLinearScale(d3.extent(data, d => d[colorMetric])) : () => 'grey'; const color = d => colorScale(d[colorMetric]); - const container = d3.select(element).classed('superset-legacy-chart-parallel-coordinates', true); + const container = d3 + .select(element) + .classed('superset-legacy-chart-parallel-coordinates', true); container.selectAll('*').remove(); const effHeight = showDatatable ? height / 2 : height; - const div = container.append('div').style('height', `${effHeight}px`).classed('parcoords', true); + const div = container + .append('div') + .style('height', `${effHeight}px`) + .classed('parcoords', true); const chart = parcoords()(div.node()) .width(width) diff --git a/plugins/legacy-plugin-chart-parallel-coordinates/src/transformProps.js b/plugins/legacy-plugin-chart-parallel-coordinates/src/transformProps.js index 1a7cafba87..5d9a145753 100644 --- a/plugins/legacy-plugin-chart-parallel-coordinates/src/transformProps.js +++ b/plugins/legacy-plugin-chart-parallel-coordinates/src/transformProps.js @@ -18,8 +18,14 @@ */ export default function transformProps(chartProps) { const { width, height, formData, queriesData } = chartProps; - const { includeSeries, linearColorScheme, metrics, secondaryMetric, series, showDatatable } = - formData; + const { + includeSeries, + linearColorScheme, + metrics, + secondaryMetric, + series, + showDatatable, + } = formData; return { width, @@ -28,7 +34,10 @@ export default function transformProps(chartProps) { includeSeries, linearColorScheme, metrics: metrics.map(m => m.label || m), - colorMetric: secondaryMetric && secondaryMetric.label ? secondaryMetric.label : secondaryMetric, + colorMetric: + secondaryMetric && secondaryMetric.label + ? secondaryMetric.label + : secondaryMetric, series, showDatatable, }; diff --git a/plugins/legacy-plugin-chart-parallel-coordinates/src/vendor/parcoords/d3.parcoords.js b/plugins/legacy-plugin-chart-parallel-coordinates/src/vendor/parcoords/d3.parcoords.js index 884973dad0..9344f2a985 100644 --- a/plugins/legacy-plugin-chart-parallel-coordinates/src/vendor/parcoords/d3.parcoords.js +++ b/plugins/legacy-plugin-chart-parallel-coordinates/src/vendor/parcoords/d3.parcoords.js @@ -48,13 +48,23 @@ export default function (config) { .attr('width', __.width) .attr('height', __.height) .append('svg:g') - .attr('transform', 'translate(' + __.margin.left + ',' + __.margin.top + ')'); + .attr( + 'transform', + 'translate(' + __.margin.left + ',' + __.margin.top + ')', + ); return pc; }; var events = d3.dispatch.apply( this, - ['render', 'resize', 'highlight', 'brush', 'brushend', 'axesreorder'].concat(d3.keys(__)), + [ + 'render', + 'resize', + 'highlight', + 'brush', + 'brushend', + 'axesreorder', + ].concat(d3.keys(__)), ), w = function () { return __.width - __.margin.right - __.margin.left; @@ -173,9 +183,20 @@ export default function (config) { /** adjusts an axis' default range [h()+1, 1] if a NullValueSeparator is set */ function getRange() { if (__.nullValueSeparator == 'bottom') { - return [h() + 1 - __.nullValueSeparatorPadding.bottom - __.nullValueSeparatorPadding.top, 1]; + return [ + h() + + 1 - + __.nullValueSeparatorPadding.bottom - + __.nullValueSeparatorPadding.top, + 1, + ]; } else if (__.nullValueSeparator == 'top') { - return [h() + 1, 1 + __.nullValueSeparatorPadding.bottom + __.nullValueSeparatorPadding.top]; + return [ + h() + 1, + 1 + + __.nullValueSeparatorPadding.bottom + + __.nullValueSeparatorPadding.top, + ]; } return [h() + 1, 1]; } @@ -501,7 +522,10 @@ export default function (config) { cps.push(centroids[0]); cps.push( - $V([centroids[0].e(1) + a * 2 * (centroids[1].e(1) - centroids[0].e(1)), centroids[0].e(2)]), + $V([ + centroids[0].e(1) + a * 2 * (centroids[1].e(1) - centroids[0].e(1)), + centroids[0].e(2), + ]), ); for (var col = 1; col < cols - 1; ++col) { var mid = centroids[col]; @@ -515,7 +539,8 @@ export default function (config) { } cps.push( $V([ - centroids[cols - 1].e(1) + a * 2 * (centroids[cols - 2].e(1) - centroids[cols - 1].e(1)), + centroids[cols - 1].e(1) + + a * 2 * (centroids[cols - 2].e(1) - centroids[cols - 1].e(1)), centroids[cols - 1].e(2), ]), ); @@ -575,7 +600,10 @@ export default function (config) { // draw single polyline function color_path(d, ctx) { ctx.beginPath(); - if ((__.bundleDimension !== null && __.bundlingStrength > 0) || __.smoothness > 0) { + if ( + (__.bundleDimension !== null && __.bundlingStrength > 0) || + __.smoothness > 0 + ) { single_curve(d, ctx); } else { single_path(d, ctx); @@ -588,7 +616,10 @@ export default function (config) { ctx.clearRect(-1, -1, w() + 2, h() + 2); ctx.beginPath(); data.forEach(function (d) { - if ((__.bundleDimension !== null && __.bundlingStrength > 0) || __.smoothness > 0) { + if ( + (__.bundleDimension !== null && __.bundlingStrength > 0) || + __.smoothness > 0 + ) { single_curve(d, ctx); } else { single_path(d, ctx); @@ -614,9 +645,15 @@ export default function (config) { function single_path(d, ctx) { __.dimensions.map(function (p, i) { if (i == 0) { - ctx.moveTo(position(p), typeof d[p] == 'undefined' ? getNullPosition() : yscale[p](d[p])); + ctx.moveTo( + position(p), + typeof d[p] == 'undefined' ? getNullPosition() : yscale[p](d[p]), + ); } else { - ctx.lineTo(position(p), typeof d[p] == 'undefined' ? getNullPosition() : yscale[p](d[p])); + ctx.lineTo( + position(p), + typeof d[p] == 'undefined' ? getNullPosition() : yscale[p](d[p]), + ); } }); } @@ -671,7 +708,10 @@ export default function (config) { pc.flip(dimension); - d3.select(this.parentElement).transition().duration(1100).call(axis.scale(yscale[dimension])); + d3.select(this.parentElement) + .transition() + .duration(1100) + .call(axis.scale(yscale[dimension])); pc.render(); } @@ -684,7 +724,10 @@ export default function (config) { __.dimensionTitleRotation += delta; pc.svg .selectAll('text.label') - .attr('transform', 'translate(0,-5) rotate(' + __.dimensionTitleRotation + ')'); + .attr( + 'transform', + 'translate(0,-5) rotate(' + __.dimensionTitleRotation + ')', + ); d3.event.preventDefault(); } @@ -804,7 +847,10 @@ export default function (config) { .transition() .duration(1100) .text(dimensionLabels) - .attr('transform', 'translate(0,-5) rotate(' + __.dimensionTitleRotation + ')'); + .attr( + 'transform', + 'translate(0,-5) rotate(' + __.dimensionTitleRotation + ')', + ); // Exit g_data.exit().remove(); @@ -846,7 +892,10 @@ export default function (config) { dragging[d] = this.__origin__ = xscale(d); }) .on('drag', function (d) { - dragging[d] = Math.min(w(), Math.max(0, (this.__origin__ += d3.event.dx))); + dragging[d] = Math.min( + w(), + Math.max(0, (this.__origin__ += d3.event.dx)), + ); __.dimensions.sort(function (a, b) { return position(a) - position(b); }); @@ -1069,25 +1118,32 @@ export default function (config) { if (typeof yscale[p].rangePoints === 'function') { // if it is ordinal return ( - extents[dimension][0] <= yscale[p](d[p]) && yscale[p](d[p]) <= extents[dimension][1] + extents[dimension][0] <= yscale[p](d[p]) && + yscale[p](d[p]) <= extents[dimension][1] ); } else { - return extents[dimension][0] <= d[p] && d[p] <= extents[dimension][1]; + return ( + extents[dimension][0] <= d[p] && d[p] <= extents[dimension][1] + ); } }, number: function (d, p, dimension) { if (typeof yscale[p].rangePoints === 'function') { // if it is ordinal return ( - extents[dimension][0] <= yscale[p](d[p]) && yscale[p](d[p]) <= extents[dimension][1] + extents[dimension][0] <= yscale[p](d[p]) && + yscale[p](d[p]) <= extents[dimension][1] ); } else { - return extents[dimension][0] <= d[p] && d[p] <= extents[dimension][1]; + return ( + extents[dimension][0] <= d[p] && d[p] <= extents[dimension][1] + ); } }, string: function (d, p, dimension) { return ( - extents[dimension][0] <= yscale[p](d[p]) && yscale[p](d[p]) <= extents[dimension][1] + extents[dimension][0] <= yscale[p](d[p]) && + yscale[p](d[p]) <= extents[dimension][1] ); }, }; @@ -1253,7 +1309,10 @@ export default function (config) { .on('drag', function (d, i) { var ev = d3.event; i = i + 1; - strum['p' + i][0] = Math.min(Math.max(strum.minX + 1, ev.x), strum.maxX); + strum['p' + i][0] = Math.min( + Math.max(strum.minX + 1, ev.x), + strum.maxX, + ); strum['p' + i][1] = Math.min(Math.max(strum.minY, ev.y), strum.maxY); drawStrum(strum, i - 1); }) @@ -1351,8 +1410,14 @@ export default function (config) { strum = strums[strums.active]; // Make sure that the point is within the bounds - strum.p2[0] = Math.min(Math.max(strum.minX + 1, ev.x - __.margin.left), strum.maxX); - strum.p2[1] = Math.min(Math.max(strum.minY, ev.y - __.margin.top), strum.maxY); + strum.p2[0] = Math.min( + Math.max(strum.minX + 1, ev.x - __.margin.left), + strum.maxX, + ); + strum.p2[1] = Math.min( + Math.max(strum.minY, ev.y - __.margin.top), + strum.maxY, + ); drawStrum(strum, 1); }; } @@ -1437,7 +1502,11 @@ export default function (config) { // Okay, somewhat unexpected, but not totally unsurprising, a mousclick is // considered a drag without move. So we have to deal with that case - if (strum && strum.p1[0] === strum.p2[0] && strum.p1[1] === strum.p2[1]) { + if ( + strum && + strum.p1[0] === strum.p2[0] && + strum.p1[1] === strum.p2[1] + ) { removeStrum(strums); } @@ -1492,7 +1561,9 @@ export default function (config) { function consecutive(first, second) { var length = __.dimensions.length; return __.dimensions.some(function (d, i) { - return d === first ? i + i < length && __.dimensions[i + 1] === second : false; + return d === first + ? i + i < length && __.dimensions[i + 1] === second + : false; }); } @@ -1516,7 +1587,10 @@ export default function (config) { .select('svg') .append('g') .attr('id', 'strums') - .attr('transform', 'translate(' + __.margin.left + ',' + __.margin.top + ')'); + .attr( + 'transform', + 'translate(' + __.margin.left + ',' + __.margin.top + ')', + ); // Install the required brushReset function pc.brushReset = brushReset(strums); @@ -1742,7 +1816,9 @@ export default function (config) { .style('fill', 'orange') .style('opacity', 0.5); - path.attr('d', arc.arc).attr('transform', 'translate(' + arc.p1[0] + ',' + arc.p1[1] + ')'); + path + .attr('d', arc.arc) + .attr('transform', 'translate(' + arc.p1[0] + ',' + arc.p1[1] + ')'); line .enter() @@ -1779,8 +1855,12 @@ export default function (config) { angle = i === 3 ? arcs.startAngle(id) : arcs.endAngle(id); if ( - (arc.startAngle < Math.PI && arc.endAngle < Math.PI && angle < Math.PI) || - (arc.startAngle >= Math.PI && arc.endAngle >= Math.PI && angle >= Math.PI) + (arc.startAngle < Math.PI && + arc.endAngle < Math.PI && + angle < Math.PI) || + (arc.startAngle >= Math.PI && + arc.endAngle >= Math.PI && + angle >= Math.PI) ) { if (i === 2) { arc.endAngle = angle; @@ -1891,8 +1971,14 @@ export default function (config) { arc = arcs[arcs.active]; // Make sure that the point is within the bounds - arc.p2[0] = Math.min(Math.max(arc.minX + 1, ev.x - __.margin.left), arc.maxX); - arc.p2[1] = Math.min(Math.max(arc.minY, ev.y - __.margin.top), arc.maxY); + arc.p2[0] = Math.min( + Math.max(arc.minX + 1, ev.x - __.margin.left), + arc.maxX, + ); + arc.p2[1] = Math.min( + Math.max(arc.minY, ev.y - __.margin.top), + arc.maxY, + ); arc.p3 = arc.p2.slice(); drawStrum(arc, 1); }; @@ -2026,7 +2112,10 @@ export default function (config) { arc.startAngle = angle; arc.endAngle = angle; - arc.arc.outerRadius(arcs.length(arcs.active)).startAngle(angle).endAngle(angle); + arc.arc + .outerRadius(arcs.length(arcs.active)) + .startAngle(angle) + .endAngle(angle); } brushed = selected(arcs); @@ -2135,7 +2224,9 @@ export default function (config) { function consecutive(first, second) { var length = __.dimensions.length; return __.dimensions.some(function (d, i) { - return d === first ? i + i < length && __.dimensions[i + 1] === second : false; + return d === first + ? i + i < length && __.dimensions[i + 1] === second + : false; }); } @@ -2159,7 +2250,10 @@ export default function (config) { .select('svg') .append('g') .attr('id', 'arcs') - .attr('transform', 'translate(' + __.margin.left + ',' + __.margin.top + ')'); + .attr( + 'transform', + 'translate(' + __.margin.left + ',' + __.margin.top + ')', + ); // Install the required brushReset function pc.brushReset = brushReset(arcs); @@ -2219,8 +2313,14 @@ export default function (config) { // TODO currently assumes chart is brushable, and destroys old brushes pc.resize = function () { // selection size - pc.selection.select('svg').attr('width', __.width).attr('height', __.height); - pc.svg.attr('transform', 'translate(' + __.margin.left + ',' + __.margin.top + ')'); + pc.selection + .select('svg') + .attr('width', __.width) + .attr('height', __.height); + pc.svg.attr( + 'transform', + 'translate(' + __.margin.left + ',' + __.margin.top + ')', + ); // FIXME: the current brush state should pass through if (flags.brushable) pc.brushReset(); @@ -2233,7 +2333,11 @@ export default function (config) { if (flags.brushable) pc.brushable(); if (flags.reorderable) pc.reorderable(); - events.resize.call(this, { width: __.width, height: __.height, margin: __.margin }); + events.resize.call(this, { + width: __.width, + height: __.height, + margin: __.margin, + }); return this; }; @@ -2264,10 +2368,12 @@ export default function (config) { pc.intersection = function (a, b, c, d) { return { x: - ((a.x * b.y - a.y * b.x) * (c.x - d.x) - (a.x - b.x) * (c.x * d.y - c.y * d.x)) / + ((a.x * b.y - a.y * b.x) * (c.x - d.x) - + (a.x - b.x) * (c.x * d.y - c.y * d.x)) / ((a.x - b.x) * (c.y - d.y) - (a.y - b.y) * (c.x - d.x)), y: - ((a.x * b.y - a.y * b.x) * (c.y - d.y) - (a.y - b.y) * (c.x * d.y - c.y * d.x)) / + ((a.x * b.y - a.y * b.x) * (c.y - d.y) - + (a.y - b.y) * (c.x * d.y - c.y * d.x)) / ((a.x - b.x) * (c.y - d.y) - (a.y - b.y) * (c.x - d.x)), }; }; diff --git a/plugins/legacy-plugin-chart-parallel-coordinates/src/vendor/parcoords/divgrid.js b/plugins/legacy-plugin-chart-parallel-coordinates/src/vendor/parcoords/divgrid.js index a4996990cf..2d79761ebd 100644 --- a/plugins/legacy-plugin-chart-parallel-coordinates/src/vendor/parcoords/divgrid.js +++ b/plugins/legacy-plugin-chart-parallel-coordinates/src/vendor/parcoords/divgrid.js @@ -8,7 +8,12 @@ export default function (config) { if (columns.length == 0) columns = d3.keys(selection.data()[0][0]); // header - selection.selectAll('.header').data([true]).enter().append('div').attr('class', 'header'); + selection + .selectAll('.header') + .data([true]) + .enter() + .append('div') + .attr('class', 'header'); var header = selection.select('.header').selectAll('.cell').data(columns); diff --git a/plugins/legacy-plugin-chart-partition/src/OptionDescription.tsx b/plugins/legacy-plugin-chart-partition/src/OptionDescription.tsx index 719bf8e4ca..e771323795 100644 --- a/plugins/legacy-plugin-chart-partition/src/OptionDescription.tsx +++ b/plugins/legacy-plugin-chart-partition/src/OptionDescription.tsx @@ -20,7 +20,10 @@ import React from 'react'; import PropTypes from 'prop-types'; -import { ColumnMeta, InfoTooltipWithTrigger } from '@superset-ui/chart-controls'; +import { + ColumnMeta, + InfoTooltipWithTrigger, +} from '@superset-ui/chart-controls'; const propTypes = { option: PropTypes.object.isRequired, diff --git a/plugins/legacy-plugin-chart-partition/src/Partition.js b/plugins/legacy-plugin-chart-partition/src/Partition.js index c662092e8b..224ff85af7 100644 --- a/plugins/legacy-plugin-chart-partition/src/Partition.js +++ b/plugins/legacy-plugin-chart-partition/src/Partition.js @@ -21,7 +21,11 @@ import d3 from 'd3'; import PropTypes from 'prop-types'; import { hierarchy } from 'd3-hierarchy'; -import { getNumberFormatter, getTimeFormatter, CategoricalColorNamespace } from '@superset-ui/core'; +import { + getNumberFormatter, + getTimeFormatter, + CategoricalColorNamespace, +} from '@superset-ui/core'; import './Partition.css'; // Compute dx, dy, x, y for each node and @@ -59,7 +63,10 @@ const parentShape = { name: PropTypes.string, val: PropTypes.number.isRequired, children: PropTypes.arrayOf( - PropTypes.oneOfType([PropTypes.shape(lazyFunction(() => parentShape)), leafType]), + PropTypes.oneOfType([ + PropTypes.shape(lazyFunction(() => parentShape)), + leafType, + ]), ), }; const nodeType = PropTypes.oneOfType([PropTypes.shape(parentShape), leafType]); @@ -72,7 +79,9 @@ const propTypes = { dateTimeFormat: PropTypes.string, equalDateSize: PropTypes.bool, levels: PropTypes.arrayOf(PropTypes.string), - metrics: PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.string, PropTypes.object])), + metrics: PropTypes.arrayOf( + PropTypes.oneOfType([PropTypes.string, PropTypes.object]), + ), numberFormat: PropTypes.string, partitionLimit: PropTypes.number, partitionThreshold: PropTypes.number, @@ -185,7 +194,10 @@ function Icicle(element, props) { n.name = timeFormat(n.name); } if (useLogScale) n.weight = Math.log(n.weight + 1); - n.disp = n.disp && !Number.isNaN(n.disp) && Number.isFinite(n.disp) ? format(n.disp) : ''; + n.disp = + n.disp && !Number.isNaN(n.disp) && Number.isFinite(n.disp) + ? format(n.disp) + : ''; }); // Perform sort by weight root.sort((a, b) => { @@ -202,7 +214,9 @@ function Icicle(element, props) { if (partitionThreshold && partitionThreshold >= 0) { // Compute weight sums as we go root.each(n => { - n.sum = n.children ? n.children.reduce((a, v) => a + v.weight, 0) || 1 : 1; + n.sum = n.children + ? n.children.reduce((a, v) => a + v.weight, 0) || 1 + : 1; if (n.children) { // Dates are not ordered by weight if (hasDateNode(n)) { @@ -243,7 +257,9 @@ function Icicle(element, props) { } // Compute final weight sums root.eachAfter(n => { - n.sum = n.children ? n.children.reduce((a, v) => a + v.weight, 0) || 1 : 1; + n.sum = n.children + ? n.children.reduce((a, v) => a + v.weight, 0) || 1 + : 1; }); function positionAndPopulate(tip, d) { diff --git a/plugins/legacy-plugin-chart-partition/src/controlPanel.tsx b/plugins/legacy-plugin-chart-partition/src/controlPanel.tsx index 7da0d93e3a..4881689129 100644 --- a/plugins/legacy-plugin-chart-partition/src/controlPanel.tsx +++ b/plugins/legacy-plugin-chart-partition/src/controlPanel.tsx @@ -100,17 +100,23 @@ const config: ControlPanelConfig = { { label: t('Difference'), value: 'point_diff', - description: t('Metric change in value from `since` to `until`'), + description: t( + 'Metric change in value from `since` to `until`', + ), }, { label: t('Percent Change'), value: 'point_percent', - description: t('Metric percent change in value from `since` to `until`'), + description: t( + 'Metric percent change in value from `since` to `until`', + ), }, { label: t('Factor'), value: 'point_factor', - description: t('Metric factor change from `since` to `until`'), + description: t( + 'Metric factor change from `since` to `until`', + ), }, { label: t('Advanced Analytics'), @@ -118,8 +124,12 @@ const config: ControlPanelConfig = { description: t('Use the Advanced Analytics options below'), }, ], - optionRenderer: (op: ColumnMeta) => , - valueRenderer: (op: ColumnMeta) => , + optionRenderer: (op: ColumnMeta) => ( + + ), + valueRenderer: (op: ColumnMeta) => ( + + ), description: t('Settings for time series'), }, }, @@ -206,7 +216,9 @@ const config: ControlPanelConfig = { label: t('Equal Date Sizes'), default: true, renderTrigger: true, - description: t('Check to force date partitions to have the same height'), + description: t( + 'Check to force date partitions to have the same height', + ), }, }, ], @@ -218,7 +230,9 @@ const config: ControlPanelConfig = { label: t('Rich Tooltip'), renderTrigger: true, default: true, - description: t('The rich tooltip shows a list of all series for that point in time'), + description: t( + 'The rich tooltip shows a list of all series for that point in time', + ), }, }, ], @@ -242,7 +256,13 @@ const config: ControlPanelConfig = { type: 'SelectControl', label: t('Rolling Function'), default: 'None', - choices: formatSelectOptions(['None', 'mean', 'sum', 'std', 'cumsum']), + choices: formatSelectOptions([ + 'None', + 'mean', + 'sum', + 'std', + 'cumsum', + ]), description: t( 'Defines a rolling window function to apply, works along ' + 'with the [Periods] text box', @@ -339,7 +359,14 @@ const config: ControlPanelConfig = { freeForm: true, label: t('Rule'), default: null, - choices: formatSelectOptions(['1T', '1H', '1D', '7D', '1M', '1AS']), + choices: formatSelectOptions([ + '1T', + '1H', + '1D', + '7D', + '1M', + '1AS', + ]), description: t('Pandas resample rule'), }, }, @@ -350,7 +377,14 @@ const config: ControlPanelConfig = { freeForm: true, label: t('Method'), default: null, - choices: formatSelectOptions(['asfreq', 'bfill', 'ffill', 'median', 'mean', 'sum']), + choices: formatSelectOptions([ + 'asfreq', + 'bfill', + 'ffill', + 'median', + 'mean', + 'sum', + ]), description: t('Pandas resample method'), }, }, diff --git a/plugins/legacy-plugin-chart-pivot-table/src/PivotTable.js b/plugins/legacy-plugin-chart-pivot-table/src/PivotTable.js index 9c6f8d017f..cebfec288d 100644 --- a/plugins/legacy-plugin-chart-pivot-table/src/PivotTable.js +++ b/plugins/legacy-plugin-chart-pivot-table/src/PivotTable.js @@ -38,7 +38,10 @@ const propTypes = { // TODO: replace this with raw data in SIP-6 html: PropTypes.string, columns: PropTypes.arrayOf( - PropTypes.oneOfType([PropTypes.string, PropTypes.arrayOf(PropTypes.string)]), + PropTypes.oneOfType([ + PropTypes.string, + PropTypes.arrayOf(PropTypes.string), + ]), ), }), height: PropTypes.number, @@ -49,7 +52,8 @@ const propTypes = { }; const hasOnlyTextChild = node => - node.childNodes.length === 1 && node.childNodes[0].nodeType === Node.TEXT_NODE; + node.childNodes.length === 1 && + node.childNodes[0].nodeType === Node.TEXT_NODE; function PivotTable(element, props) { const { @@ -84,7 +88,12 @@ function PivotTable(element, props) { $container.find('th').each(function formatTh() { if (hasOnlyTextChild(this)) { - const cellValue = formatDateCellValue($(this).text(), verboseMap, dateRegex, dateFormatter); + const cellValue = formatDateCellValue( + $(this).text(), + verboseMap, + dateRegex, + dateFormatter, + ); $(this).text(cellValue); } }); diff --git a/plugins/legacy-plugin-chart-pivot-table/src/controlPanel.ts b/plugins/legacy-plugin-chart-pivot-table/src/controlPanel.ts index 8395a46384..d992829c78 100644 --- a/plugins/legacy-plugin-chart-pivot-table/src/controlPanel.ts +++ b/plugins/legacy-plugin-chart-pivot-table/src/controlPanel.ts @@ -62,7 +62,14 @@ const config: ControlPanelConfig = { type: 'SelectControl', label: t('Aggregation function'), clearable: false, - choices: formatSelectOptions(['sum', 'mean', 'min', 'max', 'std', 'var']), + choices: formatSelectOptions([ + 'sum', + 'mean', + 'min', + 'max', + 'std', + 'var', + ]), default: 'sum', description: t( 'Aggregate function to apply when pivoting and ' + diff --git a/plugins/legacy-plugin-chart-pivot-table/src/utils/fixTableHeight.js b/plugins/legacy-plugin-chart-pivot-table/src/utils/fixTableHeight.js index 07746d3076..4e55d27c46 100644 --- a/plugins/legacy-plugin-chart-pivot-table/src/utils/fixTableHeight.js +++ b/plugins/legacy-plugin-chart-pivot-table/src/utils/fixTableHeight.js @@ -25,7 +25,8 @@ export default function fixTableHeight($tableDom, height) { const filterHeight = $tableDom.find('.dataTables_filter').height() || 0; const pageLengthHeight = $tableDom.find('.dataTables_length').height() || 0; const paginationHeight = $tableDom.find('.dataTables_paginate').height() || 0; - const controlsHeight = pageLengthHeight > filterHeight ? pageLengthHeight : filterHeight; + const controlsHeight = + pageLengthHeight > filterHeight ? pageLengthHeight : filterHeight; $tableDom .find('.dataTables_scrollBody') .css('max-height', height - headHeight - controlsHeight - paginationHeight); diff --git a/plugins/legacy-plugin-chart-pivot-table/src/utils/formatCells.ts b/plugins/legacy-plugin-chart-pivot-table/src/utils/formatCells.ts index 7e3734ac4c..5e32235da3 100644 --- a/plugins/legacy-plugin-chart-pivot-table/src/utils/formatCells.ts +++ b/plugins/legacy-plugin-chart-pivot-table/src/utils/formatCells.ts @@ -51,7 +51,12 @@ function formatCellValue( return { textContent, sortAttributeValue }; } -function formatDateCellValue(text: string, verboseMap: any, dateRegex: RegExp, dateFormatter: any) { +function formatDateCellValue( + text: string, + verboseMap: any, + dateRegex: RegExp, + dateFormatter: any, +) { const regexMatch = dateRegex.exec(text); let cellValue; if (regexMatch) { diff --git a/plugins/legacy-plugin-chart-rose/src/Rose.js b/plugins/legacy-plugin-chart-rose/src/Rose.js index 8daec52839..1a60fdbc95 100644 --- a/plugins/legacy-plugin-chart-rose/src/Rose.js +++ b/plugins/legacy-plugin-chart-rose/src/Rose.js @@ -22,7 +22,11 @@ import d3 from 'd3'; import PropTypes from 'prop-types'; import nv from 'nvd3'; -import { getTimeFormatter, getNumberFormatter, CategoricalColorNamespace } from '@superset-ui/core'; +import { + getTimeFormatter, + getNumberFormatter, + CategoricalColorNamespace, +} from '@superset-ui/core'; import './Rose.css'; const propTypes = { @@ -142,10 +146,18 @@ function Rose(element, props) { const gro = 8; // mouseover radius growth in pixels const mini = 0.075; - const centerTranslate = `translate(${width / 2},${roseHeight / 2 + margin.top})`; - const roseWrap = g.append('g').attr('transform', centerTranslate).attr('class', 'roseWrap'); + const centerTranslate = `translate(${width / 2},${ + roseHeight / 2 + margin.top + })`; + const roseWrap = g + .append('g') + .attr('transform', centerTranslate) + .attr('class', 'roseWrap'); - const labelsWrap = g.append('g').attr('transform', centerTranslate).attr('class', 'labelsWrap'); + const labelsWrap = g + .append('g') + .attr('transform', centerTranslate) + .attr('class', 'labelsWrap'); const groupLabelsWrap = g .append('g') @@ -159,7 +171,10 @@ function Rose(element, props) { let grain = 0; const sums = []; for (const t of times) { - const sum = datum[t].reduce((a, v, i) => a + (state.disabled[i] ? 0 : v.value), 0); + const sum = datum[t].reduce( + (a, v, i) => a + (state.disabled[i] ? 0 : v.value), + 0, + ); maxSum = sum > maxSum ? sum : maxSum; sums[grain] = sum; grain += 1; @@ -206,7 +221,16 @@ function Rose(element, props) { const { name, time } = v; v.id = arcId; outerRadius = computeOuterRadius(val, innerRadius); - arcSt.data.push({ startAngle, endAngle, innerRadius, outerRadius, name, arcId, val, time }); + arcSt.data.push({ + startAngle, + endAngle, + innerRadius, + outerRadius, + name, + arcId, + val, + time, + }); arcSt.extend[arcId] = { startAngle, endAngle, @@ -301,7 +325,10 @@ function Rose(element, props) { return segmentsInTimeCache[arcId]; } const timeIndex = Math.floor(arcId / numGroups); - segmentsInTimeCache[arcId] = [timeIndex * numGroups, (timeIndex + 1) * numGroups - 1]; + segmentsInTimeCache[arcId] = [ + timeIndex * numGroups, + (timeIndex + 1) * numGroups - 1, + ]; return segmentsInTimeCache[arcId]; } @@ -465,11 +492,15 @@ function Rose(element, props) { })(d), ) .style('opacity', d => - state.disabled[d.arcId] || arcSt.pie[segments[0] + d.arcId].percent < labelThreshold + state.disabled[d.arcId] || + arcSt.pie[segments[0] + d.arcId].percent < labelThreshold ? 0 : 1, ); - ae.classed('clickable', d => segments[0] > d.arcId || d.arcId > segments[1]); + ae.classed( + 'clickable', + d => segments[0] > d.arcId || d.arcId > segments[1], + ); arcs .filter(d => segments[0] <= d.arcId && d.arcId <= segments[1]) .interrupt() @@ -496,7 +527,9 @@ function Rose(element, props) { .transition() .delay(delay) .duration(delay) - .attrTween('transform', d => translateTween(arcSt.labels[d.arcId / numGroups])(d)) + .attrTween('transform', d => + translateTween(arcSt.labels[d.arcId / numGroups])(d), + ) .style('opacity', 1); groupLabels .interrupt() @@ -587,7 +620,8 @@ function Rose(element, props) { })(d), ) .style('opacity', d => - state.disabled[d.arcId] || arcSt.pie[segments[0] + d.arcId].percent < labelThreshold + state.disabled[d.arcId] || + arcSt.pie[segments[0] + d.arcId].percent < labelThreshold ? 0 : 1, ); diff --git a/plugins/legacy-plugin-chart-rose/src/controlPanel.tsx b/plugins/legacy-plugin-chart-rose/src/controlPanel.tsx index d4dde69341..ed173951dd 100644 --- a/plugins/legacy-plugin-chart-rose/src/controlPanel.tsx +++ b/plugins/legacy-plugin-chart-rose/src/controlPanel.tsx @@ -100,7 +100,9 @@ const config: ControlPanelConfig = { label: t('Rich Tooltip'), renderTrigger: true, default: true, - description: t('The rich tooltip shows a list of all series for that point in time'), + description: t( + 'The rich tooltip shows a list of all series for that point in time', + ), }, }, { @@ -137,7 +139,13 @@ const config: ControlPanelConfig = { type: 'SelectControl', label: t('Rolling Function'), default: 'None', - choices: formatSelectOptions(['None', 'mean', 'sum', 'std', 'cumsum']), + choices: formatSelectOptions([ + 'None', + 'mean', + 'sum', + 'std', + 'cumsum', + ]), description: t( 'Defines a rolling window function to apply, works along ' + 'with the [Periods] text box', @@ -234,7 +242,14 @@ const config: ControlPanelConfig = { freeForm: true, label: t('Rule'), default: null, - choices: formatSelectOptions(['1T', '1H', '1D', '7D', '1M', '1AS']), + choices: formatSelectOptions([ + '1T', + '1H', + '1D', + '7D', + '1M', + '1AS', + ]), description: t('Pandas resample rule'), }, }, @@ -245,7 +260,14 @@ const config: ControlPanelConfig = { freeForm: true, label: t('Method'), default: null, - choices: formatSelectOptions(['asfreq', 'bfill', 'ffill', 'median', 'mean', 'sum']), + choices: formatSelectOptions([ + 'asfreq', + 'bfill', + 'ffill', + 'median', + 'mean', + 'sum', + ]), description: t('Pandas resample method'), }, }, diff --git a/plugins/legacy-plugin-chart-rose/src/transformProps.js b/plugins/legacy-plugin-chart-rose/src/transformProps.js index a384841f76..1e5407b16d 100644 --- a/plugins/legacy-plugin-chart-rose/src/transformProps.js +++ b/plugins/legacy-plugin-chart-rose/src/transformProps.js @@ -18,7 +18,13 @@ */ export default function transformProps(chartProps) { const { width, height, formData, queriesData } = chartProps; - const { colorScheme, dateTimeFormat, numberFormat, richTooltip, roseAreaProportion } = formData; + const { + colorScheme, + dateTimeFormat, + numberFormat, + richTooltip, + roseAreaProportion, + } = formData; return { width, diff --git a/plugins/legacy-plugin-chart-sankey-loop/src/SankeyLoop.js b/plugins/legacy-plugin-chart-sankey-loop/src/SankeyLoop.js index 3bb54d2f29..bddf570026 100644 --- a/plugins/legacy-plugin-chart-sankey-loop/src/SankeyLoop.js +++ b/plugins/legacy-plugin-chart-sankey-loop/src/SankeyLoop.js @@ -20,7 +20,11 @@ import PropTypes from 'prop-types'; import { select } from 'd3-selection'; import { sankeyDiagram, sankey } from 'd3-sankey-diagram'; -import { getNumberFormatter, NumberFormats, CategoricalColorNamespace } from '@superset-ui/core'; +import { + getNumberFormatter, + NumberFormats, + CategoricalColorNamespace, +} from '@superset-ui/core'; import './SankeyLoop.css'; @@ -64,7 +68,10 @@ const countFormat = getNumberFormatter(); function computeGraph(links) { // this assumes source and target are string values const nodes = Array.from( - links.reduce((set, { source, target }) => set.add(source).add(target), new Set()), + links.reduce( + (set, { source, target }) => set.add(source).add(target), + new Set(), + ), ).map(id => ({ id, name: id })); return { @@ -93,8 +100,14 @@ function SankeyLoop(element, props) { const diagram = sankeyDiagram() .nodeTitle(d => d.name) .linkTitle( - ({ source: { name: sName, value: sValue }, target: { name: tName }, value }) => - `${sName} → ${tName}: ${countFormat(value)} (${percentFormat(value / sValue)})`, + ({ + source: { name: sName, value: sValue }, + target: { name: tName }, + value, + }) => + `${sName} → ${tName}: ${countFormat(value)} (${percentFormat( + value / sValue, + )})`, ) .linkColor(d => color(d.source.name)); @@ -117,7 +130,10 @@ function SankeyLoop(element, props) { .attr('y', d => d.points[0].y) .attr('dy', 3) .attr('dx', 2) - .text(d => `${countFormat(d.value)} (${percentFormat(d.value / d.source.value)})`); + .text( + d => + `${countFormat(d.value)} (${percentFormat(d.value / d.source.value)})`, + ); } SankeyLoop.displayName = 'SankeyLoop'; diff --git a/plugins/legacy-plugin-chart-sankey-loop/src/controlPanel.ts b/plugins/legacy-plugin-chart-sankey-loop/src/controlPanel.ts index 0b2c8a0e55..d09c4aedc7 100644 --- a/plugins/legacy-plugin-chart-sankey-loop/src/controlPanel.ts +++ b/plugins/legacy-plugin-chart-sankey-loop/src/controlPanel.ts @@ -25,7 +25,12 @@ const config: ControlPanelConfig = { { label: t('Query'), expanded: true, - controlSetRows: [['groupby'], ['metric'], ['adhoc_filters'], ['row_limit']], + controlSetRows: [ + ['groupby'], + ['metric'], + ['adhoc_filters'], + ['row_limit'], + ], }, { label: t('Chart Options'), diff --git a/plugins/legacy-plugin-chart-sankey/src/Sankey.js b/plugins/legacy-plugin-chart-sankey/src/Sankey.js index 34a5bbfc7e..b847f75413 100644 --- a/plugins/legacy-plugin-chart-sankey/src/Sankey.js +++ b/plugins/legacy-plugin-chart-sankey/src/Sankey.js @@ -21,7 +21,11 @@ import d3 from 'd3'; import PropTypes from 'prop-types'; import { sankey as d3Sankey } from 'd3-sankey'; -import { getNumberFormatter, NumberFormats, CategoricalColorNamespace } from '@superset-ui/core'; +import { + getNumberFormatter, + NumberFormats, + CategoricalColorNamespace, +} from '@superset-ui/core'; import { getOverlappingElements } from './utils'; const propTypes = { @@ -53,7 +57,10 @@ function Sankey(element, props) { const innerHeight = height - margin.top - margin.bottom; div.selectAll('*').remove(); - const tooltip = div.append('div').attr('class', 'sankey-tooltip').style('opacity', 0); + const tooltip = div + .append('div') + .attr('class', 'sankey-tooltip') + .style('opacity', 0); const svg = div .append('svg') .attr('width', innerWidth + margin.left + margin.right) @@ -63,7 +70,10 @@ function Sankey(element, props) { const colorFn = CategoricalColorNamespace.getScale(colorScheme); - const sankey = d3Sankey().nodeWidth(15).nodePadding(10).size([innerWidth, innerHeight]); + const sankey = d3Sankey() + .nodeWidth(15) + .nodePadding(10) + .size([innerWidth, innerHeight]); const path = sankey.link(); @@ -71,8 +81,10 @@ function Sankey(element, props) { // Compute the distinct nodes from the links. const links = data.map(row => { const link = { ...row }; - link.source = nodes[link.source] || (nodes[link.source] = { name: link.source }); - link.target = nodes[link.target] || (nodes[link.target] = { name: link.target }); + link.source = + nodes[link.source] || (nodes[link.source] = { name: link.source }); + link.target = + nodes[link.target] || (nodes[link.target] = { name: link.target }); link.value = Number(link.value); return link; @@ -86,7 +98,9 @@ function Sankey(element, props) { if (d.sourceLinks) { // is node - html = `${d.name} Value: ${formatNumber(d.value)}`; + html = `${d.name} Value: ${formatNumber( + d.value, + )}`; } else { const val = formatNumber(d.value); const sourcePercent = d3.round((d.value / d.source.value) * 100, 1); @@ -102,7 +116,9 @@ function Sankey(element, props) { '% of ', d.source.name, '
', - `${Number.isFinite(targetPercent) ? targetPercent : '--'}% of `, + `${ + Number.isFinite(targetPercent) ? targetPercent : '--' + }% of `, d.target.name, '
', ].join(''); @@ -116,10 +132,18 @@ function Sankey(element, props) { .html(() => getTooltipHtml(d)) .transition() .duration(200); - const { height: tooltipHeight, width: tooltipWidth } = tooltip.node().getBoundingClientRect(); + const { height: tooltipHeight, width: tooltipWidth } = tooltip + .node() + .getBoundingClientRect(); tooltip - .style('left', `${Math.min(d3.event.offsetX + 10, width - tooltipWidth)}px`) - .style('top', `${Math.min(d3.event.offsetY + 10, height - tooltipHeight)}px`) + .style( + 'left', + `${Math.min(d3.event.offsetX + 10, width - tooltipWidth)}px`, + ) + .style( + 'top', + `${Math.min(d3.event.offsetY + 10, height - tooltipHeight)}px`, + ) .style('position', 'absolute') .style('opacity', 0.95); } @@ -144,7 +168,10 @@ function Sankey(element, props) { function dragmove(d) { d3.select(this).attr( 'transform', - `translate(${d.x},${(d.y = Math.max(0, Math.min(height - d.dy, d3.event.y)))})`, + `translate(${d.x},${(d.y = Math.max( + 0, + Math.min(height - d.dy, d3.event.y), + ))})`, ); sankey.relayout(); link.attr('d', path); diff --git a/plugins/legacy-plugin-chart-sankey/src/controlPanel.ts b/plugins/legacy-plugin-chart-sankey/src/controlPanel.ts index 7c7a2a5db9..6ee16465cf 100644 --- a/plugins/legacy-plugin-chart-sankey/src/controlPanel.ts +++ b/plugins/legacy-plugin-chart-sankey/src/controlPanel.ts @@ -53,7 +53,9 @@ const config: ControlPanelConfig = { config: { type: 'CheckboxControl', label: t('Sort by metric'), - description: t('Whether to sort results by the selected metric in descending order.'), + description: t( + 'Whether to sort results by the selected metric in descending order.', + ), }, }, ], diff --git a/plugins/legacy-plugin-chart-sankey/src/utils.ts b/plugins/legacy-plugin-chart-sankey/src/utils.ts index b84afe89eb..a68dd7bbfb 100644 --- a/plugins/legacy-plugin-chart-sankey/src/utils.ts +++ b/plugins/legacy-plugin-chart-sankey/src/utils.ts @@ -39,7 +39,12 @@ export const isOverlapping = (rect1: Rect, rect2: Rect): boolean => { const { x: x1, y: y1, width: width1, height: height1 } = rect1; const { x: x2, y: y2, width: width2, height: height2 } = rect2; - return !(x1 > x2 + width2 || x1 + width1 < x2 || y1 > y2 + height2 || y1 + height1 < y2); + return !( + x1 > x2 + width2 || + x1 + width1 < x2 || + y1 > y2 + height2 || + y1 + height1 < y2 + ); }; export const getRectangle = (element: SVGElement, offset = 0): Rect => { @@ -53,7 +58,9 @@ export const getRectangle = (element: SVGElement, offset = 0): Rect => { }; }; -export const getOverlappingElements = (elements: SVGElement[]): SVGElement[] => { +export const getOverlappingElements = ( + elements: SVGElement[], +): SVGElement[] => { const overlappingElements: SVGElement[] = []; elements.forEach((e1, index1) => { diff --git a/plugins/legacy-plugin-chart-sunburst/src/Sunburst.js b/plugins/legacy-plugin-chart-sunburst/src/Sunburst.js index 88dd7464e1..75bebdaa14 100644 --- a/plugins/legacy-plugin-chart-sunburst/src/Sunburst.js +++ b/plugins/legacy-plugin-chart-sunburst/src/Sunburst.js @@ -46,7 +46,9 @@ const propTypes = { }; function metricLabel(metric) { - return typeof metric === 'string' || metric instanceof String ? metric : metric.label; + return typeof metric === 'string' || metric instanceof String + ? metric + : metric.label; } // Given a node in a partition layout, return an array of all of its ancestor @@ -86,7 +88,9 @@ function buildHierarchy(rows) { let childNode; if (!isLeafNode) { - childNode = children.find(child => child.name === nodeName && child.level === level); + childNode = children.find( + child => child.name === nodeName && child.level === level, + ); if (!childNode) { childNode = { @@ -158,7 +162,15 @@ function getYOffset(width) { // Modified from http://bl.ocks.org/kerryrodden/7090426 function Sunburst(element, props) { const container = d3.select(element); - const { data, width, height, colorScheme, linearColorScheme, metrics, numberFormat } = props; + const { + data, + width, + height, + colorScheme, + linearColorScheme, + metrics, + numberFormat, + } = props; const responsiveClass = getResponsiveContainerClass(width); const isSmallWidth = responsiveClass === 's'; container.attr('class', `superset-legacy-chart-sunburst ${responsiveClass}`); @@ -168,7 +180,8 @@ function Sunburst(element, props) { const containerHeight = height; const breadcrumbHeight = containerHeight * 0.085; const visWidth = containerWidth - margin.left - margin.right; - const visHeight = containerHeight - margin.top - margin.bottom - breadcrumbHeight; + const visHeight = + containerHeight - margin.top - margin.bottom - breadcrumbHeight; const radius = Math.min(visWidth, visHeight) / 2; let colorByCategory = true; // color by category if primary/secondary metrics match @@ -196,7 +209,9 @@ function Sunburst(element, props) { .innerRadius(d => Math.sqrt(d.y)) .outerRadius(d => Math.sqrt(d.y + d.dy)); - const formatNum = getNumberFormatter(numberFormat || NumberFormats.SI_3_DIGIT); + const formatNum = getNumberFormatter( + numberFormat || NumberFormats.SI_3_DIGIT, + ); const formatPerc = getNumberFormatter(NumberFormats.PERCENT_3_POINT); container.select('svg').remove(); @@ -241,13 +256,17 @@ function Sunburst(element, props) { points.push('0,0'); points.push(`${breadcrumbDims.width},0`); points.push( - `${breadcrumbDims.width + breadcrumbDims.tipTailWidth},${breadcrumbDims.height / 2}`, + `${breadcrumbDims.width + breadcrumbDims.tipTailWidth},${ + breadcrumbDims.height / 2 + }`, ); points.push(`${breadcrumbDims.width},${breadcrumbDims.height}`); points.push(`0,${breadcrumbDims.height}`); if (i > 0) { // Leftmost breadcrumb; don't include 6th vertex. - points.push(`${breadcrumbDims.tipTailWidth},${breadcrumbDims.height / 2}`); + points.push( + `${breadcrumbDims.tipTailWidth},${breadcrumbDims.height / 2}`, + ); } } @@ -256,7 +275,9 @@ function Sunburst(element, props) { function updateBreadcrumbs(sequenceArray, percentageString) { const breadcrumbWidth = isSmallWidth ? width : breadcrumbDims.width; - const g = breadcrumbs.selectAll('g').data(sequenceArray, d => d.name + d.depth); + const g = breadcrumbs + .selectAll('g') + .data(sequenceArray, d => d.name + d.depth); // Add breadcrumb and label for entering nodes. const entering = g.enter().append('svg:g'); @@ -265,7 +286,9 @@ function Sunburst(element, props) { .append('svg:polygon') .attr('points', breadcrumbPoints) .style('fill', d => - colorByCategory ? categoricalColorScale(d.name) : linearColorScale(d.m2 / d.m1), + colorByCategory + ? categoricalColorScale(d.name) + : linearColorScale(d.m2 / d.m1), ); entering @@ -276,7 +299,9 @@ function Sunburst(element, props) { .style('fill', d => { // Make text white or black based on the lightness of the background const col = d3.hsl( - colorByCategory ? categoricalColorScale(d.name) : linearColorScale(d.m2 / d.m1), + colorByCategory + ? categoricalColorScale(d.name) + : linearColorScale(d.m2 / d.m1), ); return col.l < 0.5 ? 'white' : 'black'; @@ -288,9 +313,13 @@ function Sunburst(element, props) { // Set position for entering and updating nodes. g.attr('transform', (d, i) => { if (isSmallWidth) { - return `translate(0, ${i * (breadcrumbDims.height + breadcrumbDims.spacing)})`; + return `translate(0, ${ + i * (breadcrumbDims.height + breadcrumbDims.spacing) + })`; } - return `translate(${i * (breadcrumbDims.width + breadcrumbDims.spacing)}, 0)`; + return `translate(${ + i * (breadcrumbDims.width + breadcrumbDims.spacing) + }, 0)`; }); // Remove exiting nodes. @@ -304,7 +333,10 @@ function Sunburst(element, props) { return (breadcrumbWidth + breadcrumbDims.tipTailWidth) / 2; } - return (sequenceArray.length + 0.5) * (breadcrumbDims.width + breadcrumbDims.spacing); + return ( + (sequenceArray.length + 0.5) * + (breadcrumbDims.width + breadcrumbDims.spacing) + ); }) .attr('y', () => { if (isSmallWidth) { @@ -326,10 +358,14 @@ function Sunburst(element, props) { const parentOfD = sequenceArray[sequenceArray.length - 2] || null; const absolutePercentage = (d.m1 / totalSize).toPrecision(3); - const conditionalPercentage = parentOfD ? (d.m1 / parentOfD.m1).toPrecision(3) : null; + const conditionalPercentage = parentOfD + ? (d.m1 / parentOfD.m1).toPrecision(3) + : null; const absolutePercString = formatPerc(absolutePercentage); - const conditionalPercString = parentOfD ? formatPerc(conditionalPercentage) : ''; + const conditionalPercString = parentOfD + ? formatPerc(conditionalPercentage) + : ''; // 3 levels of text if inner-most level, 4 otherwise const yOffsets = getYOffset(width); @@ -375,11 +411,17 @@ function Sunburst(element, props) { .text( metricsMatch ? '' - : `${metricLabel(metrics[1])}/${metricLabel(metrics[0])}: ${formatPerc(d.m2 / d.m1)}`, + : `${metricLabel(metrics[1])}/${metricLabel( + metrics[0], + )}: ${formatPerc(d.m2 / d.m1)}`, ); // Reset and fade all the segments. - arcs.selectAll('path').style('stroke-width', null).style('stroke', null).style('opacity', 0.3); + arcs + .selectAll('path') + .style('stroke-width', null) + .style('stroke', null) + .style('opacity', 0.3); // Then highlight only those that are an ancestor of the current segment. arcs @@ -427,7 +469,9 @@ function Sunburst(element, props) { `${margin.left + visWidth / 2},` + `${ margin.top + - (isSmallWidth ? breadcrumbHeight * maxBreadcrumbs : breadcrumbHeight) + + (isSmallWidth + ? breadcrumbHeight * maxBreadcrumbs + : breadcrumbHeight) + visHeight / 2 }` + ')', @@ -462,7 +506,9 @@ function Sunburst(element, props) { .attr('d', arc) .attr('fill-rule', 'evenodd') .style('fill', d => - colorByCategory ? categoricalColorScale(d.name) : linearColorScale(d.m2 / d.m1), + colorByCategory + ? categoricalColorScale(d.name) + : linearColorScale(d.m2 / d.m1), ) .style('opacity', 1) .on('mouseenter', mouseenter); diff --git a/plugins/legacy-plugin-chart-sunburst/src/controlPanel.ts b/plugins/legacy-plugin-chart-sunburst/src/controlPanel.ts index cb1a26c27a..065964687b 100644 --- a/plugins/legacy-plugin-chart-sunburst/src/controlPanel.ts +++ b/plugins/legacy-plugin-chart-sunburst/src/controlPanel.ts @@ -37,7 +37,9 @@ const config: ControlPanelConfig = { config: { type: 'CheckboxControl', label: t('Sort by metric'), - description: t('Whether to sort results by the selected metric in descending order.'), + description: t( + 'Whether to sort results by the selected metric in descending order.', + ), }, }, ], @@ -52,7 +54,9 @@ const config: ControlPanelConfig = { controlOverrides: { metric: { label: t('Primary Metric'), - description: t('The primary metric is used to define the arc segment sizes'), + description: t( + 'The primary metric is used to define the arc segment sizes', + ), }, secondary_metric: { label: t('Secondary Metric'), @@ -64,10 +68,14 @@ const config: ControlPanelConfig = { ), }, color_scheme: { - description: t('When only a primary metric is provided, a categorical color scale is used.'), + description: t( + 'When only a primary metric is provided, a categorical color scale is used.', + ), }, linear_color_scheme: { - description: t('When a secondary metric is provided, a linear color scale is used.'), + description: t( + 'When a secondary metric is provided, a linear color scale is used.', + ), }, groupby: { label: t('Hierarchy'), diff --git a/plugins/legacy-plugin-chart-sunburst/src/transformProps.js b/plugins/legacy-plugin-chart-sunburst/src/transformProps.js index 2c42e4ae2d..9952fc4992 100644 --- a/plugins/legacy-plugin-chart-sunburst/src/transformProps.js +++ b/plugins/legacy-plugin-chart-sunburst/src/transformProps.js @@ -31,7 +31,8 @@ export default function transformProps(chartProps) { if (datasource && datasource.metrics) { const metricWithFormat = datasource.metrics.find( - ({ metric_name: metricName, d3format }) => metricName === formData.metric && d3format, + ({ metric_name: metricName, d3format }) => + metricName === formData.metric && d3format, ); if (metricWithFormat) { Object.assign(returnProps, { numberFormat: metricWithFormat.d3format }); diff --git a/plugins/legacy-plugin-chart-sunburst/src/utils/wrapSvgText.js b/plugins/legacy-plugin-chart-sunburst/src/utils/wrapSvgText.js index 4a62e9430f..12cdead8d3 100644 --- a/plugins/legacy-plugin-chart-sunburst/src/utils/wrapSvgText.js +++ b/plugins/legacy-plugin-chart-sunburst/src/utils/wrapSvgText.js @@ -37,7 +37,12 @@ export default function wrapSvgText(text, width, adjustedY) { const x = d3Text.attr('x'); const y = d3Text.attr('y'); const dy = parseFloat(d3Text.attr('dy')); - let tspan = d3Text.text(null).append('tspan').attr('x', x).attr('y', y).attr('dy', `${dy}em`); + let tspan = d3Text + .text(null) + .append('tspan') + .attr('x', x) + .attr('y', y) + .attr('dy', `${dy}em`); let didWrap = false; words.forEach(word => { diff --git a/plugins/legacy-plugin-chart-time-table/src/SparklineCell.tsx b/plugins/legacy-plugin-chart-time-table/src/SparklineCell.tsx index 769201c749..8d6c208358 100644 --- a/plugins/legacy-plugin-chart-time-table/src/SparklineCell.tsx +++ b/plugins/legacy-plugin-chart-time-table/src/SparklineCell.tsx @@ -79,9 +79,13 @@ function getSparklineTextWidth(text: string) { ); } -function isValidBoundValue(value?: number) { - // @ts-ignore - return value !== null && value !== undefined && value !== '' && !Number.isNaN(value); +function isValidBoundValue(value?: number | string) { + return ( + value !== null && + value !== undefined && + value !== '' && + !Number.isNaN(value) + ); } class SparklineCell extends React.Component { @@ -133,12 +137,19 @@ class SparklineCell extends React.Component { let labelLength = 0; if (showYAxis) { const [minBound, maxBound] = yAxisBounds; - min = hasMinBound ? minBound : data.reduce((acc, current) => Math.min(acc, current), data[0]); - max = hasMaxBound ? maxBound : data.reduce((acc, current) => Math.max(acc, current), data[0]); + min = hasMinBound + ? minBound + : data.reduce((acc, current) => Math.min(acc, current), data[0]); + max = hasMaxBound + ? maxBound + : data.reduce((acc, current) => Math.max(acc, current), data[0]); minLabel = formatNumber(numberFormat, min); maxLabel = formatNumber(numberFormat, max); - labelLength = Math.max(getSparklineTextWidth(minLabel), getSparklineTextWidth(maxLabel)); + labelLength = Math.max( + getSparklineTextWidth(minLabel), + getSparklineTextWidth(maxLabel), + ); } const margin = { @@ -147,7 +158,11 @@ class SparklineCell extends React.Component { }; return ( - + {({ onMouseLeave, onMouseMove, tooltipData }: TooltipProps) => ( { /> )} {tooltipData && ( - + )} )} diff --git a/plugins/legacy-plugin-chart-time-table/src/TimeTable.tsx b/plugins/legacy-plugin-chart-time-table/src/TimeTable.tsx index e118bc8567..20076e1268 100644 --- a/plugins/legacy-plugin-chart-time-table/src/TimeTable.tsx +++ b/plugins/legacy-plugin-chart-time-table/src/TimeTable.tsx @@ -21,7 +21,10 @@ import Mustache from 'mustache'; import { scaleLinear } from 'd3-scale'; import { Table, Thead, Th, Tr, Td } from 'reactable-arc'; import { formatNumber, formatTime, styled } from '@superset-ui/core'; -import { InfoTooltipWithTrigger, MetricOption } from '@superset-ui/chart-controls'; +import { + InfoTooltipWithTrigger, + MetricOption, +} from '@superset-ui/chart-controls'; import moment from 'moment'; import FormattedNumber from './FormattedNumber'; @@ -117,11 +120,22 @@ class TimeTable extends React.PureComponent { return column.label; } - return ; + return ( + + ); } // eslint-disable-next-line class-methods-use-this - renderSparklineCell(valueField: string, column: ColumnConfigProps, entries: Entry[]) { + renderSparklineCell( + valueField: string, + column: ColumnConfigProps, + entries: Entry[], + ) { let sparkData: number[]; if (column.timeRatio) { // Period ratio sparkline @@ -140,7 +154,11 @@ class TimeTable extends React.PureComponent { } return ( - + { renderTooltip={({ index }: { index: number }) => (
{formatNumber(column.d3format, sparkData[index])} -
{formatTime(column.dateFormat, moment.utc(entries[index].time).toDate())}
+
+ {formatTime( + column.dateFormat, + moment.utc(entries[index].time).toDate(), + )} +
)} /> @@ -161,7 +184,11 @@ class TimeTable extends React.PureComponent { } // eslint-disable-next-line class-methods-use-this - renderValueCell(valueField: string, column: ColumnConfigProps, reversedEntries: Entry[]) { + renderValueCell( + valueField: string, + column: ColumnConfigProps, + reversedEntries: Entry[], + ) { const recent = reversedEntries[0][valueField]; let v = 0; let errorMsg; @@ -193,7 +220,9 @@ class TimeTable extends React.PureComponent { // Average over the last {timeLag} v = reversedEntries - .map((k: Entry, i: number) => (i < column.timeLag ? k[valueField] : 0)) + .map((k: Entry, i: number) => + i < column.timeLag ? k[valueField] : 0, + ) .reduce((a: number, b: number) => a + b) / column.timeLag; } @@ -242,7 +271,8 @@ class TimeTable extends React.PureComponent { } render() { - const { className, height, data, columnConfigs, rowType, rows } = this.props; + const { className, height, data, columnConfigs, rowType, rows } = + this.props; const entries = Object.keys(data) .sort() // @ts-ignore @@ -270,7 +300,11 @@ class TimeTable extends React.PureComponent { Metric {columnConfigs.map((c, i) => ( - + {c?.label}{' '} {c?.tooltip && ( (typeof column === 'object' ? column : { label: column })); + rows = columns.map(column => + typeof column === 'object' ? column : { label: column }, + ); } else { const metricMap = datasource.metrics.reduce((acc, current) => { const map = acc; @@ -61,7 +63,9 @@ export default function transformProps(chartProps: TableChartProps) { } return map; }, {} as Record); - rows = metrics.map(metric => (typeof metric === 'object' ? metric : metricMap[metric])); + rows = metrics.map(metric => + typeof metric === 'object' ? metric : metricMap[metric], + ); } // TODO: Better parse this from controls instead of mutative value here. diff --git a/plugins/legacy-plugin-chart-treemap/src/Treemap.js b/plugins/legacy-plugin-chart-treemap/src/Treemap.js index 6d12838e76..a155a050b3 100644 --- a/plugins/legacy-plugin-chart-treemap/src/Treemap.js +++ b/plugins/legacy-plugin-chart-treemap/src/Treemap.js @@ -19,9 +19,16 @@ /* eslint-disable no-param-reassign, func-names */ /* eslint-disable react/sort-prop-types */ import { select as d3Select, selectAll as d3SelectAll } from 'd3-selection'; -import { treemap as d3Treemap, hierarchy as d3Hierarchy, treemapSquarify } from 'd3-hierarchy'; +import { + treemap as d3Treemap, + hierarchy as d3Hierarchy, + treemapSquarify, +} from 'd3-hierarchy'; import PropTypes from 'prop-types'; -import { getNumberFormatter, CategoricalColorNamespace } from '@superset-ui/core'; +import { + getNumberFormatter, + CategoricalColorNamespace, +} from '@superset-ui/core'; import './Treemap.css'; // Declare PropTypes for recursive data structures @@ -37,7 +44,10 @@ const leafType = PropTypes.shape({ const parentShape = { name: PropTypes.string, children: PropTypes.arrayOf( - PropTypes.oneOfType([PropTypes.shape(lazyFunction(() => parentShape)), leafType]), + PropTypes.oneOfType([ + PropTypes.shape(lazyFunction(() => parentShape)), + leafType, + ]), ), }; @@ -70,7 +80,14 @@ function hovered(hover) { /* Modified from https://bl.ocks.org/mbostock/911ad09bdead40ec0061 */ function Treemap(element, props) { - const { data: rawData, width, height, numberFormat, colorScheme, treemapRatio } = props; + const { + data: rawData, + width, + height, + numberFormat, + colorScheme, + treemapRatio, + } = props; const div = d3Select(element); div.classed('superset-legacy-chart-treemap', true); @@ -129,7 +146,9 @@ function Treemap(element, props) { .append('use') .attr('xlink:href', d => `#rect-${d.data.name}`); - const label = cell.append('text').attr('clip-path', d => `url(#clip-${d.data.name})`); + const label = cell + .append('text') + .attr('clip-path', d => `url(#clip-${d.data.name})`); label .filter(d => d.children) diff --git a/plugins/legacy-plugin-chart-treemap/src/index.js b/plugins/legacy-plugin-chart-treemap/src/index.js index a9d58c6e73..0b517d6a2d 100644 --- a/plugins/legacy-plugin-chart-treemap/src/index.js +++ b/plugins/legacy-plugin-chart-treemap/src/index.js @@ -31,9 +31,20 @@ const metadata = new ChartMetadata({ description: t( 'Shows the composition of a dataset by segmenting a given rectangle as smaller rectangles with areas proportional to their value or contribution to the whole. Those rectangles may also, in turn, be further segmented hierarchically.', ), - exampleGallery: [{ url: example1 }, { url: example2 }, { url: example3 }, { url: example4 }], + exampleGallery: [ + { url: example1 }, + { url: example2 }, + { url: example3 }, + { url: example4 }, + ], name: t('Treemap'), - tags: [t('Categorical'), t('Legacy'), t('Multi-Levels'), t('Percentages'), t('Proportional')], + tags: [ + t('Categorical'), + t('Legacy'), + t('Multi-Levels'), + t('Percentages'), + t('Proportional'), + ], thumbnail, useLegacyApi: true, }); diff --git a/plugins/legacy-plugin-chart-treemap/src/transformProps.js b/plugins/legacy-plugin-chart-treemap/src/transformProps.js index 9c6c915830..adba34c09b 100644 --- a/plugins/legacy-plugin-chart-treemap/src/transformProps.js +++ b/plugins/legacy-plugin-chart-treemap/src/transformProps.js @@ -23,7 +23,10 @@ export default function transformProps(chartProps) { if (!numberFormat && chartProps.datasource && chartProps.datasource.metrics) { chartProps.datasource.metrics.forEach(metric => { - if (metric.metric_name === chartProps.formData.metrics[0] && metric.d3format) { + if ( + metric.metric_name === chartProps.formData.metrics[0] && + metric.d3format + ) { numberFormat = metric.d3format; } }); diff --git a/plugins/legacy-plugin-chart-world-map/src/WorldMap.js b/plugins/legacy-plugin-chart-world-map/src/WorldMap.js index 8db8950404..c7253e10d0 100644 --- a/plugins/legacy-plugin-chart-world-map/src/WorldMap.js +++ b/plugins/legacy-plugin-chart-world-map/src/WorldMap.js @@ -20,7 +20,10 @@ import d3 from 'd3'; import PropTypes from 'prop-types'; import { extent as d3Extent } from 'd3-array'; -import { getNumberFormatter, getSequentialSchemeRegistry } from '@superset-ui/core'; +import { + getNumberFormatter, + getSequentialSchemeRegistry, +} from '@superset-ui/core'; import Datamap from 'datamaps/dist/datamaps.world.min'; const propTypes = { @@ -44,7 +47,15 @@ const propTypes = { const formatter = getNumberFormatter(); function WorldMap(element, props) { - const { data, width, height, maxBubbleSize, showBubbles, linearColorScheme, color } = props; + const { + data, + width, + height, + maxBubbleSize, + showBubbles, + linearColorScheme, + color, + } = props; const div = d3.select(element); div.classed('superset-legacy-chart-world-map', true); div.selectAll('*').remove(); @@ -90,7 +101,9 @@ function WorldMap(element, props) { highlightFillColor: color, highlightBorderWidth: 1, popupTemplate: (geo, d) => - `
${d.name}
${formatter(d.m1)}
`, + `
${d.name}
${formatter( + d.m1, + )}
`, }, bubblesConfig: { borderWidth: 1, @@ -99,7 +112,9 @@ function WorldMap(element, props) { popupOnHover: true, radius: null, popupTemplate: (geo, d) => - `
${d.name}
${formatter(d.m2)}
`, + `
${d.name}
${formatter( + d.m2, + )}
`, fillOpacity: 0.5, animate: true, highlightOnHover: true, @@ -117,7 +132,10 @@ function WorldMap(element, props) { if (showBubbles) { map.bubbles(processedData); - div.selectAll('circle.datamaps-bubble').style('fill', color).style('stroke', color); + div + .selectAll('circle.datamaps-bubble') + .style('fill', color) + .style('stroke', color); } } diff --git a/plugins/legacy-plugin-chart-world-map/src/controlPanel.ts b/plugins/legacy-plugin-chart-world-map/src/controlPanel.ts index a28204e2db..ec8aafc7b8 100644 --- a/plugins/legacy-plugin-chart-world-map/src/controlPanel.ts +++ b/plugins/legacy-plugin-chart-world-map/src/controlPanel.ts @@ -17,7 +17,11 @@ * under the License. */ import { t } from '@superset-ui/core'; -import { ControlPanelConfig, formatSelectOptions, sections } from '@superset-ui/chart-controls'; +import { + ControlPanelConfig, + formatSelectOptions, + sections, +} from '@superset-ui/chart-controls'; const config: ControlPanelConfig = { controlPanelSections: [ @@ -56,7 +60,9 @@ const config: ControlPanelConfig = { config: { type: 'CheckboxControl', label: t('Sort by metric'), - description: t('Whether to sort results by the selected metric in descending order.'), + description: t( + 'Whether to sort results by the selected metric in descending order.', + ), }, }, ], @@ -87,7 +93,15 @@ const config: ControlPanelConfig = { freeForm: true, label: t('Max Bubble Size'), default: '25', - choices: formatSelectOptions(['5', '10', '15', '25', '50', '75', '100']), + choices: formatSelectOptions([ + '5', + '10', + '15', + '25', + '50', + '75', + '100', + ]), }, }, ], diff --git a/plugins/legacy-plugin-chart-world-map/src/index.js b/plugins/legacy-plugin-chart-world-map/src/index.js index 3b59553b44..d97adfadf3 100644 --- a/plugins/legacy-plugin-chart-world-map/src/index.js +++ b/plugins/legacy-plugin-chart-world-map/src/index.js @@ -26,7 +26,9 @@ import controlPanel from './controlPanel'; const metadata = new ChartMetadata({ category: t('Map'), credits: ['http://datamaps.github.io/'], - description: t('A map of the world, that can indicate values in different countries.'), + description: t( + 'A map of the world, that can indicate values in different countries.', + ), exampleGallery: [{ url: example1 }, { url: example2 }], name: t('World Map'), tags: [ diff --git a/plugins/legacy-plugin-chart-world-map/src/transformProps.js b/plugins/legacy-plugin-chart-world-map/src/transformProps.js index ed10ba292c..464dd53afa 100644 --- a/plugins/legacy-plugin-chart-world-map/src/transformProps.js +++ b/plugins/legacy-plugin-chart-world-map/src/transformProps.js @@ -20,7 +20,8 @@ import { rgb } from 'd3-color'; export default function transformProps(chartProps) { const { width, height, formData, queriesData } = chartProps; - const { maxBubbleSize, showBubbles, linearColorScheme, colorPicker } = formData; + const { maxBubbleSize, showBubbles, linearColorScheme, colorPicker } = + formData; const { r, g, b } = colorPicker; return { diff --git a/plugins/legacy-preset-chart-big-number/README.md b/plugins/legacy-preset-chart-big-number/README.md index 7c888576a7..cecb5d5451 100644 --- a/plugins/legacy-preset-chart-big-number/README.md +++ b/plugins/legacy-preset-chart-big-number/README.md @@ -26,7 +26,9 @@ import { } from '@superset-ui/legacy-preset-chart-big-number'; new BigNumberChartPlugin().configure({ key: 'big-number' }).register(); -new BigNumberTotalChartPlugin().configure({ key: 'big-number-total' }).register(); +new BigNumberTotalChartPlugin() + .configure({ key: 'big-number-total' }) + .register(); ``` Then use it via `SuperChart`. See diff --git a/plugins/legacy-preset-chart-big-number/src/BigNumber/BigNumber.tsx b/plugins/legacy-preset-chart-big-number/src/BigNumber/BigNumber.tsx index 266026b73d..6f559f3e71 100644 --- a/plugins/legacy-preset-chart-big-number/src/BigNumber/BigNumber.tsx +++ b/plugins/legacy-preset-chart-big-number/src/BigNumber/BigNumber.tsx @@ -28,7 +28,12 @@ import { BRAND_COLOR, styled, } from '@superset-ui/core'; -import { XYChart, AreaSeries, CrossHair, LinearGradient } from '@data-ui/xy-chart'; +import { + XYChart, + AreaSeries, + CrossHair, + LinearGradient, +} from '@data-ui/xy-chart'; const defaultNumberFormatter = getNumberFormatter(); @@ -57,7 +62,11 @@ export function renderTooltipFactory( formatDate = smartDateVerboseFormatter, formatValue = defaultNumberFormatter, ) { - return function renderTooltip({ datum: { x, y } }: { datum: TimeSeriesDatum }) { + return function renderTooltip({ + datum: { x, y }, + }: { + datum: TimeSeriesDatum; + }) { // even though `formatDate` supports timestamp as numbers, we need // `new Date` to pass type check return ( @@ -135,7 +144,10 @@ class BigNumberVis extends React.PureComponent { {t('Not up to date')} @@ -207,7 +219,9 @@ class BigNumberVis extends React.PureComponent { const NO_DATA_OR_HASNT_LANDED = t( 'No data after filtering or data is NULL for the latest time record', ); - const NO_DATA = t('Try applying different filters or ensuring your datasource has data'); + const NO_DATA = t( + 'Try applying different filters or ensuring your datasource has data', + ); let text = subheader; if (bigNumber === null) { text = bigNumberFallback ? NO_DATA : NO_DATA_OR_HASNT_LANDED; @@ -284,7 +298,10 @@ class BigNumberVis extends React.PureComponent { snapTooltipToDataX ariaLabel={`Big number visualization ${subheader}`} // headerFormatter always NumberFormatter in BigNumber with treadline - renderTooltip={renderTooltipFactory(formatTime, headerFormatter as NumberFormatter)} + renderTooltip={renderTooltipFactory( + formatTime, + headerFormatter as NumberFormatter, + )} xScale={xScale} yScale={{ type: 'linear', @@ -296,7 +313,11 @@ class BigNumberVis extends React.PureComponent { eventTrigger="container" > - + { } render() { - const { showTrendLine, height, kickerFontSize, headerFontSize, subheaderFontSize } = this.props; + const { + showTrendLine, + height, + kickerFontSize, + headerFontSize, + subheaderFontSize, + } = this.props; const className = this.getClassName(); if (showTrendLine) { @@ -321,10 +348,16 @@ class BigNumberVis extends React.PureComponent {
{this.renderFallbackWarning()} - {this.renderKicker(Math.ceil(kickerFontSize * (1 - PROPORTION.TRENDLINE) * height))} - {this.renderHeader(Math.ceil(headerFontSize * (1 - PROPORTION.TRENDLINE) * height))} + {this.renderKicker( + Math.ceil(kickerFontSize * (1 - PROPORTION.TRENDLINE) * height), + )} + {this.renderHeader( + Math.ceil(headerFontSize * (1 - PROPORTION.TRENDLINE) * height), + )} {this.renderSubheader( - Math.ceil(subheaderFontSize * (1 - PROPORTION.TRENDLINE) * height), + Math.ceil( + subheaderFontSize * (1 - PROPORTION.TRENDLINE) * height, + ), )}
{this.renderTrendline(chartHeight)} diff --git a/plugins/legacy-preset-chart-big-number/src/BigNumber/controlPanel.tsx b/plugins/legacy-preset-chart-big-number/src/BigNumber/controlPanel.tsx index f3e4ee98d5..045f7fc7bd 100644 --- a/plugins/legacy-preset-chart-big-number/src/BigNumber/controlPanel.tsx +++ b/plugins/legacy-preset-chart-big-number/src/BigNumber/controlPanel.tsx @@ -47,7 +47,9 @@ const config: ControlPanelConfig = { type: 'TextControl', label: t('Comparison Period Lag'), isInt: true, - description: t('Based on granularity, number of time periods to compare against'), + description: t( + 'Based on granularity, number of time periods to compare against', + ), }, }, ], @@ -136,7 +138,11 @@ const config: ControlPanelConfig = { { label: t('Chart Options'), expanded: true, - controlSetRows: [['color_picker', null], [headerFontSize], [subheaderFontSize]], + controlSetRows: [ + ['color_picker', null], + [headerFontSize], + [subheaderFontSize], + ], }, { label: t('Advanced Analytics'), @@ -151,7 +157,13 @@ const config: ControlPanelConfig = { type: 'SelectControl', label: t('Rolling Function'), default: 'None', - choices: formatSelectOptions(['None', 'mean', 'sum', 'std', 'cumsum']), + choices: formatSelectOptions([ + 'None', + 'mean', + 'sum', + 'std', + 'cumsum', + ]), description: t( 'Defines a rolling window function to apply, works along ' + 'with the [Periods] text box', diff --git a/plugins/legacy-preset-chart-big-number/src/BigNumber/index.ts b/plugins/legacy-preset-chart-big-number/src/BigNumber/index.ts index cc53ee9a4c..2cfee291fc 100644 --- a/plugins/legacy-preset-chart-big-number/src/BigNumber/index.ts +++ b/plugins/legacy-preset-chart-big-number/src/BigNumber/index.ts @@ -18,7 +18,10 @@ */ import { t, ChartMetadata, ChartPlugin } from '@superset-ui/core'; import controlPanel from './controlPanel'; -import transformProps, { BigNumberChartProps, BigNumberFormData } from './transformProps'; +import transformProps, { + BigNumberChartProps, + BigNumberFormData, +} from './transformProps'; import example from './images/Big_Number_Trendline.jpg'; import thumbnail from './images/thumbnail.png'; diff --git a/plugins/legacy-preset-chart-big-number/src/BigNumber/transformProps.ts b/plugins/legacy-preset-chart-big-number/src/BigNumber/transformProps.ts index 4d9cc4a930..6e4674dca1 100644 --- a/plugins/legacy-preset-chart-big-number/src/BigNumber/transformProps.ts +++ b/plugins/legacy-preset-chart-big-number/src/BigNumber/transformProps.ts @@ -30,7 +30,9 @@ import { } from '@superset-ui/core'; const TIME_COLUMN = '__timestamp'; -const formatPercentChange = getNumberFormatter(NumberFormats.PERCENT_SIGNED_1_POINT); +const formatPercentChange = getNumberFormatter( + NumberFormats.PERCENT_SIGNED_1_POINT, +); // we trust both the x (time) and y (big number) to be numeric export interface BigNumberDatum { @@ -79,7 +81,11 @@ export default function transformProps(chartProps: BigNumberChartProps) { const granularity = extractTimegrain(rawFormData as QueryFormData); let { yAxisFormat } = formData; const { headerFormatSelector, headerTimestampFormat } = formData; - const { data = [], from_dttm: fromDatetime, to_dttm: toDatetime } = queriesData[0]; + const { + data = [], + from_dttm: fromDatetime, + to_dttm: toDatetime, + } = queriesData[0]; const metricName = typeof metric === 'string' ? metric : metric.label; const compareLag = Number(compareLag_) || 0; const supportTrendLine = vizType === 'big_number'; @@ -120,7 +126,9 @@ export default function transformProps(chartProps: BigNumberChartProps) { // compare values must both be non-nulls if (bigNumber !== null && compareValue !== null && compareValue !== 0) { percentChange = (bigNumber - compareValue) / Math.abs(compareValue); - formattedSubheader = `${formatPercentChange(percentChange)} ${compareSuffix}`; + formattedSubheader = `${formatPercentChange( + percentChange, + )} ${compareSuffix}`; } } } diff --git a/plugins/legacy-preset-chart-big-number/src/BigNumberTotal/controlPanel.ts b/plugins/legacy-preset-chart-big-number/src/BigNumberTotal/controlPanel.ts index 835bc47732..f6ab2f3c6e 100644 --- a/plugins/legacy-preset-chart-big-number/src/BigNumberTotal/controlPanel.ts +++ b/plugins/legacy-preset-chart-big-number/src/BigNumberTotal/controlPanel.ts @@ -45,7 +45,9 @@ export default { type: 'TextControl', label: t('Subheader'), renderTrigger: true, - description: t('Description text that shows up below your Big Number'), + description: t( + 'Description text that shows up below your Big Number', + ), }, }, ], diff --git a/plugins/legacy-preset-chart-big-number/test/transformProps.test.ts b/plugins/legacy-preset-chart-big-number/test/transformProps.test.ts index 0bec086974..d19139b0fd 100644 --- a/plugins/legacy-preset-chart-big-number/test/transformProps.test.ts +++ b/plugins/legacy-preset-chart-big-number/test/transformProps.test.ts @@ -117,7 +117,9 @@ describe('BigNumber', () => { expect(transformed.bigNumberFallback).not.toBeNull(); // should successfully formatTime by ganularity - expect(transformed.formatTime(new Date('2020-01-01'))).toStrictEqual('2020-01-01 00:00:00'); + expect(transformed.formatTime(new Date('2020-01-01'))).toStrictEqual( + '2020-01-01 00:00:00', + ); }); it('should respect datasource d3 format', () => { @@ -135,7 +137,9 @@ describe('BigNumber', () => { }, }; const transformed = transformProps(propsWithDatasource); - expect(transformed.headerFormatter(transformed.bigNumber)).toStrictEqual('1.23'); + expect(transformed.headerFormatter(transformed.bigNumber)).toStrictEqual( + '1.23', + ); }); }); }); diff --git a/plugins/legacy-preset-chart-nvd3/README.md b/plugins/legacy-preset-chart-nvd3/README.md index fbe3ce2540..e62ef17810 100644 --- a/plugins/legacy-preset-chart-nvd3/README.md +++ b/plugins/legacy-preset-chart-nvd3/README.md @@ -19,7 +19,10 @@ or register charts one by one. Configure `key`, which can be any `string`, and r This `key` will be used to lookup this chart throughout the app. ```js -import { AreaChartPlugin, LineChartPlugin } from '@superset-ui/legacy-preset-chart-nvd3'; +import { + AreaChartPlugin, + LineChartPlugin, +} from '@superset-ui/legacy-preset-chart-nvd3'; new AreaChartPlugin().configure({ key: 'area' }).register(); new LineChartPlugin().configure({ key: 'line' }).register(); diff --git a/plugins/legacy-preset-chart-nvd3/src/Bubble/controlPanel.ts b/plugins/legacy-preset-chart-nvd3/src/Bubble/controlPanel.ts index 5dc3e97b30..33a4ea6bf0 100644 --- a/plugins/legacy-preset-chart-nvd3/src/Bubble/controlPanel.ts +++ b/plugins/legacy-preset-chart-nvd3/src/Bubble/controlPanel.ts @@ -58,7 +58,15 @@ const config: ControlPanelConfig = { freeForm: true, label: t('Max Bubble Size'), default: '25', - choices: formatSelectOptions(['5', '10', '15', '25', '50', '75', '100']), + choices: formatSelectOptions([ + '5', + '10', + '15', + '25', + '50', + '75', + '100', + ]), }, }, ], diff --git a/plugins/legacy-preset-chart-nvd3/src/DistBar/controlPanel.ts b/plugins/legacy-preset-chart-nvd3/src/DistBar/controlPanel.ts index 923a2bfc05..d0f83ddd91 100644 --- a/plugins/legacy-preset-chart-nvd3/src/DistBar/controlPanel.ts +++ b/plugins/legacy-preset-chart-nvd3/src/DistBar/controlPanel.ts @@ -104,7 +104,12 @@ const config: ControlPanelConfig = { { label: t('X Axis'), expanded: true, - controlSetRows: [[xAxisLabel], [bottomMargin], [xTicksLayout], [reduceXTicks]], + controlSetRows: [ + [xAxisLabel], + [bottomMargin], + [xTicksLayout], + [reduceXTicks], + ], }, ], controlOverrides: { @@ -112,9 +117,12 @@ const config: ControlPanelConfig = { label: t('Series'), validators: [validateNonEmpty], mapStateToProps: (state, controlState) => { - const groupbyProps = sharedControls.groupby.mapStateToProps?.(state, controlState) || {}; + const groupbyProps = + sharedControls.groupby.mapStateToProps?.(state, controlState) || {}; groupbyProps.canDropValue = (column: ColumnMeta) => - !ensureIsArray(state.controls?.columns?.value).includes(column.column_name); + !ensureIsArray(state.controls?.columns?.value).includes( + column.column_name, + ); return groupbyProps; }, rerender: ['columns'], @@ -123,9 +131,12 @@ const config: ControlPanelConfig = { label: t('Breakdowns'), description: t('Defines how each series is broken down'), mapStateToProps: (state, controlState) => { - const columnsProps = sharedControls.columns.mapStateToProps?.(state, controlState) || {}; + const columnsProps = + sharedControls.columns.mapStateToProps?.(state, controlState) || {}; columnsProps.canDropValue = (column: ColumnMeta) => - !ensureIsArray(state.controls?.groupby?.value).includes(column.column_name); + !ensureIsArray(state.controls?.groupby?.value).includes( + column.column_name, + ); return columnsProps; }, rerender: ['groupby'], diff --git a/plugins/legacy-preset-chart-nvd3/src/DualLine/controlPanel.ts b/plugins/legacy-preset-chart-nvd3/src/DualLine/controlPanel.ts index 1c01cb4758..94137d1aef 100644 --- a/plugins/legacy-preset-chart-nvd3/src/DualLine/controlPanel.ts +++ b/plugins/legacy-preset-chart-nvd3/src/DualLine/controlPanel.ts @@ -39,12 +39,22 @@ const config: ControlPanelConfig = { { label: t('Y Axis 1'), expanded: true, - controlSetRows: [['metric'], ['y_axis_format'], [yAxisShowMinmax], [yAxisBounds]], + controlSetRows: [ + ['metric'], + ['y_axis_format'], + [yAxisShowMinmax], + [yAxisBounds], + ], }, { label: t('Y Axis 2'), expanded: true, - controlSetRows: [['metric_2'], [yAxis2Format], [yAxis2ShowMinmax], [yAxis2Bounds]], + controlSetRows: [ + ['metric_2'], + [yAxis2Format], + [yAxis2ShowMinmax], + [yAxis2Bounds], + ], }, { label: t('Query'), diff --git a/plugins/legacy-preset-chart-nvd3/src/LineMulti/controlPanel.ts b/plugins/legacy-preset-chart-nvd3/src/LineMulti/controlPanel.ts index 488b020198..b3a88c08cb 100644 --- a/plugins/legacy-preset-chart-nvd3/src/LineMulti/controlPanel.ts +++ b/plugins/legacy-preset-chart-nvd3/src/LineMulti/controlPanel.ts @@ -98,7 +98,8 @@ const config: ControlPanelConfig = { validators: [validateNonEmpty], default: [], description: t('Choose one or more charts for left axis'), - dataEndpoint: '/sliceasync/api/read?_flt_0_viz_type=line&_flt_7_viz_type=line_multi', + dataEndpoint: + '/sliceasync/api/read?_flt_0_viz_type=line&_flt_7_viz_type=line_multi', placeholder: t('Select charts'), onAsyncErrorMessage: t('Error while fetching charts'), mutator: (data?: Data) => { @@ -132,7 +133,8 @@ const config: ControlPanelConfig = { validators: [], default: [], description: t('Choose one or more charts for right axis'), - dataEndpoint: '/sliceasync/api/read?_flt_0_viz_type=line&_flt_7_viz_type=line_multi', + dataEndpoint: + '/sliceasync/api/read?_flt_0_viz_type=line&_flt_7_viz_type=line_multi', placeholder: t('Select charts'), onAsyncErrorMessage: t('Error while fetching charts'), mutator: (data: Data) => { diff --git a/plugins/legacy-preset-chart-nvd3/src/NVD3Controls.tsx b/plugins/legacy-preset-chart-nvd3/src/NVD3Controls.tsx index 359aa29c8f..8a84263ba8 100644 --- a/plugins/legacy-preset-chart-nvd3/src/NVD3Controls.tsx +++ b/plugins/legacy-preset-chart-nvd3/src/NVD3Controls.tsx @@ -78,7 +78,9 @@ export const leftMargin: CustomControlItem = { choices: formatSelectOptions(['auto', 50, 75, 100, 125, 150, 200]), default: 'auto', renderTrigger: true, - description: t('Left margin, in pixels, allowing for more room for axis labels'), + description: t( + 'Left margin, in pixels, allowing for more room for axis labels', + ), }, }; @@ -186,7 +188,9 @@ export const bottomMargin: CustomControlItem = { choices: formatSelectOptions(['auto', 50, 75, 100, 125, 150, 200]), default: 'auto', renderTrigger: true, - description: t('Bottom margin, in pixels, allowing for more room for axis labels'), + description: t( + 'Bottom margin, in pixels, allowing for more room for axis labels', + ), }, }; @@ -277,7 +281,9 @@ export const richTooltip: CustomControlItem = { label: t('Rich Tooltip'), renderTrigger: true, default: true, - description: t('The rich tooltip shows a list of all series for that point in time'), + description: t( + 'The rich tooltip shows a list of all series for that point in time', + ), }, }; @@ -382,7 +388,13 @@ export const timeSeriesSection: ControlPanelSectionConfig[] = [ type: 'SelectControl', label: t('Rolling Function'), default: 'None', - choices: formatSelectOptions(['None', 'mean', 'sum', 'std', 'cumsum']), + choices: formatSelectOptions([ + 'None', + 'mean', + 'sum', + 'std', + 'cumsum', + ]), description: t( 'Defines a rolling window function to apply, works along ' + 'with the [Periods] text box', @@ -493,7 +505,14 @@ export const timeSeriesSection: ControlPanelSectionConfig[] = [ freeForm: true, label: t('Method'), default: null, - choices: formatSelectOptions(['asfreq', 'bfill', 'ffill', 'median', 'mean', 'sum']), + choices: formatSelectOptions([ + 'asfreq', + 'bfill', + 'ffill', + 'median', + 'mean', + 'sum', + ]), description: t('Pandas resample method'), }, }, diff --git a/plugins/legacy-preset-chart-nvd3/src/NVD3Vis.js b/plugins/legacy-preset-chart-nvd3/src/NVD3Vis.js index 774739bcac..66bf9328ae 100644 --- a/plugins/legacy-preset-chart-nvd3/src/NVD3Vis.js +++ b/plugins/legacy-preset-chart-nvd3/src/NVD3Vis.js @@ -36,7 +36,9 @@ import { import 'nvd3-fork/build/nv.d3.css'; /* eslint-disable-next-line */ -import ANNOTATION_TYPES, { applyNativeColumns } from './vendor/superset/AnnotationTypes'; +import ANNOTATION_TYPES, { + applyNativeColumns, +} from './vendor/superset/AnnotationTypes'; import isTruthy from './utils/isTruthy'; import { cleanColorInput, @@ -74,7 +76,11 @@ import { const NO_DATA_RENDER_DATA = [ { text: 'No data', dy: '-.75em', class: 'header' }, - { text: 'Adjust filters or check the Datasource.', dy: '.75em', class: 'body' }, + { + text: 'Adjust filters or check the Datasource.', + dy: '.75em', + class: 'body', + }, ]; // Override the noData render function to make a prettier UX @@ -90,7 +96,9 @@ nv.utils.noData = function noData(chart, container) { // Remove any previously created chart components container.selectAll('g').remove(); - const noDataText = container.selectAll('.nv-noData').data(NO_DATA_RENDER_DATA); + const noDataText = container + .selectAll('.nv-noData') + .data(NO_DATA_RENDER_DATA); noDataText .enter() @@ -349,18 +357,23 @@ function nvd3Vis(element, props) { // Handling xAxis ticks settings const staggerLabels = xTicksLayout === 'staggered'; const xLabelRotation = - (xTicksLayout === 'auto' && isVizTypes(['column', 'dist_bar'])) || xTicksLayout === '45°' + (xTicksLayout === 'auto' && isVizTypes(['column', 'dist_bar'])) || + xTicksLayout === '45°' ? 45 : 0; if (xLabelRotation === 45 && isTruthy(showBrush)) { - onError(t('You cannot use 45° tick layout along with the time range filter')); + onError( + t('You cannot use 45° tick layout along with the time range filter'), + ); return null; } const canShowBrush = isTruthy(showBrush) || - (showBrush === 'auto' && maxHeight >= MIN_HEIGHT_FOR_BRUSH && xTicksLayout !== '45°'); + (showBrush === 'auto' && + maxHeight >= MIN_HEIGHT_FOR_BRUSH && + xTicksLayout !== '45°'); const numberFormatter = getNumberFormatter(numberFormat); switch (vizType) { @@ -395,7 +408,10 @@ function nvd3Vis(element, props) { break; case 'bar': - chart = nv.models.multiBarChart().showControls(showControls).groupSpacing(0.1); + chart = nv.models + .multiBarChart() + .showControls(showControls) + .groupSpacing(0.1); if (!reduceXTicks) { width = computeBarChartWidth(data, isBarStacked, maxWidth); @@ -446,10 +462,14 @@ function nvd3Vis(element, props) { } else { // pieLabelType in ['key_percent', 'key_value_percent'] const total = d3.sum(data, d => d.y); - const percentFormatter = getNumberFormatter(NumberFormats.PERCENT_2_POINT); + const percentFormatter = getNumberFormatter( + NumberFormats.PERCENT_2_POINT, + ); if (pieLabelType === 'key_percent') { chart.tooltip.valueFormatter(d => percentFormatter(d)); - chart.labelType(d => `${d.data.x}: ${percentFormatter(d.data.y / total)}`); + chart.labelType( + d => `${d.data.x}: ${percentFormatter(d.data.y / total)}`, + ); } else { // pieLabelType === 'key_value_percent' chart.tooltip.valueFormatter( @@ -457,7 +477,9 @@ function nvd3Vis(element, props) { ); chart.labelType( d => - `${d.data.x}: ${numberFormatter(d.data.y)} (${percentFormatter(d.data.y / total)})`, + `${d.data.x}: ${numberFormatter(d.data.y)} (${percentFormatter( + d.data.y / total, + )})`, ); } } @@ -493,7 +515,10 @@ function nvd3Vis(element, props) { }), ); chart.pointRange([5, maxBubbleSize ** 2]); - chart.pointDomain([0, d3.max(data, d => d3.max(d.values, v => v.size))]); + chart.pointDomain([ + 0, + d3.max(data, d => d3.max(d.values, v => v.size)), + ]); break; case 'area': @@ -652,12 +677,21 @@ function nvd3Vis(element, props) { chart.useInteractiveGuideline(true); if (vizType === 'line') { chart.interactiveLayer.tooltip.contentGenerator(d => - generateRichLineTooltipContent(d, smartDateVerboseFormatter, yAxisFormatter), + generateRichLineTooltipContent( + d, + smartDateVerboseFormatter, + yAxisFormatter, + ), ); } else { // area chart chart.interactiveLayer.tooltip.contentGenerator(d => - generateAreaChartTooltipContent(d, smartDateVerboseFormatter, yAxisFormatter, chart), + generateAreaChartTooltipContent( + d, + smartDateVerboseFormatter, + yAxisFormatter, + chart, + ), ); } } @@ -695,7 +729,9 @@ function nvd3Vis(element, props) { // For log scale, only show 1, 10, 100, 1000, ... if (yIsLogScale) { - chart.yAxis.tickFormat(d => (d !== 0 && Math.log10(d) % 1 === 0 ? yAxisFormatter(d) : '')); + chart.yAxis.tickFormat(d => + d !== 0 && Math.log10(d) % 1 === 0 ? yAxisFormatter(d) : '', + ); } if (xLabelRotation > 0) { @@ -705,12 +741,20 @@ function nvd3Vis(element, props) { } const applyYAxisBounds = () => { - if (chart.yDomain && Array.isArray(yAxisBounds) && yAxisBounds.length === 2) { + if ( + chart.yDomain && + Array.isArray(yAxisBounds) && + yAxisBounds.length === 2 + ) { const [customMin, customMax] = yAxisBounds; const hasCustomMin = isDefined(customMin) && !Number.isNaN(customMin); const hasCustomMax = isDefined(customMax) && !Number.isNaN(customMax); - if ((hasCustomMin || hasCustomMax) && vizType === 'area' && chart.style() === 'expand') { + if ( + (hasCustomMin || hasCustomMax) && + vizType === 'area' && + chart.style() === 'expand' + ) { // Because there are custom bounds, we need to override them back to 0%-100% since this // is an expanded area chart chart.yDomain([0, 1]); @@ -732,7 +776,10 @@ function nvd3Vis(element, props) { // These viz types can be stacked // They correspond to the nvd3 stackedAreaChart and multiBarChart - if (vizType === 'area' || (isVizTypes(['bar', 'dist_bar']) && chart.stacked())) { + if ( + vizType === 'area' || + (isVizTypes(['bar', 'dist_bar']) && chart.stacked()) + ) { // This is a stacked area chart or a stacked bar chart [trueMin, trueMax] = computeStackedYDomain(data); } else { @@ -756,8 +803,16 @@ function nvd3Vis(element, props) { // align yAxis1 and yAxis2 ticks if (isVizTypes(['dual_line', 'line_multi'])) { const count = chart.yAxis1.ticks(); - const ticks1 = chart.yAxis1.scale().domain(chart.yAxis1.domain()).nice(count).ticks(count); - const ticks2 = chart.yAxis2.scale().domain(chart.yAxis2.domain()).nice(count).ticks(count); + const ticks1 = chart.yAxis1 + .scale() + .domain(chart.yAxis1.domain()) + .nice(count) + .ticks(count); + const ticks2 = chart.yAxis2 + .scale() + .domain(chart.yAxis2.domain()) + .nice(count) + .ticks(count); // match number of ticks in both axes const difference = ticks1.length - ticks2.length; @@ -777,25 +832,39 @@ function nvd3Vis(element, props) { chart.yAxis2.tickValues(ticks2); } - chart.yDomain1([yAxisBounds[0] || ticks1[0], yAxisBounds[1] || ticks1[ticks1.length - 1]]); - chart.yDomain2([yAxis2Bounds[0] || ticks2[0], yAxis2Bounds[1] || ticks2[ticks2.length - 1]]); + chart.yDomain1([ + yAxisBounds[0] || ticks1[0], + yAxisBounds[1] || ticks1[ticks1.length - 1], + ]); + chart.yDomain2([ + yAxis2Bounds[0] || ticks2[0], + yAxis2Bounds[1] || ticks2[ticks2.length - 1], + ]); } if (showMarkers) { - svg.selectAll('.nv-point').style('stroke-opacity', 1).style('fill-opacity', 1); + svg + .selectAll('.nv-point') + .style('stroke-opacity', 1) + .style('fill-opacity', 1); // redo on legend toggle; nvd3 calls the callback *before* the line is // drawn, so we need to add a small delay here chart.dispatch.on('stateChange.showMarkers', () => { setTimeout(() => { - svg.selectAll('.nv-point').style('stroke-opacity', 1).style('fill-opacity', 1); + svg + .selectAll('.nv-point') + .style('stroke-opacity', 1) + .style('fill-opacity', 1); }, 10); }); } if (chart.yAxis !== undefined || chart.yAxis2 !== undefined) { // Hack to adjust y axis left margin to accommodate long numbers - const marginPad = Math.ceil(Math.min(maxWidth * (isExplore ? 0.01 : 0.03), MAX_MARGIN_PAD)); + const marginPad = Math.ceil( + Math.min(maxWidth * (isExplore ? 0.01 : 0.03), MAX_MARGIN_PAD), + ); // Hack to adjust margins to accommodate long axis tick labels. // - has to be done only after the chart has been rendered once // - measure the width or height of the labels @@ -805,7 +874,10 @@ function nvd3Vis(element, props) { if (chart.xAxis) { margins.bottom = 28; } - const maxYAxisLabelWidth = getMaxLabelSize(svg, chart.yAxis2 ? 'nv-y1' : 'nv-y'); + const maxYAxisLabelWidth = getMaxLabelSize( + svg, + chart.yAxis2 ? 'nv-y1' : 'nv-y', + ); const maxXAxisLabelHeight = getMaxLabelSize(svg, 'nv-x'); margins.left = maxYAxisLabelWidth + marginPad; @@ -822,9 +894,12 @@ function nvd3Vis(element, props) { } if (xLabelRotation === 45) { margins.bottom = - maxXAxisLabelHeight * Math.sin((Math.PI * xLabelRotation) / 180) + marginPad + 30; + maxXAxisLabelHeight * Math.sin((Math.PI * xLabelRotation) / 180) + + marginPad + + 30; margins.right = - maxXAxisLabelHeight * Math.cos((Math.PI * xLabelRotation) / 180) + marginPad; + maxXAxisLabelHeight * Math.cos((Math.PI * xLabelRotation) / 180) + + marginPad; } else if (staggerLabels) { margins.bottom = 40; } @@ -861,7 +936,9 @@ function nvd3Vis(element, props) { if (isTimeSeries && annotationData && activeAnnotationLayers.length > 0) { // Time series annotations add additional data const timeSeriesAnnotations = activeAnnotationLayers - .filter(layer => layer.annotationType === ANNOTATION_TYPES.TIME_SERIES) + .filter( + layer => layer.annotationType === ANNOTATION_TYPES.TIME_SERIES, + ) .reduce( (bushel, a) => bushel.concat( @@ -891,7 +968,9 @@ function nvd3Vis(element, props) { // controls its own tooltips if (chartId) { if (chart && chart.interactiveLayer && chart.interactiveLayer.tooltip) { - chart.interactiveLayer.tooltip.classes([generateTooltipClassName(chartId)]); + chart.interactiveLayer.tooltip.classes([ + generateTooltipClassName(chartId), + ]); } if (chart && chart.tooltip) { @@ -929,7 +1008,10 @@ function nvd3Vis(element, props) { if (vizType === 'bar') { xMin = d3.min(data[0].values, d => d.x); xMax = d3.max(data[0].values, d => d.x); - xScale = d3.scale.quantile().domain([xMin, xMax]).range(chart.xAxis.range()); + xScale = d3.scale + .quantile() + .domain([xMin, xMax]) + .range(chart.xAxis.range()); } else { xMin = chart.xAxis.scale().domain()[0].valueOf(); xMax = chart.xAxis.scale().domain()[1].valueOf(); @@ -961,7 +1043,11 @@ function nvd3Vis(element, props) { // For every other time visualization it should be ok, to have a // data points in even intervals. let period = Math.min( - ...data.map(d => Math.min(...d.values.slice(1).map((v, i) => v.x - d.values[i].x))), + ...data.map(d => + Math.min( + ...d.values.slice(1).map((v, i) => v.x - d.values[i].x), + ), + ), ); const dataPoints = (xMax - xMin) / (period || 1); // make sure that there are enough data points and not too many @@ -1010,7 +1096,8 @@ function nvd3Vis(element, props) { .select('.nv-wrap') .append('g') .attr('class', `nv-event-annotation-layer-${index}`); - const aColor = e.color || getColor(cleanColorInput(e.name), colorScheme); + const aColor = + e.color || getColor(cleanColorInput(e.name), colorScheme); const tip = tipFactory({ ...e, @@ -1025,7 +1112,10 @@ function nvd3Vis(element, props) { [e.timeColumn]: timeValue, }; }) - .filter(record => !Number.isNaN(record[e.timeColumn].getMilliseconds())); + .filter( + record => + !Number.isNaN(record[e.timeColumn].getMilliseconds()), + ); if (records.length > 0) { annotations @@ -1085,13 +1175,16 @@ function nvd3Vis(element, props) { .append('g') .attr('class', `nv-interval-annotation-layer-${index}`); - const aColor = e.color || getColor(cleanColorInput(e.name), colorScheme); + const aColor = + e.color || getColor(cleanColorInput(e.name), colorScheme); const tip = tipFactory(e); const records = (annotationData[e.name].records || []) .map(r => { const timeValue = new Date(moment.utc(r[e.timeColumn])); - const intervalEndValue = new Date(moment.utc(r[e.intervalEndColumn])); + const intervalEndValue = new Date( + moment.utc(r[e.intervalEndColumn]), + ); return { ...r, @@ -1102,7 +1195,9 @@ function nvd3Vis(element, props) { .filter( record => !Number.isNaN(record[e.timeColumn].getMilliseconds()) && - !Number.isNaN(record[e.intervalEndColumn].getMilliseconds()), + !Number.isNaN( + record[e.intervalEndColumn].getMilliseconds(), + ), ); if (records.length > 0) { @@ -1163,13 +1258,14 @@ function nvd3Vis(element, props) { // Display styles for Time Series Annotations chart.dispatch.on('renderEnd.timeseries-annotation', () => { - d3.selectAll('.slice_container .nv-timeseries-annotation-layer.showMarkerstrue .nv-point') + d3.selectAll( + '.slice_container .nv-timeseries-annotation-layer.showMarkerstrue .nv-point', + ) .style('stroke-opacity', 1) .style('fill-opacity', 1); - d3.selectAll('.slice_container .nv-timeseries-annotation-layer.hideLinetrue').style( - 'stroke-width', - 0, - ); + d3.selectAll( + '.slice_container .nv-timeseries-annotation-layer.hideLinetrue', + ).style('stroke-width', 0); }); } } diff --git a/plugins/legacy-preset-chart-nvd3/src/Pie/controlPanel.ts b/plugins/legacy-preset-chart-nvd3/src/Pie/controlPanel.ts index 05baeb63d9..9145d5a842 100644 --- a/plugins/legacy-preset-chart-nvd3/src/Pie/controlPanel.ts +++ b/plugins/legacy-preset-chart-nvd3/src/Pie/controlPanel.ts @@ -17,7 +17,10 @@ * under the License. */ import { t } from '@superset-ui/core'; -import { ControlPanelConfig, D3_FORMAT_OPTIONS } from '@superset-ui/chart-controls'; +import { + ControlPanelConfig, + D3_FORMAT_OPTIONS, +} from '@superset-ui/chart-controls'; import { showLegend } from '../NVD3Controls'; const config: ControlPanelConfig = { @@ -25,7 +28,12 @@ const config: ControlPanelConfig = { { label: t('Query'), expanded: true, - controlSetRows: [['groupby'], ['metric'], ['adhoc_filters'], ['row_limit']], + controlSetRows: [ + ['groupby'], + ['metric'], + ['adhoc_filters'], + ['row_limit'], + ], }, { label: t('Chart Options'), @@ -59,7 +67,9 @@ const config: ControlPanelConfig = { renderTrigger: true, default: 'SMART_NUMBER', choices: D3_FORMAT_OPTIONS, - description: `${t('D3 format syntax: https://github.com/d3/d3-format')} ${t( + description: `${t( + 'D3 format syntax: https://github.com/d3/d3-format', + )} ${t( 'Only applies when the "Label Type" is not set to a percentage.', )}`, }, diff --git a/plugins/legacy-preset-chart-nvd3/src/PropTypes.js b/plugins/legacy-preset-chart-nvd3/src/PropTypes.js index 9c13087ba4..99bf998f40 100644 --- a/plugins/legacy-preset-chart-nvd3/src/PropTypes.js +++ b/plugins/legacy-preset-chart-nvd3/src/PropTypes.js @@ -20,7 +20,10 @@ import PropTypes from 'prop-types'; import { ANNOTATION_TYPES } from './vendor/superset/AnnotationTypes'; -export const numberOrAutoType = PropTypes.oneOfType([PropTypes.number, PropTypes.oneOf(['auto'])]); +export const numberOrAutoType = PropTypes.oneOfType([ + PropTypes.number, + PropTypes.oneOf(['auto']), +]); export const stringOrObjectWithLabelType = PropTypes.oneOfType([ PropTypes.string, diff --git a/plugins/legacy-preset-chart-nvd3/src/TimePivot/controlPanel.ts b/plugins/legacy-preset-chart-nvd3/src/TimePivot/controlPanel.ts index 2c83e7b293..2d1f765c31 100644 --- a/plugins/legacy-preset-chart-nvd3/src/TimePivot/controlPanel.ts +++ b/plugins/legacy-preset-chart-nvd3/src/TimePivot/controlPanel.ts @@ -17,7 +17,11 @@ * under the License. */ import { t } from '@superset-ui/core'; -import { ControlPanelConfig, D3_FORMAT_OPTIONS, sections } from '@superset-ui/chart-controls'; +import { + ControlPanelConfig, + D3_FORMAT_OPTIONS, + sections, +} from '@superset-ui/chart-controls'; import { lineInterpolation, showLegend, @@ -76,7 +80,11 @@ const config: ControlPanelConfig = { { label: t('Chart Options'), expanded: true, - controlSetRows: [[showLegend], [lineInterpolation], ['color_picker', null]], + controlSetRows: [ + [showLegend], + [lineInterpolation], + ['color_picker', null], + ], }, { label: t('X Axis'), diff --git a/plugins/legacy-preset-chart-nvd3/src/transformProps.js b/plugins/legacy-preset-chart-nvd3/src/transformProps.js index 09631a3995..454314c502 100644 --- a/plugins/legacy-preset-chart-nvd3/src/transformProps.js +++ b/plugins/legacy-preset-chart-nvd3/src/transformProps.js @@ -17,7 +17,10 @@ * under the License. */ import isTruthy from './utils/isTruthy'; -import { tokenizeToNumericArray, tokenizeToStringArray } from './utils/tokenize'; +import { + tokenizeToNumericArray, + tokenizeToStringArray, +} from './utils/tokenize'; import { formatLabel } from './utils'; const NOOP = () => {}; @@ -35,7 +38,15 @@ const grabD3Format = (datasource, targetMetric) => { }; export default function transformProps(chartProps) { - const { width, height, annotationData, datasource, formData, hooks, queriesData } = chartProps; + const { + width, + height, + annotationData, + datasource, + formData, + hooks, + queriesData, + } = chartProps; const { onAddFilter = NOOP, onError = NOOP } = hooks; @@ -110,9 +121,12 @@ export default function transformProps(chartProps) { } else if (vizType === 'dual_line') { yAxisFormat = yAxisFormat || grabD3Format(datasource, metric); yAxis2Format = yAxis2Format || grabD3Format(datasource, metric2); - } else if (['line', 'dist_bar', 'bar', 'area'].includes(chartProps.formData.vizType)) { + } else if ( + ['line', 'dist_bar', 'bar', 'area'].includes(chartProps.formData.vizType) + ) { yAxisFormat = - yAxisFormat || grabD3Format(datasource, metrics.length > 0 ? metrics[0] : undefined); + yAxisFormat || + grabD3Format(datasource, metrics.length > 0 ? metrics[0] : undefined); } else if (vizType === 'bullet') { ranges = tokenizeToNumericArray(ranges) || [0, data.measures * 1.1]; rangeLabels = tokenizeToStringArray(rangeLabels); diff --git a/plugins/legacy-preset-chart-nvd3/src/utils.js b/plugins/legacy-preset-chart-nvd3/src/utils.js index 6f62111860..344388fffd 100644 --- a/plugins/legacy-preset-chart-nvd3/src/utils.js +++ b/plugins/legacy-preset-chart-nvd3/src/utils.js @@ -42,7 +42,9 @@ export function cleanColorInput(value) { * @param {*} format */ export function getTimeOrNumberFormatter(format) { - return format === 'smart_date' ? smartDateFormatter : getNumberFormatter(format); + return format === 'smart_date' + ? smartDateFormatter + : getNumberFormatter(format); } export function drawBarValues(svg, data, stacked, axisFormat) { @@ -51,7 +53,9 @@ export function drawBarValues(svg, data, stacked, axisFormat) { const totalStackedValues = stacked && data.length !== 0 ? data[0].values.map((bar, iBar) => { - const bars = data.filter(series => !series.disabled).map(series => series.values[iBar]); + const bars = data + .filter(series => !series.disabled) + .map(series => series.values[iBar]); return d3.sum(bars, d => d.y); }) @@ -105,7 +109,11 @@ function getFormattedKey(seriesKey, shouldDompurify) { // Custom sorted tooltip // use a verbose formatter for times -export function generateRichLineTooltipContent(d, timeFormatter, valueFormatter) { +export function generateRichLineTooltipContent( + d, + timeFormatter, + valueFormatter, +) { let tooltip = ''; tooltip += "` + - `' + `` + @@ -143,11 +153,13 @@ export function generateCompareTooltipContent(d, valueFormatter) { const key = getFormattedKey(series.key, true); tooltip += `` + - `' + `` + @@ -159,7 +171,12 @@ export function generateCompareTooltipContent(d, valueFormatter) { return dompurify.sanitize(tooltip); } -export function generateAreaChartTooltipContent(d, timeFormatter, valueFormatter, chart) { +export function generateAreaChartTooltipContent( + d, + timeFormatter, + valueFormatter, + chart, +) { const total = chart.style() === 'expand' ? // expand mode does not include total row @@ -182,7 +199,9 @@ export function generateAreaChartTooltipContent(d, timeFormatter, valueFormatter } tooltip += `` + - `` + + `` + `` + `` + `` + @@ -339,7 +358,9 @@ export function tipFactory(layer) { ? layer.descriptionColumns.map(c => d[c]) : Object.values(d); - return `
${title}

${body.join(', ')}
`; + return `
${title}

${body.join( + ', ', + )}
`; }); } @@ -362,7 +383,9 @@ export function formatLabel(input, verboseMap = {}) { const verboseLookup = s => verboseMap[s] || s; return Array.isArray(input) && input.length > 0 - ? input.map(l => (TIME_SHIFT_PATTERN.test(l) ? l : verboseLookup(l))).join(', ') + ? input + .map(l => (TIME_SHIFT_PATTERN.test(l) ? l : verboseLookup(l))) + .join(', ') : verboseLookup(input); } @@ -401,7 +424,9 @@ export function setAxisShowMaxMin(axis, showminmax) { export function computeYDomain(data) { if (Array.isArray(data) && data.length > 0 && Array.isArray(data[0].values)) { - const extents = data.filter(d => !d.disabled).map(row => d3.extent(row.values, v => v.y)); + const extents = data + .filter(d => !d.disabled) + .map(row => d3.extent(row.values, v => v.y)); const minOfMin = d3.min(extents, ([min]) => min); const maxOfMax = d3.max(extents, ([, max]) => max); @@ -413,8 +438,12 @@ export function computeYDomain(data) { export function computeStackedYDomain(data) { if (Array.isArray(data) && data.length > 0 && Array.isArray(data[0].values)) { - const series = data.filter(d => !d.disabled).map(d => d.values.map(v => v.y)); - const stackedValues = series[0].map((_, i) => series.reduce((acc, cur) => acc + cur[i], 0)); + const series = data + .filter(d => !d.disabled) + .map(d => d.values.map(v => v.y)); + const stackedValues = series[0].map((_, i) => + series.reduce((acc, cur) => acc + cur[i], 0), + ); return [Math.min(0, ...stackedValues), Math.max(0, ...stackedValues)]; } diff --git a/plugins/legacy-preset-chart-nvd3/src/utils/tokenize.ts b/plugins/legacy-preset-chart-nvd3/src/utils/tokenize.ts index c29f267a53..996d3cc824 100644 --- a/plugins/legacy-preset-chart-nvd3/src/utils/tokenize.ts +++ b/plugins/legacy-preset-chart-nvd3/src/utils/tokenize.ts @@ -21,7 +21,8 @@ import { validateNumber } from '@superset-ui/core'; export function tokenizeToNumericArray(value?: string): number[] | null { if (!value?.trim()) return null; const tokens = value.split(','); - if (tokens.some(token => validateNumber(token))) throw new Error('All values should be numeric'); + if (tokens.some(token => validateNumber(token))) + throw new Error('All values should be numeric'); return tokens.map(token => parseFloat(token)); } diff --git a/plugins/legacy-preset-chart-nvd3/src/vendor/superset/AnnotationTypes.js b/plugins/legacy-preset-chart-nvd3/src/vendor/superset/AnnotationTypes.js index bf87360e81..384c29b304 100644 --- a/plugins/legacy-preset-chart-nvd3/src/vendor/superset/AnnotationTypes.js +++ b/plugins/legacy-preset-chart-nvd3/src/vendor/superset/AnnotationTypes.js @@ -57,7 +57,9 @@ export const ANNOTATION_SOURCE_TYPES_METADATA = { }, }; -export const ANNOTATION_SOURCE_TYPES = extractTypes(ANNOTATION_SOURCE_TYPES_METADATA); +export const ANNOTATION_SOURCE_TYPES = extractTypes( + ANNOTATION_SOURCE_TYPES_METADATA, +); export function requiresQuery(annotationSourceType) { return !!annotationSourceType; diff --git a/plugins/legacy-preset-chart-nvd3/src/vendor/superset/exploreUtils.js b/plugins/legacy-preset-chart-nvd3/src/vendor/superset/exploreUtils.js index baae3297fa..cb2561efb8 100644 --- a/plugins/legacy-preset-chart-nvd3/src/vendor/superset/exploreUtils.js +++ b/plugins/legacy-preset-chart-nvd3/src/vendor/superset/exploreUtils.js @@ -32,7 +32,12 @@ export function getURIDirectory(formData, endpointType = 'base') { return directory; } -export function getExploreLongUrl(formData, endpointType, allowOverflow = true, extraSearch = {}) { +export function getExploreLongUrl( + formData, + endpointType, + allowOverflow = true, + extraSearch = {}, +) { if (!formData.datasource) { return null; } diff --git a/plugins/legacy-preset-chart-nvd3/test/utils.test.js b/plugins/legacy-preset-chart-nvd3/test/utils.test.js index 96c042e451..6745ecdeb3 100644 --- a/plugins/legacy-preset-chart-nvd3/test/utils.test.js +++ b/plugins/legacy-preset-chart-nvd3/test/utils.test.js @@ -140,13 +140,17 @@ describe('nvd3/utils', () => { expect(formatLabel('foo', verboseMap)).toBe('Foo'); expect(formatLabel('baz', verboseMap)).toBe('baz'); expect(formatLabel(['foo'], verboseMap)).toBe('Foo'); - expect(formatLabel(['foo', 'bar', 'baz'], verboseMap)).toBe('Foo, Bar, baz'); + expect(formatLabel(['foo', 'bar', 'baz'], verboseMap)).toBe( + 'Foo, Bar, baz', + ); }); it('deals with time shift properly', () => { - expect(formatLabel(['foo', '1 hour offset'], verboseMap)).toBe('Foo, 1 hour offset'); - expect(formatLabel(['foo', 'bar', 'baz', '2 hours offset'], verboseMap)).toBe( - 'Foo, Bar, baz, 2 hours offset', + expect(formatLabel(['foo', '1 hour offset'], verboseMap)).toBe( + 'Foo, 1 hour offset', ); + expect( + formatLabel(['foo', 'bar', 'baz', '2 hours offset'], verboseMap), + ).toBe('Foo, Bar, baz, 2 hours offset'); }); }); @@ -169,7 +173,9 @@ describe('nvd3/utils', () => { }); it('works with some series disabled', () => { - expect(computeYDomain(DATA_WITH_DISABLED_SERIES)).toEqual([660881033.0, 668526708.0]); + expect(computeYDomain(DATA_WITH_DISABLED_SERIES)).toEqual([ + 660881033.0, 668526708.0, + ]); }); }); @@ -183,7 +189,9 @@ describe('nvd3/utils', () => { }); it('works with some series disabled', () => { - expect(computeStackedYDomain(DATA_WITH_DISABLED_SERIES)).toEqual([0, 668526708.0]); + expect(computeStackedYDomain(DATA_WITH_DISABLED_SERIES)).toEqual([ + 0, 668526708.0, + ]); }); }); }); diff --git a/plugins/legacy-preset-chart-nvd3/test/utils/tokenize.test.js b/plugins/legacy-preset-chart-nvd3/test/utils/tokenize.test.js index c7bacfe9c4..e9c46db976 100644 --- a/plugins/legacy-preset-chart-nvd3/test/utils/tokenize.test.js +++ b/plugins/legacy-preset-chart-nvd3/test/utils/tokenize.test.js @@ -16,14 +16,21 @@ * specific language governing permissions and limitations * under the License. */ -import { tokenizeToNumericArray, tokenizeToStringArray } from '../../src/utils/tokenize'; +import { + tokenizeToNumericArray, + tokenizeToStringArray, +} from '../../src/utils/tokenize'; describe('tokenizeToNumericArray', () => { it('evals numeric strings properly', () => { expect(tokenizeToNumericArray('1')).toStrictEqual([1]); expect(tokenizeToNumericArray('1,2,3,4')).toStrictEqual([1, 2, 3, 4]); - expect(tokenizeToNumericArray('1.1,2.2,3.0,4')).toStrictEqual([1.1, 2.2, 3, 4]); - expect(tokenizeToNumericArray(' 1, 2, 3, 4 ')).toStrictEqual([1, 2, 3, 4]); + expect(tokenizeToNumericArray('1.1,2.2,3.0,4')).toStrictEqual([ + 1.1, 2.2, 3, 4, + ]); + expect(tokenizeToNumericArray(' 1, 2, 3, 4 ')).toStrictEqual([ + 1, 2, 3, 4, + ]); }); it('evals undefined to null', () => { @@ -43,8 +50,19 @@ describe('tokenizeToNumericArray', () => { describe('tokenizeToStringArray', () => { it('evals numeric strings properly', () => { expect(tokenizeToStringArray('a')).toStrictEqual(['a']); - expect(tokenizeToStringArray('1.1 , 2.2, 3.0 ,4')).toStrictEqual(['1.1', '2.2', '3.0', '4']); - expect(tokenizeToStringArray('1.1,a,3, bc ,d')).toStrictEqual(['1.1', 'a', '3', 'bc', 'd']); + expect(tokenizeToStringArray('1.1 , 2.2, 3.0 ,4')).toStrictEqual([ + '1.1', + '2.2', + '3.0', + '4', + ]); + expect(tokenizeToStringArray('1.1,a,3, bc ,d')).toStrictEqual([ + '1.1', + 'a', + '3', + 'bc', + 'd', + ]); }); it('evals undefined to null', () => { diff --git a/plugins/plugin-chart-echarts/src/BoxPlot/controlPanel.ts b/plugins/plugin-chart-echarts/src/BoxPlot/controlPanel.ts index 80af0ca60b..a9456dce38 100644 --- a/plugins/plugin-chart-echarts/src/BoxPlot/controlPanel.ts +++ b/plugins/plugin-chart-echarts/src/BoxPlot/controlPanel.ts @@ -50,7 +50,9 @@ const config: ControlPanelConfig = { freeForm: true, label: t('Whisker/outlier options'), default: 'Tukey', - description: t('Determines how whiskers and outliers are calculated.'), + description: t( + 'Determines how whiskers and outliers are calculated.', + ), choices: formatSelectOptions([ 'Tukey', 'Min/max (no outliers)', @@ -74,7 +76,13 @@ const config: ControlPanelConfig = { config: { type: 'SelectControl', label: t('X Tick Layout'), - choices: formatSelectOptions(['auto', 'flat', '45°', '90°', 'staggered']), + choices: formatSelectOptions([ + 'auto', + 'flat', + '45°', + '90°', + 'staggered', + ]), default: 'auto', clearable: false, renderTrigger: true, @@ -92,9 +100,9 @@ const config: ControlPanelConfig = { renderTrigger: true, default: 'SMART_NUMBER', choices: D3_FORMAT_OPTIONS, - description: `${t('D3 format syntax: https://github.com/d3/d3-format')} ${t( - 'Only applies when "Label Type" is set to show values.', - )}`, + description: `${t( + 'D3 format syntax: https://github.com/d3/d3-format', + )} ${t('Only applies when "Label Type" is set to show values.')}`, }, }, ], diff --git a/plugins/plugin-chart-echarts/src/BoxPlot/transformProps.ts b/plugins/plugin-chart-echarts/src/BoxPlot/transformProps.ts index 2718250879..67a3d81db3 100644 --- a/plugins/plugin-chart-echarts/src/BoxPlot/transformProps.ts +++ b/plugins/plugin-chart-echarts/src/BoxPlot/transformProps.ts @@ -30,7 +30,11 @@ import { BoxPlotQueryFormData, EchartsBoxPlotChartProps, } from './types'; -import { extractGroupbyLabel, getColtypesMapping, sanitizeHtml } from '../utils/series'; +import { + extractGroupbyLabel, + getColtypesMapping, + sanitizeHtml, +} from '../utils/series'; import { defaultGrid, defaultTooltip, defaultYAxis } from '../defaults'; import { getPadding } from '../Timeseries/transformers'; import { OpacityEnum } from '../constants'; @@ -38,7 +42,8 @@ import { OpacityEnum } from '../constants'; export default function transformProps( chartProps: EchartsBoxPlotChartProps, ): BoxPlotChartTransformedProps { - const { width, height, formData, hooks, filterState, queriesData } = chartProps; + const { width, height, formData, hooks, filterState, queriesData } = + chartProps; const { data = [] } = queriesData[0]; const { setDataMask = () => {} } = hooks; const coltypeMapping = getColtypesMapping(queriesData[0]); @@ -69,8 +74,13 @@ export default function transformProps( timeFormatter: getTimeFormatter(dateFormat), }); return metricLabels.map(metric => { - const name = metricLabels.length === 1 ? groupbyLabel : `${groupbyLabel}, ${metric}`; - const isFiltered = filterState.selectedValues && !filterState.selectedValues.includes(name); + const name = + metricLabels.length === 1 + ? groupbyLabel + : `${groupbyLabel}, ${metric}`; + const isFiltered = + filterState.selectedValues && + !filterState.selectedValues.includes(name); return { name, value: [ @@ -101,10 +111,15 @@ export default function transformProps( coltypeMapping, timeFormatter: getTimeFormatter(dateFormat), }); - const name = metricLabels.length === 1 ? groupbyLabel : `${groupbyLabel}, ${metric}`; + const name = + metricLabels.length === 1 + ? groupbyLabel + : `${groupbyLabel}, ${metric}`; // Outlier data is a nested array of numbers (uncommon, therefore no need to add to DataRecordValue) const outlierDatum = (datum[`${metric}__outliers`] || []) as number[]; - const isFiltered = filterState.selectedValues && !filterState.selectedValues.includes(name); + const isFiltered = + filterState.selectedValues && + !filterState.selectedValues.includes(name); return { name: 'outlier', type: 'scatter', @@ -120,29 +135,36 @@ export default function transformProps( }, itemStyle: { color: colorFn(groupbyLabel), - opacity: isFiltered ? OpacityEnum.SemiTransparent : OpacityEnum.NonTransparent, + opacity: isFiltered + ? OpacityEnum.SemiTransparent + : OpacityEnum.NonTransparent, }, }; }), ) .flat(2); - const labelMap = data.reduce((acc: Record, datum) => { - const label = extractGroupbyLabel({ - datum, - groupby, - coltypeMapping, - timeFormatter: getTimeFormatter(dateFormat), - }); - return { - ...acc, - [label]: groupby.map(col => datum[col]), - }; - }, {}); + const labelMap = data.reduce( + (acc: Record, datum) => { + const label = extractGroupbyLabel({ + datum, + groupby, + coltypeMapping, + timeFormatter: getTimeFormatter(dateFormat), + }); + return { + ...acc, + [label]: groupby.map(col => datum[col]), + }; + }, + {}, + ); const selectedValues = (filterState.selectedValues || []).reduce( (acc: Record, selectedValue: string) => { - const index = transformedData.findIndex(({ name }) => name === selectedValue); + const index = transformedData.findIndex( + ({ name }) => name === selectedValue, + ); return { ...acc, [index]: selectedValue, @@ -170,10 +192,22 @@ export default function transformProps( value, name, }: { - value: [number, number, number, number, number, number, number, number, number[]]; + value: [ + number, + number, + number, + number, + number, + number, + number, + number, + number[], + ]; name: string; } = param; - const headline = name ? `

${sanitizeHtml(name)}

` : ''; + const headline = name + ? `

${sanitizeHtml(name)}

` + : ''; const stats = [ `Max: ${numberFormatter(value[5])}`, `3rd Quartile: ${numberFormatter(value[4])}`, diff --git a/plugins/plugin-chart-echarts/src/BoxPlot/types.ts b/plugins/plugin-chart-echarts/src/BoxPlot/types.ts index bd6b720bcf..a38113e309 100644 --- a/plugins/plugin-chart-echarts/src/BoxPlot/types.ts +++ b/plugins/plugin-chart-echarts/src/BoxPlot/types.ts @@ -39,7 +39,12 @@ export type BoxPlotFormDataWhiskerOptions = | '2/98 percentiles' | '9/91 percentiles'; -export type BoxPlotFormXTickLayout = '45°' | '90°' | 'auto' | 'flat' | 'staggered'; +export type BoxPlotFormXTickLayout = + | '45°' + | '90°' + | 'auto' + | 'flat' + | 'staggered'; // @ts-ignore export const DEFAULT_FORM_DATA: BoxPlotQueryFormData = { diff --git a/plugins/plugin-chart-echarts/src/Funnel/controlPanel.tsx b/plugins/plugin-chart-echarts/src/Funnel/controlPanel.tsx index 21a9a1f60a..e1950bf9a5 100644 --- a/plugins/plugin-chart-echarts/src/Funnel/controlPanel.tsx +++ b/plugins/plugin-chart-echarts/src/Funnel/controlPanel.tsx @@ -61,7 +61,9 @@ const config: ControlPanelConfig = { default: true, type: 'CheckboxControl', label: t('Sort by metric'), - description: t('Whether to sort results by the selected metric in descending order.'), + description: t( + 'Whether to sort results by the selected metric in descending order.', + ), }, }, ], @@ -88,8 +90,14 @@ const config: ControlPanelConfig = { [EchartsFunnelLabelTypeType.Value, 'Value'], [EchartsFunnelLabelTypeType.Percent, 'Percentage'], [EchartsFunnelLabelTypeType.KeyValue, 'Category and Value'], - [EchartsFunnelLabelTypeType.KeyPercent, 'Category and Percentage'], - [EchartsFunnelLabelTypeType.KeyValuePercent, 'Category, Value and Percentage'], + [ + EchartsFunnelLabelTypeType.KeyPercent, + 'Category and Percentage', + ], + [ + EchartsFunnelLabelTypeType.KeyValuePercent, + 'Category, Value and Percentage', + ], ], description: t('What should be shown on the label?'), }, @@ -105,9 +113,9 @@ const config: ControlPanelConfig = { renderTrigger: true, default: numberFormat, choices: D3_FORMAT_OPTIONS, - description: `${t('D3 format syntax: https://github.com/d3/d3-format')} ${t( - 'Only applies when "Label Type" is set to show values.', - )}`, + description: `${t( + 'D3 format syntax: https://github.com/d3/d3-format', + )} ${t('Only applies when "Label Type" is set to show values.')}`, }, }, ], diff --git a/plugins/plugin-chart-echarts/src/Funnel/transformProps.ts b/plugins/plugin-chart-echarts/src/Funnel/transformProps.ts index 6087dd79c8..ac8e72af63 100644 --- a/plugins/plugin-chart-echarts/src/Funnel/transformProps.ts +++ b/plugins/plugin-chart-echarts/src/Funnel/transformProps.ts @@ -82,7 +82,8 @@ export function formatFunnelLabel({ export default function transformProps( chartProps: EchartsFunnelChartProps, ): FunnelChartTransformedProps { - const { formData, height, hooks, filterState, queriesData, width } = chartProps; + const { formData, height, hooks, filterState, queriesData, width } = + chartProps; const data: DataRecord[] = queriesData[0].data || []; const { @@ -107,18 +108,23 @@ export default function transformProps( ...formData, }; const metricLabel = getMetricLabel(metric); - const keys = data.map(datum => extractGroupbyLabel({ datum, groupby, coltypeMapping: {} })); - const labelMap = data.reduce((acc: Record, datum) => { - const label = extractGroupbyLabel({ - datum, - groupby, - coltypeMapping: {}, - }); - return { - ...acc, - [label]: groupby.map(col => datum[col]), - }; - }, {}); + const keys = data.map(datum => + extractGroupbyLabel({ datum, groupby, coltypeMapping: {} }), + ); + const labelMap = data.reduce( + (acc: Record, datum) => { + const label = extractGroupbyLabel({ + datum, + groupby, + coltypeMapping: {}, + }); + return { + ...acc, + [label]: groupby.map(col => datum[col]), + }; + }, + {}, + ); const { setDataMask = () => {} } = hooks; @@ -127,20 +133,25 @@ export default function transformProps( const transformedData: FunnelSeriesOption[] = data.map(datum => { const name = extractGroupbyLabel({ datum, groupby, coltypeMapping: {} }); - const isFiltered = filterState.selectedValues && !filterState.selectedValues.includes(name); + const isFiltered = + filterState.selectedValues && !filterState.selectedValues.includes(name); return { value: datum[metricLabel], name, itemStyle: { color: colorFn(name), - opacity: isFiltered ? OpacityEnum.SemiTransparent : OpacityEnum.NonTransparent, + opacity: isFiltered + ? OpacityEnum.SemiTransparent + : OpacityEnum.NonTransparent, }, }; }); const selectedValues = (filterState.selectedValues || []).reduce( (acc: Record, selectedValue: string) => { - const index = transformedData.findIndex(({ name }) => name === selectedValue); + const index = transformedData.findIndex( + ({ name }) => name === selectedValue, + ); return { ...acc, [index]: selectedValue, diff --git a/plugins/plugin-chart-echarts/src/Gauge/controlPanel.tsx b/plugins/plugin-chart-echarts/src/Gauge/controlPanel.tsx index 8fcf6587b5..81af7d3963 100644 --- a/plugins/plugin-chart-echarts/src/Gauge/controlPanel.tsx +++ b/plugins/plugin-chart-echarts/src/Gauge/controlPanel.tsx @@ -63,7 +63,9 @@ const config: ControlPanelConfig = { config: { type: 'CheckboxControl', label: t('Sort by metric'), - description: t('Whether to sort results by the selected metric in descending order.'), + description: t( + 'Whether to sort results by the selected metric in descending order.', + ), }, }, ], @@ -129,7 +131,9 @@ const config: ControlPanelConfig = { config: { type: 'SliderControl', label: t('Font size'), - description: t('Font size for axis labels, detail value and other text elements'), + description: t( + 'Font size for axis labels, detail value and other text elements', + ), renderTrigger: true, min: 10, max: 20, @@ -143,7 +147,9 @@ const config: ControlPanelConfig = { config: { type: 'SelectControl', label: t('Number format'), - description: t('D3 format syntax: https://github.com/d3/d3-format'), + description: t( + 'D3 format syntax: https://github.com/d3/d3-format', + ), freeForm: true, renderTrigger: true, default: DEFAULT_FORM_DATA.numberFormat, @@ -157,7 +163,9 @@ const config: ControlPanelConfig = { config: { type: 'TextControl', label: t('Value format'), - description: t('Additional text to add before or after the value, e.g. unit'), + description: t( + 'Additional text to add before or after the value, e.g. unit', + ), renderTrigger: true, default: DEFAULT_FORM_DATA.valueFormatter, }, @@ -181,7 +189,9 @@ const config: ControlPanelConfig = { config: { type: 'CheckboxControl', label: t('Animation'), - description: t('Whether to animate the progress and the value or just display them'), + description: t( + 'Whether to animate the progress and the value or just display them', + ), renderTrigger: true, default: DEFAULT_FORM_DATA.animation, }, @@ -259,7 +269,9 @@ const config: ControlPanelConfig = { config: { type: 'CheckboxControl', label: t('Round cap'), - description: t('Style the ends of the progress bar with a round cap'), + description: t( + 'Style the ends of the progress bar with a round cap', + ), renderTrigger: true, default: DEFAULT_FORM_DATA.roundCap, }, diff --git a/plugins/plugin-chart-echarts/src/Gauge/index.ts b/plugins/plugin-chart-echarts/src/Gauge/index.ts index 9e3f76b48f..16a8b6a6cc 100644 --- a/plugins/plugin-chart-echarts/src/Gauge/index.ts +++ b/plugins/plugin-chart-echarts/src/Gauge/index.ts @@ -40,7 +40,13 @@ export default class EchartsGaugeChartPlugin extends ChartPlugin< 'Uses a gauge to showcase progress of a metric towards a target. The position of the dial represents the progress and the terminal value in the gauge represents the target value.', ), name: t('Gauge Chart'), - tags: [t('Multi-Variables'), t('Business'), t('Comparison'), t('ECharts'), t('Report')], + tags: [ + t('Multi-Variables'), + t('Business'), + t('Comparison'), + t('ECharts'), + t('Report'), + ], thumbnail, }), transformProps, diff --git a/plugins/plugin-chart-echarts/src/Gauge/transformProps.ts b/plugins/plugin-chart-echarts/src/Gauge/transformProps.ts index d79960412a..597c8d084a 100644 --- a/plugins/plugin-chart-echarts/src/Gauge/transformProps.ts +++ b/plugins/plugin-chart-echarts/src/Gauge/transformProps.ts @@ -60,7 +60,9 @@ const setIntervalBoundsAndColors = ( intervalColorIndicesArray = [] as number[]; } - const intervalBounds = intervalBoundsNonNormalized.map(bound => bound / normalizer); + const intervalBounds = intervalBoundsNonNormalized.map( + bound => bound / normalizer, + ); const intervalColors = intervalColorIndicesArray.map( ind => colorFn.colors[(ind - 1) % colorFn.colors.length], ); @@ -71,13 +73,17 @@ const setIntervalBoundsAndColors = ( }); }; -const calculateAxisLineWidth = (data: DataRecord[], fontSize: number, overlap: boolean): number => - overlap ? fontSize : data.length * fontSize; +const calculateAxisLineWidth = ( + data: DataRecord[], + fontSize: number, + overlap: boolean, +): number => (overlap ? fontSize : data.length * fontSize); export default function transformProps( chartProps: EchartsGaugeChartProps, ): GaugeChartTransformedProps { - const { width, height, formData, queriesData, hooks, filterState } = chartProps; + const { width, height, formData, queriesData, hooks, filterState } = + chartProps; const { groupby, metric, @@ -110,11 +116,14 @@ export default function transformProps( const axisLabelLength = Math.max( ...axisLabels.map(label => numberFormatter(label).length).concat([1]), ); - const formatValue = (value: number) => valueFormatter.replace('{value}', numberFormatter(value)); + const formatValue = (value: number) => + valueFormatter.replace('{value}', numberFormatter(value)); const axisTickLength = FONT_SIZE_MULTIPLIERS.axisTickLength * fontSize; const splitLineLength = FONT_SIZE_MULTIPLIERS.splitLineLength * fontSize; - const titleOffsetFromTitle = FONT_SIZE_MULTIPLIERS.titleOffsetFromTitle * fontSize; - const detailOffsetFromTitle = FONT_SIZE_MULTIPLIERS.detailOffsetFromTitle * fontSize; + const titleOffsetFromTitle = + FONT_SIZE_MULTIPLIERS.titleOffsetFromTitle * fontSize; + const detailOffsetFromTitle = + FONT_SIZE_MULTIPLIERS.detailOffsetFromTitle * fontSize; const intervalBoundsAndColors = setIntervalBoundsAndColors( intervals, intervalColorIndices, @@ -123,47 +132,61 @@ export default function transformProps( ); const columnsLabelMap = new Map(); - const transformedData: GaugeDataItemOption[] = data.map((data_point, index) => { - const name = groupby.map(column => `${column}: ${data_point[column]}`).join(', '); - columnsLabelMap.set( - name, - groupby.map(col => data_point[col]), - ); - let item: GaugeDataItemOption = { - value: data_point[getMetricLabel(metric as QueryFormMetric)] as number, - name, - itemStyle: { - color: colorFn(index), - }, - title: { - offsetCenter: ['0%', `${index * titleOffsetFromTitle + OFFSETS.titleFromCenter}%`], - fontSize, - }, - detail: { - offsetCenter: [ - '0%', - `${index * titleOffsetFromTitle + OFFSETS.titleFromCenter + detailOffsetFromTitle}%`, - ], - fontSize: FONT_SIZE_MULTIPLIERS.detailFontSize * fontSize, - }, - }; - if (filterState.selectedValues && !filterState.selectedValues.includes(name)) { - item = { - ...item, + const transformedData: GaugeDataItemOption[] = data.map( + (data_point, index) => { + const name = groupby + .map(column => `${column}: ${data_point[column]}`) + .join(', '); + columnsLabelMap.set( + name, + groupby.map(col => data_point[col]), + ); + let item: GaugeDataItemOption = { + value: data_point[getMetricLabel(metric as QueryFormMetric)] as number, + name, itemStyle: { color: colorFn(index), - opacity: OpacityEnum.SemiTransparent, - }, - detail: { - show: false, }, title: { - show: false, + offsetCenter: [ + '0%', + `${index * titleOffsetFromTitle + OFFSETS.titleFromCenter}%`, + ], + fontSize, + }, + detail: { + offsetCenter: [ + '0%', + `${ + index * titleOffsetFromTitle + + OFFSETS.titleFromCenter + + detailOffsetFromTitle + }%`, + ], + fontSize: FONT_SIZE_MULTIPLIERS.detailFontSize * fontSize, }, }; - } - return item; - }); + if ( + filterState.selectedValues && + !filterState.selectedValues.includes(name) + ) { + item = { + ...item, + itemStyle: { + color: colorFn(index), + opacity: OpacityEnum.SemiTransparent, + }, + detail: { + show: false, + }, + title: { + show: false, + }, + }; + } + return item; + }, + ); const { setDataMask = () => {} } = hooks; @@ -207,7 +230,8 @@ export default function transformProps( show: showAxisTick, distance: -axisLineWidth - axisTickLength - OFFSETS.ticksFromLine, length: axisTickLength, - lineStyle: DEFAULT_GAUGE_SERIES_OPTION.axisTick?.lineStyle as AxisTickLineStyle, + lineStyle: DEFAULT_GAUGE_SERIES_OPTION.axisTick + ?.lineStyle as AxisTickLineStyle, }; const detail = { valueAnimation: animation, @@ -217,8 +241,10 @@ export default function transformProps( let pointer; if (intervalBoundsAndColors.length) { - splitLine.lineStyle.color = INTERVAL_GAUGE_SERIES_OPTION.splitLine?.lineStyle?.color; - axisTick.lineStyle.color = INTERVAL_GAUGE_SERIES_OPTION?.axisTick?.lineStyle?.color as string; + splitLine.lineStyle.color = + INTERVAL_GAUGE_SERIES_OPTION.splitLine?.lineStyle?.color; + axisTick.lineStyle.color = INTERVAL_GAUGE_SERIES_OPTION?.axisTick?.lineStyle + ?.color as string; axisLabel.color = INTERVAL_GAUGE_SERIES_OPTION.axisLabel?.color; axisLine.lineStyle.color = intervalBoundsAndColors; pointer = { diff --git a/plugins/plugin-chart-echarts/src/Gauge/types.ts b/plugins/plugin-chart-echarts/src/Gauge/types.ts index 90058af167..a73632e09a 100644 --- a/plugins/plugin-chart-echarts/src/Gauge/types.ts +++ b/plugins/plugin-chart-echarts/src/Gauge/types.ts @@ -16,7 +16,11 @@ * specific language governing permissions and limitations * under the License. */ -import { ChartDataResponseResult, ChartProps, QueryFormData } from '@superset-ui/core'; +import { + ChartDataResponseResult, + ChartProps, + QueryFormData, +} from '@superset-ui/core'; import { DEFAULT_LEGEND_FORM_DATA, EChartTransformedProps } from '../types'; export type AxisTickLineStyle = { @@ -78,4 +82,5 @@ export interface EchartsGaugeChartProps extends ChartProps { queriesData: ChartDataResponseResult[]; } -export type GaugeChartTransformedProps = EChartTransformedProps; +export type GaugeChartTransformedProps = + EChartTransformedProps; diff --git a/plugins/plugin-chart-echarts/src/Graph/EchartsGraph.tsx b/plugins/plugin-chart-echarts/src/Graph/EchartsGraph.tsx index 4620c1fe74..9b42c6e553 100644 --- a/plugins/plugin-chart-echarts/src/Graph/EchartsGraph.tsx +++ b/plugins/plugin-chart-echarts/src/Graph/EchartsGraph.tsx @@ -20,6 +20,10 @@ import React from 'react'; import { EchartsProps } from '../types'; import Echart from '../components/Echart'; -export default function EchartsGraph({ height, width, echartOptions }: EchartsProps) { +export default function EchartsGraph({ + height, + width, + echartOptions, +}: EchartsProps) { return ; } diff --git a/plugins/plugin-chart-echarts/src/Graph/controlPanel.tsx b/plugins/plugin-chart-echarts/src/Graph/controlPanel.tsx index 11a009770a..cdefae16ca 100644 --- a/plugins/plugin-chart-echarts/src/Graph/controlPanel.tsx +++ b/plugins/plugin-chart-echarts/src/Graph/controlPanel.tsx @@ -18,7 +18,11 @@ */ import React from 'react'; import { t } from '@superset-ui/core'; -import { ControlPanelConfig, sections, sharedControls } from '@superset-ui/chart-controls'; +import { + ControlPanelConfig, + sections, + sharedControls, +} from '@superset-ui/chart-controls'; import { DEFAULT_FORM_DATA } from './types'; import { legendSection } from '../controls'; @@ -137,9 +141,14 @@ const controlPanel: ControlPanelConfig = { label: t('Enable node dragging'), renderTrigger: true, default: DEFAULT_FORM_DATA.draggable, - description: t('Whether to enable node dragging in force layout mode.'), + description: t( + 'Whether to enable node dragging in force layout mode.', + ), visibility({ form_data: { layout } }) { - return layout === 'force' || (!layout && DEFAULT_FORM_DATA.layout === 'force'); + return ( + layout === 'force' || + (!layout && DEFAULT_FORM_DATA.layout === 'force') + ); }, }, }, @@ -158,7 +167,9 @@ const controlPanel: ControlPanelConfig = { ['move', t('Move only')], [true, t('Scale and Move')], ], - description: t('Whether to enable changing graph position and scaling.'), + description: t( + 'Whether to enable changing graph position and scaling.', + ), }, }, ], @@ -188,7 +199,9 @@ const controlPanel: ControlPanelConfig = { renderTrigger: true, isInt: true, default: DEFAULT_FORM_DATA.showSymbolThreshold, - description: t('Minimum value for label to be displayed on graph.'), + description: t( + 'Minimum value for label to be displayed on graph.', + ), }, }, ], @@ -233,7 +246,10 @@ const controlPanel: ControlPanelConfig = { default: DEFAULT_FORM_DATA.edgeLength, description: t('Edge length between nodes'), visibility({ form_data: { layout } }) { - return layout === 'force' || (!layout && DEFAULT_FORM_DATA.layout === 'force'); + return ( + layout === 'force' || + (!layout && DEFAULT_FORM_DATA.layout === 'force') + ); }, }, }, @@ -251,7 +267,10 @@ const controlPanel: ControlPanelConfig = { default: DEFAULT_FORM_DATA.gravity, description: t('Strength to pull the graph toward center'), visibility({ form_data: { layout } }) { - return layout === 'force' || (!layout && DEFAULT_FORM_DATA.layout === 'force'); + return ( + layout === 'force' || + (!layout && DEFAULT_FORM_DATA.layout === 'force') + ); }, }, }, @@ -269,7 +288,10 @@ const controlPanel: ControlPanelConfig = { default: DEFAULT_FORM_DATA.repulsion, description: t('Repulsion strength between nodes'), visibility({ form_data: { layout } }) { - return layout === 'force' || (!layout && DEFAULT_FORM_DATA.layout === 'force'); + return ( + layout === 'force' || + (!layout && DEFAULT_FORM_DATA.layout === 'force') + ); }, }, }, @@ -287,7 +309,10 @@ const controlPanel: ControlPanelConfig = { default: DEFAULT_FORM_DATA.friction, description: t('Friction between nodes'), visibility({ form_data: { layout } }) { - return layout === 'force' || (!layout && DEFAULT_FORM_DATA.layout === 'force'); + return ( + layout === 'force' || + (!layout && DEFAULT_FORM_DATA.layout === 'force') + ); }, }, }, diff --git a/plugins/plugin-chart-echarts/src/Graph/transformProps.ts b/plugins/plugin-chart-echarts/src/Graph/transformProps.ts index 5576756d34..ea9c6f1524 100644 --- a/plugins/plugin-chart-echarts/src/Graph/transformProps.ts +++ b/plugins/plugin-chart-echarts/src/Graph/transformProps.ts @@ -81,12 +81,17 @@ function normalizeStyles( const maxNodeSize = baseNodeSize * 2; const minEdgeWidth = baseEdgeWidth * 0.5; const maxEdgeWidth = baseEdgeWidth * 2; - const [nodeMinValue, nodeMaxValue] = d3Extent(nodes, x => x.value) as [number, number]; + const [nodeMinValue, nodeMaxValue] = d3Extent(nodes, x => x.value) as [ + number, + number, + ]; const nodeSpread = nodeMaxValue - nodeMinValue; nodes.forEach(node => { // eslint-disable-next-line no-param-reassign - node.symbolSize = (((node.value - nodeMinValue) / nodeSpread) * maxNodeSize || 0) + minNodeSize; + node.symbolSize = + (((node.value - nodeMinValue) / nodeSpread) * maxNodeSize || 0) + + minNodeSize; // eslint-disable-next-line no-param-reassign node.label = { ...node.label, @@ -94,11 +99,15 @@ function normalizeStyles( }; }); - const [linkMinValue, linkMaxValue] = d3Extent(links, x => x.value) as [number, number]; + const [linkMinValue, linkMaxValue] = d3Extent(links, x => x.value) as [ + number, + number, + ]; const linkSpread = linkMaxValue - linkMinValue; links.forEach(link => { const lineWidth = - ((link.value! - linkMinValue) / linkSpread) * maxEdgeWidth || 0 + minEdgeWidth; + ((link.value! - linkMinValue) / linkSpread) * maxEdgeWidth || + 0 + minEdgeWidth; // eslint-disable-next-line no-param-reassign link.lineStyle.width = lineWidth; // eslint-disable-next-line no-param-reassign @@ -115,7 +124,10 @@ function normalizeStyles( }); } -function getKeyByValue(object: { [name: string]: number }, value: number): string { +function getKeyByValue( + object: { [name: string]: number }, + value: number, +): string { return Object.keys(object).find(key => object[key] === value) as string; } @@ -238,7 +250,11 @@ export default function transformProps(chartProps: ChartProps): EchartsProps { }); }); - normalizeStyles(echartNodes, echartLinks, { showSymbolThreshold, baseEdgeWidth, baseNodeSize }); + normalizeStyles(echartNodes, echartLinks, { + showSymbolThreshold, + baseEdgeWidth, + baseNodeSize, + }); const categoryList = [...categories]; @@ -246,9 +262,18 @@ export default function transformProps(chartProps: ChartProps): EchartsProps { { zoom: DEFAULT_GRAPH_SERIES_OPTION.zoom, type: 'graph', - categories: categoryList.map(c => ({ name: c, itemStyle: { color: colorFn(c) } })), + categories: categoryList.map(c => ({ + name: c, + itemStyle: { color: colorFn(c) }, + })), layout, - force: { ...DEFAULT_GRAPH_SERIES_OPTION.force, edgeLength, gravity, repulsion, friction }, + force: { + ...DEFAULT_GRAPH_SERIES_OPTION.force, + edgeLength, + gravity, + repulsion, + friction, + }, circular: DEFAULT_GRAPH_SERIES_OPTION.circular, data: echartNodes, links: echartLinks, @@ -270,7 +295,12 @@ export default function transformProps(chartProps: ChartProps): EchartsProps { animationEasing: DEFAULT_GRAPH_SERIES_OPTION.animationEasing, tooltip: { formatter: (params: any): string => - edgeFormatter(params.data.source, params.data.target, params.value, nodes), + edgeFormatter( + params.data.source, + params.data.target, + params.value, + nodes, + ), }, legend: { ...getLegendProps(legendType, legendOrientation, showLegend), diff --git a/plugins/plugin-chart-echarts/src/MixedTimeseries/EchartsMixedTimeseries.tsx b/plugins/plugin-chart-echarts/src/MixedTimeseries/EchartsMixedTimeseries.tsx index f319fb97a1..d8d4191b43 100644 --- a/plugins/plugin-chart-echarts/src/MixedTimeseries/EchartsMixedTimeseries.tsx +++ b/plugins/plugin-chart-echarts/src/MixedTimeseries/EchartsMixedTimeseries.tsx @@ -42,14 +42,18 @@ export default function EchartsMixedTimeseries({ const handleChange = useCallback( (values: string[], seriesIndex: number) => { - const emitFilter = isFirstQuery(seriesIndex) ? formData.emitFilter : formData.emitFilterB; + const emitFilter = isFirstQuery(seriesIndex) + ? formData.emitFilter + : formData.emitFilterB; if (!emitFilter) { return; } const currentGroupBy = isFirstQuery(seriesIndex) ? groupby : groupbyB; const currentLabelMap = isFirstQuery(seriesIndex) ? labelMap : labelMapB; - const groupbyValues = values.map(value => currentLabelMap[value]).filter(value => !!value); + const groupbyValues = values + .map(value => currentLabelMap[value]) + .filter(value => !!value); setDataMask({ extraFormData: { diff --git a/plugins/plugin-chart-echarts/src/MixedTimeseries/buildQuery.ts b/plugins/plugin-chart-echarts/src/MixedTimeseries/buildQuery.ts index 20ce9ce876..bc6fb6a729 100644 --- a/plugins/plugin-chart-echarts/src/MixedTimeseries/buildQuery.ts +++ b/plugins/plugin-chart-echarts/src/MixedTimeseries/buildQuery.ts @@ -16,7 +16,12 @@ * specific language governing permissions and limitations * under the License. */ -import { buildQueryContext, QueryFormData, QueryObject, normalizeOrderBy } from '@superset-ui/core'; +import { + buildQueryContext, + QueryFormData, + QueryObject, + normalizeOrderBy, +} from '@superset-ui/core'; import { pivotOperator } from '@superset-ui/chart-controls'; export default function buildQuery(formData: QueryFormData) { @@ -59,7 +64,9 @@ export default function buildQuery(formData: QueryFormData) { const queryObjectA = { ...baseQueryObject, is_timeseries: true, - post_processing: [pivotOperator(formData1, { ...baseQueryObject, is_timeseries: true })], + post_processing: [ + pivotOperator(formData1, { ...baseQueryObject, is_timeseries: true }), + ], } as QueryObject; return [normalizeOrderBy(queryObjectA)]; }); @@ -68,7 +75,9 @@ export default function buildQuery(formData: QueryFormData) { const queryObjectB = { ...baseQueryObject, is_timeseries: true, - post_processing: [pivotOperator(formData2, { ...baseQueryObject, is_timeseries: true })], + post_processing: [ + pivotOperator(formData2, { ...baseQueryObject, is_timeseries: true }), + ], } as QueryObject; return [normalizeOrderBy(queryObjectB)]; }); diff --git a/plugins/plugin-chart-echarts/src/MixedTimeseries/controlPanel.tsx b/plugins/plugin-chart-echarts/src/MixedTimeseries/controlPanel.tsx index ebe479f12d..67a7a21f96 100644 --- a/plugins/plugin-chart-echarts/src/MixedTimeseries/controlPanel.tsx +++ b/plugins/plugin-chart-echarts/src/MixedTimeseries/controlPanel.tsx @@ -51,7 +51,10 @@ const { yAxisIndex, } = DEFAULT_FORM_DATA; -function createQuerySection(label: string, controlSuffix: string): ControlPanelSectionConfig { +function createQuerySection( + label: string, + controlSuffix: string, +): ControlPanelSectionConfig { return { label, expanded: true, @@ -118,7 +121,10 @@ function createQuerySection(label: string, controlSuffix: string): ControlPanelS }; } -function createCustomizeSection(label: string, controlSuffix: string): ControlSetRow[] { +function createCustomizeSection( + label: string, + controlSuffix: string, +): ControlSetRow[] { return [ [

{label}

], [ @@ -162,7 +168,9 @@ function createCustomizeSection(label: string, controlSuffix: string): ControlSe label: t('Area chart'), renderTrigger: true, default: area, - description: t('Draw area under curves. Only applicable for line types.'), + description: t( + 'Draw area under curves. Only applicable for line types.', + ), }, }, ], @@ -174,7 +182,9 @@ function createCustomizeSection(label: string, controlSuffix: string): ControlSe label: t('Show Values'), renderTrigger: true, default: showValues, - description: t('Whether to display the numerical values within the cells'), + description: t( + 'Whether to display the numerical values within the cells', + ), }, }, ], @@ -201,7 +211,9 @@ function createCustomizeSection(label: string, controlSuffix: string): ControlSe label: t('Marker'), renderTrigger: true, default: markerEnabled, - description: t('Draw a marker on data points. Only applicable for line types.'), + description: t( + 'Draw a marker on data points. Only applicable for line types.', + ), }, }, ], @@ -215,7 +227,9 @@ function createCustomizeSection(label: string, controlSuffix: string): ControlSe min: 0, max: 100, default: markerSize, - description: t('Size of marker. Also applies to forecast observations.'), + description: t( + 'Size of marker. Also applies to forecast observations.', + ), }, }, ], @@ -297,7 +311,9 @@ const config: ControlPanelConfig = { ], default: xAxisLabelRotation, renderTrigger: true, - description: t('Input field supports custom rotation. e.g. 30 for 30°'), + description: t( + 'Input field supports custom rotation. e.g. 30 for 30°', + ), }, }, ], diff --git a/plugins/plugin-chart-echarts/src/MixedTimeseries/index.ts b/plugins/plugin-chart-echarts/src/MixedTimeseries/index.ts index 4f490f9513..880c050a5e 100644 --- a/plugins/plugin-chart-echarts/src/MixedTimeseries/index.ts +++ b/plugins/plugin-chart-echarts/src/MixedTimeseries/index.ts @@ -16,12 +16,21 @@ * specific language governing permissions and limitations * under the License. */ -import { t, ChartMetadata, ChartPlugin, AnnotationType, Behavior } from '@superset-ui/core'; +import { + t, + ChartMetadata, + ChartPlugin, + AnnotationType, + Behavior, +} from '@superset-ui/core'; import buildQuery from './buildQuery'; import controlPanel from './controlPanel'; import transformProps from './transformProps'; import thumbnail from './images/thumbnail.png'; -import { EchartsMixedTimeseriesProps, EchartsMixedTimeseriesFormData } from './types'; +import { + EchartsMixedTimeseriesProps, + EchartsMixedTimeseriesFormData, +} from './types'; export default class EchartsTimeseriesChartPlugin extends ChartPlugin< EchartsMixedTimeseriesFormData, diff --git a/plugins/plugin-chart-echarts/src/MixedTimeseries/transformProps.ts b/plugins/plugin-chart-echarts/src/MixedTimeseries/transformProps.ts index 7c912e7fb1..3d7b8174be 100644 --- a/plugins/plugin-chart-echarts/src/MixedTimeseries/transformProps.ts +++ b/plugins/plugin-chart-echarts/src/MixedTimeseries/transformProps.ts @@ -65,7 +65,8 @@ import { TIMESERIES_CONSTANTS } from '../constants'; export default function transformProps( chartProps: EchartsMixedTimeseriesFormData, ): EchartsMixedTimeseriesChartTransformedProps { - const { width, height, formData, queriesData, hooks, filterState } = chartProps; + const { width, height, formData, queriesData, hooks, filterState } = + chartProps; const { annotation_data: annotationData_ } = queriesData[0]; const annotationData = annotationData_ || {}; const data1: TimeseriesDataRecord[] = queriesData[0].data || []; @@ -129,19 +130,28 @@ export default function transformProps( const series: SeriesOption[] = []; const formatter = getNumberFormatter(contributionMode ? ',.0%' : yAxisFormat); - const formatterSecondary = getNumberFormatter(contributionMode ? ',.0%' : yAxisFormatSecondary); + const formatterSecondary = getNumberFormatter( + contributionMode ? ',.0%' : yAxisFormatSecondary, + ); const primarySeries = new Set(); const secondarySeries = new Set(); - const mapSeriesIdToAxis = (seriesOption: SeriesOption, index?: number): void => { + const mapSeriesIdToAxis = ( + seriesOption: SeriesOption, + index?: number, + ): void => { if (index === 1) { secondarySeries.add(seriesOption.id as string); } else { primarySeries.add(seriesOption.id as string); } }; - rawSeriesA.forEach(seriesOption => mapSeriesIdToAxis(seriesOption, yAxisIndex)); - rawSeriesB.forEach(seriesOption => mapSeriesIdToAxis(seriesOption, yAxisIndexB)); + rawSeriesA.forEach(seriesOption => + mapSeriesIdToAxis(seriesOption, yAxisIndex), + ); + rawSeriesB.forEach(seriesOption => + mapSeriesIdToAxis(seriesOption, yAxisIndexB), + ); rawSeriesA.forEach(entry => { const transformedSeries = transformSeries(entry, colorScale, { @@ -178,11 +188,27 @@ export default function transformProps( if (isFormulaAnnotationLayer(layer)) series.push(transformFormulaAnnotation(layer, data1, colorScale)); else if (isIntervalAnnotationLayer(layer)) { - series.push(...transformIntervalAnnotation(layer, data1, annotationData, colorScale)); + series.push( + ...transformIntervalAnnotation( + layer, + data1, + annotationData, + colorScale, + ), + ); } else if (isEventAnnotationLayer(layer)) { - series.push(...transformEventAnnotation(layer, data1, annotationData, colorScale)); + series.push( + ...transformEventAnnotation(layer, data1, annotationData, colorScale), + ); } else if (isTimeseriesAnnotationLayer(layer)) { - series.push(...transformTimeseriesAnnotation(layer, markerSize, data1, annotationData)); + series.push( + ...transformTimeseriesAnnotation( + layer, + markerSize, + data1, + annotationData, + ), + ); } }); @@ -278,7 +304,9 @@ export default function transformProps( appendToBody: true, trigger: richTooltip ? 'axis' : 'item', formatter: (params: any) => { - const xValue: number = richTooltip ? params[0].value[0] : params.value[0]; + const xValue: number = richTooltip + ? params[0].value[0] + : params.value[0]; const prophetValue: any[] = richTooltip ? params : [params]; if (richTooltip && tooltipSortByMetric) { @@ -286,7 +314,8 @@ export default function transformProps( } const rows: Array = [`${tooltipTimeFormatter(xValue)}`]; - const prophetValues = extractProphetValuesFromTooltipParams(prophetValue); + const prophetValues = + extractProphetValuesFromTooltipParams(prophetValue); Object.keys(prophetValues).forEach(key => { const value = prophetValues[key]; diff --git a/plugins/plugin-chart-echarts/src/Pie/controlPanel.tsx b/plugins/plugin-chart-echarts/src/Pie/controlPanel.tsx index 1205d80192..aab4af5458 100644 --- a/plugins/plugin-chart-echarts/src/Pie/controlPanel.tsx +++ b/plugins/plugin-chart-echarts/src/Pie/controlPanel.tsx @@ -60,7 +60,9 @@ const config: ControlPanelConfig = { default: true, type: 'CheckboxControl', label: t('Sort by metric'), - description: t('Whether to sort results by the selected metric in descending order.'), + description: t( + 'Whether to sort results by the selected metric in descending order.', + ), }, }, ], @@ -80,7 +82,9 @@ const config: ControlPanelConfig = { renderTrigger: true, isFloat: true, default: 5, - description: t('Minimum threshold in percentage points for showing labels.'), + description: t( + 'Minimum threshold in percentage points for showing labels.', + ), }, }, ], @@ -117,9 +121,9 @@ const config: ControlPanelConfig = { renderTrigger: true, default: numberFormat, choices: D3_FORMAT_OPTIONS, - description: `${t('D3 format syntax: https://github.com/d3/d3-format')} ${t( - 'Only applies when "Label Type" is set to show values.', - )}`, + description: `${t( + 'D3 format syntax: https://github.com/d3/d3-format', + )} ${t('Only applies when "Label Type" is set to show values.')}`, }, }, ], @@ -171,7 +175,9 @@ const config: ControlPanelConfig = { label: t('Label Line'), default: labelLine, renderTrigger: true, - description: t('Draw line from Pie to label when labels outside?'), + description: t( + 'Draw line from Pie to label when labels outside?', + ), visibility: ({ controls }: ControlPanelsContainerProps) => Boolean(controls?.show_labels?.value), }, diff --git a/plugins/plugin-chart-echarts/src/Pie/transformProps.ts b/plugins/plugin-chart-echarts/src/Pie/transformProps.ts index b063667858..a7c35d5502 100644 --- a/plugins/plugin-chart-echarts/src/Pie/transformProps.ts +++ b/plugins/plugin-chart-echarts/src/Pie/transformProps.ts @@ -81,8 +81,11 @@ export function formatPieLabel({ } } -export default function transformProps(chartProps: EchartsPieChartProps): PieChartTransformedProps { - const { formData, height, hooks, filterState, queriesData, width } = chartProps; +export default function transformProps( + chartProps: EchartsPieChartProps, +): PieChartTransformedProps { + const { formData, height, hooks, filterState, queriesData, width } = + chartProps; const { data = [] } = queriesData[0]; const coltypeMapping = getColtypesMapping(queriesData[0]); @@ -105,7 +108,11 @@ export default function transformProps(chartProps: EchartsPieChartProps): PieCha showLegend, showLabelsThreshold, emitFilter, - }: EchartsPieFormData = { ...DEFAULT_LEGEND_FORM_DATA, ...DEFAULT_PIE_FORM_DATA, ...formData }; + }: EchartsPieFormData = { + ...DEFAULT_LEGEND_FORM_DATA, + ...DEFAULT_PIE_FORM_DATA, + ...formData, + }; const metricLabel = getMetricLabel(metric); const minShowLabelAngle = (showLabelsThreshold || 0) * 3.6; @@ -117,18 +124,21 @@ export default function transformProps(chartProps: EchartsPieChartProps): PieCha timeFormatter: getTimeFormatter(dateFormat), }), ); - const labelMap = data.reduce((acc: Record, datum) => { - const label = extractGroupbyLabel({ - datum, - groupby, - coltypeMapping, - timeFormatter: getTimeFormatter(dateFormat), - }); - return { - ...acc, - [label]: groupby.map(col => datum[col]), - }; - }, {}); + const labelMap = data.reduce( + (acc: Record, datum) => { + const label = extractGroupbyLabel({ + datum, + groupby, + coltypeMapping, + timeFormatter: getTimeFormatter(dateFormat), + }); + return { + ...acc, + [label]: groupby.map(col => datum[col]), + }; + }, + {}, + ); const { setDataMask = () => {} } = hooks; @@ -143,21 +153,26 @@ export default function transformProps(chartProps: EchartsPieChartProps): PieCha timeFormatter: getTimeFormatter(dateFormat), }); - const isFiltered = filterState.selectedValues && !filterState.selectedValues.includes(name); + const isFiltered = + filterState.selectedValues && !filterState.selectedValues.includes(name); return { value: datum[metricLabel], name, itemStyle: { color: colorFn(name), - opacity: isFiltered ? OpacityEnum.SemiTransparent : OpacityEnum.NonTransparent, + opacity: isFiltered + ? OpacityEnum.SemiTransparent + : OpacityEnum.NonTransparent, }, }; }); const selectedValues = (filterState.selectedValues || []).reduce( (acc: Record, selectedValue: string) => { - const index = transformedData.findIndex(({ name }) => name === selectedValue); + const index = transformedData.findIndex( + ({ name }) => name === selectedValue, + ); return { ...acc, [index]: selectedValue, diff --git a/plugins/plugin-chart-echarts/src/Radar/buildQuery.ts b/plugins/plugin-chart-echarts/src/Radar/buildQuery.ts index 1171224fa2..c48f4293e1 100644 --- a/plugins/plugin-chart-echarts/src/Radar/buildQuery.ts +++ b/plugins/plugin-chart-echarts/src/Radar/buildQuery.ts @@ -16,7 +16,11 @@ * specific language governing permissions and limitations * under the License. */ -import { buildQueryContext, QueryFormData, ensureIsArray } from '@superset-ui/core'; +import { + buildQueryContext, + QueryFormData, + ensureIsArray, +} from '@superset-ui/core'; export default function buildQuery(formData: QueryFormData) { const { timeseries_limit_metric } = formData; diff --git a/plugins/plugin-chart-echarts/src/Radar/controlPanel.tsx b/plugins/plugin-chart-echarts/src/Radar/controlPanel.tsx index 41b63a6c9f..5819b8a70b 100644 --- a/plugins/plugin-chart-echarts/src/Radar/controlPanel.tsx +++ b/plugins/plugin-chart-echarts/src/Radar/controlPanel.tsx @@ -38,14 +38,17 @@ import { DEFAULT_FORM_DATA } from './types'; import { LABEL_POSITION } from '../constants'; import { legendSection } from '../controls'; -const { labelType, labelPosition, numberFormat, showLabels, isCircle } = DEFAULT_FORM_DATA; +const { labelType, labelPosition, numberFormat, showLabels, isCircle } = + DEFAULT_FORM_DATA; const radarMetricMaxValue: { name: string; config: ControlFormItemSpec } = { name: 'radarMetricMaxValue', config: { controlType: 'InputNumber', label: t('Max'), - description: t('The maximum value of metrics. It is an optional configuration'), + description: t( + 'The maximum value of metrics. It is an optional configuration', + ), width: 120, placeholder: 'auto', debounceDelay: 400, @@ -135,9 +138,9 @@ const config: ControlPanelConfig = { renderTrigger: true, default: numberFormat, choices: D3_FORMAT_OPTIONS, - description: `${t('D3 format syntax: https://github.com/d3/d3-format. ')} ${t( - 'Only applies when "Label Type" is set to show values.', - )}`, + description: `${t( + 'D3 format syntax: https://github.com/d3/d3-format. ', + )} ${t('Only applies when "Label Type" is set to show values.')}`, }, }, ], @@ -168,7 +171,9 @@ const config: ControlPanelConfig = { [GenericDataType.NUMERIC]: [[radarMetricMaxValue]], }, mapStateToProps(explore, control, chart) { - const values = (explore?.controls?.metrics?.value as QueryFormMetric[]) ?? []; + const values = + (explore?.controls?.metrics?.value as QueryFormMetric[]) ?? + []; const metricColumn = values.map(value => { if (typeof value === 'string') { return value; @@ -176,7 +181,9 @@ const config: ControlPanelConfig = { return value.label; }); return { - queryResponse: chart?.queriesResponse?.[0] as ChartDataResponseResult | undefined, + queryResponse: chart?.queriesResponse?.[0] as + | ChartDataResponseResult + | undefined, appliedColumnNames: metricColumn, }; }, @@ -191,7 +198,9 @@ const config: ControlPanelConfig = { label: t('Circle radar shape'), renderTrigger: true, default: isCircle, - description: t("Radar render type, whether to display 'circle' shape."), + description: t( + "Radar render type, whether to display 'circle' shape.", + ), }, }, ], diff --git a/plugins/plugin-chart-echarts/src/Radar/transformProps.ts b/plugins/plugin-chart-echarts/src/Radar/transformProps.ts index c42cef7eba..af1999c66c 100644 --- a/plugins/plugin-chart-echarts/src/Radar/transformProps.ts +++ b/plugins/plugin-chart-echarts/src/Radar/transformProps.ts @@ -36,7 +36,11 @@ import { RadarChartTransformedProps, } from './types'; import { DEFAULT_LEGEND_FORM_DATA } from '../types'; -import { extractGroupbyLabel, getColtypesMapping, getLegendProps } from '../utils/series'; +import { + extractGroupbyLabel, + getColtypesMapping, + getLegendProps, +} from '../utils/series'; import { defaultGrid, defaultTooltip } from '../defaults'; import { OpacityEnum } from '../constants'; @@ -65,7 +69,8 @@ export function formatLabel({ export default function transformProps( chartProps: EchartsRadarChartProps, ): RadarChartTransformedProps { - const { formData, height, hooks, filterState, queriesData, width } = chartProps; + const { formData, height, hooks, filterState, queriesData, width } = + chartProps; const { data = [] } = queriesData[0]; const coltypeMapping = getColtypesMapping(queriesData[0]); @@ -125,7 +130,10 @@ export default function transformProps( metricLabel, Math.max( value as number, - ensureIsInt(metricLabelAndMaxValueMap.get(metricLabel), Number.MIN_SAFE_INTEGER), + ensureIsInt( + metricLabelAndMaxValueMap.get(metricLabel), + Number.MIN_SAFE_INTEGER, + ), ), ); } else { @@ -134,7 +142,8 @@ export default function transformProps( } const isFiltered = - filterState.selectedValues && !filterState.selectedValues.includes(joinedName); + filterState.selectedValues && + !filterState.selectedValues.includes(joinedName); // generate transformedData transformedData.push({ @@ -142,10 +151,14 @@ export default function transformProps( name: joinedName, itemStyle: { color: colorFn(joinedName), - opacity: isFiltered ? OpacityEnum.Transparent : OpacityEnum.NonTransparent, + opacity: isFiltered + ? OpacityEnum.Transparent + : OpacityEnum.NonTransparent, }, lineStyle: { - opacity: isFiltered ? OpacityEnum.SemiTransparent : OpacityEnum.NonTransparent, + opacity: isFiltered + ? OpacityEnum.SemiTransparent + : OpacityEnum.NonTransparent, }, label: { show: showLabels, @@ -157,7 +170,9 @@ export default function transformProps( const selectedValues = (filterState.selectedValues || []).reduce( (acc: Record, selectedValue: string) => { - const index = transformedData.findIndex(({ name }) => name === selectedValue); + const index = transformedData.findIndex( + ({ name }) => name === selectedValue, + ); return { ...acc, [index]: selectedValue, @@ -173,7 +188,8 @@ export default function transformProps( metricLabelAndMaxValueMap.get(metricLabel) === 0 ? Number.MAX_SAFE_INTEGER : metricLabelAndMaxValueMap.get(metricLabel); - const max = maxValueInControl === null ? metricValueAsMax : maxValueInControl; + const max = + maxValueInControl === null ? metricValueAsMax : maxValueInControl; return { name: metricLabel, max, diff --git a/plugins/plugin-chart-echarts/src/Timeseries/Area/controlPanel.tsx b/plugins/plugin-chart-echarts/src/Timeseries/Area/controlPanel.tsx index b58f3d0c14..44d1e80d19 100644 --- a/plugins/plugin-chart-echarts/src/Timeseries/Area/controlPanel.tsx +++ b/plugins/plugin-chart-echarts/src/Timeseries/Area/controlPanel.tsx @@ -32,7 +32,11 @@ import { EchartsTimeseriesContributionType, EchartsTimeseriesSeriesType, } from '../types'; -import { legendSection, richTooltipSection, showValueSection } from '../../controls'; +import { + legendSection, + richTooltipSection, + showValueSection, +} from '../../controls'; const { contributionMode, @@ -130,7 +134,9 @@ const config: ControlPanelConfig = { max: 1, step: 0.1, default: opacity, - description: t('Opacity of Area Chart. Also applies to confidence band.'), + description: t( + 'Opacity of Area Chart. Also applies to confidence band.', + ), }, }, ], @@ -143,7 +149,9 @@ const config: ControlPanelConfig = { label: t('Marker'), renderTrigger: true, default: markerEnabled, - description: t('Draw a marker on data points. Only applicable for line types.'), + description: t( + 'Draw a marker on data points. Only applicable for line types.', + ), }, }, ], @@ -157,7 +165,9 @@ const config: ControlPanelConfig = { min: 0, max: 20, default: markerSize, - description: t('Size of marker. Also applies to forecast observations.'), + description: t( + 'Size of marker. Also applies to forecast observations.', + ), visibility: ({ controls }: ControlPanelsContainerProps) => Boolean(controls?.markerEnabled?.value), }, @@ -203,7 +213,9 @@ const config: ControlPanelConfig = { ], default: xAxisLabelRotation, renderTrigger: true, - description: t('Input field supports custom rotation. e.g. 30 for 30°'), + description: t( + 'Input field supports custom rotation. e.g. 30 for 30°', + ), }, }, ], diff --git a/plugins/plugin-chart-echarts/src/Timeseries/Area/index.ts b/plugins/plugin-chart-echarts/src/Timeseries/Area/index.ts index 2f667137e7..e0c0af2706 100644 --- a/plugins/plugin-chart-echarts/src/Timeseries/Area/index.ts +++ b/plugins/plugin-chart-echarts/src/Timeseries/Area/index.ts @@ -16,12 +16,21 @@ * specific language governing permissions and limitations * under the License. */ -import { t, ChartMetadata, ChartPlugin, AnnotationType, Behavior } from '@superset-ui/core'; +import { + t, + ChartMetadata, + ChartPlugin, + AnnotationType, + Behavior, +} from '@superset-ui/core'; import buildQuery from '../buildQuery'; import controlPanel from './controlPanel'; import transformProps from '../transformProps'; import thumbnail from './images/thumbnail.png'; -import { EchartsTimeseriesChartProps, EchartsTimeseriesFormData } from '../types'; +import { + EchartsTimeseriesChartProps, + EchartsTimeseriesFormData, +} from '../types'; import example1 from './images/Area1.png'; const areaTransformProps = (chartProps: EchartsTimeseriesChartProps) => diff --git a/plugins/plugin-chart-echarts/src/Timeseries/Regular/Bar/index.ts b/plugins/plugin-chart-echarts/src/Timeseries/Regular/Bar/index.ts index 061eea0e33..1ee11f4462 100644 --- a/plugins/plugin-chart-echarts/src/Timeseries/Regular/Bar/index.ts +++ b/plugins/plugin-chart-echarts/src/Timeseries/Regular/Bar/index.ts @@ -16,7 +16,13 @@ * specific language governing permissions and limitations * under the License. */ -import { t, ChartMetadata, ChartPlugin, AnnotationType, Behavior } from '@superset-ui/core'; +import { + t, + ChartMetadata, + ChartPlugin, + AnnotationType, + Behavior, +} from '@superset-ui/core'; import buildQuery from '../../buildQuery'; import controlPanel from '../controlPanel'; import transformProps from '../../transformProps'; @@ -33,7 +39,10 @@ import example3 from './images/Bar3.png'; const barTransformProps = (chartProps: EchartsTimeseriesChartProps) => transformProps({ ...chartProps, - formData: { ...chartProps.formData, seriesType: EchartsTimeseriesSeriesType.Bar }, + formData: { + ...chartProps.formData, + seriesType: EchartsTimeseriesSeriesType.Bar, + }, }); export default class EchartsTimeseriesBarChartPlugin extends ChartPlugin< @@ -52,7 +61,11 @@ export default class EchartsTimeseriesBarChartPlugin extends ChartPlugin< description: t( 'Time-series Bar Charts are used to show the changes in a metric over time as a series of bars.', ), - exampleGallery: [{ url: example1 }, { url: example2 }, { url: example3 }], + exampleGallery: [ + { url: example1 }, + { url: example2 }, + { url: example3 }, + ], supportedAnnotationTypes: [ AnnotationType.Event, AnnotationType.Formula, diff --git a/plugins/plugin-chart-echarts/src/Timeseries/Regular/Line/index.ts b/plugins/plugin-chart-echarts/src/Timeseries/Regular/Line/index.ts index 3acec78243..0ee78dae10 100644 --- a/plugins/plugin-chart-echarts/src/Timeseries/Regular/Line/index.ts +++ b/plugins/plugin-chart-echarts/src/Timeseries/Regular/Line/index.ts @@ -16,7 +16,13 @@ * specific language governing permissions and limitations * under the License. */ -import { t, ChartMetadata, ChartPlugin, AnnotationType, Behavior } from '@superset-ui/core'; +import { + t, + ChartMetadata, + ChartPlugin, + AnnotationType, + Behavior, +} from '@superset-ui/core'; import buildQuery from '../../buildQuery'; import controlPanel from '../controlPanel'; import transformProps from '../../transformProps'; @@ -32,7 +38,10 @@ import example2 from './images/Line2.png'; const lineTransformProps = (chartProps: EchartsTimeseriesChartProps) => transformProps({ ...chartProps, - formData: { ...chartProps.formData, seriesType: EchartsTimeseriesSeriesType.Line }, + formData: { + ...chartProps.formData, + seriesType: EchartsTimeseriesSeriesType.Line, + }, }); export default class EchartsTimeseriesLineChartPlugin extends ChartPlugin< diff --git a/plugins/plugin-chart-echarts/src/Timeseries/Regular/Scatter/controlPanel.tsx b/plugins/plugin-chart-echarts/src/Timeseries/Regular/Scatter/controlPanel.tsx index 33c99b0e77..772e2b06f9 100644 --- a/plugins/plugin-chart-echarts/src/Timeseries/Regular/Scatter/controlPanel.tsx +++ b/plugins/plugin-chart-echarts/src/Timeseries/Regular/Scatter/controlPanel.tsx @@ -28,7 +28,11 @@ import { } from '@superset-ui/chart-controls'; import { DEFAULT_FORM_DATA } from '../../types'; -import { legendSection, richTooltipSection, showValueSection } from '../../../controls'; +import { + legendSection, + richTooltipSection, + showValueSection, +} from '../../../controls'; const { logAxis, @@ -86,7 +90,9 @@ const config: ControlPanelConfig = { label: t('Marker'), renderTrigger: true, default: markerEnabled, - description: t('Draw a marker on data points. Only applicable for line types.'), + description: t( + 'Draw a marker on data points. Only applicable for line types.', + ), }, }, ], @@ -100,7 +106,9 @@ const config: ControlPanelConfig = { min: 0, max: 100, default: markerSize, - description: t('Size of marker. Also applies to forecast observations.'), + description: t( + 'Size of marker. Also applies to forecast observations.', + ), visibility: ({ controls }: ControlPanelsContainerProps) => Boolean(controls?.markerEnabled?.value), }, @@ -147,7 +155,9 @@ const config: ControlPanelConfig = { ], default: xAxisLabelRotation, renderTrigger: true, - description: t('Input field supports custom rotation. e.g. 30 for 30°'), + description: t( + 'Input field supports custom rotation. e.g. 30 for 30°', + ), }, }, ], diff --git a/plugins/plugin-chart-echarts/src/Timeseries/Regular/Scatter/index.ts b/plugins/plugin-chart-echarts/src/Timeseries/Regular/Scatter/index.ts index 2dc298f818..98a7898932 100644 --- a/plugins/plugin-chart-echarts/src/Timeseries/Regular/Scatter/index.ts +++ b/plugins/plugin-chart-echarts/src/Timeseries/Regular/Scatter/index.ts @@ -16,7 +16,13 @@ * specific language governing permissions and limitations * under the License. */ -import { t, ChartMetadata, ChartPlugin, AnnotationType, Behavior } from '@superset-ui/core'; +import { + t, + ChartMetadata, + ChartPlugin, + AnnotationType, + Behavior, +} from '@superset-ui/core'; import buildQuery from '../../buildQuery'; import controlPanel from './controlPanel'; import transformProps from '../../transformProps'; @@ -31,7 +37,10 @@ import example1 from './images/Scatter1.png'; const scatterTransformProps = (chartProps: EchartsTimeseriesChartProps) => transformProps({ ...chartProps, - formData: { ...chartProps.formData, seriesType: EchartsTimeseriesSeriesType.Scatter }, + formData: { + ...chartProps.formData, + seriesType: EchartsTimeseriesSeriesType.Scatter, + }, }); export default class EchartsTimeseriesScatterChartPlugin extends ChartPlugin< diff --git a/plugins/plugin-chart-echarts/src/Timeseries/Regular/SmoothLine/index.ts b/plugins/plugin-chart-echarts/src/Timeseries/Regular/SmoothLine/index.ts index cdc3f1041f..db592e1b80 100644 --- a/plugins/plugin-chart-echarts/src/Timeseries/Regular/SmoothLine/index.ts +++ b/plugins/plugin-chart-echarts/src/Timeseries/Regular/SmoothLine/index.ts @@ -16,7 +16,13 @@ * specific language governing permissions and limitations * under the License. */ -import { t, ChartMetadata, ChartPlugin, AnnotationType, Behavior } from '@superset-ui/core'; +import { + t, + ChartMetadata, + ChartPlugin, + AnnotationType, + Behavior, +} from '@superset-ui/core'; import buildQuery from '../../buildQuery'; import controlPanel from '../controlPanel'; import transformProps from '../../transformProps'; @@ -31,7 +37,10 @@ import example1 from './images/SmoothLine1.png'; const smoothTransformProps = (chartProps: EchartsTimeseriesChartProps) => transformProps({ ...chartProps, - formData: { ...chartProps.formData, seriesType: EchartsTimeseriesSeriesType.Smooth }, + formData: { + ...chartProps.formData, + seriesType: EchartsTimeseriesSeriesType.Smooth, + }, }); export default class EchartsTimeseriesSmoothLineChartPlugin extends ChartPlugin< diff --git a/plugins/plugin-chart-echarts/src/Timeseries/Regular/controlPanel.tsx b/plugins/plugin-chart-echarts/src/Timeseries/Regular/controlPanel.tsx index 3caee6194f..d7159472fa 100644 --- a/plugins/plugin-chart-echarts/src/Timeseries/Regular/controlPanel.tsx +++ b/plugins/plugin-chart-echarts/src/Timeseries/Regular/controlPanel.tsx @@ -28,7 +28,11 @@ import { } from '@superset-ui/chart-controls'; import { DEFAULT_FORM_DATA, EchartsTimeseriesContributionType } from '../types'; -import { legendSection, richTooltipSection, showValueSection } from '../../controls'; +import { + legendSection, + richTooltipSection, + showValueSection, +} from '../../controls'; const { contributionMode, @@ -103,7 +107,9 @@ const config: ControlPanelConfig = { label: t('Marker'), renderTrigger: true, default: markerEnabled, - description: t('Draw a marker on data points. Only applicable for line types.'), + description: t( + 'Draw a marker on data points. Only applicable for line types.', + ), }, }, ], @@ -117,7 +123,9 @@ const config: ControlPanelConfig = { min: 0, max: 20, default: markerSize, - description: t('Size of marker. Also applies to forecast observations.'), + description: t( + 'Size of marker. Also applies to forecast observations.', + ), visibility: ({ controls }: ControlPanelsContainerProps) => Boolean(controls?.markerEnabled?.value), }, @@ -163,7 +171,9 @@ const config: ControlPanelConfig = { ], default: xAxisLabelRotation, renderTrigger: true, - description: t('Input field supports custom rotation. e.g. 30 for 30°'), + description: t( + 'Input field supports custom rotation. e.g. 30 for 30°', + ), }, }, ], diff --git a/plugins/plugin-chart-echarts/src/Timeseries/Step/controlPanel.tsx b/plugins/plugin-chart-echarts/src/Timeseries/Step/controlPanel.tsx index adf39a564d..a006d0f666 100644 --- a/plugins/plugin-chart-echarts/src/Timeseries/Step/controlPanel.tsx +++ b/plugins/plugin-chart-echarts/src/Timeseries/Step/controlPanel.tsx @@ -32,7 +32,11 @@ import { EchartsTimeseriesContributionType, EchartsTimeseriesSeriesType, } from '../types'; -import { legendSection, richTooltipSection, showValueSection } from '../../controls'; +import { + legendSection, + richTooltipSection, + showValueSection, +} from '../../controls'; const { area, @@ -128,7 +132,9 @@ const config: ControlPanelConfig = { label: t('Area Chart'), renderTrigger: true, default: area, - description: t('Draw area under curves. Only applicable for line types.'), + description: t( + 'Draw area under curves. Only applicable for line types.', + ), }, }, ], @@ -143,7 +149,9 @@ const config: ControlPanelConfig = { max: 1, step: 0.1, default: opacity, - description: t('Opacity of Area Chart. Also applies to confidence band.'), + description: t( + 'Opacity of Area Chart. Also applies to confidence band.', + ), visibility: ({ controls }: ControlPanelsContainerProps) => Boolean(controls?.area?.value), }, @@ -157,7 +165,9 @@ const config: ControlPanelConfig = { label: t('Marker'), renderTrigger: true, default: markerEnabled, - description: t('Draw a marker on data points. Only applicable for line types.'), + description: t( + 'Draw a marker on data points. Only applicable for line types.', + ), }, }, ], @@ -171,7 +181,9 @@ const config: ControlPanelConfig = { min: 0, max: 20, default: markerSize, - description: t('Size of marker. Also applies to forecast observations.'), + description: t( + 'Size of marker. Also applies to forecast observations.', + ), visibility: ({ controls }: ControlPanelsContainerProps) => Boolean(controls?.markerEnabled?.value), }, @@ -217,7 +229,9 @@ const config: ControlPanelConfig = { ], default: xAxisLabelRotation, renderTrigger: true, - description: t('Input field supports custom rotation. e.g. 30 for 30°'), + description: t( + 'Input field supports custom rotation. e.g. 30 for 30°', + ), }, }, ], diff --git a/plugins/plugin-chart-echarts/src/Timeseries/Step/index.ts b/plugins/plugin-chart-echarts/src/Timeseries/Step/index.ts index b1f4bde196..ddf18ebe5b 100644 --- a/plugins/plugin-chart-echarts/src/Timeseries/Step/index.ts +++ b/plugins/plugin-chart-echarts/src/Timeseries/Step/index.ts @@ -16,12 +16,21 @@ * specific language governing permissions and limitations * under the License. */ -import { t, ChartMetadata, ChartPlugin, AnnotationType, Behavior } from '@superset-ui/core'; +import { + t, + ChartMetadata, + ChartPlugin, + AnnotationType, + Behavior, +} from '@superset-ui/core'; import buildQuery from '../buildQuery'; import controlPanel from './controlPanel'; import transformProps from '../transformProps'; import thumbnail from './images/thumbnail.png'; -import { EchartsTimeseriesChartProps, EchartsTimeseriesFormData } from '../types'; +import { + EchartsTimeseriesChartProps, + EchartsTimeseriesFormData, +} from '../types'; import example1 from './images/Step1.png'; import example2 from './images/Step2.png'; diff --git a/plugins/plugin-chart-echarts/src/Timeseries/buildQuery.ts b/plugins/plugin-chart-echarts/src/Timeseries/buildQuery.ts index fc5335f031..5d02f2fb0f 100644 --- a/plugins/plugin-chart-echarts/src/Timeseries/buildQuery.ts +++ b/plugins/plugin-chart-echarts/src/Timeseries/buildQuery.ts @@ -36,11 +36,15 @@ import { export default function buildQuery(formData: QueryFormData) { return buildQueryContext(formData, baseQueryObject => { - const pivotOperatorInRuntime: PostProcessingPivot | undefined = pivotOperator(formData, { - ...baseQueryObject, - is_timeseries: true, - }); - if (pivotOperatorInRuntime && Object.values(RollingType).includes(formData.rolling_type)) { + const pivotOperatorInRuntime: PostProcessingPivot | undefined = + pivotOperator(formData, { + ...baseQueryObject, + is_timeseries: true, + }); + if ( + pivotOperatorInRuntime && + Object.values(RollingType).includes(formData.rolling_type) + ) { pivotOperatorInRuntime.options = { ...pivotOperatorInRuntime.options, ...{ @@ -56,7 +60,9 @@ export default function buildQuery(formData: QueryFormData) { is_timeseries: true, // todo: move `normalizeOrderBy to extractQueryFields` orderby: normalizeOrderBy(baseQueryObject).orderby, - time_offsets: isValidTimeCompare(formData, baseQueryObject) ? formData.time_compare : [], + time_offsets: isValidTimeCompare(formData, baseQueryObject) + ? formData.time_compare + : [], post_processing: [ resampleOperator(formData, baseQueryObject), timeCompareOperator(formData, baseQueryObject), diff --git a/plugins/plugin-chart-echarts/src/Timeseries/controlPanel.tsx b/plugins/plugin-chart-echarts/src/Timeseries/controlPanel.tsx index 7cd89bdf2a..2763a62c05 100644 --- a/plugins/plugin-chart-echarts/src/Timeseries/controlPanel.tsx +++ b/plugins/plugin-chart-echarts/src/Timeseries/controlPanel.tsx @@ -32,7 +32,11 @@ import { EchartsTimeseriesContributionType, EchartsTimeseriesSeriesType, } from './types'; -import { legendSection, richTooltipSection, showValueSection } from '../controls'; +import { + legendSection, + richTooltipSection, + showValueSection, +} from '../controls'; const { area, @@ -131,7 +135,9 @@ const config: ControlPanelConfig = { label: t('Area Chart'), renderTrigger: true, default: area, - description: t('Draw area under curves. Only applicable for line types.'), + description: t( + 'Draw area under curves. Only applicable for line types.', + ), }, }, ], @@ -146,7 +152,9 @@ const config: ControlPanelConfig = { max: 1, step: 0.1, default: opacity, - description: t('Opacity of Area Chart. Also applies to confidence band.'), + description: t( + 'Opacity of Area Chart. Also applies to confidence band.', + ), visibility: ({ controls }: ControlPanelsContainerProps) => Boolean(controls?.area?.value), }, @@ -160,7 +168,9 @@ const config: ControlPanelConfig = { label: t('Marker'), renderTrigger: true, default: markerEnabled, - description: t('Draw a marker on data points. Only applicable for line types.'), + description: t( + 'Draw a marker on data points. Only applicable for line types.', + ), }, }, ], @@ -174,7 +184,9 @@ const config: ControlPanelConfig = { min: 0, max: 20, default: markerSize, - description: t('Size of marker. Also applies to forecast observations.'), + description: t( + 'Size of marker. Also applies to forecast observations.', + ), visibility: ({ controls }: ControlPanelsContainerProps) => Boolean(controls?.markerEnabled?.value), }, @@ -220,7 +232,9 @@ const config: ControlPanelConfig = { ], default: xAxisLabelRotation, renderTrigger: true, - description: t('Input field supports custom rotation. e.g. 30 for 30°'), + description: t( + 'Input field supports custom rotation. e.g. 30 for 30°', + ), }, }, ], diff --git a/plugins/plugin-chart-echarts/src/Timeseries/index.ts b/plugins/plugin-chart-echarts/src/Timeseries/index.ts index 4e5d38364a..48856ab5a3 100644 --- a/plugins/plugin-chart-echarts/src/Timeseries/index.ts +++ b/plugins/plugin-chart-echarts/src/Timeseries/index.ts @@ -16,12 +16,21 @@ * specific language governing permissions and limitations * under the License. */ -import { t, ChartMetadata, ChartPlugin, AnnotationType, Behavior } from '@superset-ui/core'; +import { + t, + ChartMetadata, + ChartPlugin, + AnnotationType, + Behavior, +} from '@superset-ui/core'; import buildQuery from './buildQuery'; import controlPanel from './controlPanel'; import transformProps from './transformProps'; import thumbnail from './images/thumbnail.png'; -import { EchartsTimeseriesChartProps, EchartsTimeseriesFormData } from './types'; +import { + EchartsTimeseriesChartProps, + EchartsTimeseriesFormData, +} from './types'; import example from './images/Time-series_Chart.jpg'; export default class EchartsTimeseriesChartPlugin extends ChartPlugin< diff --git a/plugins/plugin-chart-echarts/src/Timeseries/transformProps.ts b/plugins/plugin-chart-echarts/src/Timeseries/transformProps.ts index 90639e65b2..9726c3ac06 100644 --- a/plugins/plugin-chart-echarts/src/Timeseries/transformProps.ts +++ b/plugins/plugin-chart-echarts/src/Timeseries/transformProps.ts @@ -67,7 +67,15 @@ import { TIMESERIES_CONSTANTS } from '../constants'; export default function transformProps( chartProps: EchartsTimeseriesChartProps, ): TimeseriesChartTransformedProps { - const { width, height, filterState, formData, hooks, queriesData, datasource } = chartProps; + const { + width, + height, + filterState, + formData, + hooks, + queriesData, + datasource, + } = chartProps; const { verboseMap = {} } = datasource; const { annotation_data: annotationData_, data = [] } = queriesData[0] as TimeseriesChartDataResponseResult; @@ -181,11 +189,27 @@ export default function transformProps( if (isFormulaAnnotationLayer(layer)) series.push(transformFormulaAnnotation(layer, data, colorScale)); else if (isIntervalAnnotationLayer(layer)) { - series.push(...transformIntervalAnnotation(layer, data, annotationData, colorScale)); + series.push( + ...transformIntervalAnnotation( + layer, + data, + annotationData, + colorScale, + ), + ); } else if (isEventAnnotationLayer(layer)) { - series.push(...transformEventAnnotation(layer, data, annotationData, colorScale)); + series.push( + ...transformEventAnnotation(layer, data, annotationData, colorScale), + ); } else if (isTimeseriesAnnotationLayer(layer)) { - series.push(...transformTimeseriesAnnotation(layer, markerSize, data, annotationData)); + series.push( + ...transformTimeseriesAnnotation( + layer, + markerSize, + data, + annotationData, + ), + ); } }); @@ -201,13 +225,16 @@ export default function transformProps( const tooltipFormatter = getTooltipTimeFormatter(tooltipTimeFormat); const xAxisFormatter = getXAxisFormatter(xAxisTimeFormat); - const labelMap = series.reduce((acc: Record, datum) => { - const name: string = datum.name as string; - return { - ...acc, - [name]: [name], - }; - }, {}); + const labelMap = series.reduce( + (acc: Record, datum) => { + const name: string = datum.name as string; + return { + ...acc, + [name]: [name], + }; + }, + {}, + ); const { setDataMask = () => {} } = hooks; @@ -228,7 +255,8 @@ export default function transformProps( const legendData = rawSeries .filter( entry => - extractForecastSeriesContext(entry.name || '').type === ForecastSeriesEnum.Observation, + extractForecastSeriesContext(entry.name || '').type === + ForecastSeriesEnum.Observation, ) .map(entry => entry.name || '') .concat(extractAnnotationLabels(annotationLayers, annotationData)); @@ -268,7 +296,9 @@ export default function transformProps( appendToBody: true, trigger: richTooltip ? 'axis' : 'item', formatter: (params: any) => { - const xValue: number = richTooltip ? params[0].value[0] : params.value[0]; + const xValue: number = richTooltip + ? params[0].value[0] + : params.value[0]; const prophetValue: any[] = richTooltip ? params : [params]; if (richTooltip && tooltipSortByMetric) { diff --git a/plugins/plugin-chart-echarts/src/Timeseries/transformers.ts b/plugins/plugin-chart-echarts/src/Timeseries/transformers.ts index aa4dc61c15..b190354442 100644 --- a/plugins/plugin-chart-echarts/src/Timeseries/transformers.ts +++ b/plugins/plugin-chart-echarts/src/Timeseries/transformers.ts @@ -112,8 +112,11 @@ export function transformSeries( const isConfidenceBand = forecastSeries.type === ForecastSeriesEnum.ForecastLower || forecastSeries.type === ForecastSeriesEnum.ForecastUpper; - const isFiltered = filterState?.selectedValues && !filterState?.selectedValues.includes(name); - const opacity = isFiltered ? OpacityEnum.SemiTransparent : OpacityEnum.NonTransparent; + const isFiltered = + filterState?.selectedValues && !filterState?.selectedValues.includes(name); + const opacity = isFiltered + ? OpacityEnum.SemiTransparent + : OpacityEnum.NonTransparent; // don't create a series if doing a stack or area chart and the result // is a confidence band @@ -132,7 +135,10 @@ export function transformSeries( stackId = forecastSeries.type; } let plotType; - if (!isConfidenceBand && (seriesType === 'scatter' || (hasForecast && isObservation))) { + if ( + !isConfidenceBand && + (seriesType === 'scatter' || (hasForecast && isObservation)) + ) { plotType = 'scatter'; } else if (isConfidenceBand) { plotType = 'line'; @@ -166,7 +172,9 @@ export function transformSeries( showSymbol = true; } } - const lineStyle = isConfidenceBand ? { opacity: OpacityEnum.Transparent } : { opacity }; + const lineStyle = isConfidenceBand + ? { opacity: OpacityEnum.Transparent } + : { opacity }; return { ...series, yAxisIndex, @@ -177,13 +185,17 @@ export function transformSeries( smooth: seriesType === 'smooth', triggerLineEvent: true, // @ts-ignore - step: ['start', 'middle', 'end'].includes(seriesType as string) ? seriesType : undefined, + step: ['start', 'middle', 'end'].includes(seriesType as string) + ? seriesType + : undefined, stack: stackId, lineStyle, areaStyle: area ? { opacity: - forecastSeries.type === ForecastSeriesEnum.ForecastUpper ? opacity * areaOpacity : 0, + forecastSeries.type === ForecastSeriesEnum.ForecastUpper + ? opacity * areaOpacity + : 0, } : undefined, emphasis, @@ -249,7 +261,10 @@ export function transformIntervalAnnotation( const { name, color, opacity, showLabel } = layer; const { descriptions, intervalEnd, time, title } = annotation; const label = formatAnnotationLabel(name, title, descriptions); - const intervalData: (MarkArea1DDataItemOption | MarkArea2DDataItemOption)[] = [ + const intervalData: ( + | MarkArea1DDataItemOption + | MarkArea2DDataItemOption + )[] = [ [ { name: label, @@ -423,7 +438,9 @@ export function getPadding( right: number; top: number; } { - const yAxisOffset = addYAxisTitleOffset ? TIMESERIES_CONSTANTS.yAxisLabelTopOffset : 0; + const yAxisOffset = addYAxisTitleOffset + ? TIMESERIES_CONSTANTS.yAxisLabelTopOffset + : 0; const xAxisOffset = addXAxisTitleOffset ? xAxisTitleMargin || 0 : 0; return getChartPadding(showLegend, legendOrientation, margin, { top: @@ -444,7 +461,9 @@ export function getPadding( }); } -export function getTooltipTimeFormatter(format?: string): TimeFormatter | StringConstructor { +export function getTooltipTimeFormatter( + format?: string, +): TimeFormatter | StringConstructor { if (format === smartDateFormatter.id) { return smartDateDetailedFormatter; } @@ -454,7 +473,9 @@ export function getTooltipTimeFormatter(format?: string): TimeFormatter | String return String; } -export function getXAxisFormatter(format?: string): TimeFormatter | StringConstructor | undefined { +export function getXAxisFormatter( + format?: string, +): TimeFormatter | StringConstructor | undefined { if (format === smartDateFormatter.id || !format) { return undefined; } diff --git a/plugins/plugin-chart-echarts/src/Timeseries/types.ts b/plugins/plugin-chart-echarts/src/Timeseries/types.ts index 060e43950b..47d81622f0 100644 --- a/plugins/plugin-chart-echarts/src/Timeseries/types.ts +++ b/plugins/plugin-chart-echarts/src/Timeseries/types.ts @@ -91,9 +91,12 @@ export const DEFAULT_FORM_DATA: EchartsTimeseriesFormData = { forecastEnabled: sections.FORECAST_DEFAULT_DATA.forecastEnabled, forecastInterval: sections.FORECAST_DEFAULT_DATA.forecastInterval, forecastPeriods: sections.FORECAST_DEFAULT_DATA.forecastPeriods, - forecastSeasonalityDaily: sections.FORECAST_DEFAULT_DATA.forecastSeasonalityDaily, - forecastSeasonalityWeekly: sections.FORECAST_DEFAULT_DATA.forecastSeasonalityWeekly, - forecastSeasonalityYearly: sections.FORECAST_DEFAULT_DATA.forecastSeasonalityYearly, + forecastSeasonalityDaily: + sections.FORECAST_DEFAULT_DATA.forecastSeasonalityDaily, + forecastSeasonalityWeekly: + sections.FORECAST_DEFAULT_DATA.forecastSeasonalityWeekly, + forecastSeasonalityYearly: + sections.FORECAST_DEFAULT_DATA.forecastSeasonalityYearly, logAxis: false, markerEnabled: false, markerSize: 6, @@ -121,4 +124,5 @@ export interface EchartsTimeseriesChartProps extends ChartProps { queriesData: ChartDataResponseResult[]; } -export type TimeseriesChartTransformedProps = EChartTransformedProps; +export type TimeseriesChartTransformedProps = + EChartTransformedProps; diff --git a/plugins/plugin-chart-echarts/src/Tree/EchartsTree.tsx b/plugins/plugin-chart-echarts/src/Tree/EchartsTree.tsx index 4620c1fe74..9b42c6e553 100644 --- a/plugins/plugin-chart-echarts/src/Tree/EchartsTree.tsx +++ b/plugins/plugin-chart-echarts/src/Tree/EchartsTree.tsx @@ -20,6 +20,10 @@ import React from 'react'; import { EchartsProps } from '../types'; import Echart from '../components/Echart'; -export default function EchartsGraph({ height, width, echartOptions }: EchartsProps) { +export default function EchartsGraph({ + height, + width, + echartOptions, +}: EchartsProps) { return ; } diff --git a/plugins/plugin-chart-echarts/src/Tree/controlPanel.tsx b/plugins/plugin-chart-echarts/src/Tree/controlPanel.tsx index 27a6c2f4f3..aa4a38fca8 100644 --- a/plugins/plugin-chart-echarts/src/Tree/controlPanel.tsx +++ b/plugins/plugin-chart-echarts/src/Tree/controlPanel.tsx @@ -18,7 +18,11 @@ */ import React from 'react'; import { FeatureFlag, isFeatureEnabled, t } from '@superset-ui/core'; -import { ControlPanelConfig, sections, sharedControls } from '@superset-ui/chart-controls'; +import { + ControlPanelConfig, + sections, + sharedControls, +} from '@superset-ui/chart-controls'; import { DEFAULT_FORM_DATA } from './types'; const requiredEntity = { @@ -54,7 +58,9 @@ const controlPanel: ControlPanelConfig = { config: { ...requiredEntity, label: t('Parent'), - description: t('Name of the column containing the id of the parent node'), + description: t( + 'Name of the column containing the id of the parent node', + ), }, }, ], @@ -270,7 +276,9 @@ const controlPanel: ControlPanelConfig = { ['move', t('Move only')], [true, t('Scale and Move')], ], - description: t('Whether to enable changing graph position and scaling.'), + description: t( + 'Whether to enable changing graph position and scaling.', + ), }, }, ], diff --git a/plugins/plugin-chart-echarts/src/Tree/index.ts b/plugins/plugin-chart-echarts/src/Tree/index.ts index 2adcfb1d24..5514c372f3 100644 --- a/plugins/plugin-chart-echarts/src/Tree/index.ts +++ b/plugins/plugin-chart-echarts/src/Tree/index.ts @@ -37,7 +37,13 @@ export default class EchartsTreeChartPlugin extends ChartPlugin { ), exampleGallery: [{ url: example }], name: t('Tree Chart'), - tags: [t('Categorical'), t('ECharts'), t('Multi-Levels'), t('Relational'), t('Structural')], + tags: [ + t('Categorical'), + t('ECharts'), + t('Multi-Levels'), + t('Relational'), + t('Structural'), + ], thumbnail, }), transformProps, diff --git a/plugins/plugin-chart-echarts/src/Tree/transformProps.ts b/plugins/plugin-chart-echarts/src/Tree/transformProps.ts index f30f260c4e..c89fbe8b37 100644 --- a/plugins/plugin-chart-echarts/src/Tree/transformProps.ts +++ b/plugins/plugin-chart-echarts/src/Tree/transformProps.ts @@ -43,7 +43,10 @@ export function formatTooltip({ .map(pathInfo => pathInfo?.name || '') .filter(path => path !== ''); - return [`
${treePath.join(' ▸ ')}
`, value ? `${metricLabel}: ${value}` : ''].join(''); + return [ + `
${treePath.join(' ▸ ')}
`, + value ? `${metricLabel}: ${value}` : '', + ].join(''); } export default function transformProps(chartProps: ChartProps): EchartsProps { @@ -176,7 +179,10 @@ export default function transformProps(chartProps: ChartProps): EchartsProps { { type: 'tree', data: [finalTree], - label: { ...DEFAULT_TREE_SERIES_OPTION.label, position: nodeLabelPosition }, + label: { + ...DEFAULT_TREE_SERIES_OPTION.label, + position: nodeLabelPosition, + }, emphasis: { focus: emphasis }, animation: DEFAULT_TREE_SERIES_OPTION.animation, layout, diff --git a/plugins/plugin-chart-echarts/src/Treemap/constants.ts b/plugins/plugin-chart-echarts/src/Treemap/constants.ts index c9654ae15e..080565229a 100644 --- a/plugins/plugin-chart-echarts/src/Treemap/constants.ts +++ b/plugins/plugin-chart-echarts/src/Treemap/constants.ts @@ -25,7 +25,9 @@ export const BORDER_WIDTH = 2; export const GAP_WIDTH = 2; export const BORDER_COLOR = '#fff'; -export const extractTreePathInfo = (treePathInfo: TreePathInfo[] | undefined) => { +export const extractTreePathInfo = ( + treePathInfo: TreePathInfo[] | undefined, +) => { const treePath = (treePathInfo ?? []) .map(pathInfo => pathInfo?.name || '') .filter(path => path !== ''); diff --git a/plugins/plugin-chart-echarts/src/Treemap/controlPanel.tsx b/plugins/plugin-chart-echarts/src/Treemap/controlPanel.tsx index 6c33ef62b2..9f6d4e297e 100644 --- a/plugins/plugin-chart-echarts/src/Treemap/controlPanel.tsx +++ b/plugins/plugin-chart-echarts/src/Treemap/controlPanel.tsx @@ -28,7 +28,8 @@ import { } from '@superset-ui/chart-controls'; import { DEFAULT_FORM_DATA } from './types'; -const { labelType, numberFormat, showLabels, showUpperLabels, dateFormat } = DEFAULT_FORM_DATA; +const { labelType, numberFormat, showLabels, showUpperLabels, dateFormat } = + DEFAULT_FORM_DATA; const config: ControlPanelConfig = { controlPanelSections: [ @@ -46,7 +47,9 @@ const config: ControlPanelConfig = { config: { type: 'CheckboxControl', label: t('Sort by metric'), - description: t('Whether to sort results by the selected metric in descending order.'), + description: t( + 'Whether to sort results by the selected metric in descending order.', + ), }, }, ], @@ -111,9 +114,9 @@ const config: ControlPanelConfig = { renderTrigger: true, default: numberFormat, choices: D3_FORMAT_OPTIONS, - description: `${t('D3 format syntax: https://github.com/d3/d3-format. ')} ${t( - 'Only applies when "Label Type" is set to show values.', - )}`, + description: `${t( + 'D3 format syntax: https://github.com/d3/d3-format. ', + )} ${t('Only applies when "Label Type" is set to show values.')}`, }, }, ], diff --git a/plugins/plugin-chart-echarts/src/Treemap/transformProps.ts b/plugins/plugin-chart-echarts/src/Treemap/transformProps.ts index 00603fd140..95bd8fd6bb 100644 --- a/plugins/plugin-chart-echarts/src/Treemap/transformProps.ts +++ b/plugins/plugin-chart-echarts/src/Treemap/transformProps.ts @@ -108,7 +108,8 @@ export function formatTooltip({ export default function transformProps( chartProps: EchartsTreemapChartProps, ): TreemapTransformedProps { - const { formData, height, queriesData, width, hooks, filterState } = chartProps; + const { formData, height, queriesData, width, hooks, filterState } = + chartProps; const { data = [] } = queriesData[0]; const { setDataMask = () => {} } = hooks; const coltypeMapping = getColtypesMapping(queriesData[0]); @@ -158,7 +159,9 @@ export default function transformProps( const name = formatSeriesName(key, { numberFormatter, timeFormatter: getTimeFormatter(dateFormat), - ...(coltypeMapping[currGroupby] && { coltype: coltypeMapping[currGroupby] }), + ...(coltypeMapping[currGroupby] && { + coltype: coltypeMapping[currGroupby], + }), }); const item: TreemapSeriesNodeItemOption = { name, @@ -167,7 +170,10 @@ export default function transformProps( const joinedName = path.concat(name).join(','); // map(joined_name: [columnLabel_1, columnLabel_2, ...]) columnsLabelMap.set(joinedName, path.concat(name)); - if (filterState.selectedValues && !filterState.selectedValues.includes(joinedName)) { + if ( + filterState.selectedValues && + !filterState.selectedValues.includes(joinedName) + ) { item.itemStyle = { colorAlpha: OpacityEnum.SemiTransparent, }; @@ -187,13 +193,24 @@ export default function transformProps( const name = formatSeriesName(key, { numberFormatter, timeFormatter: getTimeFormatter(dateFormat), - ...(coltypeMapping[currGroupby] && { coltype: coltypeMapping[currGroupby] }), + ...(coltypeMapping[currGroupby] && { + coltype: coltypeMapping[currGroupby], + }), }); - const children = transformer(value, restGroupby, metric, depth + 1, path.concat(name)); + const children = transformer( + value, + restGroupby, + metric, + depth + 1, + path.concat(name), + ); result.push({ name, children, - value: children.reduce((prev, cur) => prev + (cur.value as number), 0), + value: children.reduce( + (prev, cur) => prev + (cur.value as number), + 0, + ), }); result.sort((a, b) => (b.value as number) - (a.value as number)); }, diff --git a/plugins/plugin-chart-echarts/src/components/Echart.tsx b/plugins/plugin-chart-echarts/src/components/Echart.tsx index 324bae6ce8..51ea5d5796 100644 --- a/plugins/plugin-chart-echarts/src/components/Echart.tsx +++ b/plugins/plugin-chart-echarts/src/components/Echart.tsx @@ -16,7 +16,13 @@ * specific language governing permissions and limitations * under the License. */ -import React, { useRef, useEffect, useMemo, forwardRef, useImperativeHandle } from 'react'; +import React, { + useRef, + useEffect, + useMemo, + forwardRef, + useImperativeHandle, +} from 'react'; import { styled } from '@superset-ui/core'; import { ECharts, init } from 'echarts'; import { EchartsHandler, EchartsProps, EchartsStylesProps } from '../types'; @@ -39,7 +45,10 @@ function Echart( ) { const divRef = useRef(null); const chartRef = useRef(); - const currentSelection = useMemo(() => Object.keys(selectedValues) || [], [selectedValues]); + const currentSelection = useMemo( + () => Object.keys(selectedValues) || [], + [selectedValues], + ); const previousSelection = useRef([]); useImperativeHandle(ref, () => ({ @@ -70,7 +79,9 @@ function Echart( if (!chartRef.current) return; chartRef.current.dispatchAction({ type: 'downplay', - dataIndex: previousSelection.current.filter(value => !currentSelection.includes(value)), + dataIndex: previousSelection.current.filter( + value => !currentSelection.includes(value), + ), }); if (currentSelection.length) { chartRef.current.dispatchAction({ diff --git a/plugins/plugin-chart-echarts/src/controls.tsx b/plugins/plugin-chart-echarts/src/controls.tsx index d5ce1a954e..76c7c42186 100644 --- a/plugins/plugin-chart-echarts/src/controls.tsx +++ b/plugins/plugin-chart-echarts/src/controls.tsx @@ -25,7 +25,8 @@ import { } from '@superset-ui/chart-controls'; import { DEFAULT_LEGEND_FORM_DATA } from './types'; -const { legendMargin, legendOrientation, legendType, showLegend } = DEFAULT_LEGEND_FORM_DATA; +const { legendMargin, legendOrientation, legendType, showLegend } = + DEFAULT_LEGEND_FORM_DATA; const showLegendControl = { name: 'show_legend', @@ -135,7 +136,11 @@ const onlyTotalControl = { }, }; -export const showValueSection = [[showValueControl], [stackControl], [onlyTotalControl]]; +export const showValueSection = [ + [showValueControl], + [stackControl], + [onlyTotalControl], +]; const richTooltipControl = { name: 'rich_tooltip', @@ -144,7 +149,9 @@ const richTooltipControl = { label: t('Rich tooltip'), renderTrigger: true, default: true, - description: t('Shows a list of all series available at that point in time'), + description: t( + 'Shows a list of all series available at that point in time', + ), }, }; @@ -165,7 +172,9 @@ const tooltipSortByMetricControl = { label: t('Tooltip sort by metric'), renderTrigger: true, default: false, - description: t('Whether to sort tooltip by the selected metric in descending order.'), + description: t( + 'Whether to sort tooltip by the selected metric in descending order.', + ), visibility: ({ controls }: ControlPanelsContainerProps) => Boolean(controls?.rich_tooltip?.value), }, diff --git a/plugins/plugin-chart-echarts/src/utils/annotation.ts b/plugins/plugin-chart-echarts/src/utils/annotation.ts index e13705fc12..9ccd7bb2db 100644 --- a/plugins/plugin-chart-echarts/src/utils/annotation.ts +++ b/plugins/plugin-chart-echarts/src/utils/annotation.ts @@ -76,10 +76,14 @@ export function extractRecordAnnotations( intervalEndColumn = '', timeColumn = '', titleColumn = '', - } = isTableAnnotationLayer(annotationLayer) ? annotationLayer : NATIVE_COLUMN_NAMES; + } = isTableAnnotationLayer(annotationLayer) + ? annotationLayer + : NATIVE_COLUMN_NAMES; return records.map(record => ({ - descriptions: descriptionColumns.map(column => (record[column] || '') as string) as string[], + descriptions: descriptionColumns.map( + column => (record[column] || '') as string, + ) as string[], intervalEnd: (record[intervalEndColumn] || '') as string, time: (record[timeColumn] || '') as string, title: (record[titleColumn] || '') as string, @@ -95,23 +99,33 @@ export function formatAnnotationLabel( ): string { const labels: string[] = []; const titleLabels: string[] = []; - const filteredDescriptions = descriptions.filter(description => !!description); + const filteredDescriptions = descriptions.filter( + description => !!description, + ); if (name) titleLabels.push(name); if (title) titleLabels.push(title); if (titleLabels.length > 0) labels.push(titleLabels.join(' - ')); - if (filteredDescriptions.length > 0) labels.push(filteredDescriptions.join('\n')); + if (filteredDescriptions.length > 0) + labels.push(filteredDescriptions.join('\n')); return labels.join('\n\n'); } -export function extractAnnotationLabels(layers: AnnotationLayer[], data: AnnotationData): string[] { +export function extractAnnotationLabels( + layers: AnnotationLayer[], + data: AnnotationData, +): string[] { const formulaAnnotationLabels = layers .filter(anno => anno.annotationType === AnnotationType.Formula && anno.show) .map(anno => anno.name); const timeseriesAnnotationLabels = layers - .filter(anno => anno.annotationType === AnnotationType.Timeseries && anno.show) + .filter( + anno => anno.annotationType === AnnotationType.Timeseries && anno.show, + ) .flatMap(anno => { const result = data[anno.name]; - return isTimeseriesAnnotationResult(result) ? result.map(annoSeries => annoSeries.key) : []; + return isTimeseriesAnnotationResult(result) + ? result.map(annoSeries => annoSeries.key) + : []; }); return formulaAnnotationLabels.concat(timeseriesAnnotationLabels); diff --git a/plugins/plugin-chart-echarts/src/utils/controls.ts b/plugins/plugin-chart-echarts/src/utils/controls.ts index c0385bf5c0..af91596b5e 100644 --- a/plugins/plugin-chart-echarts/src/utils/controls.ts +++ b/plugins/plugin-chart-echarts/src/utils/controls.ts @@ -20,7 +20,9 @@ import { validateNumber } from '@superset-ui/core'; // eslint-disable-next-line import/prefer-default-export -export function parseYAxisBound(bound?: string | number | null): number | undefined { +export function parseYAxisBound( + bound?: string | number | null, +): number | undefined { if (bound === undefined || bound === null || Number.isNaN(Number(bound))) { return undefined; } diff --git a/plugins/plugin-chart-echarts/src/utils/prophet.ts b/plugins/plugin-chart-echarts/src/utils/prophet.ts index fc6b4c1a4d..2f8acf3060 100644 --- a/plugins/plugin-chart-echarts/src/utils/prophet.ts +++ b/plugins/plugin-chart-echarts/src/utils/prophet.ts @@ -19,13 +19,19 @@ import { TimeseriesDataRecord, NumberFormatter } from '@superset-ui/core'; import { CallbackDataParams, OptionName } from 'echarts/types/src/util/types'; import { TooltipMarker } from 'echarts/types/src/util/format'; -import { ForecastSeriesContext, ForecastSeriesEnum, ProphetValue } from '../types'; +import { + ForecastSeriesContext, + ForecastSeriesEnum, + ProphetValue, +} from '../types'; import { sanitizeHtml } from './series'; const seriesTypeRegex = new RegExp( `(.+)(${ForecastSeriesEnum.ForecastLower}|${ForecastSeriesEnum.ForecastTrend}|${ForecastSeriesEnum.ForecastUpper})$`, ); -export const extractForecastSeriesContext = (seriesName: OptionName): ForecastSeriesContext => { +export const extractForecastSeriesContext = ( + seriesName: OptionName, +): ForecastSeriesContext => { const name = seriesName as string; const regexMatch = seriesTypeRegex.exec(name); if (!regexMatch) return { name, type: ForecastSeriesEnum.Observation }; @@ -59,7 +65,8 @@ export const extractProphetValuesFromTooltipParams = ( marker: marker || '', }; const prophetValues = values[context.name]; - if (context.type === ForecastSeriesEnum.Observation) prophetValues.observation = numericValue; + if (context.type === ForecastSeriesEnum.Observation) + prophetValues.observation = numericValue; if (context.type === ForecastSeriesEnum.ForecastTrend) prophetValues.forecastTrend = numericValue; if (context.type === ForecastSeriesEnum.ForecastLower) @@ -123,7 +130,8 @@ export function rebaseTimeseriesDatum( ) { value -= row[lowerKey] as number; } - const newKey = key !== '__timestamp' && verboseMap[key] ? verboseMap[key] : key; + const newKey = + key !== '__timestamp' && verboseMap[key] ? verboseMap[key] : key; newRow[newKey] = value; }); // eslint-disable-next-line @typescript-eslint/no-unsafe-return diff --git a/plugins/plugin-chart-echarts/src/utils/series.ts b/plugins/plugin-chart-echarts/src/utils/series.ts index 552046d4d5..8eb1516e0b 100644 --- a/plugins/plugin-chart-echarts/src/utils/series.ts +++ b/plugins/plugin-chart-echarts/src/utils/series.ts @@ -43,7 +43,10 @@ export function extractTimeseriesSeries( if (data.length === 0) return []; const rows: TimeseriesDataRecord[] = data.map(datum => ({ ...datum, - __timestamp: datum.__timestamp || datum.__timestamp === 0 ? new Date(datum.__timestamp) : null, + __timestamp: + datum.__timestamp || datum.__timestamp === 0 + ? new Date(datum.__timestamp) + : null, })); return Object.keys(rows[0]) @@ -56,7 +59,9 @@ export function extractTimeseriesSeries( isDefined(rows[idx - 1]?.[key]) || isDefined(rows[idx + 1]?.[key]); return [ row.__timestamp, - !isDefined(row[key]) && isNextToDefinedValue && fillNeighborValue !== undefined + !isDefined(row[key]) && + isNextToDefinedValue && + fillNeighborValue !== undefined ? fillNeighborValue : row[key], ]; @@ -97,7 +102,10 @@ export const getColtypesMapping = ({ coltypes = [], colnames = [], }: ChartDataResponseResult): Record => - colnames.reduce((accumulator, item, index) => ({ ...accumulator, [item]: coltypes[index] }), {}); + colnames.reduce( + (accumulator, item, index) => ({ ...accumulator, [item]: coltypes[index] }), + {}, + ); export function extractGroupbyLabel({ datum = {}, @@ -130,7 +138,9 @@ export function getLegendProps( zoomable = false, ): LegendComponentOption | LegendComponentOption[] { const legend: LegendComponentOption | LegendComponentOption[] = { - orient: [LegendOrientation.Top, LegendOrientation.Bottom].includes(orientation) + orient: [LegendOrientation.Top, LegendOrientation.Bottom].includes( + orientation, + ) ? 'horizontal' : 'vertical', show, @@ -170,7 +180,11 @@ export function getChartPadding( let legendMargin; if (!show) { legendMargin = 0; - } else if (margin === null || margin === undefined || typeof margin === 'string') { + } else if ( + margin === null || + margin === undefined || + typeof margin === 'string' + ) { legendMargin = defaultLegendPadding[orientation]; } else { legendMargin = margin; @@ -181,7 +195,8 @@ export function getChartPadding( left: left + (orientation === LegendOrientation.Left ? legendMargin : 0), right: right + (orientation === LegendOrientation.Right ? legendMargin : 0), top: top + (orientation === LegendOrientation.Top ? legendMargin : 0), - bottom: bottom + (orientation === LegendOrientation.Bottom ? legendMargin : 0), + bottom: + bottom + (orientation === LegendOrientation.Bottom ? legendMargin : 0), }; } diff --git a/plugins/plugin-chart-echarts/test/BoxPlot/transformProps.test.ts b/plugins/plugin-chart-echarts/test/BoxPlot/transformProps.test.ts index 6fc4f26a8d..7ddeb0b5c9 100644 --- a/plugins/plugin-chart-echarts/test/BoxPlot/transformProps.test.ts +++ b/plugins/plugin-chart-echarts/test/BoxPlot/transformProps.test.ts @@ -79,11 +79,29 @@ describe('BoxPlot tranformProps', () => { data: expect.arrayContaining([ expect.objectContaining({ name: 'organic, Charlotte', - value: [1.4775, 1.73875, 1.9025, 2.105, 2.505, 1.9405512820512825, 39, [2.735]], + value: [ + 1.4775, + 1.73875, + 1.9025, + 2.105, + 2.505, + 1.9405512820512825, + 39, + [2.735], + ], }), expect.objectContaining({ name: 'organic, Hartford Springfield', - value: [1.862, 2.1285, 2.265, 2.32625, 2.595, 2.231141025641026, 39, []], + value: [ + 1.862, + 2.1285, + 2.265, + 2.32625, + 2.595, + 2.231141025641026, + 39, + [], + ], }), ]), }), diff --git a/plugins/plugin-chart-echarts/test/Funnel/transformProps.test.ts b/plugins/plugin-chart-echarts/test/Funnel/transformProps.test.ts index 5a28836a15..1ee293474e 100644 --- a/plugins/plugin-chart-echarts/test/Funnel/transformProps.test.ts +++ b/plugins/plugin-chart-echarts/test/Funnel/transformProps.test.ts @@ -17,7 +17,9 @@ * under the License. */ import { ChartProps, getNumberFormatter } from '@superset-ui/core'; -import transformProps, { formatFunnelLabel } from '../../src/Funnel/transformProps'; +import transformProps, { + formatFunnelLabel, +} from '../../src/Funnel/transformProps'; import { EchartsFunnelLabelTypeType } from '../../src/Funnel/types'; describe('Funnel tranformProps', () => { @@ -73,13 +75,25 @@ describe('formatFunnelLabel', () => { const numberFormatter = getNumberFormatter(); const params = { name: 'My Label', value: 1234, percent: 12.34 }; expect( - formatFunnelLabel({ params, numberFormatter, labelType: EchartsFunnelLabelTypeType.Key }), + formatFunnelLabel({ + params, + numberFormatter, + labelType: EchartsFunnelLabelTypeType.Key, + }), ).toEqual('My Label'); expect( - formatFunnelLabel({ params, numberFormatter, labelType: EchartsFunnelLabelTypeType.Value }), + formatFunnelLabel({ + params, + numberFormatter, + labelType: EchartsFunnelLabelTypeType.Value, + }), ).toEqual('1.23k'); expect( - formatFunnelLabel({ params, numberFormatter, labelType: EchartsFunnelLabelTypeType.Percent }), + formatFunnelLabel({ + params, + numberFormatter, + labelType: EchartsFunnelLabelTypeType.Percent, + }), ).toEqual('12.34%'); expect( formatFunnelLabel({ diff --git a/plugins/plugin-chart-echarts/test/Graph/buildQuery.test.ts b/plugins/plugin-chart-echarts/test/Graph/buildQuery.test.ts index f7230569d5..b8471c4d93 100644 --- a/plugins/plugin-chart-echarts/test/Graph/buildQuery.test.ts +++ b/plugins/plugin-chart-echarts/test/Graph/buildQuery.test.ts @@ -56,7 +56,11 @@ describe('Graph buildQuery', () => { }; const queryContext = buildQuery(formDataWithCategories); const [query] = queryContext.queries; - expect(query.columns).toEqual(['dummy_source', 'dummy_target', 'dummy_source_category']); + expect(query.columns).toEqual([ + 'dummy_source', + 'dummy_target', + 'dummy_source_category', + ]); expect(query.metrics).toEqual(['foo', 'bar']); }); @@ -69,12 +73,20 @@ describe('Graph buildQuery', () => { }; const queryContext = buildQuery(formDataWithCategories); const [query] = queryContext.queries; - expect(query.columns).toEqual(['dummy_source', 'dummy_target', 'dummy_target_category']); + expect(query.columns).toEqual([ + 'dummy_source', + 'dummy_target', + 'dummy_target_category', + ]); expect(query.metrics).toEqual(['foo', 'bar']); }); it('should build groupby without any category', () => { - const formDataWithCategories = { ...formData, source: 'dummy_source', target: 'dummy_target' }; + const formDataWithCategories = { + ...formData, + source: 'dummy_source', + target: 'dummy_target', + }; const queryContext = buildQuery(formDataWithCategories); const [query] = queryContext.queries; expect(query.columns).toEqual(['dummy_source', 'dummy_target']); diff --git a/plugins/plugin-chart-echarts/test/Graph/transformProps.test.ts b/plugins/plugin-chart-echarts/test/Graph/transformProps.test.ts index 7bf475aadd..bb73d77f11 100644 --- a/plugins/plugin-chart-echarts/test/Graph/transformProps.test.ts +++ b/plugins/plugin-chart-echarts/test/Graph/transformProps.test.ts @@ -126,7 +126,9 @@ describe('EchartsGraph tranformProps', () => { { emphasis: { lineStyle: { width: 12 } }, lineStyle: { width: 6 }, - select: { lineStyle: { opacity: 1, width: 9.600000000000001 } }, + select: { + lineStyle: { opacity: 1, width: 9.600000000000001 }, + }, source: '0', target: '1', value: 6, diff --git a/plugins/plugin-chart-echarts/test/Pie/transformProps.test.ts b/plugins/plugin-chart-echarts/test/Pie/transformProps.test.ts index 60047dbf54..a2b429b4a3 100644 --- a/plugins/plugin-chart-echarts/test/Pie/transformProps.test.ts +++ b/plugins/plugin-chart-echarts/test/Pie/transformProps.test.ts @@ -16,7 +16,11 @@ * specific language governing permissions and limitations * under the License. */ -import { ChartProps, getNumberFormatter, SqlaFormData } from '@superset-ui/core'; +import { + ChartProps, + getNumberFormatter, + SqlaFormData, +} from '@superset-ui/core'; import transformProps, { formatPieLabel } from '../../src/Pie/transformProps'; import { EchartsPieLabelType } from '../../src/Pie/types'; @@ -74,23 +78,47 @@ describe('formatPieLabel', () => { it('should generate a valid pie chart label', () => { const numberFormatter = getNumberFormatter(); const params = { name: 'My Label', value: 1234, percent: 12.34 }; - expect(formatPieLabel({ params, numberFormatter, labelType: EchartsPieLabelType.Key })).toEqual( - 'My Label', - ); expect( - formatPieLabel({ params, numberFormatter, labelType: EchartsPieLabelType.Value }), + formatPieLabel({ + params, + numberFormatter, + labelType: EchartsPieLabelType.Key, + }), + ).toEqual('My Label'); + expect( + formatPieLabel({ + params, + numberFormatter, + labelType: EchartsPieLabelType.Value, + }), ).toEqual('1.23k'); expect( - formatPieLabel({ params, numberFormatter, labelType: EchartsPieLabelType.Percent }), + formatPieLabel({ + params, + numberFormatter, + labelType: EchartsPieLabelType.Percent, + }), ).toEqual('12.34%'); expect( - formatPieLabel({ params, numberFormatter, labelType: EchartsPieLabelType.KeyValue }), + formatPieLabel({ + params, + numberFormatter, + labelType: EchartsPieLabelType.KeyValue, + }), ).toEqual('My Label: 1.23k'); expect( - formatPieLabel({ params, numberFormatter, labelType: EchartsPieLabelType.KeyPercent }), + formatPieLabel({ + params, + numberFormatter, + labelType: EchartsPieLabelType.KeyPercent, + }), ).toEqual('My Label: 12.34%'); expect( - formatPieLabel({ params, numberFormatter, labelType: EchartsPieLabelType.KeyValuePercent }), + formatPieLabel({ + params, + numberFormatter, + labelType: EchartsPieLabelType.KeyValuePercent, + }), ).toEqual('My Label: 1.23k (12.34%)'); expect( formatPieLabel({ diff --git a/plugins/plugin-chart-echarts/test/Timeseries/transformProps.test.ts b/plugins/plugin-chart-echarts/test/Timeseries/transformProps.test.ts index aeb76714a6..96c5865d76 100644 --- a/plugins/plugin-chart-echarts/test/Timeseries/transformProps.test.ts +++ b/plugins/plugin-chart-echarts/test/Timeseries/transformProps.test.ts @@ -173,7 +173,13 @@ describe('EchartsTimeseries tranformProps', () => { ...queriesData[0], annotation_data: { 'My Event': { - columns: ['start_dttm', 'end_dttm', 'short_descr', 'long_descr', 'json_metadata'], + columns: [ + 'start_dttm', + 'end_dttm', + 'short_descr', + 'long_descr', + 'json_metadata', + ], records: [ { start_dttm: 0, diff --git a/plugins/plugin-chart-echarts/test/Tree/transformProps.test.ts b/plugins/plugin-chart-echarts/test/Tree/transformProps.test.ts index ce84ca6121..bcb762b68c 100644 --- a/plugins/plugin-chart-echarts/test/Tree/transformProps.test.ts +++ b/plugins/plugin-chart-echarts/test/Tree/transformProps.test.ts @@ -87,7 +87,9 @@ describe('EchartsTree tranformProps', () => { { name: 'second_child', value: 10, - children: [{ name: 'third_child', value: 10, children: [] }], + children: [ + { name: 'third_child', value: 10, children: [] }, + ], }, ], }, diff --git a/plugins/plugin-chart-echarts/test/utils/annotation.test.ts b/plugins/plugin-chart-echarts/test/utils/annotation.test.ts index 0a09a5f05f..96a75b7e93 100644 --- a/plugins/plugin-chart-echarts/test/utils/annotation.test.ts +++ b/plugins/plugin-chart-echarts/test/utils/annotation.test.ts @@ -48,16 +48,24 @@ describe('formatAnnotationLabel', () => { expect(formatAnnotationLabel('name', undefined, ['description'])).toEqual( 'name\n\ndescription', ); - expect(formatAnnotationLabel(undefined, undefined, ['description'])).toEqual('description'); + expect( + formatAnnotationLabel(undefined, undefined, ['description']), + ).toEqual('description'); }); it('should handle multiple descriptions properly', () => { - expect(formatAnnotationLabel('name', 'title', ['description 1', 'description 2'])).toEqual( - 'name - title\n\ndescription 1\ndescription 2', - ); - expect(formatAnnotationLabel(undefined, undefined, ['description 1', 'description 2'])).toEqual( - 'description 1\ndescription 2', - ); + expect( + formatAnnotationLabel('name', 'title', [ + 'description 1', + 'description 2', + ]), + ).toEqual('name - title\n\ndescription 1\ndescription 2'); + expect( + formatAnnotationLabel(undefined, undefined, [ + 'description 1', + 'description 2', + ]), + ).toEqual('description 1\ndescription 2'); }); }); @@ -124,7 +132,11 @@ describe('extractAnnotationLabels', () => { ], }; - expect(extractAnnotationLabels(layers, results)).toEqual(['My Formula', 'Line 1', 'Line 2']); + expect(extractAnnotationLabels(layers, results)).toEqual([ + 'My Formula', + 'Line 1', + 'Line 2', + ]); }); }); @@ -137,7 +149,10 @@ describe('evalFormula', () => { value: 'x+1', }; it('Should evaluate a regular formula', () => { - const data: TimeseriesDataRecord[] = [{ __timestamp: 0 }, { __timestamp: 10 }]; + const data: TimeseriesDataRecord[] = [ + { __timestamp: 0 }, + { __timestamp: 10 }, + ]; expect(evalFormula(layer, data)).toEqual([ [new Date(0), 1], @@ -146,7 +161,10 @@ describe('evalFormula', () => { }); it('Should evaluate a formula containing redundant characters', () => { - const data: TimeseriesDataRecord[] = [{ __timestamp: 0 }, { __timestamp: 10 }]; + const data: TimeseriesDataRecord[] = [ + { __timestamp: 0 }, + { __timestamp: 10 }, + ]; expect(evalFormula({ ...layer, value: 'y = x* 2 -1' }, data)).toEqual([ [new Date(0), -1], diff --git a/plugins/plugin-chart-echarts/test/utils/series.test.ts b/plugins/plugin-chart-echarts/test/utils/series.test.ts index 3987078a2e..91b9872ec8 100644 --- a/plugins/plugin-chart-echarts/test/utils/series.test.ts +++ b/plugins/plugin-chart-echarts/test/utils/series.test.ts @@ -137,13 +137,18 @@ describe('extractTimeseriesSeries', () => { describe('extractGroupbyLabel', () => { it('should join together multiple groupby labels', () => { - expect(extractGroupbyLabel({ datum: { a: 'abc', b: 'qwerty' }, groupby: ['a', 'b'] })).toEqual( - 'abc, qwerty', - ); + expect( + extractGroupbyLabel({ + datum: { a: 'abc', b: 'qwerty' }, + groupby: ['a', 'b'], + }), + ).toEqual('abc, qwerty'); }); it('should handle a single groupby', () => { - expect(extractGroupbyLabel({ datum: { xyz: 'qqq' }, groupby: ['xyz'] })).toEqual('qqq'); + expect( + extractGroupbyLabel({ datum: { xyz: 'qqq' }, groupby: ['xyz'] }), + ).toEqual('qqq'); }); it('should handle mixed types', () => { @@ -191,7 +196,9 @@ describe('formatSeriesName', () => { }); it('should use default formatting for for date values without formatter', () => { - expect(formatSeriesName(new Date('2020-09-11'))).toEqual('2020-09-11T00:00:00.000Z'); + expect(formatSeriesName(new Date('2020-09-11'))).toEqual( + '2020-09-11T00:00:00.000Z', + ); }); it('should use timeFormatter for date values when formatter is provided', () => { @@ -202,7 +209,9 @@ describe('formatSeriesName', () => { describe('getLegendProps', () => { it('should return the correct props for scroll type with top orientation without zoom', () => { - expect(getLegendProps(LegendType.Scroll, LegendOrientation.Top, true, false)).toEqual({ + expect( + getLegendProps(LegendType.Scroll, LegendOrientation.Top, true, false), + ).toEqual({ show: true, top: 0, right: 0, @@ -212,7 +221,9 @@ describe('formatSeriesName', () => { }); it('should return the correct props for scroll type with top orientation with zoom', () => { - expect(getLegendProps(LegendType.Scroll, LegendOrientation.Top, true, true)).toEqual({ + expect( + getLegendProps(LegendType.Scroll, LegendOrientation.Top, true, true), + ).toEqual({ show: true, top: 0, right: 55, @@ -222,7 +233,9 @@ describe('formatSeriesName', () => { }); it('should return the correct props for plain type with left orientation', () => { - expect(getLegendProps(LegendType.Plain, LegendOrientation.Left, true)).toEqual({ + expect( + getLegendProps(LegendType.Plain, LegendOrientation.Left, true), + ).toEqual({ show: true, left: 0, orient: 'vertical', @@ -231,7 +244,9 @@ describe('formatSeriesName', () => { }); it('should return the correct props for plain type with right orientation without zoom', () => { - expect(getLegendProps(LegendType.Plain, LegendOrientation.Right, false, false)).toEqual({ + expect( + getLegendProps(LegendType.Plain, LegendOrientation.Right, false, false), + ).toEqual({ show: false, right: 0, top: 0, @@ -241,7 +256,9 @@ describe('formatSeriesName', () => { }); it('should return the correct props for plain type with right orientation with zoom', () => { - expect(getLegendProps(LegendType.Plain, LegendOrientation.Right, false, true)).toEqual({ + expect( + getLegendProps(LegendType.Plain, LegendOrientation.Right, false, true), + ).toEqual({ show: false, right: 0, top: 30, @@ -251,7 +268,9 @@ describe('formatSeriesName', () => { }); it('should return the correct props for plain type with bottom orientation', () => { - expect(getLegendProps(LegendType.Plain, LegendOrientation.Bottom, false)).toEqual({ + expect( + getLegendProps(LegendType.Plain, LegendOrientation.Bottom, false), + ).toEqual({ show: false, bottom: 0, orient: 'horizontal', @@ -349,7 +368,12 @@ describe('formatSeriesName', () => { id: 'foo', }, ]), - ).toEqual([{ id: 'foo' }, { id: 'bar' }, { id: 'foo (1)' }, { id: 'foo (2)' }]); + ).toEqual([ + { id: 'foo' }, + { id: 'bar' }, + { id: 'foo (1)' }, + { id: 'foo (2)' }, + ]); }); }); diff --git a/plugins/plugin-chart-pivot-table/src/PivotTableChart.tsx b/plugins/plugin-chart-pivot-table/src/PivotTableChart.tsx index 92565a565f..e04d471f88 100644 --- a/plugins/plugin-chart-pivot-table/src/PivotTableChart.tsx +++ b/plugins/plugin-chart-pivot-table/src/PivotTableChart.tsx @@ -28,8 +28,11 @@ import { } from '@superset-ui/core'; // @ts-ignore import PivotTable from '@superset-ui/react-pivottable/PivotTable'; -// @ts-ignore -import { sortAs, aggregatorTemplates } from '@superset-ui/react-pivottable/Utilities'; +import { + sortAs, + aggregatorTemplates, + // @ts-ignore +} from '@superset-ui/react-pivottable/Utilities'; import '@superset-ui/react-pivottable/pivottable.css'; import { FilterType, @@ -43,7 +46,9 @@ const Styles = styled.div` ${({ height, width, margin }) => ` margin: ${margin}px; height: ${height - margin * 2}px; - width: ${typeof width === 'string' ? parseInt(width, 10) : width - margin * 2}px; + width: ${ + typeof width === 'string' ? parseInt(width, 10) : width - margin * 2 + }px; `} `; @@ -140,7 +145,10 @@ export default function PivotTableChart(props: PivotTableProps) { const metricFormatters = hasCustomMetricFormatters && Object.fromEntries( - columnFormatsArray.map(([metric, format]) => [metric, getNumberFormatter(format)]), + columnFormatsArray.map(([metric, format]) => [ + metric, + getNumberFormatter(format), + ]), ); const metricNames = useMemo( @@ -169,7 +177,9 @@ export default function PivotTableChart(props: PivotTableProps) { [data, metricNames], ); - let [rows, cols] = transposePivot ? [groupbyColumns, groupbyRows] : [groupbyRows, groupbyColumns]; + let [rows, cols] = transposePivot + ? [groupbyColumns, groupbyRows] + : [groupbyRows, groupbyColumns]; if (metricsLayout === MetricsLayoutEnum.ROWS) { rows = combineMetric ? [...rows, METRIC_KEY] : [METRIC_KEY, ...rows]; @@ -200,8 +210,12 @@ export default function PivotTableChart(props: PivotTableProps) { }), }, filterState: { - value: filters && Object.keys(filters).length ? Object.values(filters) : null, - selectedFilters: filters && Object.keys(filters).length ? filters : null, + value: + filters && Object.keys(filters).length + ? Object.values(filters) + : null, + selectedFilters: + filters && Object.keys(filters).length ? filters : null, }, }); }, @@ -249,7 +263,10 @@ export default function PivotTableChart(props: PivotTableProps) { [key]: [val], }; } - if (Array.isArray(updatedFilters[key]) && updatedFilters[key].length === 0) { + if ( + Array.isArray(updatedFilters[key]) && + updatedFilters[key].length === 0 + ) { delete updatedFilters[key]; } handleChange(updatedFilters); @@ -267,7 +284,9 @@ export default function PivotTableChart(props: PivotTableProps) { aggregatorsFactory={aggregatorsFactory} defaultFormatter={defaultFormatter} customFormatters={ - hasCustomMetricFormatters ? { [METRIC_KEY]: metricFormatters } : undefined + hasCustomMetricFormatters + ? { [METRIC_KEY]: metricFormatters } + : undefined } aggregatorName={aggregateFunction} vals={['value']} diff --git a/plugins/plugin-chart-pivot-table/src/plugin/buildQuery.ts b/plugins/plugin-chart-pivot-table/src/plugin/buildQuery.ts index 04e7274b04..43b55a1ffa 100644 --- a/plugins/plugin-chart-pivot-table/src/plugin/buildQuery.ts +++ b/plugins/plugin-chart-pivot-table/src/plugin/buildQuery.ts @@ -25,18 +25,29 @@ import { import { PivotTableQueryFormData } from '../types'; export default function buildQuery(formData: PivotTableQueryFormData) { - const { groupbyColumns = [], groupbyRows = [], order_desc = true, legacy_order_by } = formData; + const { + groupbyColumns = [], + groupbyRows = [], + order_desc = true, + legacy_order_by, + } = formData; const groupbySet = new Set([ ...ensureIsArray(groupbyColumns), ...ensureIsArray(groupbyRows), ]); return buildQueryContext(formData, baseQueryObject => { - const queryObject = normalizeOrderBy({ ...baseQueryObject, order_desc, legacy_order_by }); + const queryObject = normalizeOrderBy({ + ...baseQueryObject, + order_desc, + legacy_order_by, + }); const { metrics } = queryObject; const orderBy = ensureIsArray(legacy_order_by); if ( orderBy.length && - !metrics?.find(metric => getMetricLabel(metric) === getMetricLabel(orderBy[0])) + !metrics?.find( + metric => getMetricLabel(metric) === getMetricLabel(orderBy[0]), + ) ) { metrics?.push(orderBy[0]); } diff --git a/plugins/plugin-chart-pivot-table/src/plugin/controlPanel.ts b/plugins/plugin-chart-pivot-table/src/plugin/controlPanel.ts index 812d23cfa0..e8ff6266d5 100644 --- a/plugins/plugin-chart-pivot-table/src/plugin/controlPanel.ts +++ b/plugins/plugin-chart-pivot-table/src/plugin/controlPanel.ts @@ -16,7 +16,12 @@ * specific language governing permissions and limitations * under the License. */ -import { QueryFormMetric, smartDateFormatter, t, validateNonEmpty } from '@superset-ui/core'; +import { + QueryFormMetric, + smartDateFormatter, + t, + validateNonEmpty, +} from '@superset-ui/core'; import { ControlPanelConfig, D3_TIME_FORMAT_OPTIONS, @@ -76,7 +81,9 @@ const config: ControlPanelConfig = { [MetricsLayoutEnum.COLUMNS, t('Columns')], [MetricsLayoutEnum.ROWS, t('Rows')], ], - description: t('Use metrics as a top level group for columns or for rows'), + description: t( + 'Use metrics as a top level group for columns or for rows', + ), }, }, ], @@ -193,7 +200,10 @@ const config: ControlPanelConfig = { [ { name: 'valueFormat', - config: { ...sharedControls.y_axis_format, label: t('Value format') }, + config: { + ...sharedControls.y_axis_format, + label: t('Value format'), + }, }, ], [ @@ -291,7 +301,9 @@ const config: ControlPanelConfig = { label: t('Conditional formatting'), description: t('Apply conditional color formatting to metrics'), mapStateToProps(explore) { - const values = (explore?.controls?.metrics?.value as QueryFormMetric[]) ?? []; + const values = + (explore?.controls?.metrics?.value as QueryFormMetric[]) ?? + []; const verboseMap = explore?.datasource?.verbose_map ?? {}; const metricColumn = values.map(value => { if (typeof value === 'string') { diff --git a/plugins/plugin-chart-pivot-table/src/plugin/transformProps.ts b/plugins/plugin-chart-pivot-table/src/plugin/transformProps.ts index 1b74e14c0f..8666705b7a 100644 --- a/plugins/plugin-chart-pivot-table/src/plugin/transformProps.ts +++ b/plugins/plugin-chart-pivot-table/src/plugin/transformProps.ts @@ -34,7 +34,10 @@ const { DATABASE_DATETIME } = TimeFormats; function isNumeric(key: string, data: DataRecord[] = []) { return data.every( - record => record[key] === null || record[key] === undefined || typeof record[key] === 'number', + record => + record[key] === null || + record[key] === undefined || + typeof record[key] === 'number', ); } @@ -103,27 +106,36 @@ export default function transformProps(chartProps: ChartProps) { const granularity = extractTimegrain(rawFormData); const dateFormatters = colnames - .filter((colname: string, index: number) => coltypes[index] === GenericDataType.TEMPORAL) - .reduce((acc: Record, temporalColname: string) => { - let formatter: DateFormatter | undefined; - if (dateFormat === smartDateFormatter.id) { - if (granularity) { - // time column use formats based on granularity - formatter = getTimeFormatterForGranularity(granularity); - } else if (isNumeric(temporalColname, data)) { - formatter = getTimeFormatter(DATABASE_DATETIME); - } else { - // if no column-specific format, print cell as is - formatter = String; + .filter( + (colname: string, index: number) => + coltypes[index] === GenericDataType.TEMPORAL, + ) + .reduce( + ( + acc: Record, + temporalColname: string, + ) => { + let formatter: DateFormatter | undefined; + if (dateFormat === smartDateFormatter.id) { + if (granularity) { + // time column use formats based on granularity + formatter = getTimeFormatterForGranularity(granularity); + } else if (isNumeric(temporalColname, data)) { + formatter = getTimeFormatter(DATABASE_DATETIME); + } else { + // if no column-specific format, print cell as is + formatter = String; + } + } else if (dateFormat) { + formatter = getTimeFormatter(dateFormat); } - } else if (dateFormat) { - formatter = getTimeFormatter(dateFormat); - } - if (formatter) { - acc[temporalColname] = formatter; - } - return acc; - }, {}); + if (formatter) { + acc[temporalColname] = formatter; + } + return acc; + }, + {}, + ); const metricColorFormatters = getColorFormatters(conditionalFormatting, data); return { diff --git a/plugins/plugin-chart-pivot-table/src/types.ts b/plugins/plugin-chart-pivot-table/src/types.ts index bd484901e5..b9f1c8d768 100644 --- a/plugins/plugin-chart-pivot-table/src/types.ts +++ b/plugins/plugin-chart-pivot-table/src/types.ts @@ -38,7 +38,10 @@ export interface PivotTableStylesProps { export type FilterType = Record; export type SelectedFiltersType = Record; -export type DateFormatter = TimeFormatter | NumberFormatter | ((value: DataRecordValue) => string); +export type DateFormatter = + | TimeFormatter + | NumberFormatter + | ((value: DataRecordValue) => string); export enum MetricsLayoutEnum { ROWS = 'ROWS', COLUMNS = 'COLUMNS', diff --git a/plugins/plugin-chart-table/src/DataTable/DataTable.tsx b/plugins/plugin-chart-table/src/DataTable/DataTable.tsx index d0003d3d4f..90d876d242 100644 --- a/plugins/plugin-chart-table/src/DataTable/DataTable.tsx +++ b/plugins/plugin-chart-table/src/DataTable/DataTable.tsx @@ -37,7 +37,10 @@ import { } from 'react-table'; import { matchSorter, rankings } from 'match-sorter'; import GlobalFilter, { GlobalFilterProps } from './components/GlobalFilter'; -import SelectPageSize, { SelectPageSizeProps, SizeOption } from './components/SelectPageSize'; +import SelectPageSize, { + SelectPageSizeProps, + SizeOption, +} from './components/SelectPageSize'; import SimplePagination from './components/Pagination'; import useSticky from './hooks/useSticky'; import { PAGE_SIZE_OPTIONS } from '../consts'; @@ -140,7 +143,8 @@ export default function DataTable({ const defaultGlobalFilter: FilterType = useCallback( (rows: Row[], columnIds: IdType[], filterValue: string) => { // allow searching by "col1_value col2_value" - const joinedString = (row: Row) => columnIds.map(x => row.values[x]).join(' '); + const joinedString = (row: Row) => + columnIds.map(x => row.values[x]).join(' '); return matchSorter(rows, filterValue, { keys: [...columnIds, joinedString], threshold: rankings.ACRONYM, @@ -186,12 +190,16 @@ export default function DataTable({ }; const noResults = - typeof noResultsText === 'function' ? noResultsText(filterValue as string) : noResultsText; + typeof noResultsText === 'function' + ? noResultsText(filterValue as string) + : noResultsText; const getNoResults = () =>
{noResults}
; if (!columns || columns.length === 0) { - return (wrapStickyTable ? wrapStickyTable(getNoResults) : getNoResults()) as JSX.Element; + return ( + wrapStickyTable ? wrapStickyTable(getNoResults) : getNoResults() + ) as JSX.Element; } const shouldRenderFooter = columns.some(x => !!x.Footer); @@ -200,7 +208,8 @@ export default function DataTable({
" + @@ -116,11 +124,13 @@ export function generateRichLineTooltipContent(d, timeFormatter, valueFormatter) const key = getFormattedKey(series.key, true); tooltip += `
` + + `` + '
' + '
${key}
` + + `` + '
' + '
${key}
${series.key === 'TOTAL' ? '' : '◼'}${ + series.key === 'TOTAL' ? '' : '◼' + }${key}${valueFormatter(series.value)}${((100 * series.value) / total).toFixed(2)}%
{headerGroups.map(headerGroup => { - const { key: headerGroupKey, ...headerGroupProps } = headerGroup.getHeaderGroupProps(); + const { key: headerGroupKey, ...headerGroupProps } = + headerGroup.getHeaderGroupProps(); return ( {headerGroup.headers.map(column => @@ -220,7 +229,9 @@ export default function DataTable({ const { key: rowKey, ...rowProps } = row.getRowProps(); return ( - {row.cells.map(cell => cell.render('Cell', { key: cell.column.id }))} + {row.cells.map(cell => + cell.render('Cell', { key: cell.column.id }), + )} ); }) @@ -235,10 +246,13 @@ export default function DataTable({ {shouldRenderFooter && ( {footerGroups.map(footerGroup => { - const { key: footerGroupKey, ...footerGroupProps } = footerGroup.getHeaderGroupProps(); + const { key: footerGroupKey, ...footerGroupProps } = + footerGroup.getHeaderGroupProps(); return ( - {footerGroup.headers.map(column => column.render('Footer', { key: column.id }))} + {footerGroup.headers.map(column => + column.render('Footer', { key: column.id }), + )} ); })} @@ -258,7 +272,9 @@ export default function DataTable({ setPageSize(initialPageSize); } - const paginationStyle: CSSProperties = sticky.height ? {} : { visibility: 'hidden' }; + const paginationStyle: CSSProperties = sticky.height + ? {} + : { visibility: 'hidden' }; let resultPageCount = pageCount; let resultCurrentPageSize = pageSize; @@ -282,7 +298,10 @@ export default function DataTable({ onServerPaginationChange(pageNumber, serverPageSize); } return ( -
+
{hasGlobalControl ? (
@@ -292,7 +311,11 @@ export default function DataTable({ total={resultsSize} current={resultCurrentPageSize} options={pageSizeOptions} - selectRenderer={typeof selectPageSize === 'boolean' ? undefined : selectPageSize} + selectRenderer={ + typeof selectPageSize === 'boolean' + ? undefined + : selectPageSize + } onChange={setPageSize} /> ) : null} @@ -300,7 +323,9 @@ export default function DataTable({ {searchInput ? (
- searchInput={typeof searchInput === 'boolean' ? undefined : searchInput} + searchInput={ + typeof searchInput === 'boolean' ? undefined : searchInput + } preGlobalFilteredRows={preGlobalFilteredRows} setGlobalFilter={setGlobalFilter} filterValue={filterValue} diff --git a/plugins/plugin-chart-table/src/DataTable/components/GlobalFilter.tsx b/plugins/plugin-chart-table/src/DataTable/components/GlobalFilter.tsx index e166813b83..8e36905ee8 100644 --- a/plugins/plugin-chart-table/src/DataTable/components/GlobalFilter.tsx +++ b/plugins/plugin-chart-table/src/DataTable/components/GlobalFilter.tsx @@ -49,7 +49,9 @@ function DefaultSearchInput({ count, value, onChange }: SearchInputProps) { ); } -export default (React.memo as (fn: T) => T)(function GlobalFilter({ +export default (React.memo as (fn: T) => T)(function GlobalFilter< + D extends object, +>({ preGlobalFilteredRows, filterValue = '', searchInput, diff --git a/plugins/plugin-chart-table/src/DataTable/components/Pagination.tsx b/plugins/plugin-chart-table/src/DataTable/components/Pagination.tsx index 8ffb1aa7dc..de4ca2bd01 100644 --- a/plugins/plugin-chart-table/src/DataTable/components/Pagination.tsx +++ b/plugins/plugin-chart-table/src/DataTable/components/Pagination.tsx @@ -35,9 +35,15 @@ const MINIMAL_PAGE_ITEM_COUNT = 7; * - Always include first and last page * - Add ellipsis if needed */ -export function generatePageItems(total: number, current: number, width: number) { +export function generatePageItems( + total: number, + current: number, + width: number, +) { if (width < MINIMAL_PAGE_ITEM_COUNT) { - throw new Error(`Must allow at least ${MINIMAL_PAGE_ITEM_COUNT} page items`); + throw new Error( + `Must allow at least ${MINIMAL_PAGE_ITEM_COUNT} page items`, + ); } if (width % 2 === 0) { throw new Error(`Must allow odd number of page items`); @@ -45,7 +51,10 @@ export function generatePageItems(total: number, current: number, width: number) if (total < width) { return [...new Array(total).keys()]; } - const left = Math.max(0, Math.min(total - width, current - Math.floor(width / 2))); + const left = Math.max( + 0, + Math.min(total - width, current - Math.floor(width / 2)), + ); const items: (string | number)[] = new Array(width); for (let i = 0; i < width; i += 1) { items[i] = i + left; @@ -64,17 +73,30 @@ export function generatePageItems(total: number, current: number, width: number) export default React.memo( React.forwardRef(function Pagination( - { style, pageCount, currentPage = 0, maxPageItemCount = 9, onPageChange }: PaginationProps, + { + style, + pageCount, + currentPage = 0, + maxPageItemCount = 9, + onPageChange, + }: PaginationProps, ref: React.Ref, ) { - const pageItems = generatePageItems(pageCount, currentPage, maxPageItemCount); + const pageItems = generatePageItems( + pageCount, + currentPage, + maxPageItemCount, + ); return (
in must contain both thead and tbody.'); + throw new Error( + '
in must contain both thead and tbody.', + ); } const columnCount = useMemo(() => { - const headerRows = React.Children.toArray(thead?.props.children).pop() as TrWithTh; + const headerRows = React.Children.toArray( + thead?.props.children, + ).pop() as TrWithTh; return headerRows.props.children.length; }, [thead]); @@ -166,8 +179,10 @@ function StickyWrap({ if (!theadHeight) { return; } - const fullTableHeight = (bodyThead.parentNode as HTMLTableElement).clientHeight; - const ths = bodyThead.childNodes[0].childNodes as NodeListOf; + const fullTableHeight = (bodyThead.parentNode as HTMLTableElement) + .clientHeight; + const ths = bodyThead.childNodes[0] + .childNodes as NodeListOf; const widths = Array.from(ths).map(th => th.clientWidth); const [hasVerticalScroll, hasHorizontalScroll] = needScrollBar({ width: maxWidth, @@ -236,7 +251,10 @@ function StickyWrap({ {colWidths.map((x, i) => ( // eslint-disable-next-line react/no-array-index-key - + ))} ) : ( @@ -251,7 +269,12 @@ function StickyWrap({ overflow: 'hidden', }} > - {React.cloneElement(table, mergeStyleProp(table, fixedTableLayout), headerColgroup, thead)} + {React.cloneElement( + table, + mergeStyleProp(table, fixedTableLayout), + headerColgroup, + thead, + )} {headerTable} ); @@ -264,7 +287,12 @@ function StickyWrap({ overflow: 'hidden', }} > - {React.cloneElement(table, mergeStyleProp(table, fixedTableLayout), headerColgroup, tfoot)} + {React.cloneElement( + table, + mergeStyleProp(table, fixedTableLayout), + headerColgroup, + tfoot, + )} {footerTable} ); @@ -287,7 +315,12 @@ function StickyWrap({ }} onScroll={sticky.hasHorizontalScroll ? onScroll : undefined} > - {React.cloneElement(table, mergeStyleProp(table, fixedTableLayout), bodyColgroup, tbody)} + {React.cloneElement( + table, + mergeStyleProp(table, fixedTableLayout), + bodyColgroup, + tbody, + )} ); } @@ -331,7 +364,8 @@ function useInstance(instance: TableInstance) { ); const useStickyWrap = (renderer: TableRenderer) => { - const { width, height } = useMountedMemo(getTableSize, [getTableSize]) || sticky; + const { width, height } = + useMountedMemo(getTableSize, [getTableSize]) || sticky; // only change of data should trigger re-render // eslint-disable-next-line react-hooks/exhaustive-deps const table = useMemo(renderer, [page, rows]); @@ -349,7 +383,12 @@ function useInstance(instance: TableInstance) { return table; } return ( - + {table} ); @@ -364,7 +403,10 @@ function useInstance(instance: TableInstance) { export default function useSticky(hooks: Hooks) { hooks.useInstance.push(useInstance); hooks.stateReducers.push((newState, action_, prevState) => { - const action = action_ as ReducerAction; + const action = action_ as ReducerAction< + ReducerActions, + { size: StickyState } + >; if (action.type === ReducerActions.init) { return { ...newState, diff --git a/plugins/plugin-chart-table/src/DataTable/types/react-table.d.ts b/plugins/plugin-chart-table/src/DataTable/types/react-table.d.ts index d46ff845c0..52a18d54e1 100644 --- a/plugins/plugin-chart-table/src/DataTable/types/react-table.d.ts +++ b/plugins/plugin-chart-table/src/DataTable/types/react-table.d.ts @@ -41,7 +41,11 @@ import { TableFooterProps, } from 'react-table'; -import { UseStickyState, UseStickyTableOptions, UseStickyInstanceProps } from '../hooks/useSticky'; +import { + UseStickyState, + UseStickyTableOptions, + UseStickyInstanceProps, +} from '../hooks/useSticky'; declare module 'react-table' { export interface TableOptions @@ -90,8 +94,12 @@ declare module 'react-table' { export interface ColumnInstance extends UseGlobalFiltersColumnOptions, UseSortByColumnProps { - getSortByToggleProps: (props?: Partial) => TableSortByToggleProps; + getSortByToggleProps: ( + props?: Partial, + ) => TableSortByToggleProps; } - export interface Hooks extends UseTableHooks, UseSortByHooks {} + export interface Hooks + extends UseTableHooks, + UseSortByHooks {} } diff --git a/plugins/plugin-chart-table/src/DataTable/utils/needScrollBar.ts b/plugins/plugin-chart-table/src/DataTable/utils/needScrollBar.ts index a40082c5f2..2ac111925b 100644 --- a/plugins/plugin-chart-table/src/DataTable/utils/needScrollBar.ts +++ b/plugins/plugin-chart-table/src/DataTable/utils/needScrollBar.ts @@ -33,6 +33,7 @@ export default function needScrollBar({ innerWidth: number; }): [boolean, boolean] { const hasVerticalScroll = innerHeight > height; - const hasHorizontalScroll = innerWidth > width - (hasVerticalScroll ? scrollBarSize : 0); + const hasHorizontalScroll = + innerWidth > width - (hasVerticalScroll ? scrollBarSize : 0); return [hasVerticalScroll, hasHorizontalScroll]; } diff --git a/plugins/plugin-chart-table/src/DataTable/utils/useMountedMemo.ts b/plugins/plugin-chart-table/src/DataTable/utils/useMountedMemo.ts index 14636f79e4..70f535479c 100644 --- a/plugins/plugin-chart-table/src/DataTable/utils/useMountedMemo.ts +++ b/plugins/plugin-chart-table/src/DataTable/utils/useMountedMemo.ts @@ -22,7 +22,10 @@ import { useLayoutEffect, useRef, useMemo } from 'react'; * Execute a memoized callback only when mounted. Execute again when factory updated. * Returns undefined if not mounted yet. */ -export default function useMountedMemo(factory: () => T, deps?: unknown[]): T | undefined { +export default function useMountedMemo( + factory: () => T, + deps?: unknown[], +): T | undefined { const mounted = useRef(); useLayoutEffect(() => { mounted.current = factory; diff --git a/plugins/plugin-chart-table/src/TableChart.tsx b/plugins/plugin-chart-table/src/TableChart.tsx index 8ff4d11efc..29cc8199ed 100644 --- a/plugins/plugin-chart-table/src/TableChart.tsx +++ b/plugins/plugin-chart-table/src/TableChart.tsx @@ -17,7 +17,11 @@ * under the License. */ import React, { CSSProperties, useCallback, useMemo } from 'react'; -import { ColumnInstance, ColumnWithLooseAccessor, DefaultSortTypes } from 'react-table'; +import { + ColumnInstance, + ColumnWithLooseAccessor, + DefaultSortTypes, +} from 'react-table'; import { extent as d3Extent, max as d3Max } from 'd3-array'; import { FaSort } from '@react-icons/all-files/fa/FaSort'; import { FaSortDown as FaSortDesc } from '@react-icons/all-files/fa/FaSortDown'; @@ -89,7 +93,9 @@ function cellBar({ const posExtent = Math.abs(Math.max(maxValue, 0)); const negExtent = Math.abs(Math.min(minValue, 0)); const tot = posExtent + negExtent; - const perc1 = Math.round((Math.min(negExtent + value, negExtent) / tot) * 100); + const perc1 = Math.round( + (Math.min(negExtent + value, negExtent) / tot) * 100, + ); const perc2 = Math.round((Math.abs(value) / tot) * 100); // The 0.01 to 0.001 is a workaround for what appears to be a // CSS rendering bug on flat, transparent colors @@ -123,7 +129,11 @@ function SearchInput({ count, value, onChange }: SearchInputProps) { ); } -function SelectPageSize({ options, current, onChange }: SelectPageSizeRendererProps) { +function SelectPageSize({ + options, + current, + onChange, +}: SelectPageSizeRendererProps) { return ( {t('page_size.show')}{' '} @@ -136,7 +146,9 @@ function SelectPageSize({ options, current, onChange }: SelectPageSizeRendererPr }} > {options.map(option => { - const [size, text] = Array.isArray(option) ? option : [option, option]; + const [size, text] = Array.isArray(option) + ? option + : [option, option]; return (