Skip to content

Commit

Permalink
chore: cleanup as unknown conversion (#19587)
Browse files Browse the repository at this point in the history
  • Loading branch information
zhaoyongjie authored Apr 8, 2022
1 parent d6d2777 commit 761d5c4
Show file tree
Hide file tree
Showing 15 changed files with 70 additions and 85 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
export default function parsePostForm(requestBody: ArrayBuffer) {
type ParsedFields = Record<string, string[] | string>;
if (requestBody.constructor.name !== 'ArrayBuffer') {
return requestBody as unknown as ParsedFields;
return requestBody;
}
const lines = new TextDecoder('utf-8').decode(requestBody).split('\n');
const fields: ParsedFields = {};
Expand Down
13 changes: 10 additions & 3 deletions superset-frontend/packages/superset-ui-core/src/color/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,14 @@ export function getAnalogousColors(colors: string[], results: number) {
}

export function addAlpha(color: string, opacity: number): string {
// coerce values so ti is between 0 and 1.
const rounded = Math.round(Math.min(Math.max(opacity || 1, 0), 1) * 255);
return color + rounded.toString(16).toUpperCase();
// opacity value should be between 0 and 1.
if (opacity > 1 || opacity < 0) {
throw new Error(`The opacity should between 0 and 1, but got: ${opacity}`);
}
// the alpha value is between 00 - FF
const alpha = `0${Math.round(opacity * 255)
.toString(16)
.toUpperCase()}`.slice(-2);

return `${color}${alpha}`;
}
Original file line number Diff line number Diff line change
Expand Up @@ -67,5 +67,19 @@ describe('color utils', () => {
it('adds 50% opacity to white', () => {
expect(addAlpha('#FFFFFF', 0.5)).toBe('#FFFFFF80');
});
it('should apply transparent alpha', () => {
expect(addAlpha('#000000', 0)).toBe('#00000000');
});
it('should apply fully opaque', () => {
expect(addAlpha('#000000', 1)).toBe('#000000FF');
});
it('opacity should be between 0 and 1', () => {
expect(() => {
addAlpha('#000000', 2);
}).toThrow();
expect(() => {
addAlpha('#000000', -1);
}).toThrow();
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ describe('ExtensibleFunction', () => {
// @ts-ignore
super(function customName() {
// @ts-ignore
return customName.x as unknown;
return customName.x;
}); // named function
this.x = x;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -285,7 +285,8 @@ describe('buildQueryObject', () => {
datasource: '5__table',
granularity_sqla: 'ds',
viz_type: 'table',
url_params: null as unknown as undefined,
// @ts-expect-error
url_params: null,
}).url_params,
).toBeUndefined();
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ import {
// eslint-disable-next-line import/extensions
import birthNamesJson from './birthNames.json';

export const birthNames = birthNamesJson as unknown as TableChartProps;
export const birthNames = birthNamesJson as TableChartProps;

export const basicFormData: TableChartFormData = {
datasource: '1__table',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -357,7 +357,7 @@ export function transformEventAnnotation(
const eventData: MarkLine1DDataItemOption[] = [
{
name: label,
xAxis: time as unknown as number,
xAxis: time,
},
];

Expand Down
6 changes: 3 additions & 3 deletions superset-frontend/src/SqlLab/components/QuerySearch/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,7 @@ function QuerySearch({ actions, displayLimit }: QuerySearchProps) {
value: xt,
label: xt,
}))}
value={from as unknown as undefined}
value={{ value: from, label: from }}
autosize={false}
onChange={(selected: any) => setFrom(selected?.value)}
/>
Expand All @@ -235,7 +235,7 @@ function QuerySearch({ actions, displayLimit }: QuerySearchProps) {
name="select-to"
placeholder={t('[To]-')}
options={TIME_OPTIONS.map(xt => ({ value: xt, label: xt }))}
value={to as unknown as undefined}
value={{ value: to, label: to }}
autosize={false}
onChange={(selected: any) => setTo(selected?.value)}
/>
Expand All @@ -247,7 +247,7 @@ function QuerySearch({ actions, displayLimit }: QuerySearchProps) {
value: s,
label: s,
}))}
value={status as unknown as undefined}
value={{ value: status, label: status }}
isLoading={false}
autosize={false}
onChange={(selected: any) => setStatus(selected?.value)}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,9 @@
* specific language governing permissions and limitations
* under the License.
*/
import { Filter } from '@superset-ui/core';
import getFormDataWithExtraFilters, {
GetFormDataWithExtraFiltersArguments,
} from 'src/dashboard/util/charts/getFormDataWithExtraFilters';
import { DASHBOARD_ROOT_ID } from 'src/dashboard/util/constants';
import { LayoutItem } from 'src/dashboard/types';
import { dashboardLayout } from 'spec/fixtures/mockDashboardLayout';
import { sliceId as chartId } from 'spec/fixtures/mockChartQueries';

describe('getFormDataWithExtraFilters', () => {
Expand Down Expand Up @@ -63,16 +59,8 @@ describe('getFormDataWithExtraFilters', () => {
},
sliceId: chartId,
nativeFilters: {
filters: {},
filterSets: {},
filters: {
[filterId]: {
id: filterId,
scope: {
rootPath: [DASHBOARD_ROOT_ID],
excluded: [],
},
} as unknown as Filter,
},
},
dataMask: {
[filterId]: {
Expand All @@ -82,9 +70,7 @@ describe('getFormDataWithExtraFilters', () => {
ownState: {},
},
},
layout: dashboardLayout.present as unknown as {
[key: string]: LayoutItem;
},
layout: {},
};

it('should include filters from the passed filters', () => {
Expand Down
2 changes: 1 addition & 1 deletion superset-frontend/src/dashboard/util/injectCustomCss.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ export default function injectCustomCss(css: string) {
document.querySelector(`.${className}`) || createStyleElement(className);

if ('styleSheet' in style) {
(style as unknown as MysteryStyleElement).styleSheet.cssText = css;
(style as HTMLStyleElement & MysteryStyleElement).styleSheet.cssText = css;
} else {
style.innerHTML = css;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
*/

import React from 'react';
import { Slice } from 'src/types/Chart';
import { render, screen } from 'spec/helpers/testing-library';
import userEvent from '@testing-library/user-event';
import ExploreHeader from '.';
Expand Down Expand Up @@ -80,7 +79,7 @@ const createProps = () => ({
slice_id: 318,
slice_name: 'Age distribution of respondents',
slice_url: '/superset/explore/?form_data=%7B%22slice_id%22%3A%20318%7D',
} as unknown as Slice,
},
slice_name: 'Age distribution of respondents',
actions: {
postChartFormData: () => null,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,57 +18,27 @@
*/

import React from 'react';
import { Slice } from 'src/types/Chart';
import { render, screen, waitFor } from 'spec/helpers/testing-library';
import fetchMock from 'fetch-mock';
import userEvent from '@testing-library/user-event';
import PropertiesModal, { PropertiesModalProps } from '.';

const createProps = () => ({
slice: {
cache_timeout: null,
certified_by: 'John Doe',
certification_details: 'Sample certification',
changed_on: '2021-03-19T16:30:56.750230',
changed_on_humanized: '7 days ago',
datasource: 'FCC 2018 Survey',
description: null,
description_markeddown: '',
edit_url: '/chart/edit/318',
form_data: {
adhoc_filters: [],
all_columns_x: ['age'],
color_scheme: 'supersetColors',
datasource: '49__table',
granularity_sqla: 'time_start',
groupby: null,
label_colors: {},
link_length: '25',
queryFields: { groupby: 'groupby' },
row_limit: 10000,
const createProps = () =>
({
slice: {
cache_timeout: null,
certified_by: 'John Doe',
certification_details: 'Sample certification',
description: null,
slice_id: 318,
time_range: 'No filter',
url_params: {},
viz_type: 'histogram',
x_axis_label: 'age',
y_axis_label: 'count',
slice_name: 'Age distribution of respondents',
is_managed_externally: false,
},
modified: '<span class="no-wrap">7 days ago</span>',
owners: [
{
text: 'Superset Admin',
value: 1,
},
],
slice_id: 318,
slice_name: 'Age distribution of respondents',
slice_url: '/superset/explore/?form_data=%7B%22slice_id%22%3A%20318%7D',
} as unknown as Slice,
show: true,
onHide: jest.fn(),
onSave: jest.fn(),
addSuccessToast: jest.fn(),
});
show: true,
onHide: jest.fn(),
onSave: jest.fn(),
addSuccessToast: jest.fn(),
} as PropertiesModalProps);

fetchMock.get('glob:*/api/v1/chart/318', {
body: {
Expand Down
16 changes: 13 additions & 3 deletions superset-frontend/src/explore/controlUtils/controlUtils.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,15 @@
* specific language governing permissions and limitations
* under the License.
*/
import { getChartControlPanelRegistry, t } from '@superset-ui/core';
import {
DatasourceType,
getChartControlPanelRegistry,
t,
} from '@superset-ui/core';
import {
ControlConfig,
ControlPanelState,
CustomControlItem,
DatasourceMeta,
} from '@superset-ui/chart-controls';
import {
getControlConfig,
Expand All @@ -44,9 +47,16 @@ const getKnownControlState = (...args: Parameters<typeof getControlState>) =>
describe('controlUtils', () => {
const state: ControlPanelState = {
datasource: {
id: 1,
type: DatasourceType.Table,
columns: [{ column_name: 'a' }],
metrics: [{ metric_name: 'first' }, { metric_name: 'second' }],
} as unknown as DatasourceMeta,
column_format: {},
verbose_map: {},
main_dttm_col: '',
datasource_name: '1__table',
description: null,
},
controls: {},
form_data: { datasource: '1__table', viz_type: 'table' },
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -371,11 +371,11 @@ function dbReducer(
action.payload.configuration_method ===
CONFIGURATION_METHOD.DYNAMIC_FORM
) {
const engineParamsCatalog = Object.keys(
const engineParamsCatalog = Object.entries(
extra_json?.engine_params?.catalog || {},
).map(e => ({
name: e,
value: extra_json?.engine_params?.catalog[e],
).map(([key, value]) => ({
name: key,
value,
}));
return {
...action.payload,
Expand Down Expand Up @@ -418,9 +418,7 @@ const serializeExtra = (extraJson: DatabaseObject['extra_json']) =>
JSON.stringify({
...extraJson,
metadata_params: JSON.parse((extraJson?.metadata_params as string) || '{}'),
engine_params: JSON.parse(
(extraJson?.engine_params as unknown as string) || '{}',
),
engine_params: JSON.parse((extraJson?.engine_params as string) || '{}'),
schemas_allowed_for_file_upload: (
extraJson?.schemas_allowed_for_file_upload || []
).filter(schema => schema !== ''),
Expand Down
2 changes: 1 addition & 1 deletion superset-frontend/src/views/CRUD/data/database/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ export type DatabaseObject = {
// Extra
extra_json?: {
engine_params?: {
catalog: Record<any, any> | string;
catalog?: Record<any, any> | string;
};
metadata_params?: {} | string;
metadata_cache_timeout?: {
Expand Down

0 comments on commit 761d5c4

Please sign in to comment.