hunk
dict | file
stringlengths 0
11.8M
| file_path
stringlengths 2
234
| label
int64 0
1
| commit_url
stringlengths 74
103
| dependency_score
sequencelengths 5
5
|
---|---|---|---|---|---|
{
"id": 4,
"code_window": [
"\n",
" render() {\n",
" const { active } = this.props;\n",
" const { tests } = this.state;\n",
"\n",
" return active && tests ? <Component tests={tests} /> : null;\n",
" }\n",
" };\n",
"\n",
"export default provideTests;"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" return active ? <Component tests={tests} /> : null;\n"
],
"file_path": "addons/jest/src/hoc/provideJestResult.tsx",
"type": "replace",
"edit_start_line_idx": 78
} | import { action } from '@storybook/addon-actions';
import { linkTo } from '@storybook/addon-links';
import { Button } from '@storybook/angular/demo';
export default {
title: 'Button',
};
export const text = () => ({
component: Button,
props: {
text: 'Hello Button',
},
});
export const emoji = () => ({
component: Button,
props: {
text: '😀 😎 👍 💯',
},
});
emoji.story = {
parameters: { notes: 'My notes on a button with emojis' },
};
export const withSomeEmojiAndAction = () => ({
component: Button,
props: {
text: '😀 😎 👍 💯',
onClick: action('This was clicked OMG'),
},
});
withSomeEmojiAndAction.story = {
name: 'with some emoji and action',
parameters: { notes: 'My notes on a button with emojis' },
};
export const buttonWithLinkToAnotherStory = () => ({
component: Button,
props: {
text: 'Go to Welcome Story',
onClick: linkTo('Welcome'),
},
});
buttonWithLinkToAnotherStory.story = {
name: 'button with link to another story',
};
| lib/cli/generators/ANGULAR/template/src/stories/Button.stories.ts | 0 | https://github.com/storybookjs/storybook/commit/8388e6b58dd930ec07e8bacd8f5b3865425201fc | [
0.0001779416634235531,
0.00017135632515419275,
0.00016607836005277932,
0.00017025836859829724,
0.000004400740635901457
] |
{
"id": 4,
"code_window": [
"\n",
" render() {\n",
" const { active } = this.props;\n",
" const { tests } = this.state;\n",
"\n",
" return active && tests ? <Component tests={tests} /> : null;\n",
" }\n",
" };\n",
"\n",
"export default provideTests;"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" return active ? <Component tests={tests} /> : null;\n"
],
"file_path": "addons/jest/src/hoc/provideJestResult.tsx",
"type": "replace",
"edit_start_line_idx": 78
} | export interface NgModuleMetadata {
declarations?: any[];
entryComponents?: any[];
imports?: any[];
schemas?: any[];
providers?: any[];
}
export interface ICollection {
[p: string]: any;
}
export interface NgStory {
component?: any;
props: ICollection;
propsMeta?: ICollection;
moduleMetadata?: NgModuleMetadata;
template?: string;
}
| addons/storyshots/storyshots-core/src/frameworks/angular/types.ts | 0 | https://github.com/storybookjs/storybook/commit/8388e6b58dd930ec07e8bacd8f5b3865425201fc | [
0.00020368782861623913,
0.0001901522045955062,
0.00017661659512668848,
0.0001901522045955062,
0.000013535616744775325
] |
{
"id": 0,
"code_window": [
" expect(getContrastRatio('#FFF', '#FFF')).toEqual(1);\n",
" });\n",
"\n",
" it('returns a ratio for dark-grey : light-grey', () => {\n",
" //expect(getContrastRatio('#707070', '#E5E5E5'))to.be.approximately(3.93, 0.01);\n",
" });\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" it('Can also take into account opacity for background', () => {\n",
" expect(getContrastRatio('#FFF', 'rgba(255,255,255,0.1)', '#000')).toEqual(17.5);\n",
" });\n",
"\n"
],
"file_path": "packages/grafana-data/src/themes/colorManipulator.test.ts",
"type": "add",
"edit_start_line_idx": 179
} | // Code based on Material-UI
// https://github.com/mui-org/material-ui/blob/1b096070faf102281f8e3c4f9b2bf50acf91f412/packages/material-ui/src/styles/colorManipulator.js#L97
// MIT License Copyright (c) 2014 Call-Em-All
/**
* Returns a number whose value is limited to the given range.
* @param value The value to be clamped
* @param min The lower boundary of the output range
* @param max The upper boundary of the output range
* @returns A number in the range [min, max]
* @beta
*/
function clamp(value: number, min = 0, max = 1) {
if (process.env.NODE_ENV !== 'production') {
if (value < min || value > max) {
console.error(`The value provided ${value} is out of range [${min}, ${max}].`);
}
}
return Math.min(Math.max(min, value), max);
}
/**
* Converts a color from CSS hex format to CSS rgb format.
* @param color - Hex color, i.e. #nnn or #nnnnnn
* @returns A CSS rgb color string
* @beta
*/
export function hexToRgb(color: string) {
color = color.substr(1);
const re = new RegExp(`.{1,${color.length >= 6 ? 2 : 1}}`, 'g');
let colors = color.match(re);
if (colors && colors[0].length === 1) {
colors = colors.map((n) => n + n);
}
return colors
? `rgb${colors.length === 4 ? 'a' : ''}(${colors
.map((n, index) => {
return index < 3 ? parseInt(n, 16) : Math.round((parseInt(n, 16) / 255) * 1000) / 1000;
})
.join(', ')})`
: '';
}
function intToHex(int: number) {
const hex = int.toString(16);
return hex.length === 1 ? `0${hex}` : hex;
}
/**
* Converts a color from CSS rgb format to CSS hex format.
* @param color - RGB color, i.e. rgb(n, n, n)
* @returns A CSS rgb color string, i.e. #nnnnnn
* @beta
*/
export function rgbToHex(color: string) {
// Idempotent
if (color.indexOf('#') === 0) {
return color;
}
const { values } = decomposeColor(color);
return `#${values.map((n: number) => intToHex(n)).join('')}`;
}
/**
* Converts a color from hsl format to rgb format.
* @param color - HSL color values
* @returns rgb color values
* @beta
*/
export function hslToRgb(color: string | DecomposeColor) {
const parts = decomposeColor(color);
const { values } = parts;
const h = values[0];
const s = values[1] / 100;
const l = values[2] / 100;
const a = s * Math.min(l, 1 - l);
const f = (n: number, k = (n + h / 30) % 12) => l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1);
let type = 'rgb';
const rgb = [Math.round(f(0) * 255), Math.round(f(8) * 255), Math.round(f(4) * 255)];
if (parts.type === 'hsla') {
type += 'a';
rgb.push(values[3]);
}
return recomposeColor({ type, values: rgb });
}
/**
* Returns an object with the type and values of a color.
*
* Note: Does not support rgb % values.
* @param color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()
* @returns {object} - A MUI color object: {type: string, values: number[]}
* @beta
*/
export function decomposeColor(color: string | DecomposeColor): DecomposeColor {
// Idempotent
if (typeof color !== 'string') {
return color;
}
if (color.charAt(0) === '#') {
return decomposeColor(hexToRgb(color));
}
const marker = color.indexOf('(');
const type = color.substring(0, marker);
if (['rgb', 'rgba', 'hsl', 'hsla', 'color'].indexOf(type) === -1) {
throw new Error(
`Unsupported '${color}' color. The following formats are supported: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), color()`
);
}
let values: any = color.substring(marker + 1, color.length - 1);
let colorSpace;
if (type === 'color') {
values = values.split(' ');
colorSpace = values.shift();
if (values.length === 4 && values[3].charAt(0) === '/') {
values[3] = values[3].substr(1);
}
if (['srgb', 'display-p3', 'a98-rgb', 'prophoto-rgb', 'rec-2020'].indexOf(colorSpace) === -1) {
throw new Error(
`Unsupported ${colorSpace} color space. The following color spaces are supported: srgb, display-p3, a98-rgb, prophoto-rgb, rec-2020.`
);
}
} else {
values = values.split(',');
}
values = values.map((value: string) => parseFloat(value));
return { type, values, colorSpace };
}
/**
* Converts a color object with type and values to a string.
* @param {object} color - Decomposed color
* @param color.type - One of: 'rgb', 'rgba', 'hsl', 'hsla'
* @param {array} color.values - [n,n,n] or [n,n,n,n]
* @returns A CSS color string
* @beta
*/
export function recomposeColor(color: DecomposeColor) {
const { type, colorSpace } = color;
let values: any = color.values;
if (type.indexOf('rgb') !== -1) {
// Only convert the first 3 values to int (i.e. not alpha)
values = values.map((n: string, i: number) => (i < 3 ? parseInt(n, 10) : n));
} else if (type.indexOf('hsl') !== -1) {
values[1] = `${values[1]}%`;
values[2] = `${values[2]}%`;
}
if (type.indexOf('color') !== -1) {
values = `${colorSpace} ${values.join(' ')}`;
} else {
values = `${values.join(', ')}`;
}
return `${type}(${values})`;
}
/**
* Calculates the contrast ratio between two colors.
*
* Formula: https://www.w3.org/TR/WCAG20-TECHS/G17.html#G17-tests
* @param foreground - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()
* @param background - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()
* @returns A contrast ratio value in the range 0 - 21.
* @beta
*/
export function getContrastRatio(foreground: string, background: string) {
const lumA = getLuminance(foreground);
const lumB = getLuminance(background);
return (Math.max(lumA, lumB) + 0.05) / (Math.min(lumA, lumB) + 0.05);
}
/**
* The relative brightness of any point in a color space,
* normalized to 0 for darkest black and 1 for lightest white.
*
* Formula: https://www.w3.org/TR/WCAG20-TECHS/G17.html#G17-tests
* @param color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), color()
* @returns The relative brightness of the color in the range 0 - 1
* @beta
*/
export function getLuminance(color: string) {
const parts = decomposeColor(color);
let rgb = parts.type === 'hsl' ? decomposeColor(hslToRgb(color)).values : parts.values;
const rgbNumbers = rgb.map((val: any) => {
if (parts.type !== 'color') {
val /= 255; // normalized
}
return val <= 0.03928 ? val / 12.92 : ((val + 0.055) / 1.055) ** 2.4;
});
// Truncate at 3 digits
return Number((0.2126 * rgbNumbers[0] + 0.7152 * rgbNumbers[1] + 0.0722 * rgbNumbers[2]).toFixed(3));
}
/**
* Darken or lighten a color, depending on its luminance.
* Light colors are darkened, dark colors are lightened.
* @param color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), color()
* @param coefficient=0.15 - multiplier in the range 0 - 1
* @returns A CSS color string. Hex input values are returned as rgb
* @beta
*/
export function emphasize(color: string, coefficient = 0.15) {
return getLuminance(color) > 0.5 ? darken(color, coefficient) : lighten(color, coefficient);
}
/**
* Set the absolute transparency of a color.
* Any existing alpha values are overwritten.
* @param color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), color()
* @param value - value to set the alpha channel to in the range 0 - 1
* @returns A CSS color string. Hex input values are returned as rgb
* @beta
*/
export function alpha(color: string, value: number) {
const parts = decomposeColor(color);
value = clamp(value);
if (parts.type === 'rgb' || parts.type === 'hsl') {
parts.type += 'a';
}
if (parts.type === 'color') {
parts.values[3] = `/${value}`;
} else {
parts.values[3] = value;
}
return recomposeColor(parts);
}
/**
* Darkens a color.
* @param color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), color()
* @param coefficient - multiplier in the range 0 - 1
* @returns A CSS color string. Hex input values are returned as rgb
* @beta
*/
export function darken(color: string, coefficient: number) {
const parts = decomposeColor(color);
coefficient = clamp(coefficient);
if (parts.type.indexOf('hsl') !== -1) {
parts.values[2] *= 1 - coefficient;
} else if (parts.type.indexOf('rgb') !== -1 || parts.type.indexOf('color') !== -1) {
for (let i = 0; i < 3; i += 1) {
parts.values[i] *= 1 - coefficient;
}
}
return recomposeColor(parts);
}
/**
* Lightens a color.
* @param color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), color()
* @param coefficient - multiplier in the range 0 - 1
* @returns A CSS color string. Hex input values are returned as rgb
* @beta
*/
export function lighten(color: string, coefficient: number) {
const parts = decomposeColor(color);
coefficient = clamp(coefficient);
if (parts.type.indexOf('hsl') !== -1) {
parts.values[2] += (100 - parts.values[2]) * coefficient;
} else if (parts.type.indexOf('rgb') !== -1) {
for (let i = 0; i < 3; i += 1) {
parts.values[i] += (255 - parts.values[i]) * coefficient;
}
} else if (parts.type.indexOf('color') !== -1) {
for (let i = 0; i < 3; i += 1) {
parts.values[i] += (1 - parts.values[i]) * coefficient;
}
}
return recomposeColor(parts);
}
interface DecomposeColor {
type: string;
values: any;
colorSpace?: string;
}
| packages/grafana-data/src/themes/colorManipulator.ts | 1 | https://github.com/grafana/grafana/commit/8ecfad69951628cc8327c23166d953f86a8d83ff | [
0.0010818714508786798,
0.00020298514573369175,
0.00016172227333299816,
0.00017407286213710904,
0.0001634003419894725
] |
{
"id": 0,
"code_window": [
" expect(getContrastRatio('#FFF', '#FFF')).toEqual(1);\n",
" });\n",
"\n",
" it('returns a ratio for dark-grey : light-grey', () => {\n",
" //expect(getContrastRatio('#707070', '#E5E5E5'))to.be.approximately(3.93, 0.01);\n",
" });\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" it('Can also take into account opacity for background', () => {\n",
" expect(getContrastRatio('#FFF', 'rgba(255,255,255,0.1)', '#000')).toEqual(17.5);\n",
" });\n",
"\n"
],
"file_path": "packages/grafana-data/src/themes/colorManipulator.test.ts",
"type": "add",
"edit_start_line_idx": 179
} | import React, { memo, useMemo, useCallback } from 'react';
import { MatcherUIProps, FieldMatcherUIRegistryItem } from './types';
import { FieldMatcherID, fieldMatchers, SelectableValue, FieldType, DataFrame } from '@grafana/data';
import { Select } from '../Select/Select';
export const FieldTypeMatcherEditor = memo<MatcherUIProps<string>>((props) => {
const { data, options, onChange: onChangeFromProps } = props;
const counts = useFieldCounts(data);
const selectOptions = useSelectOptions(counts, options);
const onChange = useCallback(
(selection: SelectableValue<string>) => {
return onChangeFromProps(selection.value!);
},
[onChangeFromProps]
);
const selectedOption = selectOptions.find((v) => v.value === options);
return <Select value={selectedOption} options={selectOptions} onChange={onChange} />;
});
FieldTypeMatcherEditor.displayName = 'FieldTypeMatcherEditor';
const allTypes: Array<SelectableValue<FieldType>> = [
{ value: FieldType.number, label: 'Numeric' },
{ value: FieldType.string, label: 'String' },
{ value: FieldType.time, label: 'Time' },
{ value: FieldType.boolean, label: 'Boolean' },
{ value: FieldType.trace, label: 'Traces' },
{ value: FieldType.other, label: 'Other' },
];
const useFieldCounts = (data: DataFrame[]): Map<FieldType, number> => {
return useMemo(() => {
const counts: Map<FieldType, number> = new Map();
for (const t of allTypes) {
counts.set(t.value!, 0);
}
for (const frame of data) {
for (const field of frame.fields) {
const key = field.type || FieldType.other;
let v = counts.get(key);
if (!v) {
v = 0;
}
counts.set(key, v + 1);
}
}
return counts;
}, [data]);
};
const useSelectOptions = (counts: Map<string, number>, opt?: string): Array<SelectableValue<string>> => {
return useMemo(() => {
let found = false;
const options: Array<SelectableValue<string>> = [];
for (const t of allTypes) {
const count = counts.get(t.value!);
const match = opt === t.value;
if (count || match) {
options.push({
...t,
label: `${t.label} (${counts.get(t.value!)})`,
});
}
if (match) {
found = true;
}
}
if (opt && !found) {
options.push({
value: opt,
label: `${opt} (No matches)`,
});
}
return options;
}, [counts, opt]);
};
export const fieldTypeMatcherItem: FieldMatcherUIRegistryItem<string> = {
id: FieldMatcherID.byType,
component: FieldTypeMatcherEditor,
matcher: fieldMatchers.get(FieldMatcherID.byType),
name: 'Fields with type',
description: 'Set properties for fields of a specific type (number, string, boolean)',
optionsToLabel: (options) => options,
};
| packages/grafana-ui/src/components/MatchersUI/FieldTypeMatcherEditor.tsx | 0 | https://github.com/grafana/grafana/commit/8ecfad69951628cc8327c23166d953f86a8d83ff | [
0.0001781161845428869,
0.00017420115182176232,
0.000167828518897295,
0.00017448209109716117,
0.00000346289380104281
] |
{
"id": 0,
"code_window": [
" expect(getContrastRatio('#FFF', '#FFF')).toEqual(1);\n",
" });\n",
"\n",
" it('returns a ratio for dark-grey : light-grey', () => {\n",
" //expect(getContrastRatio('#707070', '#E5E5E5'))to.be.approximately(3.93, 0.01);\n",
" });\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" it('Can also take into account opacity for background', () => {\n",
" expect(getContrastRatio('#FFF', 'rgba(255,255,255,0.1)', '#000')).toEqual(17.5);\n",
" });\n",
"\n"
],
"file_path": "packages/grafana-data/src/themes/colorManipulator.test.ts",
"type": "add",
"edit_start_line_idx": 179
} | package channels
import (
"github.com/prometheus/common/model"
"github.com/grafana/grafana/pkg/components/securejsondata"
"github.com/grafana/grafana/pkg/components/simplejson"
)
const (
FooterIconURL = "https://grafana.com/assets/img/fav32.png"
ColorAlertFiring = "#D63232"
ColorAlertResolved = "#36a64f"
)
func getAlertStatusColor(status model.AlertStatus) string {
if status == model.AlertFiring {
return ColorAlertFiring
}
return ColorAlertResolved
}
type NotificationChannelConfig struct {
UID string `json:"uid"`
Name string `json:"name"`
Type string `json:"type"`
DisableResolveMessage bool `json:"disableResolveMessage"`
Settings *simplejson.Json `json:"settings"`
SecureSettings securejsondata.SecureJsonData `json:"secureSettings"`
}
// DecryptedValue returns decrypted value from secureSettings
func (an *NotificationChannelConfig) DecryptedValue(field string, fallback string) string {
if value, ok := an.SecureSettings.DecryptedValue(field); ok {
return value
}
return fallback
}
| pkg/services/ngalert/notifier/channels/utils.go | 0 | https://github.com/grafana/grafana/commit/8ecfad69951628cc8327c23166d953f86a8d83ff | [
0.00017471567844040692,
0.00016779114957898855,
0.00016440539911855012,
0.00016602178220637143,
0.000004119965524296276
] |
{
"id": 0,
"code_window": [
" expect(getContrastRatio('#FFF', '#FFF')).toEqual(1);\n",
" });\n",
"\n",
" it('returns a ratio for dark-grey : light-grey', () => {\n",
" //expect(getContrastRatio('#707070', '#E5E5E5'))to.be.approximately(3.93, 0.01);\n",
" });\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" it('Can also take into account opacity for background', () => {\n",
" expect(getContrastRatio('#FFF', 'rgba(255,255,255,0.1)', '#000')).toEqual(17.5);\n",
" });\n",
"\n"
],
"file_path": "packages/grafana-data/src/themes/colorManipulator.test.ts",
"type": "add",
"edit_start_line_idx": 179
} | import React, { Component } from 'react';
import { CloudWatchLogsQuery } from '../types';
import { PanelData } from '@grafana/data';
import { Icon } from '@grafana/ui';
import { encodeUrl, AwsUrl } from '../aws_url';
import { CloudWatchDatasource } from '../datasource';
interface Props {
query: CloudWatchLogsQuery;
panelData?: PanelData;
datasource: CloudWatchDatasource;
}
interface State {
href: string;
}
export default class CloudWatchLink extends Component<Props, State> {
state: State = { href: '' };
async componentDidUpdate(prevProps: Props) {
const { panelData: panelDataNew } = this.props;
const { panelData: panelDataOld } = prevProps;
if (panelDataOld !== panelDataNew && panelDataNew?.request) {
const href = this.getExternalLink();
this.setState({ href });
}
}
getExternalLink(): string {
const { query, panelData, datasource } = this.props;
const range = panelData?.request?.range;
if (!range) {
return '';
}
const start = range.from.toISOString();
const end = range.to.toISOString();
const urlProps: AwsUrl = {
end,
start,
timeType: 'ABSOLUTE',
tz: 'UTC',
editorString: query.expression ?? '',
isLiveTail: false,
source: query.logGroupNames ?? [],
};
return encodeUrl(urlProps, datasource.getActualRegion(query.region));
}
render() {
const { href } = this.state;
return (
<a href={href} target="_blank" rel="noopener noreferrer">
<Icon name="share-alt" /> CloudWatch Logs Insights
</a>
);
}
}
| public/app/plugins/datasource/cloudwatch/components/CloudWatchLink.tsx | 0 | https://github.com/grafana/grafana/commit/8ecfad69951628cc8327c23166d953f86a8d83ff | [
0.0001770656235748902,
0.0001741035666782409,
0.0001658792607486248,
0.0001756139099597931,
0.000003469590865279315
] |
{
"id": 1,
"code_window": [
" *\n",
" * Formula: https://www.w3.org/TR/WCAG20-TECHS/G17.html#G17-tests\n",
" * @param foreground - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()\n",
" * @param background - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()\n",
" * @returns A contrast ratio value in the range 0 - 21.\n",
" * @beta\n",
" */\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" * @param canvas - A CSS color that alpha based backgrounds blends into\n"
],
"file_path": "packages/grafana-data/src/themes/colorManipulator.ts",
"type": "add",
"edit_start_line_idx": 177
} | // Code based on Material-UI
// https://github.com/mui-org/material-ui/blob/1b096070faf102281f8e3c4f9b2bf50acf91f412/packages/material-ui/src/styles/colorManipulator.js#L97
// MIT License Copyright (c) 2014 Call-Em-All
/**
* Returns a number whose value is limited to the given range.
* @param value The value to be clamped
* @param min The lower boundary of the output range
* @param max The upper boundary of the output range
* @returns A number in the range [min, max]
* @beta
*/
function clamp(value: number, min = 0, max = 1) {
if (process.env.NODE_ENV !== 'production') {
if (value < min || value > max) {
console.error(`The value provided ${value} is out of range [${min}, ${max}].`);
}
}
return Math.min(Math.max(min, value), max);
}
/**
* Converts a color from CSS hex format to CSS rgb format.
* @param color - Hex color, i.e. #nnn or #nnnnnn
* @returns A CSS rgb color string
* @beta
*/
export function hexToRgb(color: string) {
color = color.substr(1);
const re = new RegExp(`.{1,${color.length >= 6 ? 2 : 1}}`, 'g');
let colors = color.match(re);
if (colors && colors[0].length === 1) {
colors = colors.map((n) => n + n);
}
return colors
? `rgb${colors.length === 4 ? 'a' : ''}(${colors
.map((n, index) => {
return index < 3 ? parseInt(n, 16) : Math.round((parseInt(n, 16) / 255) * 1000) / 1000;
})
.join(', ')})`
: '';
}
function intToHex(int: number) {
const hex = int.toString(16);
return hex.length === 1 ? `0${hex}` : hex;
}
/**
* Converts a color from CSS rgb format to CSS hex format.
* @param color - RGB color, i.e. rgb(n, n, n)
* @returns A CSS rgb color string, i.e. #nnnnnn
* @beta
*/
export function rgbToHex(color: string) {
// Idempotent
if (color.indexOf('#') === 0) {
return color;
}
const { values } = decomposeColor(color);
return `#${values.map((n: number) => intToHex(n)).join('')}`;
}
/**
* Converts a color from hsl format to rgb format.
* @param color - HSL color values
* @returns rgb color values
* @beta
*/
export function hslToRgb(color: string | DecomposeColor) {
const parts = decomposeColor(color);
const { values } = parts;
const h = values[0];
const s = values[1] / 100;
const l = values[2] / 100;
const a = s * Math.min(l, 1 - l);
const f = (n: number, k = (n + h / 30) % 12) => l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1);
let type = 'rgb';
const rgb = [Math.round(f(0) * 255), Math.round(f(8) * 255), Math.round(f(4) * 255)];
if (parts.type === 'hsla') {
type += 'a';
rgb.push(values[3]);
}
return recomposeColor({ type, values: rgb });
}
/**
* Returns an object with the type and values of a color.
*
* Note: Does not support rgb % values.
* @param color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()
* @returns {object} - A MUI color object: {type: string, values: number[]}
* @beta
*/
export function decomposeColor(color: string | DecomposeColor): DecomposeColor {
// Idempotent
if (typeof color !== 'string') {
return color;
}
if (color.charAt(0) === '#') {
return decomposeColor(hexToRgb(color));
}
const marker = color.indexOf('(');
const type = color.substring(0, marker);
if (['rgb', 'rgba', 'hsl', 'hsla', 'color'].indexOf(type) === -1) {
throw new Error(
`Unsupported '${color}' color. The following formats are supported: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), color()`
);
}
let values: any = color.substring(marker + 1, color.length - 1);
let colorSpace;
if (type === 'color') {
values = values.split(' ');
colorSpace = values.shift();
if (values.length === 4 && values[3].charAt(0) === '/') {
values[3] = values[3].substr(1);
}
if (['srgb', 'display-p3', 'a98-rgb', 'prophoto-rgb', 'rec-2020'].indexOf(colorSpace) === -1) {
throw new Error(
`Unsupported ${colorSpace} color space. The following color spaces are supported: srgb, display-p3, a98-rgb, prophoto-rgb, rec-2020.`
);
}
} else {
values = values.split(',');
}
values = values.map((value: string) => parseFloat(value));
return { type, values, colorSpace };
}
/**
* Converts a color object with type and values to a string.
* @param {object} color - Decomposed color
* @param color.type - One of: 'rgb', 'rgba', 'hsl', 'hsla'
* @param {array} color.values - [n,n,n] or [n,n,n,n]
* @returns A CSS color string
* @beta
*/
export function recomposeColor(color: DecomposeColor) {
const { type, colorSpace } = color;
let values: any = color.values;
if (type.indexOf('rgb') !== -1) {
// Only convert the first 3 values to int (i.e. not alpha)
values = values.map((n: string, i: number) => (i < 3 ? parseInt(n, 10) : n));
} else if (type.indexOf('hsl') !== -1) {
values[1] = `${values[1]}%`;
values[2] = `${values[2]}%`;
}
if (type.indexOf('color') !== -1) {
values = `${colorSpace} ${values.join(' ')}`;
} else {
values = `${values.join(', ')}`;
}
return `${type}(${values})`;
}
/**
* Calculates the contrast ratio between two colors.
*
* Formula: https://www.w3.org/TR/WCAG20-TECHS/G17.html#G17-tests
* @param foreground - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()
* @param background - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()
* @returns A contrast ratio value in the range 0 - 21.
* @beta
*/
export function getContrastRatio(foreground: string, background: string) {
const lumA = getLuminance(foreground);
const lumB = getLuminance(background);
return (Math.max(lumA, lumB) + 0.05) / (Math.min(lumA, lumB) + 0.05);
}
/**
* The relative brightness of any point in a color space,
* normalized to 0 for darkest black and 1 for lightest white.
*
* Formula: https://www.w3.org/TR/WCAG20-TECHS/G17.html#G17-tests
* @param color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), color()
* @returns The relative brightness of the color in the range 0 - 1
* @beta
*/
export function getLuminance(color: string) {
const parts = decomposeColor(color);
let rgb = parts.type === 'hsl' ? decomposeColor(hslToRgb(color)).values : parts.values;
const rgbNumbers = rgb.map((val: any) => {
if (parts.type !== 'color') {
val /= 255; // normalized
}
return val <= 0.03928 ? val / 12.92 : ((val + 0.055) / 1.055) ** 2.4;
});
// Truncate at 3 digits
return Number((0.2126 * rgbNumbers[0] + 0.7152 * rgbNumbers[1] + 0.0722 * rgbNumbers[2]).toFixed(3));
}
/**
* Darken or lighten a color, depending on its luminance.
* Light colors are darkened, dark colors are lightened.
* @param color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), color()
* @param coefficient=0.15 - multiplier in the range 0 - 1
* @returns A CSS color string. Hex input values are returned as rgb
* @beta
*/
export function emphasize(color: string, coefficient = 0.15) {
return getLuminance(color) > 0.5 ? darken(color, coefficient) : lighten(color, coefficient);
}
/**
* Set the absolute transparency of a color.
* Any existing alpha values are overwritten.
* @param color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), color()
* @param value - value to set the alpha channel to in the range 0 - 1
* @returns A CSS color string. Hex input values are returned as rgb
* @beta
*/
export function alpha(color: string, value: number) {
const parts = decomposeColor(color);
value = clamp(value);
if (parts.type === 'rgb' || parts.type === 'hsl') {
parts.type += 'a';
}
if (parts.type === 'color') {
parts.values[3] = `/${value}`;
} else {
parts.values[3] = value;
}
return recomposeColor(parts);
}
/**
* Darkens a color.
* @param color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), color()
* @param coefficient - multiplier in the range 0 - 1
* @returns A CSS color string. Hex input values are returned as rgb
* @beta
*/
export function darken(color: string, coefficient: number) {
const parts = decomposeColor(color);
coefficient = clamp(coefficient);
if (parts.type.indexOf('hsl') !== -1) {
parts.values[2] *= 1 - coefficient;
} else if (parts.type.indexOf('rgb') !== -1 || parts.type.indexOf('color') !== -1) {
for (let i = 0; i < 3; i += 1) {
parts.values[i] *= 1 - coefficient;
}
}
return recomposeColor(parts);
}
/**
* Lightens a color.
* @param color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), color()
* @param coefficient - multiplier in the range 0 - 1
* @returns A CSS color string. Hex input values are returned as rgb
* @beta
*/
export function lighten(color: string, coefficient: number) {
const parts = decomposeColor(color);
coefficient = clamp(coefficient);
if (parts.type.indexOf('hsl') !== -1) {
parts.values[2] += (100 - parts.values[2]) * coefficient;
} else if (parts.type.indexOf('rgb') !== -1) {
for (let i = 0; i < 3; i += 1) {
parts.values[i] += (255 - parts.values[i]) * coefficient;
}
} else if (parts.type.indexOf('color') !== -1) {
for (let i = 0; i < 3; i += 1) {
parts.values[i] += (1 - parts.values[i]) * coefficient;
}
}
return recomposeColor(parts);
}
interface DecomposeColor {
type: string;
values: any;
colorSpace?: string;
}
| packages/grafana-data/src/themes/colorManipulator.ts | 1 | https://github.com/grafana/grafana/commit/8ecfad69951628cc8327c23166d953f86a8d83ff | [
0.0016547051491215825,
0.0003473516262602061,
0.00016120588406920433,
0.0001730403455439955,
0.0003763539425563067
] |
{
"id": 1,
"code_window": [
" *\n",
" * Formula: https://www.w3.org/TR/WCAG20-TECHS/G17.html#G17-tests\n",
" * @param foreground - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()\n",
" * @param background - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()\n",
" * @returns A contrast ratio value in the range 0 - 21.\n",
" * @beta\n",
" */\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" * @param canvas - A CSS color that alpha based backgrounds blends into\n"
],
"file_path": "packages/grafana-data/src/themes/colorManipulator.ts",
"type": "add",
"edit_start_line_idx": 177
} | +++
title = "Server admin tasks"
weight = 100
+++
# Server admin tasks
Grafana Server Admins use the **Server Admin** menu to manage user accounts and organizations set up on the Grafana server.
They perform tasks described in the following pages:
- [Manage users as a Server Admin]({{< relref "server-admin-manage-users.md" >}}) - Describes user management tasks that Grafana Server Admins can perform.
- [Manage organizations as a Server Admin]({{< relref "server-admin-manage-orgs.md" >}}) - Describes organization management tasks that Grafana Server Admins can perform.
- [User API]({{< relref "../../http_api/user.md" >}}) - Manage users or change passwords programmatically.
| docs/sources/manage-users/server-admin/_index.md | 0 | https://github.com/grafana/grafana/commit/8ecfad69951628cc8327c23166d953f86a8d83ff | [
0.00016493030125275254,
0.00016254540241789073,
0.0001601605035830289,
0.00016254540241789073,
0.000002384898834861815
] |
{
"id": 1,
"code_window": [
" *\n",
" * Formula: https://www.w3.org/TR/WCAG20-TECHS/G17.html#G17-tests\n",
" * @param foreground - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()\n",
" * @param background - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()\n",
" * @returns A contrast ratio value in the range 0 - 21.\n",
" * @beta\n",
" */\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" * @param canvas - A CSS color that alpha based backgrounds blends into\n"
],
"file_path": "packages/grafana-data/src/themes/colorManipulator.ts",
"type": "add",
"edit_start_line_idx": 177
} | /**********************************************
* Ink v1.0.5 - Copyright 2013 ZURB Inc *
**********************************************/
/* Client-specific Styles & Reset */
#outlook a {
padding:0;
}
body{
width:100% !important;
min-width: 100%;
-webkit-text-size-adjust:100%;
-ms-text-size-adjust:100%;
margin:0;
padding:0;
}
.ExternalClass {
width:100%;
}
.ExternalClass,
.ExternalClass p,
.ExternalClass span,
.ExternalClass font,
.ExternalClass td,
.ExternalClass div {
line-height: 100%;
}
#backgroundTable {
margin:0;
padding:0;
width:100% !important;
line-height: 100% !important;
}
img {
outline:none;
text-decoration:none;
-ms-interpolation-mode: bicubic;
width: auto;
float: left;
clear: both;
display: block;
}
center {
width: 100%;
min-width: 580px;
}
a img {
border: none;
}
p {
margin: 0 0 0 10px;
}
table {
border-spacing: 0;
border-collapse: collapse;
}
td {
word-break: break-word;
-webkit-hyphens: auto;
-moz-hyphens: auto;
hyphens: auto;
border-collapse: collapse !important;
}
table, tr, td {
padding: 0;
vertical-align: top;
text-align: left;
}
hr {
color: #d9d9d9;
background-color: #d9d9d9;
height: 1px;
border: none;
}
/* Responsive Grid */
table.body {
height: 100%;
width: 100%;
}
table.container {
width: 580px;
margin: 0 auto;
text-align: inherit;
}
table.row {
padding: 0px;
width: 100%;
position: relative;
}
table.container table.row {
display: block;
}
td.wrapper {
padding: 10px 20px 0px 0px;
position: relative;
}
table.columns,
table.column {
margin: 0 auto;
}
table.columns td,
table.column td {
padding: 0px 0px 10px;
}
table.columns td.sub-columns,
table.column td.sub-columns,
table.columns td.sub-column,
table.column td.sub-column {
padding-right: 10px;
}
td.sub-column, td.sub-columns {
min-width: 0px;
}
table.row td.last,
table.container td.last {
padding-right: 0px;
}
table.one { width: 30px; }
table.two { width: 80px; }
table.three { width: 130px; }
table.four { width: 180px; }
table.five { width: 230px; }
table.six { width: 280px; }
table.seven { width: 330px; }
table.eight { width: 380px; }
table.nine { width: 430px; }
table.ten { width: 480px; }
table.eleven { width: 530px; }
table.twelve { width: 580px; }
table.one center { min-width: 30px; }
table.two center { min-width: 80px; }
table.three center { min-width: 130px; }
table.four center { min-width: 180px; }
table.five center { min-width: 230px; }
table.six center { min-width: 280px; }
table.seven center { min-width: 330px; }
table.eight center { min-width: 380px; }
table.nine center { min-width: 430px; }
table.ten center { min-width: 480px; }
table.eleven center { min-width: 530px; }
table.twelve center { min-width: 580px; }
table.one .panel center { min-width: 10px; }
table.two .panel center { min-width: 60px; }
table.three .panel center { min-width: 110px; }
table.four .panel center { min-width: 160px; }
table.five .panel center { min-width: 210px; }
table.six .panel center { min-width: 260px; }
table.seven .panel center { min-width: 310px; }
table.eight .panel center { min-width: 360px; }
table.nine .panel center { min-width: 410px; }
table.ten .panel center { min-width: 460px; }
table.eleven .panel center { min-width: 510px; }
table.twelve .panel center { min-width: 560px; }
.body .columns td.one,
.body .column td.one { width: 8.333333%; }
.body .columns td.two,
.body .column td.two { width: 16.666666%; }
.body .columns td.three,
.body .column td.three { width: 25%; }
.body .columns td.four,
.body .column td.four { width: 33.333333%; }
.body .columns td.five,
.body .column td.five { width: 41.666666%; }
.body .columns td.six,
.body .column td.six { width: 50%; }
.body .columns td.seven,
.body .column td.seven { width: 58.333333%; }
.body .columns td.eight,
.body .column td.eight { width: 66.666666%; }
.body .columns td.nine,
.body .column td.nine { width: 75%; }
.body .columns td.ten,
.body .column td.ten { width: 83.333333%; }
.body .columns td.eleven,
.body .column td.eleven { width: 91.666666%; }
.body .columns td.twelve,
.body .column td.twelve { width: 100%; }
td.offset-by-one { padding-left: 50px; }
td.offset-by-two { padding-left: 100px; }
td.offset-by-three { padding-left: 150px; }
td.offset-by-four { padding-left: 200px; }
td.offset-by-five { padding-left: 250px; }
td.offset-by-six { padding-left: 300px; }
td.offset-by-seven { padding-left: 350px; }
td.offset-by-eight { padding-left: 400px; }
td.offset-by-nine { padding-left: 450px; }
td.offset-by-ten { padding-left: 500px; }
td.offset-by-eleven { padding-left: 550px; }
td.expander {
visibility: hidden;
width: 0px;
padding: 0 !important;
}
table.columns .text-pad,
table.column .text-pad {
padding-left: 10px;
padding-right: 10px;
}
table.columns .left-text-pad,
table.columns .text-pad-left,
table.column .left-text-pad,
table.column .text-pad-left {
padding-left: 10px;
}
table.columns .right-text-pad,
table.columns .text-pad-right,
table.column .right-text-pad,
table.column .text-pad-right {
padding-right: 10px;
}
/* Block Grid */
.block-grid {
width: 100%;
max-width: 580px;
}
.block-grid td {
display: inline-block;
padding:10px;
}
.two-up td {
width:270px;
}
.three-up td {
width:173px;
}
.four-up td {
width:125px;
}
.five-up td {
width:96px;
}
.six-up td {
width:76px;
}
.seven-up td {
width:62px;
}
.eight-up td {
width:52px;
}
/* Alignment & Visibility Classes */
table.center, td.center {
text-align: center;
}
h1.center,
h2.center,
h3.center,
h4.center,
h5.center,
h6.center {
text-align: center;
}
span.center {
display: block;
width: 100%;
text-align: center;
}
img.center {
margin: 0 auto;
float: none;
}
.show-for-small,
.hide-for-desktop {
display: none;
}
/* Typography */
body, table.body, h1, h2, h3, h4, h5, h6, p, td {
color: #222222;
font-family: "Helvetica", "Arial", sans-serif;
font-weight: normal;
padding:0;
margin: 0;
text-align: left;
line-height: 1.3;
}
h1, h2, h3, h4, h5, h6 {
word-break: normal;
}
h1 {font-size: 40px;}
h2 {font-size: 36px;}
h3 {font-size: 32px;}
h4 {font-size: 28px;}
h5 {font-size: 24px;}
h6 {font-size: 20px;}
body, table.body, p, td {font-size: 14px;line-height:19px;}
p.lead, p.lede, p.leed {
font-size: 18px;
line-height:21px;
}
p {
margin-bottom: 10px;
}
small {
font-size: 10px;
}
a {
color: #2ba6cb;
text-decoration: none;
}
a:hover {
color: #2795b6 !important;
}
a:active {
color: #2795b6 !important;
}
a:visited {
color: #2ba6cb !important;
}
h1 a,
h2 a,
h3 a,
h4 a,
h5 a,
h6 a {
color: #2ba6cb;
}
h1 a:active,
h2 a:active,
h3 a:active,
h4 a:active,
h5 a:active,
h6 a:active {
color: #2ba6cb !important;
}
h1 a:visited,
h2 a:visited,
h3 a:visited,
h4 a:visited,
h5 a:visited,
h6 a:visited {
color: #2ba6cb !important;
}
/* Panels */
.panel {
background: #f2f2f2;
border: 1px solid #d9d9d9;
padding: 10px !important;
}
.sub-grid table {
width: 100%;
}
.sub-grid td.sub-columns {
padding-bottom: 0;
}
/* Buttons */
table.button,
table.tiny-button,
table.small-button,
table.medium-button,
table.large-button {
width: 100%;
overflow: hidden;
}
table.button td,
table.tiny-button td,
table.small-button td,
table.medium-button td,
table.large-button td {
display: block;
width: auto !important;
text-align: center;
background: #2ba6cb;
border: 1px solid #2284a1;
color: #ffffff;
padding: 8px 0;
}
table.tiny-button td {
padding: 5px 0 4px;
}
table.small-button td {
padding: 8px 0 7px;
}
table.medium-button td {
padding: 12px 0 10px;
}
table.large-button td {
padding: 21px 0 18px;
}
table.button td a,
table.tiny-button td a,
table.small-button td a,
table.medium-button td a,
table.large-button td a {
font-weight: bold;
text-decoration: none;
font-family: Helvetica, Arial, sans-serif;
color: #ffffff;
font-size: 16px;
}
table.tiny-button td a {
font-size: 12px;
font-weight: normal;
}
table.small-button td a {
font-size: 16px;
}
table.medium-button td a {
font-size: 20px;
}
table.large-button td a {
font-size: 24px;
}
table.button:hover td,
table.button:visited td,
table.button:active td {
background: #2795b6 !important;
}
table.button:hover td a,
table.button:visited td a,
table.button:active td a {
color: #fff !important;
}
table.button:hover td,
table.tiny-button:hover td,
table.small-button:hover td,
table.medium-button:hover td,
table.large-button:hover td {
background: #2795b6 !important;
}
table.button:hover td a,
table.button:active td a,
table.button td a:visited,
table.tiny-button:hover td a,
table.tiny-button:active td a,
table.tiny-button td a:visited,
table.small-button:hover td a,
table.small-button:active td a,
table.small-button td a:visited,
table.medium-button:hover td a,
table.medium-button:active td a,
table.medium-button td a:visited,
table.large-button:hover td a,
table.large-button:active td a,
table.large-button td a:visited {
color: #ffffff !important;
}
table.secondary td {
background: #e9e9e9;
border-color: #d0d0d0;
color: #555;
}
table.secondary td a {
color: #555;
}
table.secondary:hover td {
background: #d0d0d0 !important;
color: #555;
}
table.secondary:hover td a,
table.secondary td a:visited,
table.secondary:active td a {
color: #555 !important;
}
table.success td {
background: #5da423;
border-color: #457a1a;
}
table.success:hover td {
background: #457a1a !important;
}
table.alert td {
background: #c60f13;
border-color: #970b0e;
}
table.alert:hover td {
background: #970b0e !important;
}
table.radius td {
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
}
table.round td {
-webkit-border-radius: 500px;
-moz-border-radius: 500px;
border-radius: 500px;
}
/* Outlook First */
body.outlook p {
display: inline !important;
}
/* Media Queries */
@media only screen and (max-width: 600px) {
table[class="body"] img {
}
table[class="body"] center {
min-width: 0 !important;
}
table[class="body"] .container {
width: 95% !important;
}
table[class="body"] .row {
width: 100% !important;
display: block !important;
}
table[class="body"] .wrapper {
display: block !important;
padding-right: 0 !important;
}
table[class="body"] .columns,
table[class="body"] .column {
table-layout: fixed !important;
float: none !important;
width: 100% !important;
padding-right: 0px !important;
padding-left: 0px !important;
display: block !important;
}
table[class="body"] .wrapper.first .columns,
table[class="body"] .wrapper.first .column {
display: table !important;
}
table[class="body"] table.columns td,
table[class="body"] table.column td {
width: 100% !important;
}
table[class="body"] .columns td.one,
table[class="body"] .column td.one { width: 8.333333% !important; }
table[class="body"] .columns td.two,
table[class="body"] .column td.two { width: 16.666666% !important; }
table[class="body"] .columns td.three,
table[class="body"] .column td.three { width: 25% !important; }
table[class="body"] .columns td.four,
table[class="body"] .column td.four { width: 33.333333% !important; }
table[class="body"] .columns td.five,
table[class="body"] .column td.five { width: 41.666666% !important; }
table[class="body"] .columns td.six,
table[class="body"] .column td.six { width: 50% !important; }
table[class="body"] .columns td.seven,
table[class="body"] .column td.seven { width: 58.333333% !important; }
table[class="body"] .columns td.eight,
table[class="body"] .column td.eight { width: 66.666666% !important; }
table[class="body"] .columns td.nine,
table[class="body"] .column td.nine { width: 75% !important; }
table[class="body"] .columns td.ten,
table[class="body"] .column td.ten { width: 83.333333% !important; }
table[class="body"] .columns td.eleven,
table[class="body"] .column td.eleven { width: 91.666666% !important; }
table[class="body"] .columns td.twelve,
table[class="body"] .column td.twelve { width: 100% !important; }
table[class="body"] td.offset-by-one,
table[class="body"] td.offset-by-two,
table[class="body"] td.offset-by-three,
table[class="body"] td.offset-by-four,
table[class="body"] td.offset-by-five,
table[class="body"] td.offset-by-six,
table[class="body"] td.offset-by-seven,
table[class="body"] td.offset-by-eight,
table[class="body"] td.offset-by-nine,
table[class="body"] td.offset-by-ten,
table[class="body"] td.offset-by-eleven {
padding-left: 0 !important;
}
table[class="body"] table.columns td.expander {
width: 1px !important;
}
table[class="body"] .right-text-pad,
table[class="body"] .text-pad-right {
padding-left: 10px !important;
}
table[class="body"] .left-text-pad,
table[class="body"] .text-pad-left {
padding-right: 10px !important;
}
table[class="body"] .hide-for-small,
table[class="body"] .show-for-desktop {
display: none !important;
}
table[class="body"] .show-for-small,
table[class="body"] .hide-for-desktop {
display: inherit !important;
}
}
| emails/assets/css/ink.css | 0 | https://github.com/grafana/grafana/commit/8ecfad69951628cc8327c23166d953f86a8d83ff | [
0.0005234660347923636,
0.0001761333114700392,
0.00016403615882154554,
0.0001708289491944015,
0.00004219861148158088
] |
{
"id": 1,
"code_window": [
" *\n",
" * Formula: https://www.w3.org/TR/WCAG20-TECHS/G17.html#G17-tests\n",
" * @param foreground - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()\n",
" * @param background - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()\n",
" * @returns A contrast ratio value in the range 0 - 21.\n",
" * @beta\n",
" */\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" * @param canvas - A CSS color that alpha based backgrounds blends into\n"
],
"file_path": "packages/grafana-data/src/themes/colorManipulator.ts",
"type": "add",
"edit_start_line_idx": 177
} | datasources:
- name: Graphite
type: graphite
access: proxy
url: http://localhost:8080
- name: Prometheus
type: prometheus
access: proxy
url: http://localhost:9090
| pkg/services/provisioning/datasources/testdata/two-datasources/two-datasources.yaml | 0 | https://github.com/grafana/grafana/commit/8ecfad69951628cc8327c23166d953f86a8d83ff | [
0.00017491186736151576,
0.00017491186736151576,
0.00017491186736151576,
0.00017491186736151576,
0
] |
{
"id": 2,
"code_window": [
" * @returns A contrast ratio value in the range 0 - 21.\n",
" * @beta\n",
" */\n",
"export function getContrastRatio(foreground: string, background: string) {\n",
" const lumA = getLuminance(foreground);\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"export function getContrastRatio(foreground: string, background: string, canvas?: string) {\n"
],
"file_path": "packages/grafana-data/src/themes/colorManipulator.ts",
"type": "replace",
"edit_start_line_idx": 180
} | import { merge } from 'lodash';
import { alpha, darken, emphasize, getContrastRatio, lighten } from './colorManipulator';
import { palette } from './palette';
import { DeepPartial, ThemeRichColor } from './types';
/** @internal */
export type ThemeColorsMode = 'light' | 'dark';
/** @internal */
export interface ThemeColorsBase<TColor> {
mode: ThemeColorsMode;
primary: TColor;
secondary: TColor;
info: TColor;
error: TColor;
success: TColor;
warning: TColor;
text: {
primary: string;
secondary: string;
disabled: string;
link: string;
/** Used for auto white or dark text on colored backgrounds */
maxContrast: string;
};
background: {
/** Dashboard and body background */
canvas: string;
/** Primary content pane background (panels etc) */
primary: string;
/** Cards and elements that need to stand out on the primary background */
secondary: string;
};
border: {
weak: string;
medium: string;
strong: string;
};
gradients: {
brandVertical: string;
brandHorizontal: string;
};
action: {
/** Used for selected menu item / select option */
selected: string;
/** Used for hovered menu item / select option */
hover: string;
/** Used for button/colored background hover opacity */
hoverOpacity: number;
/** Used focused menu item / select option */
focus: string;
/** Used for disabled buttons and inputs */
disabledBackground: string;
/** Disabled text */
disabledText: string;
/** Disablerd opacity */
disabledOpacity: number;
};
hoverFactor: number;
contrastThreshold: number;
tonalOffset: number;
}
export interface ThemeHoverStrengh {}
/** @beta */
export interface ThemeColors extends ThemeColorsBase<ThemeRichColor> {
/** Returns a text color for the background */
getContrastText(background: string, threshold?: number): string;
/* Brighten or darken a color by specified factor (0-1) */
emphasize(color: string, amount?: number): string;
}
/** @internal */
export type ThemeColorsInput = DeepPartial<ThemeColorsBase<ThemeRichColor>>;
class DarkColors implements ThemeColorsBase<Partial<ThemeRichColor>> {
mode: ThemeColorsMode = 'dark';
// Used to get more white opacity colors
whiteBase = '201, 209, 217';
border = {
weak: `rgba(${this.whiteBase}, 0.08)`,
medium: `rgba(${this.whiteBase}, 0.15)`,
strong: `rgba(${this.whiteBase}, 0.25)`,
};
text = {
primary: `rgb(${this.whiteBase})`,
secondary: `rgba(${this.whiteBase}, 0.65)`,
disabled: `rgba(${this.whiteBase}, 0.40)`,
link: palette.blueDarkText,
maxContrast: palette.white,
};
primary = {
main: palette.blueDarkMain,
text: palette.blueDarkText,
border: palette.blueDarkText,
};
secondary = {
main: `rgba(${this.whiteBase}, 0.1)`,
shade: `rgba(${this.whiteBase}, 0.15)`,
text: this.text.primary,
contrastText: `rgb(${this.whiteBase})`,
border: this.border.strong,
};
info = this.primary;
error = {
main: palette.redDarkMain,
text: palette.redDarkText,
};
success = {
main: palette.greenDarkMain,
text: palette.greenDarkText,
};
warning = {
main: palette.orangeDarkMain,
text: palette.orangeDarkText,
};
background = {
canvas: palette.gray05,
primary: palette.gray10,
secondary: palette.gray15,
};
action = {
hover: `rgba(${this.whiteBase}, 0.08)`,
selected: `rgba(${this.whiteBase}, 0.12)`,
focus: `rgba(${this.whiteBase}, 0.16)`,
hoverOpacity: 0.08,
disabledText: this.text.disabled,
disabledBackground: `rgba(${this.whiteBase}, 0.07)`,
disabledOpacity: 0.38,
};
gradients = {
brandHorizontal: ' linear-gradient(270deg, #F55F3E 0%, #FF8833 100%);',
brandVertical: 'linear-gradient(0.01deg, #F55F3E 0.01%, #FF8833 99.99%);',
};
contrastThreshold = 3;
hoverFactor = 0.03;
tonalOffset = 0.15;
}
class LightColors implements ThemeColorsBase<Partial<ThemeRichColor>> {
mode: ThemeColorsMode = 'light';
blackBase = '36, 41, 46';
primary = {
main: palette.blueLightMain,
border: palette.blueLightText,
text: palette.blueLightText,
};
text = {
primary: `rgba(${this.blackBase}, 1)`,
secondary: `rgba(${this.blackBase}, 0.75)`,
disabled: `rgba(${this.blackBase}, 0.50)`,
link: this.primary.text,
maxContrast: palette.black,
};
border = {
weak: `rgba(${this.blackBase}, 0.12)`,
medium: `rgba(${this.blackBase}, 0.30)`,
strong: `rgba(${this.blackBase}, 0.40)`,
};
secondary = {
main: `rgba(${this.blackBase}, 0.11)`,
shade: `rgba(${this.blackBase}, 0.16)`,
contrastText: `rgba(${this.blackBase}, 1)`,
text: this.text.primary,
border: this.border.strong,
};
info = {
main: palette.blueLightMain,
text: palette.blueLightText,
};
error = {
main: palette.redLightMain,
text: palette.redLightText,
border: palette.redLightText,
};
success = {
main: palette.greenLightMain,
text: palette.greenLightText,
};
warning = {
main: palette.orangeLightMain,
text: palette.orangeLightText,
};
background = {
canvas: palette.gray90,
primary: palette.white,
secondary: palette.gray100,
};
action = {
hover: `rgba(${this.blackBase}, 0.04)`,
selected: `rgba(${this.blackBase}, 0.08)`,
hoverOpacity: 0.08,
focus: `rgba(${this.blackBase}, 0.12)`,
disabledBackground: `rgba(${this.blackBase}, 0.07)`,
disabledText: this.text.disabled,
disabledOpacity: 0.38,
};
gradients = {
brandHorizontal: 'linear-gradient(90deg, #FF8833 0%, #F53E4C 100%);',
brandVertical: 'linear-gradient(0.01deg, #F53E4C -31.2%, #FF8833 113.07%);',
};
contrastThreshold = 3;
hoverFactor = 0.03;
tonalOffset = 0.2;
}
export function createColors(colors: ThemeColorsInput): ThemeColors {
const dark = new DarkColors();
const light = new LightColors();
const base = (colors.mode ?? 'dark') === 'dark' ? dark : light;
const {
primary = base.primary,
secondary = base.secondary,
info = base.info,
warning = base.warning,
success = base.success,
error = base.error,
tonalOffset = base.tonalOffset,
hoverFactor = base.hoverFactor,
contrastThreshold = base.contrastThreshold,
...other
} = colors;
function getContrastText(background: string, threshold: number = contrastThreshold) {
const contrastText =
getContrastRatio(dark.text.maxContrast, background) >= threshold ? dark.text.maxContrast : light.text.maxContrast;
// todo, need color framework
return contrastText;
}
const getRichColor = ({ color, name }: GetRichColorProps): ThemeRichColor => {
color = { ...color, name };
if (!color.main) {
throw new Error(`Missing main color for ${name}`);
}
if (!color.text) {
color.text = color.main;
}
if (!color.border) {
color.border = color.text;
}
if (!color.shade) {
color.shade = base.mode === 'light' ? darken(color.main, tonalOffset) : lighten(color.main, tonalOffset);
}
if (!color.transparent) {
color.transparent = base.mode === 'light' ? alpha(color.main, 0.08) : alpha(color.main, 0.15);
}
if (!color.contrastText) {
color.contrastText = getContrastText(color.main);
}
return color as ThemeRichColor;
};
return merge(
{
...base,
primary: getRichColor({ color: primary, name: 'primary' }),
secondary: getRichColor({ color: secondary, name: 'secondary' }),
info: getRichColor({ color: info, name: 'info' }),
error: getRichColor({ color: error, name: 'error' }),
success: getRichColor({ color: success, name: 'success' }),
warning: getRichColor({ color: warning, name: 'warning' }),
getContrastText,
emphasize: (color: string, factor?: number) => {
return emphasize(color, factor ?? hoverFactor);
},
},
other
);
}
interface GetRichColorProps {
color: Partial<ThemeRichColor>;
name: string;
}
| packages/grafana-data/src/themes/createColors.ts | 1 | https://github.com/grafana/grafana/commit/8ecfad69951628cc8327c23166d953f86a8d83ff | [
0.998969316482544,
0.06570259481668472,
0.0001637155219214037,
0.00017909129383042455,
0.24482668936252594
] |
{
"id": 2,
"code_window": [
" * @returns A contrast ratio value in the range 0 - 21.\n",
" * @beta\n",
" */\n",
"export function getContrastRatio(foreground: string, background: string) {\n",
" const lumA = getLuminance(foreground);\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"export function getContrastRatio(foreground: string, background: string, canvas?: string) {\n"
],
"file_path": "packages/grafana-data/src/themes/colorManipulator.ts",
"type": "replace",
"edit_start_line_idx": 180
} | import {
DataFrame,
DataFrameView,
FieldType,
MutableDataFrame,
NodeGraphDataFrameFieldNames as Fields,
} from '@grafana/data';
interface Row {
traceID: string;
spanID: string;
parentSpanID: string;
operationName: string;
serviceName: string;
serviceTags: string;
startTime: number;
duration: number;
logs: string;
tags: string;
}
interface Node {
[Fields.id]: string;
[Fields.title]: string;
[Fields.subTitle]: string;
[Fields.mainStat]: string;
[Fields.secondaryStat]: string;
[Fields.color]: number;
}
interface Edge {
[Fields.id]: string;
[Fields.target]: string;
[Fields.source]: string;
}
export function createGraphFrames(data: DataFrame): DataFrame[] {
const { nodes, edges } = convertTraceToGraph(data);
const nodesFrame = new MutableDataFrame({
fields: [
{ name: Fields.id, type: FieldType.string },
{ name: Fields.title, type: FieldType.string },
{ name: Fields.subTitle, type: FieldType.string },
{ name: Fields.mainStat, type: FieldType.string, config: { displayName: 'Total time (% of trace)' } },
{ name: Fields.secondaryStat, type: FieldType.string, config: { displayName: 'Self time (% of total)' } },
{ name: Fields.color, type: FieldType.number, config: { color: { mode: 'continuous-GrYlRd' } } },
],
meta: {
preferredVisualisationType: 'nodeGraph',
},
});
for (const node of nodes) {
nodesFrame.add(node);
}
const edgesFrame = new MutableDataFrame({
fields: [
{ name: Fields.id, type: FieldType.string },
{ name: Fields.target, type: FieldType.string },
{ name: Fields.source, type: FieldType.string },
],
meta: {
preferredVisualisationType: 'nodeGraph',
},
});
for (const edge of edges) {
edgesFrame.add(edge);
}
return [nodesFrame, edgesFrame];
}
function convertTraceToGraph(data: DataFrame): { nodes: Node[]; edges: Edge[] } {
const nodes: Node[] = [];
const edges: Edge[] = [];
const view = new DataFrameView<Row>(data);
const traceDuration = findTraceDuration(view);
const spanMap = makeSpanMap(view);
for (let i = 0; i < view.length; i++) {
const row = view.get(i);
const childrenDuration = getDuration(spanMap[row.spanID].children.map((c) => spanMap[c].span));
const selfDuration = row.duration - childrenDuration;
nodes.push({
[Fields.id]: row.spanID,
[Fields.title]: row.serviceName ?? '',
[Fields.subTitle]: row.operationName,
[Fields.mainStat]: `total: ${toFixedNoTrailingZeros(row.duration)}ms (${toFixedNoTrailingZeros(
(row.duration / traceDuration) * 100
)}%)`,
[Fields.secondaryStat]: `self: ${toFixedNoTrailingZeros(selfDuration)}ms (${toFixedNoTrailingZeros(
(selfDuration / row.duration) * 100
)}%)`,
[Fields.color]: selfDuration / traceDuration,
});
// Sometimes some span can be missing. Don't add edges for those.
if (row.parentSpanID && spanMap[row.parentSpanID].span) {
edges.push({
[Fields.id]: row.parentSpanID + '--' + row.spanID,
[Fields.target]: row.spanID,
[Fields.source]: row.parentSpanID,
});
}
}
return { nodes, edges };
}
function toFixedNoTrailingZeros(n: number) {
return parseFloat(n.toFixed(2));
}
/**
* Get the duration of the whole trace as it isn't a part of the response data.
* Note: Seems like this should be the same as just longest span, but this is probably safer.
*/
function findTraceDuration(view: DataFrameView<Row>): number {
let traceEndTime = 0;
let traceStartTime = Infinity;
for (let i = 0; i < view.length; i++) {
const row = view.get(i);
if (row.startTime < traceStartTime) {
traceStartTime = row.startTime;
}
if (row.startTime + row.duration > traceEndTime) {
traceEndTime = row.startTime + row.duration;
}
}
return traceEndTime - traceStartTime;
}
/**
* Returns a map of the spans with children array for easier processing. It will also contain empty spans in case
* span is missing but other spans are it's children.
*/
function makeSpanMap(view: DataFrameView<Row>): { [id: string]: { span: Row; children: string[] } } {
const spanMap: { [id: string]: { span?: Row; children: string[] } } = {};
for (let i = 0; i < view.length; i++) {
const row = view.get(i);
if (!spanMap[row.spanID]) {
spanMap[row.spanID] = {
// Need copy because of how the view works
span: { ...row },
children: [],
};
} else {
spanMap[row.spanID].span = { ...row };
}
if (!spanMap[row.parentSpanID]) {
spanMap[row.parentSpanID] = {
span: undefined,
children: [row.spanID],
};
} else {
spanMap[row.parentSpanID].children.push(row.spanID);
}
}
return spanMap as { [id: string]: { span: Row; children: string[] } };
}
/**
* Get non overlapping duration of the spans.
*/
function getDuration(rows: Row[]): number {
const ranges = rows.map<[number, number]>((r) => [r.startTime, r.startTime + r.duration]);
ranges.sort((a, b) => a[0] - b[0]);
const mergedRanges = ranges.reduce((acc, range) => {
if (!acc.length) {
return [range];
}
const tail = acc.slice(-1)[0];
const [prevStart, prevEnd] = tail;
const [start, end] = range;
if (end < prevEnd) {
// In this case the range is completely inside the prev range so we can just ignore it.
return acc;
}
if (start > prevEnd) {
// There is no overlap so we can just add it to stack
return [...acc, range];
}
// We know there is overlap and current range ends later than previous so we can just extend the range
return [...acc.slice(0, -1), [prevStart, end]] as Array<[number, number]>;
}, [] as Array<[number, number]>);
return mergedRanges.reduce((acc, range) => {
return acc + (range[1] - range[0]);
}, 0);
}
| public/app/plugins/datasource/tempo/graphTransform.ts | 0 | https://github.com/grafana/grafana/commit/8ecfad69951628cc8327c23166d953f86a8d83ff | [
0.00017744726210366935,
0.00017246289644390345,
0.0001660413108766079,
0.00017241219757124782,
0.0000024622688670206117
] |
{
"id": 2,
"code_window": [
" * @returns A contrast ratio value in the range 0 - 21.\n",
" * @beta\n",
" */\n",
"export function getContrastRatio(foreground: string, background: string) {\n",
" const lumA = getLuminance(foreground);\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"export function getContrastRatio(foreground: string, background: string, canvas?: string) {\n"
],
"file_path": "packages/grafana-data/src/themes/colorManipulator.ts",
"type": "replace",
"edit_start_line_idx": 180
} | export function getManagementApiRoute(azureCloud: string): string {
switch (azureCloud) {
case 'azuremonitor':
return 'azuremonitor';
case 'chinaazuremonitor':
return 'chinaazuremonitor';
case 'govazuremonitor':
return 'govazuremonitor';
case 'germanyazuremonitor':
return 'germanyazuremonitor';
default:
throw new Error('The cloud not supported.');
}
}
export function getLogAnalyticsManagementApiRoute(azureCloud: string): string {
switch (azureCloud) {
case 'azuremonitor':
return 'workspacesloganalytics';
case 'chinaazuremonitor':
return 'chinaworkspacesloganalytics';
case 'govazuremonitor':
return 'govworkspacesloganalytics';
default:
throw new Error('The cloud not supported.');
}
}
export function getLogAnalyticsApiRoute(azureCloud: string): string {
switch (azureCloud) {
case 'azuremonitor':
return 'loganalyticsazure';
case 'chinaazuremonitor':
return 'chinaloganalyticsazure';
case 'govazuremonitor':
return 'govloganalyticsazure';
default:
throw new Error('The cloud not supported.');
}
}
export function getAppInsightsApiRoute(azureCloud: string): string {
switch (azureCloud) {
case 'azuremonitor':
return 'appinsights';
case 'chinaazuremonitor':
return 'chinaappinsights';
default:
throw new Error('The cloud not supported.');
}
}
| public/app/plugins/datasource/grafana-azure-monitor-datasource/api/routes.ts | 0 | https://github.com/grafana/grafana/commit/8ecfad69951628cc8327c23166d953f86a8d83ff | [
0.00018185902445111424,
0.00017322467465419322,
0.00016766520275268704,
0.0001714857353363186,
0.0000049895752454176545
] |
{
"id": 2,
"code_window": [
" * @returns A contrast ratio value in the range 0 - 21.\n",
" * @beta\n",
" */\n",
"export function getContrastRatio(foreground: string, background: string) {\n",
" const lumA = getLuminance(foreground);\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"export function getContrastRatio(foreground: string, background: string, canvas?: string) {\n"
],
"file_path": "packages/grafana-data/src/themes/colorManipulator.ts",
"type": "replace",
"edit_start_line_idx": 180
} | import React from 'react';
import { RefreshPicker, defaultIntervals } from '@grafana/ui';
import { getTimeSrv } from 'app/features/dashboard/services/TimeSrv';
export type Props = {
isSmall?: boolean;
loading: boolean;
isLive: boolean;
onRun: (loading: boolean) => void;
refreshInterval?: string;
onChangeRefreshInterval: (interval: string) => void;
showDropdown: boolean;
};
export function RunButton(props: Props) {
const { isSmall, loading, onRun, onChangeRefreshInterval, refreshInterval, showDropdown, isLive } = props;
const intervals = getTimeSrv().getValidIntervals(defaultIntervals);
let text: string | undefined;
if (isLive) {
return null;
}
if (!isSmall) {
text = loading ? 'Cancel' : 'Run query';
}
return (
<RefreshPicker
onIntervalChanged={onChangeRefreshInterval}
value={refreshInterval}
isLoading={loading}
text={text}
intervals={intervals}
isLive={isLive}
onRefresh={() => onRun(loading)}
noIntervalPicker={!showDropdown}
primary={true}
/>
);
}
| public/app/features/explore/RunButton.tsx | 0 | https://github.com/grafana/grafana/commit/8ecfad69951628cc8327c23166d953f86a8d83ff | [
0.00018185902445111424,
0.0001750962546793744,
0.00016925316595006734,
0.00017515836225356907,
0.000004719461685454007
] |
{
"id": 3,
"code_window": [
" const lumA = getLuminance(foreground);\n",
" const lumB = getLuminance(background);\n",
" return (Math.max(lumA, lumB) + 0.05) / (Math.min(lumA, lumB) + 0.05);\n",
"}\n",
"\n",
"/**\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const lumB = getLuminance(background, canvas);\n"
],
"file_path": "packages/grafana-data/src/themes/colorManipulator.ts",
"type": "replace",
"edit_start_line_idx": 182
} | import {
recomposeColor,
hexToRgb,
rgbToHex,
hslToRgb,
darken,
decomposeColor,
emphasize,
alpha,
getContrastRatio,
getLuminance,
lighten,
} from './colorManipulator';
describe('utils/colorManipulator', () => {
const origError = console.error;
const consoleErrorMock = jest.fn();
afterEach(() => (console.error = origError));
beforeEach(() => (console.error = consoleErrorMock));
describe('recomposeColor', () => {
it('converts a decomposed rgb color object to a string` ', () => {
expect(
recomposeColor({
type: 'rgb',
values: [255, 255, 255],
})
).toEqual('rgb(255, 255, 255)');
});
it('converts a decomposed rgba color object to a string` ', () => {
expect(
recomposeColor({
type: 'rgba',
values: [255, 255, 255, 0.5],
})
).toEqual('rgba(255, 255, 255, 0.5)');
});
it('converts a decomposed CSS4 color object to a string` ', () => {
expect(
recomposeColor({
type: 'color',
colorSpace: 'display-p3',
values: [0.5, 0.3, 0.2],
})
).toEqual('color(display-p3 0.5 0.3 0.2)');
});
it('converts a decomposed hsl color object to a string` ', () => {
expect(
recomposeColor({
type: 'hsl',
values: [100, 50, 25],
})
).toEqual('hsl(100, 50%, 25%)');
});
it('converts a decomposed hsla color object to a string` ', () => {
expect(
recomposeColor({
type: 'hsla',
values: [100, 50, 25, 0.5],
})
).toEqual('hsla(100, 50%, 25%, 0.5)');
});
});
describe('hexToRgb', () => {
it('converts a short hex color to an rgb color` ', () => {
expect(hexToRgb('#9f3')).toEqual('rgb(153, 255, 51)');
});
it('converts a long hex color to an rgb color` ', () => {
expect(hexToRgb('#a94fd3')).toEqual('rgb(169, 79, 211)');
});
it('converts a long alpha hex color to an argb color` ', () => {
expect(hexToRgb('#111111f8')).toEqual('rgba(17, 17, 17, 0.973)');
});
});
describe('rgbToHex', () => {
it('converts an rgb color to a hex color` ', () => {
expect(rgbToHex('rgb(169, 79, 211)')).toEqual('#a94fd3');
});
it('idempotent', () => {
expect(rgbToHex('#A94FD3')).toEqual('#A94FD3');
});
});
describe('hslToRgb', () => {
it('converts an hsl color to an rgb color` ', () => {
expect(hslToRgb('hsl(281, 60%, 57%)')).toEqual('rgb(169, 80, 211)');
});
it('converts an hsla color to an rgba color` ', () => {
expect(hslToRgb('hsla(281, 60%, 57%, 0.5)')).toEqual('rgba(169, 80, 211, 0.5)');
});
it('allow to convert values only', () => {
expect(hslToRgb(decomposeColor('hsl(281, 60%, 57%)'))).toEqual('rgb(169, 80, 211)');
});
});
describe('decomposeColor', () => {
it('converts an rgb color string to an object with `type` and `value` keys', () => {
const { type, values } = decomposeColor('rgb(255, 255, 255)');
expect(type).toEqual('rgb');
expect(values).toEqual([255, 255, 255]);
});
it('converts an rgba color string to an object with `type` and `value` keys', () => {
const { type, values } = decomposeColor('rgba(255, 255, 255, 0.5)');
expect(type).toEqual('rgba');
expect(values).toEqual([255, 255, 255, 0.5]);
});
it('converts an hsl color string to an object with `type` and `value` keys', () => {
const { type, values } = decomposeColor('hsl(100, 50%, 25%)');
expect(type).toEqual('hsl');
expect(values).toEqual([100, 50, 25]);
});
it('converts an hsla color string to an object with `type` and `value` keys', () => {
const { type, values } = decomposeColor('hsla(100, 50%, 25%, 0.5)');
expect(type).toEqual('hsla');
expect(values).toEqual([100, 50, 25, 0.5]);
});
it('converts CSS4 color with color space display-3', () => {
const { type, values, colorSpace } = decomposeColor('color(display-p3 0 1 0)');
expect(type).toEqual('color');
expect(colorSpace).toEqual('display-p3');
expect(values).toEqual([0, 1, 0]);
});
it('converts an alpha CSS4 color with color space display-3', () => {
const { type, values, colorSpace } = decomposeColor('color(display-p3 0 1 0 /0.4)');
expect(type).toEqual('color');
expect(colorSpace).toEqual('display-p3');
expect(values).toEqual([0, 1, 0, 0.4]);
});
it('should throw error with inexistent color color space', () => {
const decimposeWithError = () => decomposeColor('color(foo 0 1 0)');
expect(decimposeWithError).toThrow();
});
it('idempotent', () => {
const output1 = decomposeColor('hsla(100, 50%, 25%, 0.5)');
const output2 = decomposeColor(output1);
expect(output1).toEqual(output2);
});
it('converts rgba hex', () => {
const decomposed = decomposeColor('#111111f8');
expect(decomposed).toEqual({
type: 'rgba',
colorSpace: undefined,
values: [17, 17, 17, 0.973],
});
});
});
describe('getContrastRatio', () => {
it('returns a ratio for black : white', () => {
expect(getContrastRatio('#000', '#FFF')).toEqual(21);
});
it('returns a ratio for black : black', () => {
expect(getContrastRatio('#000', '#000')).toEqual(1);
});
it('returns a ratio for white : white', () => {
expect(getContrastRatio('#FFF', '#FFF')).toEqual(1);
});
it('returns a ratio for dark-grey : light-grey', () => {
//expect(getContrastRatio('#707070', '#E5E5E5'))to.be.approximately(3.93, 0.01);
});
it('returns a ratio for black : light-grey', () => {
//expect(getContrastRatio('#000', '#888')).to.be.approximately(5.92, 0.01);
});
});
describe('getLuminance', () => {
it('returns a valid luminance for rgb black', () => {
expect(getLuminance('rgba(0, 0, 0)')).toEqual(0);
expect(getLuminance('rgb(0, 0, 0)')).toEqual(0);
expect(getLuminance('color(display-p3 0 0 0)')).toEqual(0);
});
it('returns a valid luminance for rgb white', () => {
expect(getLuminance('rgba(255, 255, 255)')).toEqual(1);
expect(getLuminance('rgb(255, 255, 255)')).toEqual(1);
});
it('returns a valid luminance for rgb mid-grey', () => {
expect(getLuminance('rgba(127, 127, 127)')).toEqual(0.212);
expect(getLuminance('rgb(127, 127, 127)')).toEqual(0.212);
});
it('returns a valid luminance for an rgb color', () => {
expect(getLuminance('rgb(255, 127, 0)')).toEqual(0.364);
});
it('returns a valid luminance from an hsl color', () => {
expect(getLuminance('hsl(100, 100%, 50%)')).toEqual(0.735);
});
it('returns an equal luminance for the same color in different formats', () => {
const hsl = 'hsl(100, 100%, 50%)';
const rgb = 'rgb(85, 255, 0)';
expect(getLuminance(hsl)).toEqual(getLuminance(rgb));
});
it('returns a valid luminance from an CSS4 color', () => {
expect(getLuminance('color(display-p3 1 1 0.1)')).toEqual(0.929);
});
it('throw on invalid colors', () => {
expect(() => {
getLuminance('black');
}).toThrowError(/Unsupported 'black' color/);
});
});
describe('emphasize', () => {
it('lightens a dark rgb color with the coefficient provided', () => {
expect(emphasize('rgb(1, 2, 3)', 0.4)).toEqual(lighten('rgb(1, 2, 3)', 0.4));
});
it('darkens a light rgb color with the coefficient provided', () => {
expect(emphasize('rgb(250, 240, 230)', 0.3)).toEqual(darken('rgb(250, 240, 230)', 0.3));
});
it('lightens a dark rgb color with the coefficient 0.15 by default', () => {
expect(emphasize('rgb(1, 2, 3)')).toEqual(lighten('rgb(1, 2, 3)', 0.15));
});
it('darkens a light rgb color with the coefficient 0.15 by default', () => {
expect(emphasize('rgb(250, 240, 230)')).toEqual(darken('rgb(250, 240, 230)', 0.15));
});
it('lightens a dark CSS4 color with the coefficient 0.15 by default', () => {
expect(emphasize('color(display-p3 0.1 0.1 0.1)')).toEqual(lighten('color(display-p3 0.1 0.1 0.1)', 0.15));
});
it('darkens a light CSS4 color with the coefficient 0.15 by default', () => {
expect(emphasize('color(display-p3 1 1 0.1)')).toEqual(darken('color(display-p3 1 1 0.1)', 0.15));
});
});
describe('alpha', () => {
it('converts an rgb color to an rgba color with the value provided', () => {
expect(alpha('rgb(1, 2, 3)', 0.4)).toEqual('rgba(1, 2, 3, 0.4)');
});
it('updates an CSS4 color with the alpha value provided', () => {
expect(alpha('color(display-p3 1 2 3)', 0.4)).toEqual('color(display-p3 1 2 3 /0.4)');
});
it('updates an rgba color with the alpha value provided', () => {
expect(alpha('rgba(255, 0, 0, 0.2)', 0.5)).toEqual('rgba(255, 0, 0, 0.5)');
});
it('converts an hsl color to an hsla color with the value provided', () => {
expect(alpha('hsl(0, 100%, 50%)', 0.1)).toEqual('hsla(0, 100%, 50%, 0.1)');
});
it('updates an hsla color with the alpha value provided', () => {
expect(alpha('hsla(0, 100%, 50%, 0.2)', 0.5)).toEqual('hsla(0, 100%, 50%, 0.5)');
});
it('throw on invalid colors', () => {
expect(() => {
alpha('white', 0.4);
}).toThrowError(/Unsupported 'white' color/);
});
});
describe('darken', () => {
it("doesn't modify rgb black", () => {
expect(darken('rgb(0, 0, 0)', 0.1)).toEqual('rgb(0, 0, 0)');
});
it("doesn't overshoot if an above-range coefficient is supplied", () => {
expect(darken('rgb(0, 127, 255)', 1.5)).toEqual('rgb(0, 0, 0)');
expect(consoleErrorMock).toHaveBeenCalledWith('The value provided 1.5 is out of range [0, 1].');
});
it("doesn't overshoot if a below-range coefficient is supplied", () => {
expect(darken('rgb(0, 127, 255)', -0.1)).toEqual('rgb(0, 127, 255)');
expect(consoleErrorMock).toHaveBeenCalledWith('The value provided 1.5 is out of range [0, 1].');
});
it('darkens rgb white to black when coefficient is 1', () => {
expect(darken('rgb(255, 255, 255)', 1)).toEqual('rgb(0, 0, 0)');
});
it('retains the alpha value in an rgba color', () => {
expect(darken('rgb(0, 0, 0, 0.5)', 0.1)).toEqual('rgb(0, 0, 0, 0.5)');
});
it('darkens rgb white by 10% when coefficient is 0.1', () => {
expect(darken('rgb(255, 255, 255)', 0.1)).toEqual('rgb(229, 229, 229)');
});
it('darkens rgb red by 50% when coefficient is 0.5', () => {
expect(darken('rgb(255, 0, 0)', 0.5)).toEqual('rgb(127, 0, 0)');
});
it('darkens rgb grey by 50% when coefficient is 0.5', () => {
expect(darken('rgb(127, 127, 127)', 0.5)).toEqual('rgb(63, 63, 63)');
});
it("doesn't modify rgb colors when coefficient is 0", () => {
expect(darken('rgb(255, 255, 255)', 0)).toEqual('rgb(255, 255, 255)');
});
it('darkens hsl red by 50% when coefficient is 0.5', () => {
expect(darken('hsl(0, 100%, 50%)', 0.5)).toEqual('hsl(0, 100%, 25%)');
});
it("doesn't modify hsl colors when coefficient is 0", () => {
expect(darken('hsl(0, 100%, 50%)', 0)).toEqual('hsl(0, 100%, 50%)');
});
it("doesn't modify hsl colors when l is 0%", () => {
expect(darken('hsl(0, 50%, 0%)', 0.5)).toEqual('hsl(0, 50%, 0%)');
});
it('darkens CSS4 color red by 50% when coefficient is 0.5', () => {
expect(darken('color(display-p3 1 0 0)', 0.5)).toEqual('color(display-p3 0.5 0 0)');
});
it("doesn't modify CSS4 color when coefficient is 0", () => {
expect(darken('color(display-p3 1 0 0)', 0)).toEqual('color(display-p3 1 0 0)');
});
});
describe('lighten', () => {
it("doesn't modify rgb white", () => {
expect(lighten('rgb(255, 255, 255)', 0.1)).toEqual('rgb(255, 255, 255)');
});
it("doesn't overshoot if an above-range coefficient is supplied", () => {
expect(lighten('rgb(0, 127, 255)', 1.5)).toEqual('rgb(255, 255, 255)');
});
it("doesn't overshoot if a below-range coefficient is supplied", () => {
expect(lighten('rgb(0, 127, 255)', -0.1)).toEqual('rgb(0, 127, 255)');
});
it('lightens rgb black to white when coefficient is 1', () => {
expect(lighten('rgb(0, 0, 0)', 1)).toEqual('rgb(255, 255, 255)');
});
it('retains the alpha value in an rgba color', () => {
expect(lighten('rgb(255, 255, 255, 0.5)', 0.1)).toEqual('rgb(255, 255, 255, 0.5)');
});
it('lightens rgb black by 10% when coefficient is 0.1', () => {
expect(lighten('rgb(0, 0, 0)', 0.1)).toEqual('rgb(25, 25, 25)');
});
it('lightens rgb red by 50% when coefficient is 0.5', () => {
expect(lighten('rgb(255, 0, 0)', 0.5)).toEqual('rgb(255, 127, 127)');
});
it('lightens rgb grey by 50% when coefficient is 0.5', () => {
expect(lighten('rgb(127, 127, 127)', 0.5)).toEqual('rgb(191, 191, 191)');
});
it("doesn't modify rgb colors when coefficient is 0", () => {
expect(lighten('rgb(127, 127, 127)', 0)).toEqual('rgb(127, 127, 127)');
});
it('lightens hsl red by 50% when coefficient is 0.5', () => {
expect(lighten('hsl(0, 100%, 50%)', 0.5)).toEqual('hsl(0, 100%, 75%)');
});
it("doesn't modify hsl colors when coefficient is 0", () => {
expect(lighten('hsl(0, 100%, 50%)', 0)).toEqual('hsl(0, 100%, 50%)');
});
it("doesn't modify hsl colors when `l` is 100%", () => {
expect(lighten('hsl(0, 50%, 100%)', 0.5)).toEqual('hsl(0, 50%, 100%)');
});
it('lightens CSS4 color red by 50% when coefficient is 0.5', () => {
expect(lighten('color(display-p3 1 0 0)', 0.5)).toEqual('color(display-p3 1 0.5 0.5)');
});
it("doesn't modify CSS4 color when coefficient is 0", () => {
expect(lighten('color(display-p3 1 0 0)', 0)).toEqual('color(display-p3 1 0 0)');
});
});
});
| packages/grafana-data/src/themes/colorManipulator.test.ts | 1 | https://github.com/grafana/grafana/commit/8ecfad69951628cc8327c23166d953f86a8d83ff | [
0.0006457692361436784,
0.00019029287796001881,
0.00016507583495695144,
0.00017717387527227402,
0.00007329343497985974
] |
{
"id": 3,
"code_window": [
" const lumA = getLuminance(foreground);\n",
" const lumB = getLuminance(background);\n",
" return (Math.max(lumA, lumB) + 0.05) / (Math.min(lumA, lumB) + 0.05);\n",
"}\n",
"\n",
"/**\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const lumB = getLuminance(background, canvas);\n"
],
"file_path": "packages/grafana-data/src/themes/colorManipulator.ts",
"type": "replace",
"edit_start_line_idx": 182
} | // Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`SelectOption renders correctly 1`] = `
<div
className="css-o8533i-Option"
id=""
onClick={[MockFunction]}
onMouseMove={[MockFunction]}
onMouseOver={[MockFunction]}
tabIndex={1}
>
<div
className="gf-form-select-box__desc-option"
>
<img
className="gf-form-select-box__desc-option__img"
src="url/to/avatar"
/>
<div
className="gf-form-select-box__desc-option__body"
>
<div>
Model title
</div>
</div>
</div>
</div>
`;
| packages/grafana-ui/src/components/Forms/Legacy/Select/__snapshots__/SelectOption.test.tsx.snap | 0 | https://github.com/grafana/grafana/commit/8ecfad69951628cc8327c23166d953f86a8d83ff | [
0.00017794047016650438,
0.00017446426500100642,
0.00016827847866807133,
0.00017717387527227402,
0.000004385200099932263
] |
{
"id": 3,
"code_window": [
" const lumA = getLuminance(foreground);\n",
" const lumB = getLuminance(background);\n",
" return (Math.max(lumA, lumB) + 0.05) / (Math.min(lumA, lumB) + 0.05);\n",
"}\n",
"\n",
"/**\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const lumB = getLuminance(background, canvas);\n"
],
"file_path": "packages/grafana-data/src/themes/colorManipulator.ts",
"type": "replace",
"edit_start_line_idx": 182
} | import { VariableModel } from '@grafana/data';
import { VariableWithOptions } from '../types';
export const formatVariableLabel = (variable: VariableModel) => {
if (!isVariableWithOptions(variable)) {
return variable.name;
}
const { current } = variable;
if (Array.isArray(current.text)) {
return current.text.join(' + ');
}
return current.text;
};
const isVariableWithOptions = (variable: VariableModel): variable is VariableWithOptions => {
return (
Array.isArray((variable as VariableWithOptions)?.options) ||
typeof (variable as VariableWithOptions)?.current === 'object'
);
};
| public/app/features/variables/shared/formatVariable.ts | 0 | https://github.com/grafana/grafana/commit/8ecfad69951628cc8327c23166d953f86a8d83ff | [
0.00017958103853743523,
0.00017726089572533965,
0.00017588069022167474,
0.00017632094386499375,
0.0000016504079667356564
] |
{
"id": 3,
"code_window": [
" const lumA = getLuminance(foreground);\n",
" const lumB = getLuminance(background);\n",
" return (Math.max(lumA, lumB) + 0.05) / (Math.min(lumA, lumB) + 0.05);\n",
"}\n",
"\n",
"/**\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const lumB = getLuminance(background, canvas);\n"
],
"file_path": "packages/grafana-data/src/themes/colorManipulator.ts",
"type": "replace",
"edit_start_line_idx": 182
} | import { each } from 'lodash';
import TableModel from 'app/core/table_model';
import { TableRenderer } from '../renderer';
import { ScopedVars, TimeZone } from '@grafana/data';
import { ColumnRender } from '../types';
import { getTheme } from '@grafana/ui';
const utc: TimeZone = 'utc';
const sanitize = (value: any): string => {
return 'sanitized';
};
const templateSrv = {
replace: (value: any, scopedVars: ScopedVars) => {
if (scopedVars) {
// For testing variables replacement in link
each(scopedVars, (val, key) => {
value = value.replace('$' + key, val.value);
});
}
return value;
},
};
describe('when rendering table', () => {
describe('given 13 columns', () => {
const table = new TableModel();
table.columns = [
{ text: 'Time' },
{ text: 'Value' },
{ text: 'Colored' },
{ text: 'Undefined' },
{ text: 'String' },
{ text: 'United', unit: 'bps' },
{ text: 'Sanitized' },
{ text: 'Link' },
{ text: 'Array' },
{ text: 'Mapping' },
{ text: 'RangeMapping' },
{ text: 'MappingColored' },
{ text: 'RangeMappingColored' },
{ text: 'HiddenType' },
{ text: 'RightAligned' },
];
table.rows = [
[
1388556366666,
1230,
40,
undefined,
'',
'',
'my.host.com',
'host1',
['value1', 'value2'],
1,
2,
1,
2,
'ignored',
42,
],
];
const panel = {
pageSize: 10,
styles: [
{
pattern: 'Time',
type: 'date',
format: 'LLL',
alias: 'Timestamp',
},
{
pattern: '/(Val)ue/',
type: 'number',
unit: 'ms',
decimals: 3,
alias: '$1',
},
{
pattern: 'Colored',
type: 'number',
unit: 'none',
decimals: 1,
colorMode: 'value',
thresholds: [50, 80],
colors: ['#00ff00', 'semi-dark-orange', 'rgb(1,0,0)'],
},
{
pattern: 'String',
type: 'string',
},
{
pattern: 'String',
type: 'string',
},
{
pattern: 'United',
type: 'number',
unit: 'ms',
decimals: 2,
},
{
pattern: 'Sanitized',
type: 'string',
sanitize: true,
},
{
pattern: 'Link',
type: 'string',
link: true,
linkUrl: '/dashboard?param=$__cell¶m_1=$__cell_1¶m_2=$__cell_2',
linkTooltip: '$__cell $__cell_1 $__cell_6',
linkTargetBlank: true,
},
{
pattern: 'Array',
type: 'number',
unit: 'ms',
decimals: 3,
},
{
pattern: 'Mapping',
type: 'string',
mappingType: 1,
valueMaps: [
{
value: '1',
text: 'on',
},
{
value: '0',
text: 'off',
},
{
value: 'HELLO WORLD',
text: 'HELLO GRAFANA',
},
{
value: 'value1, value2',
text: 'value3, value4',
},
],
},
{
pattern: 'RangeMapping',
type: 'string',
mappingType: 2,
rangeMaps: [
{
from: '1',
to: '3',
text: 'on',
},
{
from: '3',
to: '6',
text: 'off',
},
],
},
{
pattern: 'MappingColored',
type: 'string',
mappingType: 1,
valueMaps: [
{
value: '1',
text: 'on',
},
{
value: '0',
text: 'off',
},
],
colorMode: 'value',
thresholds: [1, 2],
colors: ['#00ff00', 'semi-dark-orange', 'rgb(1,0,0)'],
},
{
pattern: 'RangeMappingColored',
type: 'string',
mappingType: 2,
rangeMaps: [
{
from: '1',
to: '3',
text: 'on',
},
{
from: '3',
to: '6',
text: 'off',
},
],
colorMode: 'value',
thresholds: [2, 5],
colors: ['#00ff00', 'semi-dark-orange', 'rgb(1,0,0)'],
},
{
pattern: 'HiddenType',
type: 'hidden',
},
{
pattern: 'RightAligned',
align: 'right',
},
],
};
//@ts-ignore
const renderer = new TableRenderer(panel, table, utc, sanitize, templateSrv, getTheme());
it('time column should be formatted', () => {
const html = renderer.renderCell(0, 0, 1388556366666);
expect(html).toBe('<td>2014-01-01T06:06:06Z</td>');
});
it('time column with epoch as string should be formatted', () => {
const html = renderer.renderCell(0, 0, '1388556366666');
expect(html).toBe('<td>2014-01-01T06:06:06Z</td>');
});
it('time column with RFC2822 date as string should be formatted', () => {
const html = renderer.renderCell(0, 0, 'Sat, 01 Dec 2018 01:00:00 GMT');
expect(html).toBe('<td>2018-12-01T01:00:00Z</td>');
});
it('time column with ISO date as string should be formatted', () => {
const html = renderer.renderCell(0, 0, '2018-12-01T01:00:00Z');
expect(html).toBe('<td>2018-12-01T01:00:00Z</td>');
});
it('undefined time column should be rendered as -', () => {
const html = renderer.renderCell(0, 0, undefined);
expect(html).toBe('<td>-</td>');
});
it('null time column should be rendered as -', () => {
const html = renderer.renderCell(0, 0, null);
expect(html).toBe('<td>-</td>');
});
it('number column with unit specified should ignore style unit', () => {
const html = renderer.renderCell(5, 0, 1230);
expect(html).toBe('<td>1.23 kb/s</td>');
});
it('number column should be formated', () => {
const html = renderer.renderCell(1, 0, 1230);
expect(html).toBe('<td>1.230 s</td>');
});
it('number column should format numeric string values', () => {
const html = renderer.renderCell(1, 0, '1230');
expect(html).toBe('<td>1.230 s</td>');
});
it('number style should ignore string non-numeric values', () => {
const html = renderer.renderCell(1, 0, 'asd');
expect(html).toBe('<td>asd</td>');
});
it('colored cell should have style (handles HEX color values)', () => {
const html = renderer.renderCell(2, 0, 40);
expect(html).toBe('<td style="color:#00ff00">40.0</td>');
});
it('colored cell should have style (handles named color values', () => {
const html = renderer.renderCell(2, 0, 55);
expect(html).toBe(`<td style="color:${'#FF780A'}">55.0</td>`);
});
it('colored cell should have style handles(rgb color values)', () => {
const html = renderer.renderCell(2, 0, 85);
expect(html).toBe('<td style="color:rgb(1,0,0)">85.0</td>');
});
it('unformated undefined should be rendered as string', () => {
const html = renderer.renderCell(3, 0, 'value');
expect(html).toBe('<td>value</td>');
});
it('string style with escape html should return escaped html', () => {
const html = renderer.renderCell(4, 0, '&breaking <br /> the <br /> row');
expect(html).toBe('<td>&breaking <br /> the <br /> row</td>');
});
it('undefined formater should return escaped html', () => {
const html = renderer.renderCell(3, 0, '&breaking <br /> the <br /> row');
expect(html).toBe('<td>&breaking <br /> the <br /> row</td>');
});
it('undefined value should render as -', () => {
const html = renderer.renderCell(3, 0, undefined);
expect(html).toBe('<td></td>');
});
it('sanitized value should render as', () => {
const html = renderer.renderCell(6, 0, 'text <a href="http://google.com">link</a>');
expect(html).toBe('<td>sanitized</td>');
});
it('Time column title should be Timestamp', () => {
expect(table.columns[0].title).toBe('Timestamp');
});
it('Value column title should be Val', () => {
expect(table.columns[1].title).toBe('Val');
});
it('Colored column title should be Colored', () => {
expect(table.columns[2].title).toBe('Colored');
});
it('link should render as', () => {
const html = renderer.renderCell(7, 0, 'host1');
const expectedHtml = `
<td class="table-panel-cell-link"><a href="/dashboard?param=host1¶m_1=1230¶m_2=40"
target="_blank" data-link-tooltip data-original-title="host1 1230 my.host.com"
data-placement="right">host1</a></td>
`;
expect(normalize(html)).toBe(normalize(expectedHtml));
});
it('Array column should not use number as formatter', () => {
const html = renderer.renderCell(8, 0, ['value1', 'value2']);
expect(html).toBe('<td>value1, value2</td>');
});
it('numeric value should be mapped to text', () => {
const html = renderer.renderCell(9, 0, 1);
expect(html).toBe('<td>on</td>');
});
it('string numeric value should be mapped to text', () => {
const html = renderer.renderCell(9, 0, '0');
expect(html).toBe('<td>off</td>');
});
it('string value should be mapped to text', () => {
const html = renderer.renderCell(9, 0, 'HELLO WORLD');
expect(html).toBe('<td>HELLO GRAFANA</td>');
});
it('array column value should be mapped to text', () => {
const html = renderer.renderCell(9, 0, ['value1', 'value2']);
expect(html).toBe('<td>value3, value4</td>');
});
it('value should be mapped to text (range)', () => {
const html = renderer.renderCell(10, 0, 2);
expect(html).toBe('<td>on</td>');
});
it('value should be mapped to text (range)', () => {
const html = renderer.renderCell(10, 0, 5);
expect(html).toBe('<td>off</td>');
});
it('array column value should not be mapped to text', () => {
const html = renderer.renderCell(10, 0, ['value1', 'value2']);
expect(html).toBe('<td>value1, value2</td>');
});
it('value should be mapped to text and colored cell should have style', () => {
const html = renderer.renderCell(11, 0, 1);
expect(html).toBe(`<td style="color:${'#FF780A'}">on</td>`);
});
it('value should be mapped to text and colored cell should have style', () => {
const html = renderer.renderCell(11, 0, '1');
expect(html).toBe(`<td style="color:${'#FF780A'}">on</td>`);
});
it('value should be mapped to text and colored cell should have style', () => {
const html = renderer.renderCell(11, 0, 0);
expect(html).toBe('<td style="color:#00ff00">off</td>');
});
it('value should be mapped to text and colored cell should have style', () => {
const html = renderer.renderCell(11, 0, '0');
expect(html).toBe('<td style="color:#00ff00">off</td>');
});
it('value should be mapped to text and colored cell should have style', () => {
const html = renderer.renderCell(11, 0, '2.1');
expect(html).toBe('<td style="color:rgb(1,0,0)">2.1</td>');
});
it('value should be mapped to text (range) and colored cell should have style', () => {
const html = renderer.renderCell(12, 0, 0);
expect(html).toBe('<td style="color:#00ff00">0</td>');
});
it('value should be mapped to text (range) and colored cell should have style', () => {
const html = renderer.renderCell(12, 0, 1);
expect(html).toBe('<td style="color:#00ff00">on</td>');
});
it('value should be mapped to text (range) and colored cell should have style', () => {
const html = renderer.renderCell(12, 0, 4);
expect(html).toBe(`<td style="color:${'#FF780A'}">off</td>`);
});
it('value should be mapped to text (range) and colored cell should have style', () => {
const html = renderer.renderCell(12, 0, '7.1');
expect(html).toBe('<td style="color:rgb(1,0,0)">7.1</td>');
});
it('hidden columns should not be rendered', () => {
const html = renderer.renderCell(13, 0, 'ignored');
expect(html).toBe('');
});
it('right aligned column should have correct text-align style', () => {
const html = renderer.renderCell(14, 0, 42);
expect(html).toBe('<td style="text-align:right">42</td>');
});
it('render_values should ignore hidden columns', () => {
renderer.render(0); // this computes the hidden markers on the columns
const { columns, rows } = renderer.render_values();
expect(rows).toHaveLength(1);
expect(columns).toHaveLength(table.columns.length - 1);
expect(columns.filter((col: ColumnRender) => col.hidden)).toHaveLength(0);
});
});
});
describe('when rendering table with different patterns', () => {
it.each`
column | pattern | expected
${'Requests (Failed)'} | ${'/Requests \\(Failed\\)/'} | ${'<td>1.230 s</td>'}
${'Requests (Failed)'} | ${'/(Req)uests \\(Failed\\)/'} | ${'<td>1.230 s</td>'}
${'Requests (Failed)'} | ${'Requests (Failed)'} | ${'<td>1.230 s</td>'}
${'Requests (Failed)'} | ${'Requests \\(Failed\\)'} | ${'<td>1.230 s</td>'}
${'Requests (Failed)'} | ${'/.*/'} | ${'<td>1.230 s</td>'}
${'Some other column'} | ${'/.*/'} | ${'<td>1.230 s</td>'}
${'Requests (Failed)'} | ${'/Requests (Failed)/'} | ${'<td>1230</td>'}
${'Requests (Failed)'} | ${'Response (Failed)'} | ${'<td>1230</td>'}
`(
'number column should be formatted for a column:$column with the pattern:$pattern',
({ column, pattern, expected }) => {
const table = new TableModel();
table.columns = [{ text: 'Time' }, { text: column }];
table.rows = [[1388556366666, 1230]];
const panel = {
pageSize: 10,
styles: [
{
pattern: 'Time',
type: 'date',
format: 'LLL',
alias: 'Timestamp',
},
{
pattern: pattern,
type: 'number',
unit: 'ms',
decimals: 3,
alias: pattern,
},
],
};
//@ts-ignore
const renderer = new TableRenderer(panel, table, utc, sanitize, templateSrv, getTheme());
const html = renderer.renderCell(1, 0, 1230);
expect(html).toBe(expected);
}
);
});
describe('when rendering cells with different alignment options', () => {
const cases: Array<[string, boolean, string | null, string]> = [
//align, preserve fmt, color mode, expected
['', false, null, '<td>42</td>'],
['invalid_option', false, null, '<td>42</td>'],
['alert("no xss");', false, null, '<td>42</td>'],
['auto', false, null, '<td>42</td>'],
['justify', false, null, '<td>42</td>'],
['auto', true, null, '<td class="table-panel-cell-pre">42</td>'],
['left', false, null, '<td style="text-align:left">42</td>'],
['left', true, null, '<td class="table-panel-cell-pre" style="text-align:left">42</td>'],
['center', false, null, '<td style="text-align:center">42</td>'],
[
'center',
true,
'cell',
'<td class="table-panel-color-cell table-panel-cell-pre" style="background-color:rgba(50, 172, 45, 0.97);text-align:center">42</td>',
],
[
'right',
false,
'cell',
'<td class="table-panel-color-cell" style="background-color:rgba(50, 172, 45, 0.97);text-align:right">42</td>',
],
[
'right',
true,
'cell',
'<td class="table-panel-color-cell table-panel-cell-pre" style="background-color:rgba(50, 172, 45, 0.97);text-align:right">42</td>',
],
];
it.each(cases)(
'align option:"%s", preformatted:%s columns should be formatted with correct style',
(align: string, preserveFormat: boolean, colorMode, expected: string) => {
const table = new TableModel();
table.columns = [{ text: 'Time' }, { text: align }];
table.rows = [[0, 42]];
const panel = {
pageSize: 10,
styles: [
{
pattern: 'Time',
type: 'date',
format: 'LLL',
alias: 'Timestamp',
},
{
pattern: `/${align}/`,
align: align,
type: 'number',
unit: 'none',
preserveFormat: preserveFormat,
colorMode: colorMode,
thresholds: [1, 2],
colors: ['rgba(245, 54, 54, 0.9)', 'rgba(237, 129, 40, 0.89)', 'rgba(50, 172, 45, 0.97)'],
},
],
};
//@ts-ignore
const renderer = new TableRenderer(panel, table, utc, sanitize, templateSrv, getTheme());
const html = renderer.renderCell(1, 0, 42);
expect(html).toBe(expected);
}
);
});
function normalize(str: string) {
return str.replace(/\s+/gm, ' ').trim();
}
| public/app/plugins/panel/table-old/specs/renderer.test.ts | 0 | https://github.com/grafana/grafana/commit/8ecfad69951628cc8327c23166d953f86a8d83ff | [
0.00017993259825743735,
0.00017534001381136477,
0.00016497592150699347,
0.00017567019676789641,
0.000002086354470520746
] |
{
"id": 4,
"code_window": [
" * The relative brightness of any point in a color space,\n",
" * normalized to 0 for darkest black and 1 for lightest white.\n",
" *\n",
" * Formula: https://www.w3.org/TR/WCAG20-TECHS/G17.html#G17-tests\n",
" * @param color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), color()\n",
" * @returns The relative brightness of the color in the range 0 - 1\n",
" * @beta\n",
" */\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" * @param background - CSS color that needs to be take in to account to calculate luminance for colors with opacity\n"
],
"file_path": "packages/grafana-data/src/themes/colorManipulator.ts",
"type": "add",
"edit_start_line_idx": 192
} | // Code based on Material-UI
// https://github.com/mui-org/material-ui/blob/1b096070faf102281f8e3c4f9b2bf50acf91f412/packages/material-ui/src/styles/colorManipulator.js#L97
// MIT License Copyright (c) 2014 Call-Em-All
/**
* Returns a number whose value is limited to the given range.
* @param value The value to be clamped
* @param min The lower boundary of the output range
* @param max The upper boundary of the output range
* @returns A number in the range [min, max]
* @beta
*/
function clamp(value: number, min = 0, max = 1) {
if (process.env.NODE_ENV !== 'production') {
if (value < min || value > max) {
console.error(`The value provided ${value} is out of range [${min}, ${max}].`);
}
}
return Math.min(Math.max(min, value), max);
}
/**
* Converts a color from CSS hex format to CSS rgb format.
* @param color - Hex color, i.e. #nnn or #nnnnnn
* @returns A CSS rgb color string
* @beta
*/
export function hexToRgb(color: string) {
color = color.substr(1);
const re = new RegExp(`.{1,${color.length >= 6 ? 2 : 1}}`, 'g');
let colors = color.match(re);
if (colors && colors[0].length === 1) {
colors = colors.map((n) => n + n);
}
return colors
? `rgb${colors.length === 4 ? 'a' : ''}(${colors
.map((n, index) => {
return index < 3 ? parseInt(n, 16) : Math.round((parseInt(n, 16) / 255) * 1000) / 1000;
})
.join(', ')})`
: '';
}
function intToHex(int: number) {
const hex = int.toString(16);
return hex.length === 1 ? `0${hex}` : hex;
}
/**
* Converts a color from CSS rgb format to CSS hex format.
* @param color - RGB color, i.e. rgb(n, n, n)
* @returns A CSS rgb color string, i.e. #nnnnnn
* @beta
*/
export function rgbToHex(color: string) {
// Idempotent
if (color.indexOf('#') === 0) {
return color;
}
const { values } = decomposeColor(color);
return `#${values.map((n: number) => intToHex(n)).join('')}`;
}
/**
* Converts a color from hsl format to rgb format.
* @param color - HSL color values
* @returns rgb color values
* @beta
*/
export function hslToRgb(color: string | DecomposeColor) {
const parts = decomposeColor(color);
const { values } = parts;
const h = values[0];
const s = values[1] / 100;
const l = values[2] / 100;
const a = s * Math.min(l, 1 - l);
const f = (n: number, k = (n + h / 30) % 12) => l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1);
let type = 'rgb';
const rgb = [Math.round(f(0) * 255), Math.round(f(8) * 255), Math.round(f(4) * 255)];
if (parts.type === 'hsla') {
type += 'a';
rgb.push(values[3]);
}
return recomposeColor({ type, values: rgb });
}
/**
* Returns an object with the type and values of a color.
*
* Note: Does not support rgb % values.
* @param color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()
* @returns {object} - A MUI color object: {type: string, values: number[]}
* @beta
*/
export function decomposeColor(color: string | DecomposeColor): DecomposeColor {
// Idempotent
if (typeof color !== 'string') {
return color;
}
if (color.charAt(0) === '#') {
return decomposeColor(hexToRgb(color));
}
const marker = color.indexOf('(');
const type = color.substring(0, marker);
if (['rgb', 'rgba', 'hsl', 'hsla', 'color'].indexOf(type) === -1) {
throw new Error(
`Unsupported '${color}' color. The following formats are supported: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), color()`
);
}
let values: any = color.substring(marker + 1, color.length - 1);
let colorSpace;
if (type === 'color') {
values = values.split(' ');
colorSpace = values.shift();
if (values.length === 4 && values[3].charAt(0) === '/') {
values[3] = values[3].substr(1);
}
if (['srgb', 'display-p3', 'a98-rgb', 'prophoto-rgb', 'rec-2020'].indexOf(colorSpace) === -1) {
throw new Error(
`Unsupported ${colorSpace} color space. The following color spaces are supported: srgb, display-p3, a98-rgb, prophoto-rgb, rec-2020.`
);
}
} else {
values = values.split(',');
}
values = values.map((value: string) => parseFloat(value));
return { type, values, colorSpace };
}
/**
* Converts a color object with type and values to a string.
* @param {object} color - Decomposed color
* @param color.type - One of: 'rgb', 'rgba', 'hsl', 'hsla'
* @param {array} color.values - [n,n,n] or [n,n,n,n]
* @returns A CSS color string
* @beta
*/
export function recomposeColor(color: DecomposeColor) {
const { type, colorSpace } = color;
let values: any = color.values;
if (type.indexOf('rgb') !== -1) {
// Only convert the first 3 values to int (i.e. not alpha)
values = values.map((n: string, i: number) => (i < 3 ? parseInt(n, 10) : n));
} else if (type.indexOf('hsl') !== -1) {
values[1] = `${values[1]}%`;
values[2] = `${values[2]}%`;
}
if (type.indexOf('color') !== -1) {
values = `${colorSpace} ${values.join(' ')}`;
} else {
values = `${values.join(', ')}`;
}
return `${type}(${values})`;
}
/**
* Calculates the contrast ratio between two colors.
*
* Formula: https://www.w3.org/TR/WCAG20-TECHS/G17.html#G17-tests
* @param foreground - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()
* @param background - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()
* @returns A contrast ratio value in the range 0 - 21.
* @beta
*/
export function getContrastRatio(foreground: string, background: string) {
const lumA = getLuminance(foreground);
const lumB = getLuminance(background);
return (Math.max(lumA, lumB) + 0.05) / (Math.min(lumA, lumB) + 0.05);
}
/**
* The relative brightness of any point in a color space,
* normalized to 0 for darkest black and 1 for lightest white.
*
* Formula: https://www.w3.org/TR/WCAG20-TECHS/G17.html#G17-tests
* @param color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), color()
* @returns The relative brightness of the color in the range 0 - 1
* @beta
*/
export function getLuminance(color: string) {
const parts = decomposeColor(color);
let rgb = parts.type === 'hsl' ? decomposeColor(hslToRgb(color)).values : parts.values;
const rgbNumbers = rgb.map((val: any) => {
if (parts.type !== 'color') {
val /= 255; // normalized
}
return val <= 0.03928 ? val / 12.92 : ((val + 0.055) / 1.055) ** 2.4;
});
// Truncate at 3 digits
return Number((0.2126 * rgbNumbers[0] + 0.7152 * rgbNumbers[1] + 0.0722 * rgbNumbers[2]).toFixed(3));
}
/**
* Darken or lighten a color, depending on its luminance.
* Light colors are darkened, dark colors are lightened.
* @param color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), color()
* @param coefficient=0.15 - multiplier in the range 0 - 1
* @returns A CSS color string. Hex input values are returned as rgb
* @beta
*/
export function emphasize(color: string, coefficient = 0.15) {
return getLuminance(color) > 0.5 ? darken(color, coefficient) : lighten(color, coefficient);
}
/**
* Set the absolute transparency of a color.
* Any existing alpha values are overwritten.
* @param color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), color()
* @param value - value to set the alpha channel to in the range 0 - 1
* @returns A CSS color string. Hex input values are returned as rgb
* @beta
*/
export function alpha(color: string, value: number) {
const parts = decomposeColor(color);
value = clamp(value);
if (parts.type === 'rgb' || parts.type === 'hsl') {
parts.type += 'a';
}
if (parts.type === 'color') {
parts.values[3] = `/${value}`;
} else {
parts.values[3] = value;
}
return recomposeColor(parts);
}
/**
* Darkens a color.
* @param color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), color()
* @param coefficient - multiplier in the range 0 - 1
* @returns A CSS color string. Hex input values are returned as rgb
* @beta
*/
export function darken(color: string, coefficient: number) {
const parts = decomposeColor(color);
coefficient = clamp(coefficient);
if (parts.type.indexOf('hsl') !== -1) {
parts.values[2] *= 1 - coefficient;
} else if (parts.type.indexOf('rgb') !== -1 || parts.type.indexOf('color') !== -1) {
for (let i = 0; i < 3; i += 1) {
parts.values[i] *= 1 - coefficient;
}
}
return recomposeColor(parts);
}
/**
* Lightens a color.
* @param color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), color()
* @param coefficient - multiplier in the range 0 - 1
* @returns A CSS color string. Hex input values are returned as rgb
* @beta
*/
export function lighten(color: string, coefficient: number) {
const parts = decomposeColor(color);
coefficient = clamp(coefficient);
if (parts.type.indexOf('hsl') !== -1) {
parts.values[2] += (100 - parts.values[2]) * coefficient;
} else if (parts.type.indexOf('rgb') !== -1) {
for (let i = 0; i < 3; i += 1) {
parts.values[i] += (255 - parts.values[i]) * coefficient;
}
} else if (parts.type.indexOf('color') !== -1) {
for (let i = 0; i < 3; i += 1) {
parts.values[i] += (1 - parts.values[i]) * coefficient;
}
}
return recomposeColor(parts);
}
interface DecomposeColor {
type: string;
values: any;
colorSpace?: string;
}
| packages/grafana-data/src/themes/colorManipulator.ts | 1 | https://github.com/grafana/grafana/commit/8ecfad69951628cc8327c23166d953f86a8d83ff | [
0.5696190595626831,
0.0201675184071064,
0.0001643254654482007,
0.0004824930801987648,
0.10205044597387314
] |
{
"id": 4,
"code_window": [
" * The relative brightness of any point in a color space,\n",
" * normalized to 0 for darkest black and 1 for lightest white.\n",
" *\n",
" * Formula: https://www.w3.org/TR/WCAG20-TECHS/G17.html#G17-tests\n",
" * @param color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), color()\n",
" * @returns The relative brightness of the color in the range 0 - 1\n",
" * @beta\n",
" */\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" * @param background - CSS color that needs to be take in to account to calculate luminance for colors with opacity\n"
],
"file_path": "packages/grafana-data/src/themes/colorManipulator.ts",
"type": "add",
"edit_start_line_idx": 192
} | {
"value": {
"start": "2020-06-25T16:15:32.140Z",
"end": "2020-06-25T16:19:32.140Z",
"interval": "PT2M",
"segments": [
{
"start": "2020-06-25T16:15:32.140Z",
"end": "2020-06-25T16:16:00.000Z",
"segments": [
{
"client/countryOrRegion": "United States",
"segments": [
{
"traces/count": {
"sum": 2
},
"client/city": "Washington"
},
{
"traces/count": {
"sum": 2
},
"client/city": "Des Moines"
}
]
}
]
},
{
"start": "2020-06-25T16:16:00.000Z",
"end": "2020-06-25T16:18:00.000Z",
"segments": [
{
"client/countryOrRegion": "United States",
"segments": [
{
"traces/count": {
"sum": 11
},
"client/city": ""
},
{
"traces/count": {
"sum": 3
},
"client/city": "Chicago"
},
{
"traces/count": {
"sum": 1
},
"client/city": "Des Moines"
}
]
},
{
"client/countryOrRegion": "Japan",
"segments": [
{
"traces/count": {
"sum": 1
},
"client/city": "Tokyo"
}
]
}
]
}
]
}
}
| pkg/tsdb/azuremonitor/testdata/applicationinsights/4-application-insights-response-metrics-multi-segmented.json | 0 | https://github.com/grafana/grafana/commit/8ecfad69951628cc8327c23166d953f86a8d83ff | [
0.00016760989092290401,
0.00016604083066340536,
0.0001640377304283902,
0.00016604045231360942,
0.0000011951431133638835
] |
{
"id": 4,
"code_window": [
" * The relative brightness of any point in a color space,\n",
" * normalized to 0 for darkest black and 1 for lightest white.\n",
" *\n",
" * Formula: https://www.w3.org/TR/WCAG20-TECHS/G17.html#G17-tests\n",
" * @param color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), color()\n",
" * @returns The relative brightness of the color in the range 0 - 1\n",
" * @beta\n",
" */\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" * @param background - CSS color that needs to be take in to account to calculate luminance for colors with opacity\n"
],
"file_path": "packages/grafana-data/src/themes/colorManipulator.ts",
"type": "add",
"edit_start_line_idx": 192
} | package models
import (
"errors"
"time"
)
// Typed errors
var (
ErrTeamNotFound = errors.New("team not found")
ErrTeamNameTaken = errors.New("team name is taken")
ErrTeamMemberNotFound = errors.New("team member not found")
ErrLastTeamAdmin = errors.New("not allowed to remove last admin")
ErrNotAllowedToUpdateTeam = errors.New("user not allowed to update team")
ErrNotAllowedToUpdateTeamInDifferentOrg = errors.New("user not allowed to update team in another org")
)
// Team model
type Team struct {
Id int64 `json:"id"`
OrgId int64 `json:"orgId"`
Name string `json:"name"`
Email string `json:"email"`
Created time.Time `json:"created"`
Updated time.Time `json:"updated"`
}
// ---------------------
// COMMANDS
type CreateTeamCommand struct {
Name string `json:"name" binding:"Required"`
Email string `json:"email"`
OrgId int64 `json:"-"`
Result Team `json:"-"`
}
type UpdateTeamCommand struct {
Id int64
Name string
Email string
OrgId int64 `json:"-"`
}
type DeleteTeamCommand struct {
OrgId int64
Id int64
}
type GetTeamByIdQuery struct {
OrgId int64
Id int64
SignedInUser *SignedInUser
HiddenUsers map[string]struct{}
Result *TeamDTO
}
type GetTeamsByUserQuery struct {
OrgId int64
UserId int64 `json:"userId"`
Result []*TeamDTO `json:"teams"`
}
type SearchTeamsQuery struct {
Query string
Name string
Limit int
Page int
OrgId int64
UserIdFilter int64
SignedInUser *SignedInUser
HiddenUsers map[string]struct{}
Result SearchTeamQueryResult
}
type TeamDTO struct {
Id int64 `json:"id"`
OrgId int64 `json:"orgId"`
Name string `json:"name"`
Email string `json:"email"`
AvatarUrl string `json:"avatarUrl"`
MemberCount int64 `json:"memberCount"`
Permission PermissionType `json:"permission"`
}
type SearchTeamQueryResult struct {
TotalCount int64 `json:"totalCount"`
Teams []*TeamDTO `json:"teams"`
Page int `json:"page"`
PerPage int `json:"perPage"`
}
type IsAdminOfTeamsQuery struct {
SignedInUser *SignedInUser
Result bool
}
| pkg/models/team.go | 0 | https://github.com/grafana/grafana/commit/8ecfad69951628cc8327c23166d953f86a8d83ff | [
0.00016755844990257174,
0.00016581561067141593,
0.00016467540990561247,
0.00016548542771488428,
0.0000011171581490998506
] |
{
"id": 4,
"code_window": [
" * The relative brightness of any point in a color space,\n",
" * normalized to 0 for darkest black and 1 for lightest white.\n",
" *\n",
" * Formula: https://www.w3.org/TR/WCAG20-TECHS/G17.html#G17-tests\n",
" * @param color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), color()\n",
" * @returns The relative brightness of the color in the range 0 - 1\n",
" * @beta\n",
" */\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" * @param background - CSS color that needs to be take in to account to calculate luminance for colors with opacity\n"
],
"file_path": "packages/grafana-data/src/themes/colorManipulator.ts",
"type": "add",
"edit_start_line_idx": 192
} | import { DashboardSection, SearchAction } from '../types';
import { getFlattenedSections, getLookupField, markSelected } from '../utils';
import {
FETCH_ITEMS,
FETCH_RESULTS,
TOGGLE_SECTION,
MOVE_SELECTION_DOWN,
MOVE_SELECTION_UP,
SEARCH_START,
FETCH_ITEMS_START,
} from './actionTypes';
export interface DashboardsSearchState {
results: DashboardSection[];
loading: boolean;
selectedIndex: number;
/** Used for first time page load */
initialLoading: boolean;
}
export const dashboardsSearchState: DashboardsSearchState = {
results: [],
loading: true,
initialLoading: true,
selectedIndex: 0,
};
export const searchReducer = (state: DashboardsSearchState, action: SearchAction) => {
switch (action.type) {
case SEARCH_START:
if (!state.loading) {
return { ...state, loading: true };
}
return state;
case FETCH_RESULTS: {
const results = action.payload;
// Highlight the first item ('Starred' folder)
if (results.length > 0) {
results[0].selected = true;
}
return { ...state, results, loading: false, initialLoading: false };
}
case TOGGLE_SECTION: {
const section = action.payload;
const lookupField = getLookupField(section.title);
return {
...state,
results: state.results.map((result: DashboardSection) => {
if (section[lookupField] === result[lookupField]) {
return { ...result, expanded: !result.expanded };
}
return result;
}),
};
}
case FETCH_ITEMS: {
const { section, items } = action.payload;
return {
...state,
itemsFetching: false,
results: state.results.map((result: DashboardSection) => {
if (section.id === result.id) {
return { ...result, items, itemsFetching: false };
}
return result;
}),
};
}
case FETCH_ITEMS_START: {
const id = action.payload;
if (id) {
return {
...state,
results: state.results.map((result) => (result.id === id ? { ...result, itemsFetching: true } : result)),
};
}
return state;
}
case MOVE_SELECTION_DOWN: {
const flatIds = getFlattenedSections(state.results);
if (state.selectedIndex < flatIds.length - 1) {
const newIndex = state.selectedIndex + 1;
const selectedId = flatIds[newIndex];
return {
...state,
selectedIndex: newIndex,
results: markSelected(state.results, selectedId),
};
}
return state;
}
case MOVE_SELECTION_UP:
if (state.selectedIndex > 0) {
const flatIds = getFlattenedSections(state.results);
const newIndex = state.selectedIndex - 1;
const selectedId = flatIds[newIndex];
return {
...state,
selectedIndex: newIndex,
results: markSelected(state.results, selectedId),
};
}
return state;
default:
return state;
}
};
| public/app/features/search/reducers/dashboardSearch.ts | 0 | https://github.com/grafana/grafana/commit/8ecfad69951628cc8327c23166d953f86a8d83ff | [
0.00016631337348371744,
0.0001655063679208979,
0.00016392608813475817,
0.00016549363499507308,
6.19299385107297e-7
] |
{
"id": 5,
"code_window": [
" * @returns The relative brightness of the color in the range 0 - 1\n",
" * @beta\n",
" */\n",
"export function getLuminance(color: string) {\n",
" const parts = decomposeColor(color);\n",
"\n",
" let rgb = parts.type === 'hsl' ? decomposeColor(hslToRgb(color)).values : parts.values;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"export function getLuminance(color: string, background?: string) {\n"
],
"file_path": "packages/grafana-data/src/themes/colorManipulator.ts",
"type": "replace",
"edit_start_line_idx": 195
} | // Code based on Material-UI
// https://github.com/mui-org/material-ui/blob/1b096070faf102281f8e3c4f9b2bf50acf91f412/packages/material-ui/src/styles/colorManipulator.js#L97
// MIT License Copyright (c) 2014 Call-Em-All
/**
* Returns a number whose value is limited to the given range.
* @param value The value to be clamped
* @param min The lower boundary of the output range
* @param max The upper boundary of the output range
* @returns A number in the range [min, max]
* @beta
*/
function clamp(value: number, min = 0, max = 1) {
if (process.env.NODE_ENV !== 'production') {
if (value < min || value > max) {
console.error(`The value provided ${value} is out of range [${min}, ${max}].`);
}
}
return Math.min(Math.max(min, value), max);
}
/**
* Converts a color from CSS hex format to CSS rgb format.
* @param color - Hex color, i.e. #nnn or #nnnnnn
* @returns A CSS rgb color string
* @beta
*/
export function hexToRgb(color: string) {
color = color.substr(1);
const re = new RegExp(`.{1,${color.length >= 6 ? 2 : 1}}`, 'g');
let colors = color.match(re);
if (colors && colors[0].length === 1) {
colors = colors.map((n) => n + n);
}
return colors
? `rgb${colors.length === 4 ? 'a' : ''}(${colors
.map((n, index) => {
return index < 3 ? parseInt(n, 16) : Math.round((parseInt(n, 16) / 255) * 1000) / 1000;
})
.join(', ')})`
: '';
}
function intToHex(int: number) {
const hex = int.toString(16);
return hex.length === 1 ? `0${hex}` : hex;
}
/**
* Converts a color from CSS rgb format to CSS hex format.
* @param color - RGB color, i.e. rgb(n, n, n)
* @returns A CSS rgb color string, i.e. #nnnnnn
* @beta
*/
export function rgbToHex(color: string) {
// Idempotent
if (color.indexOf('#') === 0) {
return color;
}
const { values } = decomposeColor(color);
return `#${values.map((n: number) => intToHex(n)).join('')}`;
}
/**
* Converts a color from hsl format to rgb format.
* @param color - HSL color values
* @returns rgb color values
* @beta
*/
export function hslToRgb(color: string | DecomposeColor) {
const parts = decomposeColor(color);
const { values } = parts;
const h = values[0];
const s = values[1] / 100;
const l = values[2] / 100;
const a = s * Math.min(l, 1 - l);
const f = (n: number, k = (n + h / 30) % 12) => l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1);
let type = 'rgb';
const rgb = [Math.round(f(0) * 255), Math.round(f(8) * 255), Math.round(f(4) * 255)];
if (parts.type === 'hsla') {
type += 'a';
rgb.push(values[3]);
}
return recomposeColor({ type, values: rgb });
}
/**
* Returns an object with the type and values of a color.
*
* Note: Does not support rgb % values.
* @param color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()
* @returns {object} - A MUI color object: {type: string, values: number[]}
* @beta
*/
export function decomposeColor(color: string | DecomposeColor): DecomposeColor {
// Idempotent
if (typeof color !== 'string') {
return color;
}
if (color.charAt(0) === '#') {
return decomposeColor(hexToRgb(color));
}
const marker = color.indexOf('(');
const type = color.substring(0, marker);
if (['rgb', 'rgba', 'hsl', 'hsla', 'color'].indexOf(type) === -1) {
throw new Error(
`Unsupported '${color}' color. The following formats are supported: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), color()`
);
}
let values: any = color.substring(marker + 1, color.length - 1);
let colorSpace;
if (type === 'color') {
values = values.split(' ');
colorSpace = values.shift();
if (values.length === 4 && values[3].charAt(0) === '/') {
values[3] = values[3].substr(1);
}
if (['srgb', 'display-p3', 'a98-rgb', 'prophoto-rgb', 'rec-2020'].indexOf(colorSpace) === -1) {
throw new Error(
`Unsupported ${colorSpace} color space. The following color spaces are supported: srgb, display-p3, a98-rgb, prophoto-rgb, rec-2020.`
);
}
} else {
values = values.split(',');
}
values = values.map((value: string) => parseFloat(value));
return { type, values, colorSpace };
}
/**
* Converts a color object with type and values to a string.
* @param {object} color - Decomposed color
* @param color.type - One of: 'rgb', 'rgba', 'hsl', 'hsla'
* @param {array} color.values - [n,n,n] or [n,n,n,n]
* @returns A CSS color string
* @beta
*/
export function recomposeColor(color: DecomposeColor) {
const { type, colorSpace } = color;
let values: any = color.values;
if (type.indexOf('rgb') !== -1) {
// Only convert the first 3 values to int (i.e. not alpha)
values = values.map((n: string, i: number) => (i < 3 ? parseInt(n, 10) : n));
} else if (type.indexOf('hsl') !== -1) {
values[1] = `${values[1]}%`;
values[2] = `${values[2]}%`;
}
if (type.indexOf('color') !== -1) {
values = `${colorSpace} ${values.join(' ')}`;
} else {
values = `${values.join(', ')}`;
}
return `${type}(${values})`;
}
/**
* Calculates the contrast ratio between two colors.
*
* Formula: https://www.w3.org/TR/WCAG20-TECHS/G17.html#G17-tests
* @param foreground - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()
* @param background - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()
* @returns A contrast ratio value in the range 0 - 21.
* @beta
*/
export function getContrastRatio(foreground: string, background: string) {
const lumA = getLuminance(foreground);
const lumB = getLuminance(background);
return (Math.max(lumA, lumB) + 0.05) / (Math.min(lumA, lumB) + 0.05);
}
/**
* The relative brightness of any point in a color space,
* normalized to 0 for darkest black and 1 for lightest white.
*
* Formula: https://www.w3.org/TR/WCAG20-TECHS/G17.html#G17-tests
* @param color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), color()
* @returns The relative brightness of the color in the range 0 - 1
* @beta
*/
export function getLuminance(color: string) {
const parts = decomposeColor(color);
let rgb = parts.type === 'hsl' ? decomposeColor(hslToRgb(color)).values : parts.values;
const rgbNumbers = rgb.map((val: any) => {
if (parts.type !== 'color') {
val /= 255; // normalized
}
return val <= 0.03928 ? val / 12.92 : ((val + 0.055) / 1.055) ** 2.4;
});
// Truncate at 3 digits
return Number((0.2126 * rgbNumbers[0] + 0.7152 * rgbNumbers[1] + 0.0722 * rgbNumbers[2]).toFixed(3));
}
/**
* Darken or lighten a color, depending on its luminance.
* Light colors are darkened, dark colors are lightened.
* @param color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), color()
* @param coefficient=0.15 - multiplier in the range 0 - 1
* @returns A CSS color string. Hex input values are returned as rgb
* @beta
*/
export function emphasize(color: string, coefficient = 0.15) {
return getLuminance(color) > 0.5 ? darken(color, coefficient) : lighten(color, coefficient);
}
/**
* Set the absolute transparency of a color.
* Any existing alpha values are overwritten.
* @param color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), color()
* @param value - value to set the alpha channel to in the range 0 - 1
* @returns A CSS color string. Hex input values are returned as rgb
* @beta
*/
export function alpha(color: string, value: number) {
const parts = decomposeColor(color);
value = clamp(value);
if (parts.type === 'rgb' || parts.type === 'hsl') {
parts.type += 'a';
}
if (parts.type === 'color') {
parts.values[3] = `/${value}`;
} else {
parts.values[3] = value;
}
return recomposeColor(parts);
}
/**
* Darkens a color.
* @param color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), color()
* @param coefficient - multiplier in the range 0 - 1
* @returns A CSS color string. Hex input values are returned as rgb
* @beta
*/
export function darken(color: string, coefficient: number) {
const parts = decomposeColor(color);
coefficient = clamp(coefficient);
if (parts.type.indexOf('hsl') !== -1) {
parts.values[2] *= 1 - coefficient;
} else if (parts.type.indexOf('rgb') !== -1 || parts.type.indexOf('color') !== -1) {
for (let i = 0; i < 3; i += 1) {
parts.values[i] *= 1 - coefficient;
}
}
return recomposeColor(parts);
}
/**
* Lightens a color.
* @param color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), color()
* @param coefficient - multiplier in the range 0 - 1
* @returns A CSS color string. Hex input values are returned as rgb
* @beta
*/
export function lighten(color: string, coefficient: number) {
const parts = decomposeColor(color);
coefficient = clamp(coefficient);
if (parts.type.indexOf('hsl') !== -1) {
parts.values[2] += (100 - parts.values[2]) * coefficient;
} else if (parts.type.indexOf('rgb') !== -1) {
for (let i = 0; i < 3; i += 1) {
parts.values[i] += (255 - parts.values[i]) * coefficient;
}
} else if (parts.type.indexOf('color') !== -1) {
for (let i = 0; i < 3; i += 1) {
parts.values[i] += (1 - parts.values[i]) * coefficient;
}
}
return recomposeColor(parts);
}
interface DecomposeColor {
type: string;
values: any;
colorSpace?: string;
}
| packages/grafana-data/src/themes/colorManipulator.ts | 1 | https://github.com/grafana/grafana/commit/8ecfad69951628cc8327c23166d953f86a8d83ff | [
0.9989973902702332,
0.4333436191082001,
0.00016740498540457338,
0.030554326251149178,
0.48479828238487244
] |
{
"id": 5,
"code_window": [
" * @returns The relative brightness of the color in the range 0 - 1\n",
" * @beta\n",
" */\n",
"export function getLuminance(color: string) {\n",
" const parts = decomposeColor(color);\n",
"\n",
" let rgb = parts.type === 'hsl' ? decomposeColor(hslToRgb(color)).values : parts.values;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"export function getLuminance(color: string, background?: string) {\n"
],
"file_path": "packages/grafana-data/src/themes/colorManipulator.ts",
"type": "replace",
"edit_start_line_idx": 195
} | <svg width="1974" height="662" viewBox="0 0 1974 662" fill="none" xmlns="http://www.w3.org/2000/svg">
<mask id="mask0" mask-type="alpha" maskUnits="userSpaceOnUse" x="0" y="0" width="1974" height="662">
<rect width="1974" height="662" fill="#C4C4C4"/>
</mask>
<g mask="url(#mask0)">
<rect x="-462" y="-412" width="2898" height="1074" fill="black"/>
<ellipse opacity="0.6" cx="981" cy="125" rx="1342" ry="537" fill="url(#paint0_radial)" fill-opacity="0.8"/>
<ellipse opacity="0.25" cx="982" cy="1" rx="1192" ry="386" fill="url(#paint1_radial)"/>
<ellipse opacity="0.6" cx="981" cy="-78" rx="1049" ry="288" fill="url(#paint2_radial)"/>
<ellipse opacity="0.8" cx="983" cy="-134.5" rx="857" ry="212.5" fill="url(#paint3_radial)"/>
</g>
<defs>
<radialGradient id="paint0_radial" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(981 125) rotate(90) scale(537 1342)">
<stop stop-color="#4354E6"/>
<stop offset="1" stop-color="#2E24AA" stop-opacity="0"/>
</radialGradient>
<radialGradient id="paint1_radial" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(982 1) rotate(90) scale(386 1192)">
<stop stop-color="#F89797"/>
<stop offset="0.254209" stop-color="#E6769F" stop-opacity="0.5"/>
<stop offset="1" stop-color="#6E477C" stop-opacity="0"/>
</radialGradient>
<radialGradient id="paint2_radial" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(981 -78) rotate(90) scale(288 1049)">
<stop stop-color="#FF8A36" stop-opacity="0.6"/>
<stop offset="0.479167" stop-color="#FB5A67" stop-opacity="0.5"/>
<stop offset="1" stop-color="#68105A" stop-opacity="0"/>
</radialGradient>
<radialGradient id="paint3_radial" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(983 -134.5) rotate(90) scale(212.5 857)">
<stop offset="0.410941" stop-color="#FBC55A"/>
<stop offset="0.688779" stop-color="#FF8A36" stop-opacity="0.4"/>
<stop offset="1" stop-color="#B71B66" stop-opacity="0"/>
</radialGradient>
</defs>
</svg>
| public/img/g8_home_v2.svg | 0 | https://github.com/grafana/grafana/commit/8ecfad69951628cc8327c23166d953f86a8d83ff | [
0.00017675524577498436,
0.00017484958516433835,
0.00017344075604341924,
0.00017460115486755967,
0.0000013656978126164177
] |
{
"id": 5,
"code_window": [
" * @returns The relative brightness of the color in the range 0 - 1\n",
" * @beta\n",
" */\n",
"export function getLuminance(color: string) {\n",
" const parts = decomposeColor(color);\n",
"\n",
" let rgb = parts.type === 'hsl' ? decomposeColor(hslToRgb(color)).values : parts.values;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"export function getLuminance(color: string, background?: string) {\n"
],
"file_path": "packages/grafana-data/src/themes/colorManipulator.ts",
"type": "replace",
"edit_start_line_idx": 195
} | FROM debian:testing-20210111-slim
USER root
COPY scripts scripts
WORKDIR scripts
RUN apt-get update && \
apt-get install -y wget && \
./deploy.sh
COPY install/gget /usr/local/bin/gget
| packages/grafana-toolkit/docker/grafana-plugin-ci/Dockerfile | 0 | https://github.com/grafana/grafana/commit/8ecfad69951628cc8327c23166d953f86a8d83ff | [
0.00016500533092767,
0.00016500533092767,
0.00016500533092767,
0.00016500533092767,
0
] |
{
"id": 5,
"code_window": [
" * @returns The relative brightness of the color in the range 0 - 1\n",
" * @beta\n",
" */\n",
"export function getLuminance(color: string) {\n",
" const parts = decomposeColor(color);\n",
"\n",
" let rgb = parts.type === 'hsl' ? decomposeColor(hslToRgb(color)).values : parts.values;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"export function getLuminance(color: string, background?: string) {\n"
],
"file_path": "packages/grafana-data/src/themes/colorManipulator.ts",
"type": "replace",
"edit_start_line_idx": 195
} | import { VariableSuggestion, GrafanaTheme2 } from '@grafana/data';
import { css, cx } from '@emotion/css';
import { groupBy, capitalize } from 'lodash';
import React, { useRef, useMemo } from 'react';
import useClickAway from 'react-use/lib/useClickAway';
import { List } from '../index';
import { useStyles2 } from '../../themes';
interface DataLinkSuggestionsProps {
activeRef?: React.RefObject<HTMLDivElement>;
suggestions: VariableSuggestion[];
activeIndex: number;
onSuggestionSelect: (suggestion: VariableSuggestion) => void;
onClose?: () => void;
}
const getStyles = (theme: GrafanaTheme2) => {
return {
list: css`
border-bottom: 1px solid ${theme.colors.border.weak};
&:last-child {
border: none;
}
`,
wrapper: css`
background: ${theme.colors.background.primary};
width: 250px;
box-shadow: 0 5px 10px 0 ${theme.shadows.z1};
`,
item: css`
background: none;
padding: 2px 8px;
color: ${theme.colors.text.primary};
cursor: pointer;
&:hover {
background: ${theme.colors.action.hover};
}
`,
label: css`
color: ${theme.colors.text.secondary};
`,
activeItem: css`
background: ${theme.colors.background.secondary};
&:hover {
background: ${theme.colors.background.secondary};
}
`,
itemValue: css`
font-family: ${theme.typography.fontFamilyMonospace};
font-size: ${theme.typography.size.sm};
`,
};
};
export const DataLinkSuggestions: React.FC<DataLinkSuggestionsProps> = ({ suggestions, ...otherProps }) => {
const ref = useRef(null);
useClickAway(ref, () => {
if (otherProps.onClose) {
otherProps.onClose();
}
});
const groupedSuggestions = useMemo(() => {
return groupBy(suggestions, (s) => s.origin);
}, [suggestions]);
const styles = useStyles2(getStyles);
return (
<div ref={ref} className={styles.wrapper}>
{Object.keys(groupedSuggestions).map((key, i) => {
const indexOffset =
i === 0
? 0
: Object.keys(groupedSuggestions).reduce((acc, current, index) => {
if (index >= i) {
return acc;
}
return acc + groupedSuggestions[current].length;
}, 0);
return (
<DataLinkSuggestionsList
{...otherProps}
suggestions={groupedSuggestions[key]}
label={`${capitalize(key)}`}
activeIndex={otherProps.activeIndex}
activeIndexOffset={indexOffset}
key={key}
/>
);
})}
</div>
);
};
DataLinkSuggestions.displayName = 'DataLinkSuggestions';
interface DataLinkSuggestionsListProps extends DataLinkSuggestionsProps {
label: string;
activeIndexOffset: number;
activeRef?: React.RefObject<HTMLDivElement>;
}
const DataLinkSuggestionsList: React.FC<DataLinkSuggestionsListProps> = React.memo(
({ activeIndex, activeIndexOffset, label, onClose, onSuggestionSelect, suggestions, activeRef: selectedRef }) => {
const styles = useStyles2(getStyles);
return (
<>
<List
className={styles.list}
items={suggestions}
renderItem={(item, index) => {
const isActive = index + activeIndexOffset === activeIndex;
return (
<div
className={cx(styles.item, isActive && styles.activeItem)}
ref={isActive ? selectedRef : undefined}
onClick={() => {
onSuggestionSelect(item);
}}
title={item.documentation}
>
<span className={styles.itemValue}>
<span className={styles.label}>{label}</span> {item.label}
</span>
</div>
);
}}
/>
</>
);
}
);
DataLinkSuggestionsList.displayName = 'DataLinkSuggestionsList';
| packages/grafana-ui/src/components/DataLinks/DataLinkSuggestions.tsx | 0 | https://github.com/grafana/grafana/commit/8ecfad69951628cc8327c23166d953f86a8d83ff | [
0.00017950485926121473,
0.00017504164134152234,
0.00016920329653657973,
0.0001748569484334439,
0.0000027840183065563906
] |
{
"id": 6,
"code_window": [
" const parts = decomposeColor(color);\n",
"\n",
" let rgb = parts.type === 'hsl' ? decomposeColor(hslToRgb(color)).values : parts.values;\n",
" const rgbNumbers = rgb.map((val: any) => {\n",
" if (parts.type !== 'color') {\n",
" val /= 255; // normalized\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
" if (background && parts.type === 'rgba') {\n",
" const backgroundParts = decomposeColor(background);\n",
" const alpha = rgb[3];\n",
" rgb[0] = rgb[0] * alpha + backgroundParts.values[0] * (1 - alpha);\n",
" rgb[1] = rgb[1] * alpha + backgroundParts.values[1] * (1 - alpha);\n",
" rgb[2] = rgb[2] * alpha + backgroundParts.values[2] * (1 - alpha);\n",
" }\n",
"\n"
],
"file_path": "packages/grafana-data/src/themes/colorManipulator.ts",
"type": "add",
"edit_start_line_idx": 199
} | // Code based on Material-UI
// https://github.com/mui-org/material-ui/blob/1b096070faf102281f8e3c4f9b2bf50acf91f412/packages/material-ui/src/styles/colorManipulator.js#L97
// MIT License Copyright (c) 2014 Call-Em-All
/**
* Returns a number whose value is limited to the given range.
* @param value The value to be clamped
* @param min The lower boundary of the output range
* @param max The upper boundary of the output range
* @returns A number in the range [min, max]
* @beta
*/
function clamp(value: number, min = 0, max = 1) {
if (process.env.NODE_ENV !== 'production') {
if (value < min || value > max) {
console.error(`The value provided ${value} is out of range [${min}, ${max}].`);
}
}
return Math.min(Math.max(min, value), max);
}
/**
* Converts a color from CSS hex format to CSS rgb format.
* @param color - Hex color, i.e. #nnn or #nnnnnn
* @returns A CSS rgb color string
* @beta
*/
export function hexToRgb(color: string) {
color = color.substr(1);
const re = new RegExp(`.{1,${color.length >= 6 ? 2 : 1}}`, 'g');
let colors = color.match(re);
if (colors && colors[0].length === 1) {
colors = colors.map((n) => n + n);
}
return colors
? `rgb${colors.length === 4 ? 'a' : ''}(${colors
.map((n, index) => {
return index < 3 ? parseInt(n, 16) : Math.round((parseInt(n, 16) / 255) * 1000) / 1000;
})
.join(', ')})`
: '';
}
function intToHex(int: number) {
const hex = int.toString(16);
return hex.length === 1 ? `0${hex}` : hex;
}
/**
* Converts a color from CSS rgb format to CSS hex format.
* @param color - RGB color, i.e. rgb(n, n, n)
* @returns A CSS rgb color string, i.e. #nnnnnn
* @beta
*/
export function rgbToHex(color: string) {
// Idempotent
if (color.indexOf('#') === 0) {
return color;
}
const { values } = decomposeColor(color);
return `#${values.map((n: number) => intToHex(n)).join('')}`;
}
/**
* Converts a color from hsl format to rgb format.
* @param color - HSL color values
* @returns rgb color values
* @beta
*/
export function hslToRgb(color: string | DecomposeColor) {
const parts = decomposeColor(color);
const { values } = parts;
const h = values[0];
const s = values[1] / 100;
const l = values[2] / 100;
const a = s * Math.min(l, 1 - l);
const f = (n: number, k = (n + h / 30) % 12) => l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1);
let type = 'rgb';
const rgb = [Math.round(f(0) * 255), Math.round(f(8) * 255), Math.round(f(4) * 255)];
if (parts.type === 'hsla') {
type += 'a';
rgb.push(values[3]);
}
return recomposeColor({ type, values: rgb });
}
/**
* Returns an object with the type and values of a color.
*
* Note: Does not support rgb % values.
* @param color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()
* @returns {object} - A MUI color object: {type: string, values: number[]}
* @beta
*/
export function decomposeColor(color: string | DecomposeColor): DecomposeColor {
// Idempotent
if (typeof color !== 'string') {
return color;
}
if (color.charAt(0) === '#') {
return decomposeColor(hexToRgb(color));
}
const marker = color.indexOf('(');
const type = color.substring(0, marker);
if (['rgb', 'rgba', 'hsl', 'hsla', 'color'].indexOf(type) === -1) {
throw new Error(
`Unsupported '${color}' color. The following formats are supported: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), color()`
);
}
let values: any = color.substring(marker + 1, color.length - 1);
let colorSpace;
if (type === 'color') {
values = values.split(' ');
colorSpace = values.shift();
if (values.length === 4 && values[3].charAt(0) === '/') {
values[3] = values[3].substr(1);
}
if (['srgb', 'display-p3', 'a98-rgb', 'prophoto-rgb', 'rec-2020'].indexOf(colorSpace) === -1) {
throw new Error(
`Unsupported ${colorSpace} color space. The following color spaces are supported: srgb, display-p3, a98-rgb, prophoto-rgb, rec-2020.`
);
}
} else {
values = values.split(',');
}
values = values.map((value: string) => parseFloat(value));
return { type, values, colorSpace };
}
/**
* Converts a color object with type and values to a string.
* @param {object} color - Decomposed color
* @param color.type - One of: 'rgb', 'rgba', 'hsl', 'hsla'
* @param {array} color.values - [n,n,n] or [n,n,n,n]
* @returns A CSS color string
* @beta
*/
export function recomposeColor(color: DecomposeColor) {
const { type, colorSpace } = color;
let values: any = color.values;
if (type.indexOf('rgb') !== -1) {
// Only convert the first 3 values to int (i.e. not alpha)
values = values.map((n: string, i: number) => (i < 3 ? parseInt(n, 10) : n));
} else if (type.indexOf('hsl') !== -1) {
values[1] = `${values[1]}%`;
values[2] = `${values[2]}%`;
}
if (type.indexOf('color') !== -1) {
values = `${colorSpace} ${values.join(' ')}`;
} else {
values = `${values.join(', ')}`;
}
return `${type}(${values})`;
}
/**
* Calculates the contrast ratio between two colors.
*
* Formula: https://www.w3.org/TR/WCAG20-TECHS/G17.html#G17-tests
* @param foreground - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()
* @param background - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()
* @returns A contrast ratio value in the range 0 - 21.
* @beta
*/
export function getContrastRatio(foreground: string, background: string) {
const lumA = getLuminance(foreground);
const lumB = getLuminance(background);
return (Math.max(lumA, lumB) + 0.05) / (Math.min(lumA, lumB) + 0.05);
}
/**
* The relative brightness of any point in a color space,
* normalized to 0 for darkest black and 1 for lightest white.
*
* Formula: https://www.w3.org/TR/WCAG20-TECHS/G17.html#G17-tests
* @param color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), color()
* @returns The relative brightness of the color in the range 0 - 1
* @beta
*/
export function getLuminance(color: string) {
const parts = decomposeColor(color);
let rgb = parts.type === 'hsl' ? decomposeColor(hslToRgb(color)).values : parts.values;
const rgbNumbers = rgb.map((val: any) => {
if (parts.type !== 'color') {
val /= 255; // normalized
}
return val <= 0.03928 ? val / 12.92 : ((val + 0.055) / 1.055) ** 2.4;
});
// Truncate at 3 digits
return Number((0.2126 * rgbNumbers[0] + 0.7152 * rgbNumbers[1] + 0.0722 * rgbNumbers[2]).toFixed(3));
}
/**
* Darken or lighten a color, depending on its luminance.
* Light colors are darkened, dark colors are lightened.
* @param color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), color()
* @param coefficient=0.15 - multiplier in the range 0 - 1
* @returns A CSS color string. Hex input values are returned as rgb
* @beta
*/
export function emphasize(color: string, coefficient = 0.15) {
return getLuminance(color) > 0.5 ? darken(color, coefficient) : lighten(color, coefficient);
}
/**
* Set the absolute transparency of a color.
* Any existing alpha values are overwritten.
* @param color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), color()
* @param value - value to set the alpha channel to in the range 0 - 1
* @returns A CSS color string. Hex input values are returned as rgb
* @beta
*/
export function alpha(color: string, value: number) {
const parts = decomposeColor(color);
value = clamp(value);
if (parts.type === 'rgb' || parts.type === 'hsl') {
parts.type += 'a';
}
if (parts.type === 'color') {
parts.values[3] = `/${value}`;
} else {
parts.values[3] = value;
}
return recomposeColor(parts);
}
/**
* Darkens a color.
* @param color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), color()
* @param coefficient - multiplier in the range 0 - 1
* @returns A CSS color string. Hex input values are returned as rgb
* @beta
*/
export function darken(color: string, coefficient: number) {
const parts = decomposeColor(color);
coefficient = clamp(coefficient);
if (parts.type.indexOf('hsl') !== -1) {
parts.values[2] *= 1 - coefficient;
} else if (parts.type.indexOf('rgb') !== -1 || parts.type.indexOf('color') !== -1) {
for (let i = 0; i < 3; i += 1) {
parts.values[i] *= 1 - coefficient;
}
}
return recomposeColor(parts);
}
/**
* Lightens a color.
* @param color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), color()
* @param coefficient - multiplier in the range 0 - 1
* @returns A CSS color string. Hex input values are returned as rgb
* @beta
*/
export function lighten(color: string, coefficient: number) {
const parts = decomposeColor(color);
coefficient = clamp(coefficient);
if (parts.type.indexOf('hsl') !== -1) {
parts.values[2] += (100 - parts.values[2]) * coefficient;
} else if (parts.type.indexOf('rgb') !== -1) {
for (let i = 0; i < 3; i += 1) {
parts.values[i] += (255 - parts.values[i]) * coefficient;
}
} else if (parts.type.indexOf('color') !== -1) {
for (let i = 0; i < 3; i += 1) {
parts.values[i] += (1 - parts.values[i]) * coefficient;
}
}
return recomposeColor(parts);
}
interface DecomposeColor {
type: string;
values: any;
colorSpace?: string;
}
| packages/grafana-data/src/themes/colorManipulator.ts | 1 | https://github.com/grafana/grafana/commit/8ecfad69951628cc8327c23166d953f86a8d83ff | [
0.9991990923881531,
0.13285857439041138,
0.0001620541443116963,
0.002039034850895405,
0.3002372980117798
] |
{
"id": 6,
"code_window": [
" const parts = decomposeColor(color);\n",
"\n",
" let rgb = parts.type === 'hsl' ? decomposeColor(hslToRgb(color)).values : parts.values;\n",
" const rgbNumbers = rgb.map((val: any) => {\n",
" if (parts.type !== 'color') {\n",
" val /= 255; // normalized\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
" if (background && parts.type === 'rgba') {\n",
" const backgroundParts = decomposeColor(background);\n",
" const alpha = rgb[3];\n",
" rgb[0] = rgb[0] * alpha + backgroundParts.values[0] * (1 - alpha);\n",
" rgb[1] = rgb[1] * alpha + backgroundParts.values[1] * (1 - alpha);\n",
" rgb[2] = rgb[2] * alpha + backgroundParts.values[2] * (1 - alpha);\n",
" }\n",
"\n"
],
"file_path": "packages/grafana-data/src/themes/colorManipulator.ts",
"type": "add",
"edit_start_line_idx": 199
} | package plugins
import (
"testing"
"github.com/grafana/grafana-plugin-model/go/datasource"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/stretchr/testify/require"
)
func TestMapTables(t *testing.T) {
dpw := newDataSourcePluginWrapper(log.New("test-logger"), nil)
var qr = &datasource.QueryResult{}
qr.Tables = append(qr.Tables, &datasource.Table{
Columns: []*datasource.TableColumn{},
Rows: nil,
})
have, err := dpw.mapTables(qr)
require.NoError(t, err)
require.Len(t, have, 1)
}
func TestMapTable(t *testing.T) {
dpw := newDataSourcePluginWrapper(log.New("test-logger"), nil)
source := &datasource.Table{
Columns: []*datasource.TableColumn{{Name: "column1"}, {Name: "column2"}},
Rows: []*datasource.TableRow{{
Values: []*datasource.RowValue{
{
Kind: datasource.RowValue_TYPE_BOOL,
BoolValue: true,
},
{
Kind: datasource.RowValue_TYPE_INT64,
Int64Value: 42,
},
},
}},
}
want := DataTable{
Columns: []DataTableColumn{{Text: "column1"}, {Text: "column2"}},
}
have, err := dpw.mapTable(source)
require.NoError(t, err)
require.Equal(t, want.Columns, have.Columns)
require.Len(t, have.Rows, 1)
require.Len(t, have.Rows[0], 2)
}
func TestMappingRowValue(t *testing.T) {
dpw := newDataSourcePluginWrapper(log.New("test-logger"), nil)
boolRowValue, err := dpw.mapRowValue(&datasource.RowValue{Kind: datasource.RowValue_TYPE_BOOL, BoolValue: true})
require.NoError(t, err)
haveBool, ok := boolRowValue.(bool)
require.True(t, ok)
require.True(t, haveBool)
intRowValue, _ := dpw.mapRowValue(&datasource.RowValue{Kind: datasource.RowValue_TYPE_INT64, Int64Value: 42})
haveInt, ok := intRowValue.(int64)
require.True(t, ok)
require.Equal(t, int64(42), haveInt)
stringRowValue, _ := dpw.mapRowValue(&datasource.RowValue{Kind: datasource.RowValue_TYPE_STRING, StringValue: "grafana"})
haveString, ok := stringRowValue.(string)
require.True(t, ok)
require.Equal(t, "grafana", haveString)
doubleRowValue, _ := dpw.mapRowValue(&datasource.RowValue{Kind: datasource.RowValue_TYPE_DOUBLE, DoubleValue: 1.5})
haveDouble, ok := doubleRowValue.(float64)
require.True(t, ok)
require.Equal(t, 1.5, haveDouble)
bytesRowValue, _ := dpw.mapRowValue(&datasource.RowValue{Kind: datasource.RowValue_TYPE_BYTES, BytesValue: []byte{66}})
haveBytes, ok := bytesRowValue.([]byte)
require.True(t, ok)
require.Equal(t, []byte{66}, haveBytes)
haveNil, err := dpw.mapRowValue(&datasource.RowValue{Kind: datasource.RowValue_TYPE_NULL})
require.NoError(t, err)
require.Nil(t, haveNil)
}
| pkg/plugins/datasource_plugin_wrapper_test.go | 0 | https://github.com/grafana/grafana/commit/8ecfad69951628cc8327c23166d953f86a8d83ff | [
0.00017873544129543006,
0.00017446602578274906,
0.0001703788439044729,
0.00017500728426966816,
0.000002603613665996818
] |
{
"id": 6,
"code_window": [
" const parts = decomposeColor(color);\n",
"\n",
" let rgb = parts.type === 'hsl' ? decomposeColor(hslToRgb(color)).values : parts.values;\n",
" const rgbNumbers = rgb.map((val: any) => {\n",
" if (parts.type !== 'color') {\n",
" val /= 255; // normalized\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
" if (background && parts.type === 'rgba') {\n",
" const backgroundParts = decomposeColor(background);\n",
" const alpha = rgb[3];\n",
" rgb[0] = rgb[0] * alpha + backgroundParts.values[0] * (1 - alpha);\n",
" rgb[1] = rgb[1] * alpha + backgroundParts.values[1] * (1 - alpha);\n",
" rgb[2] = rgb[2] * alpha + backgroundParts.values[2] * (1 - alpha);\n",
" }\n",
"\n"
],
"file_path": "packages/grafana-data/src/themes/colorManipulator.ts",
"type": "add",
"edit_start_line_idx": 199
} | interface AnnotationsDataFrameViewDTO {
time: number;
text: string;
tags: string[];
alertId?: number;
newState?: string;
title?: string;
color: string;
}
| public/app/plugins/panel/timeseries/plugins/types.ts | 0 | https://github.com/grafana/grafana/commit/8ecfad69951628cc8327c23166d953f86a8d83ff | [
0.000167073609190993,
0.000167073609190993,
0.000167073609190993,
0.000167073609190993,
0
] |
{
"id": 6,
"code_window": [
" const parts = decomposeColor(color);\n",
"\n",
" let rgb = parts.type === 'hsl' ? decomposeColor(hslToRgb(color)).values : parts.values;\n",
" const rgbNumbers = rgb.map((val: any) => {\n",
" if (parts.type !== 'color') {\n",
" val /= 255; // normalized\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
" if (background && parts.type === 'rgba') {\n",
" const backgroundParts = decomposeColor(background);\n",
" const alpha = rgb[3];\n",
" rgb[0] = rgb[0] * alpha + backgroundParts.values[0] * (1 - alpha);\n",
" rgb[1] = rgb[1] * alpha + backgroundParts.values[1] * (1 - alpha);\n",
" rgb[2] = rgb[2] * alpha + backgroundParts.values[2] * (1 - alpha);\n",
" }\n",
"\n"
],
"file_path": "packages/grafana-data/src/themes/colorManipulator.ts",
"type": "add",
"edit_start_line_idx": 199
} | package scuemata
// Definition of the shape of a panel plugin's schema declarations in its
// schema.cue file.
//
// Note that these keys do not appear directly in any real JSON artifact;
// rather, they are composed into panel structures as they are defined within
// the larger Dashboard schema.
#PanelSchema: {
// Defines plugin specific options for a panel
PanelOptions: {...}
// Define the custom properties that exist within standard field config
PanelFieldConfig?: {...}
// Panels may define their own types
...
}
// A lineage of panel schema
#PanelLineage: [#PanelSchema, ...#PanelSchema]
// Panel plugin-specific Family
#PanelFamily: {
lineages: [#PanelLineage, ...#PanelLineage]
migrations: [...#Migration]
}
| cue/scuemata/panel-plugin.cue | 0 | https://github.com/grafana/grafana/commit/8ecfad69951628cc8327c23166d953f86a8d83ff | [
0.0002260889596072957,
0.00018966566130984575,
0.00017129887419287115,
0.00017160917923320085,
0.00002575546568550635
] |
{
"id": 7,
"code_window": [
"\n",
" function getContrastText(background: string, threshold: number = contrastThreshold) {\n",
" const contrastText =\n",
" getContrastRatio(dark.text.maxContrast, background) >= threshold ? dark.text.maxContrast : light.text.maxContrast;\n",
" // todo, need color framework\n",
" return contrastText;\n",
" }\n",
"\n",
" const getRichColor = ({ color, name }: GetRichColorProps): ThemeRichColor => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" getContrastRatio(dark.text.maxContrast, background, base.background.primary) >= threshold\n",
" ? dark.text.maxContrast\n",
" : light.text.maxContrast;\n"
],
"file_path": "packages/grafana-data/src/themes/createColors.ts",
"type": "replace",
"edit_start_line_idx": 259
} | // Code based on Material-UI
// https://github.com/mui-org/material-ui/blob/1b096070faf102281f8e3c4f9b2bf50acf91f412/packages/material-ui/src/styles/colorManipulator.js#L97
// MIT License Copyright (c) 2014 Call-Em-All
/**
* Returns a number whose value is limited to the given range.
* @param value The value to be clamped
* @param min The lower boundary of the output range
* @param max The upper boundary of the output range
* @returns A number in the range [min, max]
* @beta
*/
function clamp(value: number, min = 0, max = 1) {
if (process.env.NODE_ENV !== 'production') {
if (value < min || value > max) {
console.error(`The value provided ${value} is out of range [${min}, ${max}].`);
}
}
return Math.min(Math.max(min, value), max);
}
/**
* Converts a color from CSS hex format to CSS rgb format.
* @param color - Hex color, i.e. #nnn or #nnnnnn
* @returns A CSS rgb color string
* @beta
*/
export function hexToRgb(color: string) {
color = color.substr(1);
const re = new RegExp(`.{1,${color.length >= 6 ? 2 : 1}}`, 'g');
let colors = color.match(re);
if (colors && colors[0].length === 1) {
colors = colors.map((n) => n + n);
}
return colors
? `rgb${colors.length === 4 ? 'a' : ''}(${colors
.map((n, index) => {
return index < 3 ? parseInt(n, 16) : Math.round((parseInt(n, 16) / 255) * 1000) / 1000;
})
.join(', ')})`
: '';
}
function intToHex(int: number) {
const hex = int.toString(16);
return hex.length === 1 ? `0${hex}` : hex;
}
/**
* Converts a color from CSS rgb format to CSS hex format.
* @param color - RGB color, i.e. rgb(n, n, n)
* @returns A CSS rgb color string, i.e. #nnnnnn
* @beta
*/
export function rgbToHex(color: string) {
// Idempotent
if (color.indexOf('#') === 0) {
return color;
}
const { values } = decomposeColor(color);
return `#${values.map((n: number) => intToHex(n)).join('')}`;
}
/**
* Converts a color from hsl format to rgb format.
* @param color - HSL color values
* @returns rgb color values
* @beta
*/
export function hslToRgb(color: string | DecomposeColor) {
const parts = decomposeColor(color);
const { values } = parts;
const h = values[0];
const s = values[1] / 100;
const l = values[2] / 100;
const a = s * Math.min(l, 1 - l);
const f = (n: number, k = (n + h / 30) % 12) => l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1);
let type = 'rgb';
const rgb = [Math.round(f(0) * 255), Math.round(f(8) * 255), Math.round(f(4) * 255)];
if (parts.type === 'hsla') {
type += 'a';
rgb.push(values[3]);
}
return recomposeColor({ type, values: rgb });
}
/**
* Returns an object with the type and values of a color.
*
* Note: Does not support rgb % values.
* @param color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()
* @returns {object} - A MUI color object: {type: string, values: number[]}
* @beta
*/
export function decomposeColor(color: string | DecomposeColor): DecomposeColor {
// Idempotent
if (typeof color !== 'string') {
return color;
}
if (color.charAt(0) === '#') {
return decomposeColor(hexToRgb(color));
}
const marker = color.indexOf('(');
const type = color.substring(0, marker);
if (['rgb', 'rgba', 'hsl', 'hsla', 'color'].indexOf(type) === -1) {
throw new Error(
`Unsupported '${color}' color. The following formats are supported: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), color()`
);
}
let values: any = color.substring(marker + 1, color.length - 1);
let colorSpace;
if (type === 'color') {
values = values.split(' ');
colorSpace = values.shift();
if (values.length === 4 && values[3].charAt(0) === '/') {
values[3] = values[3].substr(1);
}
if (['srgb', 'display-p3', 'a98-rgb', 'prophoto-rgb', 'rec-2020'].indexOf(colorSpace) === -1) {
throw new Error(
`Unsupported ${colorSpace} color space. The following color spaces are supported: srgb, display-p3, a98-rgb, prophoto-rgb, rec-2020.`
);
}
} else {
values = values.split(',');
}
values = values.map((value: string) => parseFloat(value));
return { type, values, colorSpace };
}
/**
* Converts a color object with type and values to a string.
* @param {object} color - Decomposed color
* @param color.type - One of: 'rgb', 'rgba', 'hsl', 'hsla'
* @param {array} color.values - [n,n,n] or [n,n,n,n]
* @returns A CSS color string
* @beta
*/
export function recomposeColor(color: DecomposeColor) {
const { type, colorSpace } = color;
let values: any = color.values;
if (type.indexOf('rgb') !== -1) {
// Only convert the first 3 values to int (i.e. not alpha)
values = values.map((n: string, i: number) => (i < 3 ? parseInt(n, 10) : n));
} else if (type.indexOf('hsl') !== -1) {
values[1] = `${values[1]}%`;
values[2] = `${values[2]}%`;
}
if (type.indexOf('color') !== -1) {
values = `${colorSpace} ${values.join(' ')}`;
} else {
values = `${values.join(', ')}`;
}
return `${type}(${values})`;
}
/**
* Calculates the contrast ratio between two colors.
*
* Formula: https://www.w3.org/TR/WCAG20-TECHS/G17.html#G17-tests
* @param foreground - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()
* @param background - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()
* @returns A contrast ratio value in the range 0 - 21.
* @beta
*/
export function getContrastRatio(foreground: string, background: string) {
const lumA = getLuminance(foreground);
const lumB = getLuminance(background);
return (Math.max(lumA, lumB) + 0.05) / (Math.min(lumA, lumB) + 0.05);
}
/**
* The relative brightness of any point in a color space,
* normalized to 0 for darkest black and 1 for lightest white.
*
* Formula: https://www.w3.org/TR/WCAG20-TECHS/G17.html#G17-tests
* @param color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), color()
* @returns The relative brightness of the color in the range 0 - 1
* @beta
*/
export function getLuminance(color: string) {
const parts = decomposeColor(color);
let rgb = parts.type === 'hsl' ? decomposeColor(hslToRgb(color)).values : parts.values;
const rgbNumbers = rgb.map((val: any) => {
if (parts.type !== 'color') {
val /= 255; // normalized
}
return val <= 0.03928 ? val / 12.92 : ((val + 0.055) / 1.055) ** 2.4;
});
// Truncate at 3 digits
return Number((0.2126 * rgbNumbers[0] + 0.7152 * rgbNumbers[1] + 0.0722 * rgbNumbers[2]).toFixed(3));
}
/**
* Darken or lighten a color, depending on its luminance.
* Light colors are darkened, dark colors are lightened.
* @param color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), color()
* @param coefficient=0.15 - multiplier in the range 0 - 1
* @returns A CSS color string. Hex input values are returned as rgb
* @beta
*/
export function emphasize(color: string, coefficient = 0.15) {
return getLuminance(color) > 0.5 ? darken(color, coefficient) : lighten(color, coefficient);
}
/**
* Set the absolute transparency of a color.
* Any existing alpha values are overwritten.
* @param color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), color()
* @param value - value to set the alpha channel to in the range 0 - 1
* @returns A CSS color string. Hex input values are returned as rgb
* @beta
*/
export function alpha(color: string, value: number) {
const parts = decomposeColor(color);
value = clamp(value);
if (parts.type === 'rgb' || parts.type === 'hsl') {
parts.type += 'a';
}
if (parts.type === 'color') {
parts.values[3] = `/${value}`;
} else {
parts.values[3] = value;
}
return recomposeColor(parts);
}
/**
* Darkens a color.
* @param color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), color()
* @param coefficient - multiplier in the range 0 - 1
* @returns A CSS color string. Hex input values are returned as rgb
* @beta
*/
export function darken(color: string, coefficient: number) {
const parts = decomposeColor(color);
coefficient = clamp(coefficient);
if (parts.type.indexOf('hsl') !== -1) {
parts.values[2] *= 1 - coefficient;
} else if (parts.type.indexOf('rgb') !== -1 || parts.type.indexOf('color') !== -1) {
for (let i = 0; i < 3; i += 1) {
parts.values[i] *= 1 - coefficient;
}
}
return recomposeColor(parts);
}
/**
* Lightens a color.
* @param color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), color()
* @param coefficient - multiplier in the range 0 - 1
* @returns A CSS color string. Hex input values are returned as rgb
* @beta
*/
export function lighten(color: string, coefficient: number) {
const parts = decomposeColor(color);
coefficient = clamp(coefficient);
if (parts.type.indexOf('hsl') !== -1) {
parts.values[2] += (100 - parts.values[2]) * coefficient;
} else if (parts.type.indexOf('rgb') !== -1) {
for (let i = 0; i < 3; i += 1) {
parts.values[i] += (255 - parts.values[i]) * coefficient;
}
} else if (parts.type.indexOf('color') !== -1) {
for (let i = 0; i < 3; i += 1) {
parts.values[i] += (1 - parts.values[i]) * coefficient;
}
}
return recomposeColor(parts);
}
interface DecomposeColor {
type: string;
values: any;
colorSpace?: string;
}
| packages/grafana-data/src/themes/colorManipulator.ts | 1 | https://github.com/grafana/grafana/commit/8ecfad69951628cc8327c23166d953f86a8d83ff | [
0.0020841890946030617,
0.0002985904866363853,
0.00016183039406314492,
0.00017058741650544107,
0.0004009788390249014
] |
{
"id": 7,
"code_window": [
"\n",
" function getContrastText(background: string, threshold: number = contrastThreshold) {\n",
" const contrastText =\n",
" getContrastRatio(dark.text.maxContrast, background) >= threshold ? dark.text.maxContrast : light.text.maxContrast;\n",
" // todo, need color framework\n",
" return contrastText;\n",
" }\n",
"\n",
" const getRichColor = ({ color, name }: GetRichColorProps): ThemeRichColor => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" getContrastRatio(dark.text.maxContrast, background, base.background.primary) >= threshold\n",
" ? dark.text.maxContrast\n",
" : light.text.maxContrast;\n"
],
"file_path": "packages/grafana-data/src/themes/createColors.ts",
"type": "replace",
"edit_start_line_idx": 259
} | <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M19 21.5H5a3 3 0 01-3-3v-13a3 3 0 013-3h4.56a3 3 0 012.84 2.05l.32.95H19a3 3 0 013 3v10a3 3 0 01-3 3z"/></svg> | public/img/icons/mono/folder.svg | 0 | https://github.com/grafana/grafana/commit/8ecfad69951628cc8327c23166d953f86a8d83ff | [
0.00017388866399414837,
0.00017388866399414837,
0.00017388866399414837,
0.00017388866399414837,
0
] |
{
"id": 7,
"code_window": [
"\n",
" function getContrastText(background: string, threshold: number = contrastThreshold) {\n",
" const contrastText =\n",
" getContrastRatio(dark.text.maxContrast, background) >= threshold ? dark.text.maxContrast : light.text.maxContrast;\n",
" // todo, need color framework\n",
" return contrastText;\n",
" }\n",
"\n",
" const getRichColor = ({ color, name }: GetRichColorProps): ThemeRichColor => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" getContrastRatio(dark.text.maxContrast, background, base.background.primary) >= threshold\n",
" ? dark.text.maxContrast\n",
" : light.text.maxContrast;\n"
],
"file_path": "packages/grafana-data/src/themes/createColors.ts",
"type": "replace",
"edit_start_line_idx": 259
} | #!/bin/sh
if [ "$1" == "-rn" ]; then
false | busybox cp -i -r "$2" "$3" 2>/dev/null
else
busybox cp $*
fi
| packages/grafana-toolkit/docker/grafana-plugin-ci-alpine/install/bin/cp | 0 | https://github.com/grafana/grafana/commit/8ecfad69951628cc8327c23166d953f86a8d83ff | [
0.00017485316493548453,
0.00017485316493548453,
0.00017485316493548453,
0.00017485316493548453,
0
] |
{
"id": 7,
"code_window": [
"\n",
" function getContrastText(background: string, threshold: number = contrastThreshold) {\n",
" const contrastText =\n",
" getContrastRatio(dark.text.maxContrast, background) >= threshold ? dark.text.maxContrast : light.text.maxContrast;\n",
" // todo, need color framework\n",
" return contrastText;\n",
" }\n",
"\n",
" const getRichColor = ({ color, name }: GetRichColorProps): ThemeRichColor => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" getContrastRatio(dark.text.maxContrast, background, base.background.primary) >= threshold\n",
" ? dark.text.maxContrast\n",
" : light.text.maxContrast;\n"
],
"file_path": "packages/grafana-data/src/themes/createColors.ts",
"type": "replace",
"edit_start_line_idx": 259
} | import React, { useState, useEffect } from 'react';
import { connect } from 'react-redux';
import { hot } from 'react-hot-loader';
import { css, cx } from '@emotion/css';
import { stylesFactory, useTheme, TextArea, Button, IconButton } from '@grafana/ui';
import { getDataSourceSrv } from '@grafana/runtime';
import { GrafanaTheme, DataSourceApi } from '@grafana/data';
import { RichHistoryQuery, ExploreId } from 'app/types/explore';
import { createUrlFromRichHistory, createQueryText } from 'app/core/utils/richHistory';
import { createAndCopyShortLink } from 'app/core/utils/shortLinks';
import { copyStringToClipboard } from 'app/core/utils/explore';
import appEvents from 'app/core/app_events';
import { dispatch } from 'app/store/store';
import { notifyApp } from 'app/core/actions';
import { createSuccessNotification } from 'app/core/copy/appNotification';
import { StoreState } from 'app/types';
import { updateRichHistory } from '../state/history';
import { changeDatasource } from '../state/datasource';
import { setQueries } from '../state/query';
import { ShowConfirmModalEvent } from '../../../types/events';
export interface Props {
query: RichHistoryQuery;
dsImg: string;
isRemoved: boolean;
changeDatasource: typeof changeDatasource;
updateRichHistory: typeof updateRichHistory;
setQueries: typeof setQueries;
exploreId: ExploreId;
datasourceInstance: DataSourceApi;
}
const getStyles = stylesFactory((theme: GrafanaTheme, isRemoved: boolean) => {
/* Hard-coded value so all buttons and icons on right side of card are aligned */
const rigtColumnWidth = '240px';
const rigtColumnContentWidth = '170px';
/* If datasource was removed, card will have inactive color */
const cardColor = theme.colors.bg2;
return {
queryCard: css`
display: flex;
flex-direction: column;
border: 1px solid ${theme.colors.border1};
margin: ${theme.spacing.sm} 0;
background-color: ${cardColor};
border-radius: ${theme.border.radius.sm};
.starred {
color: ${theme.palette.orange};
}
`,
cardRow: css`
display: flex;
align-items: center;
justify-content: space-between;
padding: ${theme.spacing.sm};
border-bottom: none;
:first-of-type {
border-bottom: 1px solid ${theme.colors.border1};
padding: ${theme.spacing.xs} ${theme.spacing.sm};
}
img {
height: ${theme.typography.size.base};
max-width: ${theme.typography.size.base};
margin-right: ${theme.spacing.sm};
}
`,
datasourceContainer: css`
display: flex;
align-items: center;
font-size: ${theme.typography.size.sm};
font-weight: ${theme.typography.weight.semibold};
`,
queryActionButtons: css`
max-width: ${rigtColumnContentWidth};
display: flex;
justify-content: flex-end;
font-size: ${theme.typography.size.base};
button {
margin-left: ${theme.spacing.sm};
}
`,
queryContainer: css`
font-weight: ${theme.typography.weight.semibold};
width: calc(100% - ${rigtColumnWidth});
`,
queryRow: css`
border-top: 1px solid ${theme.colors.border1};
word-break: break-all;
padding: 4px 2px;
:first-child {
border-top: none;
padding: 0 0 4px 0;
}
`,
updateCommentContainer: css`
width: calc(100% + ${rigtColumnWidth});
margin-top: ${theme.spacing.sm};
`,
comment: css`
overflow-wrap: break-word;
font-size: ${theme.typography.size.sm};
font-weight: ${theme.typography.weight.regular};
margin-top: ${theme.spacing.xs};
`,
commentButtonRow: css`
> * {
margin-right: ${theme.spacing.sm};
}
`,
textArea: css`
width: 100%;
`,
runButton: css`
max-width: ${rigtColumnContentWidth};
display: flex;
justify-content: flex-end;
button {
height: auto;
padding: ${theme.spacing.xs} ${theme.spacing.md};
line-height: 1.4;
span {
white-space: normal !important;
}
}
`,
};
});
export function RichHistoryCard(props: Props) {
const {
query,
dsImg,
isRemoved,
updateRichHistory,
changeDatasource,
exploreId,
datasourceInstance,
setQueries,
} = props;
const [activeUpdateComment, setActiveUpdateComment] = useState(false);
const [comment, setComment] = useState<string | undefined>(query.comment);
const [queryDsInstance, setQueryDsInstance] = useState<DataSourceApi | undefined>(undefined);
useEffect(() => {
const getQueryDsInstance = async () => {
const ds = await getDataSourceSrv().get(query.datasourceName);
setQueryDsInstance(ds);
};
getQueryDsInstance();
}, [query.datasourceName]);
const theme = useTheme();
const styles = getStyles(theme, isRemoved);
const onRunQuery = async () => {
const queriesToRun = query.queries;
if (query.datasourceName !== datasourceInstance?.name) {
await changeDatasource(exploreId, query.datasourceName, { importQueries: true });
setQueries(exploreId, queriesToRun);
} else {
setQueries(exploreId, queriesToRun);
}
};
const onCopyQuery = () => {
const queriesToCopy = query.queries.map((q) => createQueryText(q, queryDsInstance)).join('\n');
copyStringToClipboard(queriesToCopy);
dispatch(notifyApp(createSuccessNotification('Query copied to clipboard')));
};
const onCreateShortLink = async () => {
const link = createUrlFromRichHistory(query);
await createAndCopyShortLink(link);
};
const onDeleteQuery = () => {
// For starred queries, we want confirmation. For non-starred, we don't.
if (query.starred) {
appEvents.publish(
new ShowConfirmModalEvent({
title: 'Delete',
text: 'Are you sure you want to permanently delete your starred query?',
yesText: 'Delete',
icon: 'trash-alt',
onConfirm: () => {
updateRichHistory(query.ts, 'delete');
dispatch(notifyApp(createSuccessNotification('Query deleted')));
},
})
);
} else {
updateRichHistory(query.ts, 'delete');
dispatch(notifyApp(createSuccessNotification('Query deleted')));
}
};
const onStarrQuery = () => {
updateRichHistory(query.ts, 'starred');
};
const toggleActiveUpdateComment = () => setActiveUpdateComment(!activeUpdateComment);
const onUpdateComment = () => {
updateRichHistory(query.ts, 'comment', comment);
setActiveUpdateComment(false);
};
const onCancelUpdateComment = () => {
setActiveUpdateComment(false);
setComment(query.comment);
};
const onKeyDown = (keyEvent: React.KeyboardEvent) => {
if (keyEvent.key === 'Enter' && (keyEvent.shiftKey || keyEvent.ctrlKey)) {
onUpdateComment();
}
if (keyEvent.key === 'Escape') {
onCancelUpdateComment();
}
};
const updateComment = (
<div className={styles.updateCommentContainer} aria-label={comment ? 'Update comment form' : 'Add comment form'}>
<TextArea
value={comment}
placeholder={comment ? undefined : 'An optional description of what the query does.'}
onChange={(e) => setComment(e.currentTarget.value)}
className={styles.textArea}
/>
<div className={styles.commentButtonRow}>
<Button onClick={onUpdateComment} aria-label="Submit button">
Save comment
</Button>
<Button variant="secondary" onClick={onCancelUpdateComment}>
Cancel
</Button>
</div>
</div>
);
const queryActionButtons = (
<div className={styles.queryActionButtons}>
<IconButton
name="comment-alt"
onClick={toggleActiveUpdateComment}
title={query.comment?.length > 0 ? 'Edit comment' : 'Add comment'}
/>
<IconButton name="copy" onClick={onCopyQuery} title="Copy query to clipboard" />
{!isRemoved && (
<IconButton name="share-alt" onClick={onCreateShortLink} title="Copy shortened link to clipboard" />
)}
<IconButton name="trash-alt" title={'Delete query'} onClick={onDeleteQuery} />
<IconButton
name={query.starred ? 'favorite' : 'star'}
iconType={query.starred ? 'mono' : 'default'}
onClick={onStarrQuery}
title={query.starred ? 'Unstar query' : 'Star query'}
/>
</div>
);
return (
<div className={styles.queryCard} onKeyDown={onKeyDown}>
<div className={styles.cardRow}>
<div className={styles.datasourceContainer}>
<img src={dsImg} aria-label="Data source icon" />
<div aria-label="Data source name">
{isRemoved ? 'Data source does not exist anymore' : query.datasourceName}
</div>
</div>
{queryActionButtons}
</div>
<div className={cx(styles.cardRow)}>
<div className={styles.queryContainer}>
{query.queries.map((q, i) => {
const queryText = createQueryText(q, queryDsInstance);
return (
<div aria-label="Query text" key={`${q}-${i}`} className={styles.queryRow}>
{queryText}
</div>
);
})}
{!activeUpdateComment && query.comment && (
<div aria-label="Query comment" className={styles.comment}>
{query.comment}
</div>
)}
{activeUpdateComment && updateComment}
</div>
{!activeUpdateComment && (
<div className={styles.runButton}>
<Button variant="secondary" onClick={onRunQuery} disabled={isRemoved}>
{datasourceInstance?.name === query.datasourceName ? 'Run query' : 'Switch data source and run query'}
</Button>
</div>
)}
</div>
</div>
);
}
function mapStateToProps(state: StoreState, { exploreId }: { exploreId: ExploreId }) {
const explore = state.explore;
const { datasourceInstance } = explore[exploreId]!;
return {
exploreId,
datasourceInstance,
};
}
const mapDispatchToProps = {
changeDatasource,
updateRichHistory,
setQueries,
};
export default hot(module)(connect(mapStateToProps, mapDispatchToProps)(RichHistoryCard));
| public/app/features/explore/RichHistory/RichHistoryCard.tsx | 0 | https://github.com/grafana/grafana/commit/8ecfad69951628cc8327c23166d953f86a8d83ff | [
0.00026555542717687786,
0.00017547559400554746,
0.00016364654584322125,
0.00017241596651729196,
0.000017237793144886382
] |
{
"id": 0,
"code_window": [
"exports.CallExpression = function (node, parent, file, scope) {\n",
" var args = node.arguments;\n",
" if (!hasSpread(args)) return;\n",
"\n",
" var contextLiteral = t.literal(null);\n",
"\n",
" node.arguments = [];\n",
"\n",
" var nodes;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" var contextLiteral = t.identifier(\"undefined\");\n"
],
"file_path": "lib/6to5/transformation/transformers/es6-spread.js",
"type": "replace",
"edit_start_line_idx": 61
} | var t = require("../../types");
var _ = require("lodash");
var getSpreadLiteral = function (spread, file) {
return file.toArray(spread.argument);
};
var hasSpread = function (nodes) {
for (var i in nodes) {
if (t.isSpreadElement(nodes[i])) {
return true;
}
}
return false;
};
var build = function (props, file) {
var nodes = [];
var _props = [];
var push = function () {
if (!_props.length) return;
nodes.push(t.arrayExpression(_props));
_props = [];
};
for (var i in props) {
var prop = props[i];
if (t.isSpreadElement(prop)) {
push();
nodes.push(getSpreadLiteral(prop, file));
} else {
_props.push(prop);
}
}
push();
return nodes;
};
exports.ArrayExpression = function (node, parent, file) {
var elements = node.elements;
if (!hasSpread(elements)) return;
var nodes = build(elements, file);
var first = nodes.shift();
if (!t.isArrayExpression(first)) {
nodes.unshift(first);
first = t.arrayExpression([]);
}
return t.callExpression(t.memberExpression(first, t.identifier("concat")), nodes);
};
exports.CallExpression = function (node, parent, file, scope) {
var args = node.arguments;
if (!hasSpread(args)) return;
var contextLiteral = t.literal(null);
node.arguments = [];
var nodes;
if (args.length === 1 && args[0].argument.name === 'arguments') {
nodes = [args[0].argument];
} else {
nodes = build(args, file);
}
var first = nodes.shift();
if (nodes.length) {
node.arguments.push(t.callExpression(t.memberExpression(first, t.identifier("concat")), nodes));
} else {
node.arguments.push(first);
}
var callee = node.callee;
if (t.isMemberExpression(callee)) {
var temp = scope.generateTempBasedOnNode(callee.object, file);
if (temp) {
callee.object = t.assignmentExpression("=", temp, callee.object);
contextLiteral = temp;
} else {
contextLiteral = callee.object;
}
t.appendToMemberExpression(callee, t.identifier("apply"));
} else {
node.callee = t.memberExpression(node.callee, t.identifier("apply"));
}
node.arguments.unshift(contextLiteral);
};
exports.NewExpression = function (node, parent, file) {
var args = node.arguments;
if (!hasSpread(args)) return;
var nativeType = t.isIdentifier(node.callee) && _.contains(t.NATIVE_TYPES_NAMES, node.callee.name);
var nodes = build(args, file);
if (nativeType) {
nodes.unshift(t.arrayExpression([t.literal(null)]));
}
var first = nodes.shift();
if (nodes.length) {
args = t.callExpression(t.memberExpression(first, t.identifier("concat")), nodes);
} else {
args = first;
}
if (nativeType) {
return t.newExpression(
t.callExpression(
t.memberExpression(file.addHelper("bind"), t.identifier("apply")),
[node.callee, args]
),
[]
);
} else {
return t.callExpression(file.addHelper("apply-constructor"), [node.callee, args]);
}
};
| lib/6to5/transformation/transformers/es6-spread.js | 1 | https://github.com/babel/babel/commit/74392470950a82eb1d6283d38ada2d7c7e053c90 | [
0.999270498752594,
0.9130438566207886,
0.00208003306761384,
0.9964894652366638,
0.26351648569107056
] |
{
"id": 0,
"code_window": [
"exports.CallExpression = function (node, parent, file, scope) {\n",
" var args = node.arguments;\n",
" if (!hasSpread(args)) return;\n",
"\n",
" var contextLiteral = t.literal(null);\n",
"\n",
" node.arguments = [];\n",
"\n",
" var nodes;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" var contextLiteral = t.identifier(\"undefined\");\n"
],
"file_path": "lib/6to5/transformation/transformers/es6-spread.js",
"type": "replace",
"edit_start_line_idx": 61
} | [a, b] = f();
| test/fixtures/transformation/es6-destructuring/assignment-statement/actual.js | 0 | https://github.com/babel/babel/commit/74392470950a82eb1d6283d38ada2d7c7e053c90 | [
0.00016183548723347485,
0.00016183548723347485,
0.00016183548723347485,
0.00016183548723347485,
0
] |
{
"id": 0,
"code_window": [
"exports.CallExpression = function (node, parent, file, scope) {\n",
" var args = node.arguments;\n",
" if (!hasSpread(args)) return;\n",
"\n",
" var contextLiteral = t.literal(null);\n",
"\n",
" node.arguments = [];\n",
"\n",
" var nodes;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" var contextLiteral = t.identifier(\"undefined\");\n"
],
"file_path": "lib/6to5/transformation/transformers/es6-spread.js",
"type": "replace",
"edit_start_line_idx": 61
} | {
"throws": "illegal kind for constructor method"
}
| test/fixtures/transformation/es6-classes/defining-constructor-as-a-mutator/options.json | 0 | https://github.com/babel/babel/commit/74392470950a82eb1d6283d38ada2d7c7e053c90 | [
0.00017574441153556108,
0.00017574441153556108,
0.00017574441153556108,
0.00017574441153556108,
0
] |
{
"id": 0,
"code_window": [
"exports.CallExpression = function (node, parent, file, scope) {\n",
" var args = node.arguments;\n",
" if (!hasSpread(args)) return;\n",
"\n",
" var contextLiteral = t.literal(null);\n",
"\n",
" node.arguments = [];\n",
"\n",
" var nodes;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" var contextLiteral = t.identifier(\"undefined\");\n"
],
"file_path": "lib/6to5/transformation/transformers/es6-spread.js",
"type": "replace",
"edit_start_line_idx": 61
} | {
"throws": "Namespace tags are not supported. ReactJSX is not XML."
}
| test/fixtures/transformation/react/should-disallow-xml-namespacing/options.json | 0 | https://github.com/babel/babel/commit/74392470950a82eb1d6283d38ada2d7c7e053c90 | [
0.00017242944159079343,
0.00017242944159079343,
0.00017242944159079343,
0.00017242944159079343,
0
] |
{
"id": 1,
"code_window": [
" var args = node.arguments;\n",
" if (!hasSpread(args)) return;\n",
"\n",
" var nativeType = t.isIdentifier(node.callee) && _.contains(t.NATIVE_TYPES_NAMES, node.callee.name);\n",
"\n",
" var nodes = build(args, file);\n",
"\n",
" if (nativeType) {\n",
" nodes.unshift(t.arrayExpression([t.literal(null)]));\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" var nativeType = t.isIdentifier(node.callee) && _.contains(t.NATIVE_TYPE_NAMES, node.callee.name);\n"
],
"file_path": "lib/6to5/transformation/transformers/es6-spread.js",
"type": "replace",
"edit_start_line_idx": 101
} | var esutils = require("esutils");
var _ = require("lodash");
var t = exports;
t.NATIVE_TYPES_NAMES = ["Array", "Object", "Number", "Boolean", "Date", "Array", "String"];
//
var addAssert = function (type, is) {
t["assert" + type] = function (node, opts) {
opts = opts || {};
if (!is(node, opts)) {
throw new Error("Expected type " + JSON.stringify(type) + " with option " + JSON.stringify(opts));
}
};
};
t.STATEMENT_OR_BLOCK_KEYS = ["consequent", "body"];
//
t.VISITOR_KEYS = require("./visitor-keys");
_.each(t.VISITOR_KEYS, function (keys, type) {
var is = t["is" + type] = function (node, opts) {
return node && node.type === type && t.shallowEqual(node, opts);
};
addAssert(type, is);
});
//
t.BUILDER_KEYS = _.defaults(require("./builder-keys"), t.VISITOR_KEYS);
_.each(t.BUILDER_KEYS, function (keys, type) {
t[type[0].toLowerCase() + type.slice(1)] = function () {
var args = arguments;
var node = { type: type };
_.each(keys, function (key, i) {
node[key] = args[i];
});
return node;
};
});
//
t.ALIAS_KEYS = require("./alias-keys");
t.FLIPPED_ALIAS_KEYS = {};
_.each(t.ALIAS_KEYS, function (aliases, type) {
_.each(aliases, function (alias) {
var types = t.FLIPPED_ALIAS_KEYS[alias] = t.FLIPPED_ALIAS_KEYS[alias] || [];
types.push(type);
});
});
_.each(t.FLIPPED_ALIAS_KEYS, function (types, type) {
t[type.toUpperCase() + "_TYPES"] = types;
var is = t["is" + type] = function (node, opts) {
return node && types.indexOf(node.type) >= 0 && t.shallowEqual(node, opts);
};
addAssert(type, is);
});
/**
* Description
*
* @param {Object} node
* @returns {Object}
*/
t.toComputedKey = function (node, key) {
if (!node.computed) {
if (t.isIdentifier(key)) key = t.literal(key.name);
}
return key;
};
/*
* Shallowly checks to see if the passed `node` will evaluate to a
* falsy. This is if `node` is a `Literal` and `value` is falsy or
* `node` is an `Identifier` with a name of `undefiend`.
*
* @param {Object} node
* @returns {Boolean}
*/
t.isFalsyExpression = function (node) {
if (t.isLiteral(node)) {
return !node.value;
} else if (t.isIdentifier(node)) {
return node.name === "undefined";
}
return false;
};
/**
* Turn an array of statement `nodes` into a `SequenceExpression`.
*
* Variable declarations are turned into simple assignments and their
* declarations hoisted to the top of the current scope.
*
* Expression statements are just resolved to their standard expression.
*/
t.toSequenceExpression = function (nodes, scope) {
var exprs = [];
_.each(nodes, function (node) {
if (t.isExpression(node)) {
exprs.push(node);
} if (t.isExpressionStatement(node)) {
exprs.push(node.expression);
} else if (t.isVariableDeclaration(node)) {
_.each(node.declarations, function (declar) {
scope.push({
kind: node.kind,
key: declar.id.name,
id: declar.id
});
exprs.push(t.assignmentExpression("=", declar.id, declar.init));
});
}
});
if (exprs.length === 1) {
return exprs[0];
} else {
return t.sequenceExpression(exprs);
}
};
//
t.shallowEqual = function (actual, expected) {
var same = true;
if (expected) {
_.each(expected, function (val, key) {
if (actual[key] !== val) {
return same = false;
}
});
}
return same;
};
/**
* Description
*
* @param {Object} member
* @param {Object} append
* @param {Boolean} [computed]
* @returns {Object} member
*/
t.appendToMemberExpression = function (member, append, computed) {
member.object = t.memberExpression(member.object, member.property, member.computed);
member.property = append;
member.computed = !!computed;
return member;
};
/**
* Description
*
* @param {Object} member
* @param {Object} append
* @returns {Object} member
*/
t.prependToMemberExpression = function (member, append) {
member.object = t.memberExpression(append, member.object);
return member;
};
/**
* Description
*
* @param {Object} node
* @param {Object} parent
* @returns {Boolean}
*/
t.isReferenced = function (node, parent) {
// we're a property key and we aren't computed so we aren't referenced
if (t.isProperty(parent) && parent.key === node && !parent.computed) return false;
// we're a variable declarator id so we aren't referenced
if (t.isVariableDeclarator(parent) && parent.id === node) return false;
var isMemberExpression = t.isMemberExpression(parent);
// we're in a member expression and we're the computed property so we're referenced
var isComputedProperty = isMemberExpression && parent.property === node && parent.computed;
// we're in a member expression and we're the object so we're referenced
var isObject = isMemberExpression && parent.object === node;
// we are referenced
if (!isMemberExpression || isComputedProperty || isObject) return true;
return false;
};
/**
* Description
*
* @param {String} name
* @returns {Boolean}
*/
t.isValidIdentifier = function (name) {
return _.isString(name) && esutils.keyword.isIdentifierName(name) && !esutils.keyword.isReservedWordES6(name, true);
};
/*
* Description
*
* @param {String} name
* @returns {String}
*/
t.toIdentifier = function (name) {
if (t.isIdentifier(name)) return name.name;
name = name + "";
// replace all non-valid identifiers with dashes
name = name.replace(/[^a-zA-Z0-9$_]/g, "-");
// remove all dashes and numbers from start of name
name = name.replace(/^[-0-9]+/, "");
// camel case
name = name.replace(/[-_\s]+(.)?/g, function (match, c) {
return c ? c.toUpperCase() : "";
});
// remove underscores from start of name
name = name.replace(/^\_/, "");
if (!t.isValidIdentifier(name)) {
name = "_" + name;
}
return name || '_';
};
/**
* Description
*
* @param {Object} node
* @param {String} key
*/
t.ensureBlock = function (node, key) {
key = key || "body";
node[key] = t.toBlock(node[key], node);
};
/**
* Description
*
* @param {Object} node
* @param {Boolean} [ignore]
* @returns {Object|Boolean}
*/
t.toStatement = function (node, ignore) {
if (t.isStatement(node)) {
return node;
}
var mustHaveId = false;
var newType;
if (t.isClass(node)) {
mustHaveId = true;
newType = "ClassDeclaration";
} else if (t.isFunction(node)) {
mustHaveId = true;
newType = "FunctionDeclaration";
}
if (mustHaveId && !node.id) {
newType = false;
}
if (!newType) {
if (ignore) {
return false;
} else {
throw new Error("cannot turn " + node.type + " to a statement");
}
}
node.type = newType;
return node;
};
/**
* Description
*
* @param {Object} node
* @param {Object} parent
* @returns {Object}
*/
t.toBlock = function (node, parent) {
if (t.isBlockStatement(node)) {
return node;
}
if (!_.isArray(node)) {
if (!t.isStatement(node)) {
if (t.isFunction(parent)) {
node = t.returnStatement(node);
} else {
node = t.expressionStatement(node);
}
}
node = [node];
}
return t.blockStatement(node);
};
/**
* Description
*
* @param {Object} node
* @param {Boolean} [map]
* @param {Array} [ignoreTypes]
* @returns {Array|Object}
*/
t.getIds = function (node, map, ignoreTypes) {
ignoreTypes = ignoreTypes || [];
var search = [].concat(node);
var ids = {};
while (search.length) {
var id = search.shift();
if (!id) continue;
if (_.contains(ignoreTypes, id.type)) continue;
var nodeKey = t.getIds.nodes[id.type];
var arrKeys = t.getIds.arrays[id.type];
if (t.isIdentifier(id)) {
ids[id.name] = id;
} else if (nodeKey) {
if (id[nodeKey]) search.push(id[nodeKey]);
} else if (arrKeys) {
for (var i in arrKeys) {
var key = arrKeys[i];
search = search.concat(id[key] || []);
}
}
}
if (!map) ids = _.keys(ids);
return ids;
};
t.getIds.nodes = {
AssignmentExpression: "left",
ImportSpecifier: "name",
ExportSpecifier: "name",
VariableDeclarator: "id",
FunctionDeclaration: "id",
ClassDeclaration: "id",
MemeberExpression: "object",
SpreadElement: "argument",
Property: "value"
};
t.getIds.arrays = {
ExportDeclaration: ["specifiers", "declaration"],
ImportDeclaration: ["specifiers"],
VariableDeclaration: ["declarations"],
ArrayPattern: ["elements"],
ObjectPattern: ["properties"]
};
/**
* Description
*
* @param {Object} node
* @returns {Boolean}
*/
t.isLet = function (node) {
return t.isVariableDeclaration(node) && (node.kind !== "var" || node._let);
};
/**
* Description
*
* @param {Object} node
* @returns {Boolean}
*/
t.isVar = function (node) {
return t.isVariableDeclaration(node, { kind: "var" }) && !node._let;
};
//
t.COMMENT_KEYS = ["leadingComments", "trailingComments"];
/**
* Description
*
* @param {Object} child
* @returns {Object} child
*/
t.removeComments = function (child) {
_.each(t.COMMENT_KEYS, function (key) {
delete child[key];
});
return child;
};
/**
* Description
*
* @param {Object} child
* @param {Object} parent
* @returns {Object} child
*/
t.inheritsComments = function (child, parent) {
_.each(t.COMMENT_KEYS, function (key) {
child[key] = _.uniq(_.compact([].concat(child[key], parent[key])));
});
return child;
};
/**
* Description
*
* @param {Object} child
* @param {Object} parent
* @returns {Object} child
*/
t.inherits = function (child, parent) {
child.loc = parent.loc;
child.end = parent.end;
child.range = parent.range;
child.start = parent.start;
t.inheritsComments(child, parent);
return child;
};
/**
* Description
*
* @param {Object} specifier
* @returns {String}
*/
t.getSpecifierName = function (specifier) {
return specifier.name || specifier.id;
};
/**
* Description
*
* @param {Object} specifier
* @returns {Boolean}
*/
t.isSpecifierDefault = function (specifier) {
return t.isIdentifier(specifier.id) && specifier.id.name === "default";
};
| lib/6to5/types/index.js | 1 | https://github.com/babel/babel/commit/74392470950a82eb1d6283d38ada2d7c7e053c90 | [
0.9823473691940308,
0.0255920197814703,
0.00016405557107646018,
0.00018869289488065988,
0.14164838194847107
] |
{
"id": 1,
"code_window": [
" var args = node.arguments;\n",
" if (!hasSpread(args)) return;\n",
"\n",
" var nativeType = t.isIdentifier(node.callee) && _.contains(t.NATIVE_TYPES_NAMES, node.callee.name);\n",
"\n",
" var nodes = build(args, file);\n",
"\n",
" if (nativeType) {\n",
" nodes.unshift(t.arrayExpression([t.literal(null)]));\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" var nativeType = t.isIdentifier(node.callee) && _.contains(t.NATIVE_TYPE_NAMES, node.callee.name);\n"
],
"file_path": "lib/6to5/transformation/transformers/es6-spread.js",
"type": "replace",
"edit_start_line_idx": 101
} | <Component.Test />;
| test/fixtures/generation/types/XJSMemberExpression/expected.js | 0 | https://github.com/babel/babel/commit/74392470950a82eb1d6283d38ada2d7c7e053c90 | [
0.0001717211416689679,
0.0001717211416689679,
0.0001717211416689679,
0.0001717211416689679,
0
] |
{
"id": 1,
"code_window": [
" var args = node.arguments;\n",
" if (!hasSpread(args)) return;\n",
"\n",
" var nativeType = t.isIdentifier(node.callee) && _.contains(t.NATIVE_TYPES_NAMES, node.callee.name);\n",
"\n",
" var nodes = build(args, file);\n",
"\n",
" if (nativeType) {\n",
" nodes.unshift(t.arrayExpression([t.literal(null)]));\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" var nativeType = t.isIdentifier(node.callee) && _.contains(t.NATIVE_TYPE_NAMES, node.callee.name);\n"
],
"file_path": "lib/6to5/transformation/transformers/es6-spread.js",
"type": "replace",
"edit_start_line_idx": 101
} | <Namespace.Component />;
| test/fixtures/transformation/react/should-allow-js-namespacing/actual.js | 0 | https://github.com/babel/babel/commit/74392470950a82eb1d6283d38ada2d7c7e053c90 | [
0.000170238854479976,
0.000170238854479976,
0.000170238854479976,
0.000170238854479976,
0
] |
{
"id": 1,
"code_window": [
" var args = node.arguments;\n",
" if (!hasSpread(args)) return;\n",
"\n",
" var nativeType = t.isIdentifier(node.callee) && _.contains(t.NATIVE_TYPES_NAMES, node.callee.name);\n",
"\n",
" var nodes = build(args, file);\n",
"\n",
" if (nativeType) {\n",
" nodes.unshift(t.arrayExpression([t.literal(null)]));\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" var nativeType = t.isIdentifier(node.callee) && _.contains(t.NATIVE_TYPE_NAMES, node.callee.name);\n"
],
"file_path": "lib/6to5/transformation/transformers/es6-spread.js",
"type": "replace",
"edit_start_line_idx": 101
} | "use strict";
| test/fixtures/transformation/es6-modules-ignore/exports-from/expected.js | 0 | https://github.com/babel/babel/commit/74392470950a82eb1d6283d38ada2d7c7e053c90 | [
0.00017268216470256448,
0.00017268216470256448,
0.00017268216470256448,
0.00017268216470256448,
0
] |
{
"id": 2,
"code_window": [
"var _ = require(\"lodash\");\n",
"\n",
"var t = exports;\n",
"\n",
"t.NATIVE_TYPES_NAMES = [\"Array\", \"Object\", \"Number\", \"Boolean\", \"Date\", \"Array\", \"String\"];\n",
"\n",
"//\n",
"\n",
"var addAssert = function (type, is) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"t.NATIVE_TYPE_NAMES = [\"Array\", \"Object\", \"Number\", \"Boolean\", \"Date\", \"Array\", \"String\"];\n"
],
"file_path": "lib/6to5/types/index.js",
"type": "replace",
"edit_start_line_idx": 5
} | var t = require("../../types");
var _ = require("lodash");
var getSpreadLiteral = function (spread, file) {
return file.toArray(spread.argument);
};
var hasSpread = function (nodes) {
for (var i in nodes) {
if (t.isSpreadElement(nodes[i])) {
return true;
}
}
return false;
};
var build = function (props, file) {
var nodes = [];
var _props = [];
var push = function () {
if (!_props.length) return;
nodes.push(t.arrayExpression(_props));
_props = [];
};
for (var i in props) {
var prop = props[i];
if (t.isSpreadElement(prop)) {
push();
nodes.push(getSpreadLiteral(prop, file));
} else {
_props.push(prop);
}
}
push();
return nodes;
};
exports.ArrayExpression = function (node, parent, file) {
var elements = node.elements;
if (!hasSpread(elements)) return;
var nodes = build(elements, file);
var first = nodes.shift();
if (!t.isArrayExpression(first)) {
nodes.unshift(first);
first = t.arrayExpression([]);
}
return t.callExpression(t.memberExpression(first, t.identifier("concat")), nodes);
};
exports.CallExpression = function (node, parent, file, scope) {
var args = node.arguments;
if (!hasSpread(args)) return;
var contextLiteral = t.literal(null);
node.arguments = [];
var nodes;
if (args.length === 1 && args[0].argument.name === 'arguments') {
nodes = [args[0].argument];
} else {
nodes = build(args, file);
}
var first = nodes.shift();
if (nodes.length) {
node.arguments.push(t.callExpression(t.memberExpression(first, t.identifier("concat")), nodes));
} else {
node.arguments.push(first);
}
var callee = node.callee;
if (t.isMemberExpression(callee)) {
var temp = scope.generateTempBasedOnNode(callee.object, file);
if (temp) {
callee.object = t.assignmentExpression("=", temp, callee.object);
contextLiteral = temp;
} else {
contextLiteral = callee.object;
}
t.appendToMemberExpression(callee, t.identifier("apply"));
} else {
node.callee = t.memberExpression(node.callee, t.identifier("apply"));
}
node.arguments.unshift(contextLiteral);
};
exports.NewExpression = function (node, parent, file) {
var args = node.arguments;
if (!hasSpread(args)) return;
var nativeType = t.isIdentifier(node.callee) && _.contains(t.NATIVE_TYPES_NAMES, node.callee.name);
var nodes = build(args, file);
if (nativeType) {
nodes.unshift(t.arrayExpression([t.literal(null)]));
}
var first = nodes.shift();
if (nodes.length) {
args = t.callExpression(t.memberExpression(first, t.identifier("concat")), nodes);
} else {
args = first;
}
if (nativeType) {
return t.newExpression(
t.callExpression(
t.memberExpression(file.addHelper("bind"), t.identifier("apply")),
[node.callee, args]
),
[]
);
} else {
return t.callExpression(file.addHelper("apply-constructor"), [node.callee, args]);
}
};
| lib/6to5/transformation/transformers/es6-spread.js | 1 | https://github.com/babel/babel/commit/74392470950a82eb1d6283d38ada2d7c7e053c90 | [
0.9987687468528748,
0.8260723948478699,
0.00017062904953490943,
0.9903444647789001,
0.3531794846057892
] |
{
"id": 2,
"code_window": [
"var _ = require(\"lodash\");\n",
"\n",
"var t = exports;\n",
"\n",
"t.NATIVE_TYPES_NAMES = [\"Array\", \"Object\", \"Number\", \"Boolean\", \"Date\", \"Array\", \"String\"];\n",
"\n",
"//\n",
"\n",
"var addAssert = function (type, is) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"t.NATIVE_TYPE_NAMES = [\"Array\", \"Object\", \"Number\", \"Boolean\", \"Date\", \"Array\", \"String\"];\n"
],
"file_path": "lib/6to5/types/index.js",
"type": "replace",
"edit_start_line_idx": 5
} | var t = require("../../types");
exports.Function = function (node, parent, file) {
if (!node.rest) return;
var rest = node.rest;
delete node.rest;
t.ensureBlock(node);
var call = file.toArray(t.identifier("arguments"));
if (node.params.length) {
call.arguments.push(t.literal(node.params.length));
}
call._ignoreAliasFunctions = true;
node.body.body.unshift(t.variableDeclaration("var", [
t.variableDeclarator(rest, call)
]));
};
| lib/6to5/transformation/transformers/es6-rest-parameters.js | 0 | https://github.com/babel/babel/commit/74392470950a82eb1d6283d38ada2d7c7e053c90 | [
0.9650102257728577,
0.3267780840396881,
0.00017890373419504613,
0.015145118348300457,
0.45133963227272034
] |
{
"id": 2,
"code_window": [
"var _ = require(\"lodash\");\n",
"\n",
"var t = exports;\n",
"\n",
"t.NATIVE_TYPES_NAMES = [\"Array\", \"Object\", \"Number\", \"Boolean\", \"Date\", \"Array\", \"String\"];\n",
"\n",
"//\n",
"\n",
"var addAssert = function (type, is) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"t.NATIVE_TYPE_NAMES = [\"Array\", \"Object\", \"Number\", \"Boolean\", \"Date\", \"Array\", \"String\"];\n"
],
"file_path": "lib/6to5/types/index.js",
"type": "replace",
"edit_start_line_idx": 5
} | "use strict";
var x = coords.x;
var y = coords.y;
var foo = "bar";
| test/fixtures/transformation/es6-destructuring/multiple/expected.js | 0 | https://github.com/babel/babel/commit/74392470950a82eb1d6283d38ada2d7c7e053c90 | [
0.00017580825078766793,
0.00017580825078766793,
0.00017580825078766793,
0.00017580825078766793,
0
] |
{
"id": 2,
"code_window": [
"var _ = require(\"lodash\");\n",
"\n",
"var t = exports;\n",
"\n",
"t.NATIVE_TYPES_NAMES = [\"Array\", \"Object\", \"Number\", \"Boolean\", \"Date\", \"Array\", \"String\"];\n",
"\n",
"//\n",
"\n",
"var addAssert = function (type, is) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"t.NATIVE_TYPE_NAMES = [\"Array\", \"Object\", \"Number\", \"Boolean\", \"Date\", \"Array\", \"String\"];\n"
],
"file_path": "lib/6to5/types/index.js",
"type": "replace",
"edit_start_line_idx": 5
} | var transform = module.exports = require("./transformation/transform");
transform.transform = transform;
transform.run = function (code, opts) {
opts = opts || {};
opts.sourceMap = "inline";
return new Function(transform(code, opts).code)();
};
transform.load = function (url, callback, opts, hold) {
opts = opts || {};
opts.filename = opts.filename || url;
var xhr = global.ActiveXObject ? new global.ActiveXObject("Microsoft.XMLHTTP") : new global.XMLHttpRequest();
xhr.open("GET", url, true);
if ("overrideMimeType" in xhr) xhr.overrideMimeType("text/plain");
xhr.onreadystatechange = function () {
if (xhr.readyState !== 4) return;
var status = xhr.status;
if (status === 0 || status === 200) {
var param = [xhr.responseText, opts];
if (!hold) transform.run.apply(transform, param);
if (callback) callback(param);
} else {
throw new Error("Could not load " + url);
}
};
xhr.send(null);
};
var runScripts = function () {
var scripts = [];
var types = ["text/ecmascript-6", "text/6to5", "module"];
var index = 0;
var exec = function () {
var param = scripts[index];
if (param instanceof Array) {
transform.run.apply(transform, param);
index++;
exec();
}
};
var run = function (script, i) {
var opts = {};
if (script.src) {
transform.load(script.src, function (param) {
scripts[i] = param;
exec();
}, opts, true);
} else {
opts.filename = "embedded";
scripts[i] = [script.innerHTML, opts];
}
};
var _scripts = global.document .getElementsByTagName("script");
for (var i = 0; i < _scripts.length; ++i) {
var _script = _scripts[i];
if (types.indexOf(_script.type) >= 0) scripts.push(_script);
}
for (i in scripts) {
run(scripts[i], i);
}
exec();
};
if (global.addEventListener) {
global.addEventListener("DOMContentLoaded", runScripts, false);
} else if (global.attachEvent) {
global.attachEvent("onload", runScripts);
}
| lib/6to5/browser.js | 0 | https://github.com/babel/babel/commit/74392470950a82eb1d6283d38ada2d7c7e053c90 | [
0.00019008535309694707,
0.0001736656849971041,
0.0001665018789935857,
0.00017307300004176795,
0.000006984035280765966
] |
{
"id": 0,
"code_window": [
" * KIND, either express or implied. See the License for the\n",
" * specific language governing permissions and limitations\n",
" * under the License.\n",
" */\n",
"import React, { CSSProperties, useCallback, useMemo, useState } from 'react';\n",
"import { ColumnInstance, ColumnWithLooseAccessor, DefaultSortTypes } from 'react-table';\n",
"import { extent as d3Extent, max as d3Max } from 'd3-array';\n",
"import { FaSort, FaSortDown as FaSortDesc, FaSortUp as FaSortAsc } from 'react-icons/fa';\n",
"import { DataRecord, DataRecordValue, GenericDataType, t, tn } from '@superset-ui/core';\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import React, { CSSProperties, useCallback, useMemo } from 'react';\n"
],
"file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/plugin-chart-table/src/TableChart.tsx",
"type": "replace",
"edit_start_line_idx": 18
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import memoizeOne from 'memoize-one';
import {
DataRecord,
extractTimegrain,
GenericDataType,
getMetricLabel,
getNumberFormatter,
getTimeFormatter,
getTimeFormatterForGranularity,
NumberFormats,
QueryMode,
smartDateFormatter,
TimeFormats,
TimeFormatter,
} from '@superset-ui/core';
import isEqualColumns from './utils/isEqualColumns';
import DateWithFormatter from './utils/DateWithFormatter';
import { DataColumnMeta, TableChartProps, TableChartTransformedProps } from './types';
const { PERCENT_3_POINT } = NumberFormats;
const { DATABASE_DATETIME } = TimeFormats;
const TIME_COLUMN = '__timestamp';
function isTimeColumn(key: string) {
return key === TIME_COLUMN;
}
function isNumeric(key: string, data: DataRecord[] = []) {
return data.every(x => x[key] === null || x[key] === undefined || typeof x[key] === 'number');
}
const processDataRecords = memoizeOne(function processDataRecords(
data: DataRecord[] | undefined,
columns: DataColumnMeta[],
) {
if (!data || !data[0]) {
return data || [];
}
const timeColumns = columns.filter(column => column.dataType === GenericDataType.TEMPORAL);
if (timeColumns.length > 0) {
return data.map(x => {
const datum = { ...x };
timeColumns.forEach(({ key, formatter }) => {
// Convert datetime with a custom date class so we can use `String(...)`
// formatted value for global search, and `date.getTime()` for sorting.
datum[key] = new DateWithFormatter(x[key], { formatter: formatter as TimeFormatter });
});
return datum;
});
}
return data;
});
const processColumns = memoizeOne(function processColumns(props: TableChartProps) {
const {
datasource: { columnFormats, verboseMap },
rawFormData: {
table_timestamp_format: tableTimestampFormat,
metrics: metrics_,
percent_metrics: percentMetrics_,
column_config: columnConfig = {},
},
queriesData,
} = props;
const granularity = extractTimegrain(props.rawFormData);
const { data: records, colnames, coltypes } = queriesData[0] || {};
// convert `metrics` and `percentMetrics` to the key names in `data.records`
const metrics = (metrics_ ?? []).map(getMetricLabel);
const rawPercentMetrics = (percentMetrics_ ?? []).map(getMetricLabel);
// column names for percent metrics always starts with a '%' sign.
const percentMetrics = rawPercentMetrics.map((x: string) => `%${x}`);
const metricsSet = new Set(metrics);
const percentMetricsSet = new Set(percentMetrics);
const rawPercentMetricsSet = new Set(rawPercentMetrics);
const columns: DataColumnMeta[] = (colnames || [])
.filter(
key =>
// if a metric was only added to percent_metrics, they should not show up in the table.
!(rawPercentMetricsSet.has(key) && !metricsSet.has(key)),
)
.map((key: string, i) => {
const label = verboseMap?.[key] || key;
const dataType = coltypes[i];
const config = columnConfig[key] || {};
// for the purpose of presentation, only numeric values are treated as metrics
// because users can also add things like `MAX(str_col)` as a metric.
const isMetric = metricsSet.has(key) && isNumeric(key, records);
const isPercentMetric = percentMetricsSet.has(key);
const isTime = dataType === GenericDataType.TEMPORAL;
const savedFormat = columnFormats?.[key];
const numberFormat = config.d3NumberFormat || savedFormat;
let formatter;
if (isTime || config.d3TimeFormat) {
// string types may also apply d3-time format
// pick adhoc format first, fallback to column level formats defined in
// datasource
const customFormat = config.d3TimeFormat || savedFormat;
const timeFormat = customFormat || tableTimestampFormat;
// When format is "Adaptive Formatting" (smart_date)
if (timeFormat === smartDateFormatter.id) {
if (isTimeColumn(key)) {
// time column use formats based on granularity
formatter = getTimeFormatterForGranularity(granularity);
} else if (customFormat) {
// other columns respect the column-specific format
formatter = getTimeFormatter(customFormat);
} else if (isNumeric(key, records)) {
// if column is numeric values, it is considered a timestamp64
formatter = getTimeFormatter(DATABASE_DATETIME);
} else {
// if no column-specific format, print cell as is
formatter = String;
}
} else if (timeFormat) {
formatter = getTimeFormatter(timeFormat);
}
} else if (isPercentMetric) {
// percent metrics have a default format
formatter = getNumberFormatter(numberFormat || PERCENT_3_POINT);
} else if (isMetric || numberFormat) {
formatter = getNumberFormatter(numberFormat);
}
return {
key,
label,
dataType,
isNumeric: dataType === GenericDataType.NUMERIC,
isMetric,
isPercentMetric,
formatter,
config,
};
});
return [
metrics,
percentMetrics,
columns,
] as [typeof metrics, typeof percentMetrics, typeof columns];
}, isEqualColumns);
/**
* Automatically set page size based on number of cells.
*/
const getPageSize = (
pageSize: number | string | null | undefined,
numRecords: number,
numColumns: number,
) => {
if (typeof pageSize === 'number') {
// NaN is also has typeof === 'number'
return pageSize || 0;
}
if (typeof pageSize === 'string') {
return Number(pageSize) || 0;
}
// when pageSize not set, automatically add pagination if too many records
return numRecords * numColumns > 5000 ? 200 : 0;
};
const transformProps = (chartProps: TableChartProps): TableChartTransformedProps => {
const {
height,
width,
rawFormData: formData,
queriesData = [],
initialValues: filters = {},
ownState: serverPaginationData = {},
hooks: { onAddFilter: onChangeFilter, setDataMask = () => {} },
} = chartProps;
const {
align_pn: alignPositiveNegative = true,
color_pn: colorPositiveNegative = true,
show_cell_bars: showCellBars = true,
include_search: includeSearch = false,
page_length: pageLength,
table_filter: tableFilter,
server_pagination: serverPagination = false,
server_page_length: serverPageLength = 10,
order_desc: sortDesc = false,
query_mode: queryMode,
show_totals: showTotals,
} = formData;
const [metrics, percentMetrics, columns] = processColumns(chartProps);
let baseQuery;
let countQuery;
let totalQuery;
let rowCount;
if (serverPagination) {
[baseQuery, countQuery, totalQuery] = queriesData;
rowCount = (countQuery?.data?.[0]?.rowcount as number) ?? 0;
} else {
[baseQuery, totalQuery] = queriesData;
rowCount = baseQuery?.rowcount ?? 0;
}
const data = processDataRecords(baseQuery?.data, columns);
const totals = showTotals && queryMode === QueryMode.aggregate ? totalQuery?.data[0] : undefined;
return {
height,
width,
isRawRecords: queryMode === QueryMode.raw,
data,
totals,
columns,
serverPagination,
metrics,
percentMetrics,
serverPaginationData,
setDataMask,
alignPositiveNegative,
colorPositiveNegative,
showCellBars,
sortDesc,
includeSearch,
rowCount,
pageSize: serverPagination
? serverPageLength
: getPageSize(pageLength, data.length, columns.length),
filters,
emitFilter: tableFilter,
onChangeFilter,
};
};
export default transformProps;
| superset-frontend/temporary_superset_ui/superset-ui/plugins/plugin-chart-table/src/transformProps.ts | 1 | https://github.com/apache/superset/commit/4051fda671b8b6d4b0a4f2ba8266d61cda73b916 | [
0.00025750507484190166,
0.00017225532792508602,
0.00016327263438142836,
0.00016958288324531168,
0.00001733400313241873
] |
{
"id": 0,
"code_window": [
" * KIND, either express or implied. See the License for the\n",
" * specific language governing permissions and limitations\n",
" * under the License.\n",
" */\n",
"import React, { CSSProperties, useCallback, useMemo, useState } from 'react';\n",
"import { ColumnInstance, ColumnWithLooseAccessor, DefaultSortTypes } from 'react-table';\n",
"import { extent as d3Extent, max as d3Max } from 'd3-array';\n",
"import { FaSort, FaSortDown as FaSortDesc, FaSortUp as FaSortAsc } from 'react-icons/fa';\n",
"import { DataRecord, DataRecordValue, GenericDataType, t, tn } from '@superset-ui/core';\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import React, { CSSProperties, useCallback, useMemo } from 'react';\n"
],
"file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/plugin-chart-table/src/TableChart.tsx",
"type": "replace",
"edit_start_line_idx": 18
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { safeStringify } from '../../utils/safeStringify';
export default function getKeyForFilterScopeTree({
activeFilterField,
checkedFilterFields,
}) {
return safeStringify(
activeFilterField ? [activeFilterField] : checkedFilterFields,
);
}
| superset-frontend/src/dashboard/util/getKeyForFilterScopeTree.js | 0 | https://github.com/apache/superset/commit/4051fda671b8b6d4b0a4f2ba8266d61cda73b916 | [
0.00017206351913046092,
0.00016876841254997998,
0.0001639731490286067,
0.00017026856949087232,
0.000003469041530479444
] |
{
"id": 0,
"code_window": [
" * KIND, either express or implied. See the License for the\n",
" * specific language governing permissions and limitations\n",
" * under the License.\n",
" */\n",
"import React, { CSSProperties, useCallback, useMemo, useState } from 'react';\n",
"import { ColumnInstance, ColumnWithLooseAccessor, DefaultSortTypes } from 'react-table';\n",
"import { extent as d3Extent, max as d3Max } from 'd3-array';\n",
"import { FaSort, FaSortDown as FaSortDesc, FaSortUp as FaSortAsc } from 'react-icons/fa';\n",
"import { DataRecord, DataRecordValue, GenericDataType, t, tn } from '@superset-ui/core';\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import React, { CSSProperties, useCallback, useMemo } from 'react';\n"
],
"file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/plugin-chart-table/src/TableChart.tsx",
"type": "replace",
"edit_start_line_idx": 18
} | ---
name: Ascend.io
menu: Connecting to Databases
route: /docs/databases/ascend
index: 7
version: 1
---
## Ascend.io
The recommended connector library to Ascend.io is [impyla](https://github.com/cloudera/impyla).
The expected connection string is formatted as follows:
```
ascend://{username}:{password}@{hostname}:{port}/{database}?auth_mechanism=PLAIN;use_ssl=true
```
| docs/src/pages/docs/Connecting to Databases/ascend.mdx | 0 | https://github.com/apache/superset/commit/4051fda671b8b6d4b0a4f2ba8266d61cda73b916 | [
0.000171855601365678,
0.0001694493112154305,
0.0001670430356170982,
0.0001694493112154305,
0.0000024062828742899
] |
{
"id": 0,
"code_window": [
" * KIND, either express or implied. See the License for the\n",
" * specific language governing permissions and limitations\n",
" * under the License.\n",
" */\n",
"import React, { CSSProperties, useCallback, useMemo, useState } from 'react';\n",
"import { ColumnInstance, ColumnWithLooseAccessor, DefaultSortTypes } from 'react-table';\n",
"import { extent as d3Extent, max as d3Max } from 'd3-array';\n",
"import { FaSort, FaSortDown as FaSortDesc, FaSortUp as FaSortAsc } from 'react-icons/fa';\n",
"import { DataRecord, DataRecordValue, GenericDataType, t, tn } from '@superset-ui/core';\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import React, { CSSProperties, useCallback, useMemo } from 'react';\n"
],
"file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/plugin-chart-table/src/TableChart.tsx",
"type": "replace",
"edit_start_line_idx": 18
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import Select from 'react-select';
import Creatable from 'react-select/creatable';
import AsyncCreatable from 'react-select/async-creatable';
import windowed from './windowed';
export * from './windowed';
export const WindowedSelect = windowed(Select);
export const WindowedCreatableSelect = windowed(Creatable);
export const WindowedAsyncCreatableSelect = windowed(AsyncCreatable);
export default WindowedSelect;
| superset-frontend/src/components/Select/WindowedSelect/index.tsx | 0 | https://github.com/apache/superset/commit/4051fda671b8b6d4b0a4f2ba8266d61cda73b916 | [
0.00017379633209202439,
0.000168885788298212,
0.0001625924778636545,
0.00017026856949087232,
0.00000467729523734306
] |
{
"id": 1,
"code_window": [
" setDataMask,\n",
" showCellBars = true,\n",
" emitFilter = false,\n",
" sortDesc = false,\n",
" filters: initialFilters = {},\n",
" sticky = true, // whether to use sticky header\n",
" } = props;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" filters,\n"
],
"file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/plugin-chart-table/src/TableChart.tsx",
"type": "replace",
"edit_start_line_idx": 163
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import React, { CSSProperties, useCallback, useMemo, useState } from 'react';
import { ColumnInstance, ColumnWithLooseAccessor, DefaultSortTypes } from 'react-table';
import { extent as d3Extent, max as d3Max } from 'd3-array';
import { FaSort, FaSortDown as FaSortDesc, FaSortUp as FaSortAsc } from 'react-icons/fa';
import { DataRecord, DataRecordValue, GenericDataType, t, tn } from '@superset-ui/core';
import { DataColumnMeta, TableChartTransformedProps } from './types';
import DataTable, {
DataTableProps,
SearchInputProps,
SelectPageSizeRendererProps,
SizeOption,
} from './DataTable';
import Styles from './Styles';
import { formatColumnValue } from './utils/formatValue';
import { PAGE_SIZE_OPTIONS } from './consts';
import { updateExternalFormData } from './DataTable/utils/externalAPIs';
type ValueRange = [number, number];
/**
* Return sortType based on data type
*/
function getSortTypeByDataType(dataType: GenericDataType): DefaultSortTypes {
if (dataType === GenericDataType.TEMPORAL) {
return 'datetime';
}
if (dataType === GenericDataType.STRING) {
return 'alphanumeric';
}
return 'basic';
}
/**
* Cell background to render columns as horizontal bar chart
*/
function cellBar({
value,
valueRange,
colorPositiveNegative = false,
alignPositiveNegative,
}: {
value: number;
valueRange: ValueRange;
colorPositiveNegative: boolean;
alignPositiveNegative: boolean;
}) {
const [minValue, maxValue] = valueRange;
const r = colorPositiveNegative && value < 0 ? 150 : 0;
if (alignPositiveNegative) {
const perc = Math.abs(Math.round((value / maxValue) * 100));
// The 0.01 to 0.001 is a workaround for what appears to be a
// CSS rendering bug on flat, transparent colors
return (
`linear-gradient(to right, rgba(${r},0,0,0.2), rgba(${r},0,0,0.2) ${perc}%, ` +
`rgba(0,0,0,0.01) ${perc}%, rgba(0,0,0,0.001) 100%)`
);
}
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 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
return (
`linear-gradient(to right, rgba(0,0,0,0.01), rgba(0,0,0,0.001) ${perc1}%, ` +
`rgba(${r},0,0,0.2) ${perc1}%, rgba(${r},0,0,0.2) ${perc1 + perc2}%, ` +
`rgba(0,0,0,0.01) ${perc1 + perc2}%, rgba(0,0,0,0.001) 100%)`
);
}
function SortIcon<D extends object>({ column }: { column: ColumnInstance<D> }) {
const { isSorted, isSortedDesc } = column;
let sortIcon = <FaSort />;
if (isSorted) {
sortIcon = isSortedDesc ? <FaSortDesc /> : <FaSortAsc />;
}
return sortIcon;
}
function SearchInput({ count, value, onChange }: SearchInputProps) {
return (
<span className="dt-global-filter">
{t('Search')}{' '}
<input
className="form-control input-sm"
placeholder={tn('search.num_records', count)}
value={value}
onChange={onChange}
/>
</span>
);
}
function SelectPageSize({ options, current, onChange }: SelectPageSizeRendererProps) {
return (
<span className="dt-select-page-size form-inline">
{t('page_size.show')}{' '}
<select
className="form-control input-sm"
value={current}
onBlur={() => {}}
onChange={e => {
onChange(Number((e.target as HTMLSelectElement).value));
}}
>
{options.map(option => {
const [size, text] = Array.isArray(option) ? option : [option, option];
return (
<option key={size} value={size}>
{text}
</option>
);
})}
</select>{' '}
{t('page_size.entries')}
</span>
);
}
export default function TableChart<D extends DataRecord = DataRecord>(
props: TableChartTransformedProps<D> & {
sticky?: DataTableProps<D>['sticky'];
},
) {
const {
height,
width,
data,
totals,
isRawRecords,
rowCount = 0,
columns: columnsMeta,
alignPositiveNegative: defaultAlignPN = false,
colorPositiveNegative: defaultColorPN = false,
includeSearch = false,
pageSize = 0,
serverPagination = false,
serverPaginationData,
setDataMask,
showCellBars = true,
emitFilter = false,
sortDesc = false,
filters: initialFilters = {},
sticky = true, // whether to use sticky header
} = props;
const [filters, setFilters] = useState(initialFilters);
const handleChange = useCallback(
(filters: { [x: string]: DataRecordValue[] }) => {
if (!emitFilter) {
return;
}
const groupBy = Object.keys(filters);
const groupByValues = Object.values(filters);
setDataMask({
extraFormData: {
filters:
groupBy.length === 0
? []
: groupBy.map(col => {
const val = filters?.[col];
if (val === null || val === undefined)
return {
col,
op: 'IS NULL',
};
return {
col,
op: 'IN',
val: val as (string | number | boolean)[],
};
}),
},
filterState: {
value: groupByValues.length ? groupByValues : null,
},
});
},
[emitFilter, setDataMask],
);
// only take relevant page size options
const pageSizeOptions = useMemo(() => {
const getServerPagination = (n: number) => n <= rowCount;
return PAGE_SIZE_OPTIONS.filter(([n]) =>
serverPagination ? getServerPagination(n) : n <= 2 * data.length,
) as SizeOption[];
}, [data.length, rowCount, serverPagination]);
const getValueRange = useCallback(
function getValueRange(key: string, alignPositiveNegative: boolean) {
if (typeof data?.[0]?.[key] === 'number') {
const nums = data.map(row => row[key]) as number[];
return (alignPositiveNegative
? [0, d3Max(nums.map(Math.abs))]
: d3Extent(nums)) as ValueRange;
}
return null;
},
[data],
);
const isActiveFilterValue = useCallback(
function isActiveFilterValue(key: string, val: DataRecordValue) {
return !!filters && filters[key]?.includes(val);
},
[filters],
);
const toggleFilter = useCallback(
function toggleFilter(key: string, val: DataRecordValue) {
const updatedFilters = { ...(filters || {}) };
if (filters && isActiveFilterValue(key, val)) {
updatedFilters[key] = filters[key].filter((x: DataRecordValue) => x !== val);
} else {
updatedFilters[key] = [...(filters?.[key] || []), val];
}
if (Array.isArray(updatedFilters[key]) && updatedFilters[key].length === 0) {
delete updatedFilters[key];
}
setFilters(updatedFilters);
handleChange(updatedFilters);
},
[filters, handleChange, isActiveFilterValue],
);
const getSharedStyle = (column: DataColumnMeta): CSSProperties => {
const { isNumeric, config = {} } = column;
const textAlign = config.horizontalAlign
? config.horizontalAlign
: isNumeric
? 'right'
: 'left';
return {
textAlign,
};
};
const getColumnConfigs = useCallback(
(column: DataColumnMeta, i: number): ColumnWithLooseAccessor<D> => {
const { key, label, isNumeric, dataType, isMetric, config = {} } = column;
const isFilter = !isNumeric && emitFilter;
const columnWidth = Number.isNaN(Number(config.columnWidth))
? config.columnWidth
: Number(config.columnWidth);
// inline style for both th and td cell
const sharedStyle: CSSProperties = getSharedStyle(column);
const alignPositiveNegative =
config.alignPositiveNegative === undefined ? defaultAlignPN : config.alignPositiveNegative;
const colorPositiveNegative =
config.colorPositiveNegative === undefined ? defaultColorPN : config.colorPositiveNegative;
const valueRange =
(config.showCellBars === undefined ? showCellBars : config.showCellBars) &&
(isMetric || isRawRecords) &&
getValueRange(key, alignPositiveNegative);
let className = '';
if (isFilter) {
className += ' dt-is-filter';
}
return {
id: String(i), // to allow duplicate column keys
// must use custom accessor to allow `.` in column names
// typing is incorrect in current version of `@types/react-table`
// so we ask TS not to check.
accessor: ((datum: D) => datum[key]) as never,
Cell: ({ value }: { value: DataRecordValue }) => {
const [isHtml, text] = formatColumnValue(column, value);
const html = isHtml ? { __html: text } : undefined;
const cellProps = {
// show raw number in title in case of numeric values
title: typeof value === 'number' ? String(value) : undefined,
onClick: emitFilter && !valueRange ? () => toggleFilter(key, value) : undefined,
className: [
className,
value == null ? 'dt-is-null' : '',
isActiveFilterValue(key, value) ? ' dt-is-active-filter' : '',
].join(' '),
style: {
...sharedStyle,
background: valueRange
? cellBar({
value: value as number,
valueRange,
alignPositiveNegative,
colorPositiveNegative,
})
: undefined,
},
};
if (html) {
// eslint-disable-next-line react/no-danger
return <td {...cellProps} dangerouslySetInnerHTML={html} />;
}
// If cellProps renderes textContent already, then we don't have to
// render `Cell`. This saves some time for large tables.
return <td {...cellProps}>{text}</td>;
},
Header: ({ column: col, onClick, style }) => (
<th
title="Shift + Click to sort by multiple columns"
className={[className, col.isSorted ? 'is-sorted' : ''].join(' ')}
style={{
...sharedStyle,
...style,
}}
onClick={onClick}
>
{/* can't use `columnWidth &&` because it may also be zero */}
{config.columnWidth ? (
// column width hint
<div
style={{
width: columnWidth,
height: 0.01,
}}
/>
) : null}
{label}
<SortIcon column={col} />
</th>
),
Footer: totals ? (
i === 0 ? (
<th>{t('Totals')}</th>
) : (
<td style={sharedStyle}>
<strong>{formatColumnValue(column, totals[key])[1]}</strong>
</td>
)
) : undefined,
sortDescFirst: sortDesc,
sortType: getSortTypeByDataType(dataType),
};
},
[
defaultAlignPN,
defaultColorPN,
emitFilter,
getValueRange,
isActiveFilterValue,
isRawRecords,
showCellBars,
sortDesc,
toggleFilter,
totals,
],
);
const columns = useMemo(() => columnsMeta.map(getColumnConfigs), [columnsMeta, getColumnConfigs]);
const handleServerPaginationChange = (pageNumber: number, pageSize: number) => {
updateExternalFormData(setDataMask, pageNumber, pageSize);
};
return (
<Styles>
<DataTable<D>
columns={columns}
data={data}
rowCount={rowCount}
tableClassName="table table-striped table-condensed"
pageSize={pageSize}
serverPaginationData={serverPaginationData}
pageSizeOptions={pageSizeOptions}
width={width}
height={height}
serverPagination={serverPagination}
onServerPaginationChange={handleServerPaginationChange}
// 9 page items in > 340px works well even for 100+ pages
maxPageItemCount={width > 340 ? 9 : 7}
noResults={(filter: string) => t(filter ? 'No matching records found' : 'No records found')}
searchInput={includeSearch && SearchInput}
selectPageSize={pageSize !== null && SelectPageSize}
// not in use in Superset, but needed for unit tests
sticky={sticky}
/>
</Styles>
);
}
| superset-frontend/temporary_superset_ui/superset-ui/plugins/plugin-chart-table/src/TableChart.tsx | 1 | https://github.com/apache/superset/commit/4051fda671b8b6d4b0a4f2ba8266d61cda73b916 | [
0.9978753328323364,
0.13744860887527466,
0.00016782819875515997,
0.00018249846471007913,
0.3171074688434601
] |
{
"id": 1,
"code_window": [
" setDataMask,\n",
" showCellBars = true,\n",
" emitFilter = false,\n",
" sortDesc = false,\n",
" filters: initialFilters = {},\n",
" sticky = true, // whether to use sticky header\n",
" } = props;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" filters,\n"
],
"file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/plugin-chart-table/src/TableChart.tsx",
"type": "replace",
"edit_start_line_idx": 163
} | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""alter type of dbs encrypted_extra
Revision ID: c2acd2cf3df2
Revises: cca2f5d568c8
Create Date: 2019-11-01 09:18:36.953603
"""
import sqlalchemy as sa
from alembic import op
from sqlalchemy_utils import EncryptedType
# revision identifiers, used by Alembic.
revision = "c2acd2cf3df2"
down_revision = "cca2f5d568c8"
def upgrade():
with op.batch_alter_table("dbs") as batch_op:
try:
# Postgres migration
batch_op.alter_column(
"encrypted_extra",
existing_type=sa.Text(),
type_=sa.LargeBinary(),
postgresql_using="encrypted_extra::bytea",
existing_nullable=True,
)
except TypeError:
# non-Postgres migration
batch_op.alter_column(
"dbs",
"encrypted_extra",
existing_type=sa.Text(),
type_=sa.LargeBinary(),
existing_nullable=True,
)
def downgrade():
with op.batch_alter_table("dbs") as batch_op:
batch_op.alter_column(
"encrypted_extra",
existing_type=sa.LargeBinary(),
type_=sa.Text(),
existing_nullable=True,
)
| superset/migrations/versions/c2acd2cf3df2_alter_type_of_dbs_encrypted_extra.py | 0 | https://github.com/apache/superset/commit/4051fda671b8b6d4b0a4f2ba8266d61cda73b916 | [
0.00017708030645735562,
0.00017221875896211714,
0.00016776226402726024,
0.0001715399557724595,
0.0000030338869692059234
] |
{
"id": 1,
"code_window": [
" setDataMask,\n",
" showCellBars = true,\n",
" emitFilter = false,\n",
" sortDesc = false,\n",
" filters: initialFilters = {},\n",
" sticky = true, // whether to use sticky header\n",
" } = props;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" filters,\n"
],
"file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/plugin-chart-table/src/TableChart.tsx",
"type": "replace",
"edit_start_line_idx": 163
} | <!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
<svg width="18" height="18" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg">
<path opacity="0.4" fill-rule="evenodd" clip-rule="evenodd" d="M15.9942 14.9661C16.0473 14.9256 16.0843 14.893 16.1094 14.8686V12.3207C15.7158 12.5563 15.2568 12.7608 14.7565 12.9359C13.2501 13.4632 11.2149 13.7763 8.99998 13.7763C6.78508 13.7763 4.74988 13.4632 3.24347 12.9359C2.74318 12.7608 2.28418 12.5563 1.89058 12.3207V14.8686C1.91568 14.893 1.95268 14.9256 2.00578 14.9661C2.26078 15.1603 2.71837 15.3956 3.40987 15.6184C4.77707 16.059 6.75368 16.3544 8.99998 16.3544C11.2463 16.3544 13.2229 16.059 14.5901 15.6184C15.2816 15.3956 15.7392 15.1603 15.9942 14.9661ZM15.7503 10.8614C16.0622 10.6033 16.1094 10.4232 16.1094 10.3388V8.41454C15.7158 8.65004 15.2568 8.85464 14.7565 9.02974C13.2501 9.55694 11.2149 9.87004 8.99998 9.87004C6.78508 9.87004 4.74988 9.55694 3.24347 9.02974C2.74318 8.85464 2.28418 8.65004 1.89058 8.41454V10.3388C1.89058 10.4232 1.93777 10.6033 2.24967 10.8614C2.55707 11.1158 3.04418 11.3763 3.70798 11.6086C5.02918 12.071 6.90007 12.37 8.99998 12.37C11.0999 12.37 12.9708 12.071 14.292 11.6086C14.9558 11.3763 15.4429 11.1158 15.7503 10.8614ZM0.484375 6.43254V10.3388V15.0165C0.484375 16.5321 4.29698 17.7607 8.99998 17.7607C13.703 17.7607 17.5156 16.5321 17.5156 15.0165V10.3388V6.43254V3.31734C17.5156 1.80174 13.703 0.573242 8.99998 0.573242H8.99508H8.99018C4.29258 0.573242 0.484375 1.80174 0.484375 3.31734V6.43254ZM16.1094 6.43254V4.81964C14.59 5.56754 11.9689 6.06144 8.99018 6.06144C6.02428 6.06144 3.41288 5.57174 1.89058 4.82924V6.43254C1.89058 6.51694 1.93777 6.69714 2.24967 6.95524C2.55707 7.20954 3.04418 7.47004 3.70798 7.70244C5.02918 8.16484 6.90007 8.46384 8.99998 8.46384C11.0999 8.46384 12.9708 8.16484 14.292 7.70244C14.9558 7.47004 15.4429 7.20954 15.7503 6.95524C16.0622 6.69714 16.1094 6.51694 16.1094 6.43254ZM2.07487 3.31764C2.33937 3.50124 2.77558 3.71554 3.40748 3.91944C4.77268 4.35984 6.74668 4.65524 8.99018 4.65524C11.2337 4.65524 13.2078 4.35984 14.573 3.91944C15.2053 3.71544 15.6416 3.50104 15.9061 3.31734C15.6416 3.13364 15.2053 2.91924 14.573 2.71524C13.2087 2.27514 11.2366 1.97984 8.99508 1.97944C6.75078 1.97984 4.77607 2.27514 3.40987 2.71544C2.77677 2.91944 2.33977 3.13384 2.07487 3.31764ZM16.1561 14.8151C16.1565 14.8152 16.1546 14.8186 16.1493 14.8253C16.1532 14.8185 16.1558 14.8151 16.1561 14.8151ZM1.84998 3.50934C1.84668 3.51524 1.84438 3.51814 1.84408 3.51804H1.84398C1.84458 3.51684 1.84648 3.51394 1.84998 3.50934ZM1.84387 14.8151C1.84417 14.8151 1.84678 14.8185 1.85068 14.8253C1.84538 14.8186 1.84347 14.8152 1.84387 14.8151Z" fill="#444E7C"/>
</svg>
| superset-frontend/src/assets/images/icons/default_db_image.svg | 0 | https://github.com/apache/superset/commit/4051fda671b8b6d4b0a4f2ba8266d61cda73b916 | [
0.00017809409473557025,
0.00017675822891760617,
0.0001741121377563104,
0.0001780684688128531,
0.0000018711016309680417
] |
{
"id": 1,
"code_window": [
" setDataMask,\n",
" showCellBars = true,\n",
" emitFilter = false,\n",
" sortDesc = false,\n",
" filters: initialFilters = {},\n",
" sticky = true, // whether to use sticky header\n",
" } = props;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" filters,\n"
],
"file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/plugin-chart-table/src/TableChart.tsx",
"type": "replace",
"edit_start_line_idx": 163
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regardin
* g copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { Behavior, ChartMetadata, ChartPlugin, t } from '@superset-ui/core';
import buildQuery from './buildQuery';
import controlPanel from './controlPanel';
import transformProps from './transformProps';
import thumbnail from './images/thumbnail.png';
import example1 from './images/treemap_v2_1.png';
import example2 from './images/treemap_v2_2.jpg';
import { EchartsTreemapChartProps, EchartsTreemapFormData } from './types';
export default class EchartsTreemapChartPlugin extends ChartPlugin<
EchartsTreemapFormData,
EchartsTreemapChartProps
> {
/**
* The constructor is used to pass relevant metadata and callbacks that get
* registered in respective registries that are used throughout the library
* and application. A more thorough description of each property is given in
* the respective imported file.
*
* It is worth noting that `buildQuery` and is optional, and only needed for
* advanced visualizations that require either post processing operations
* (pivoting, rolling aggregations, sorting etc) or submitting multiple queries.
*/
constructor() {
super({
buildQuery,
controlPanel,
loadChart: () => import('./EchartsTreemap'),
metadata: new ChartMetadata({
behaviors: [Behavior.INTERACTIVE_CHART],
category: t('Part of a Whole'),
credits: ['https://echarts.apache.org'],
description: t(
'Show hierarchical relationships of data, with with the value represented by area, showing proportion and contribution to the whole.',
),
exampleGallery: [{ url: example1 }, { url: example2 }],
name: t('Treemap v2'),
tags: [
t('Aesthetic'),
t('Categorical'),
t('Comparison'),
t('ECharts'),
t('Multi-Levels'),
t('Percentages'),
t('Proportional'),
],
thumbnail,
}),
transformProps,
});
}
}
| superset-frontend/temporary_superset_ui/superset-ui/plugins/plugin-chart-echarts/src/Treemap/index.ts | 0 | https://github.com/apache/superset/commit/4051fda671b8b6d4b0a4f2ba8266d61cda73b916 | [
0.00017672861577011645,
0.0001728719362290576,
0.0001659411209402606,
0.00017372211732435971,
0.000003153146735712653
] |
{
"id": 2,
"code_window": [
" sticky = true, // whether to use sticky header\n",
" } = props;\n",
"\n",
" const [filters, setFilters] = useState(initialFilters);\n",
"\n",
" const handleChange = useCallback(\n",
" (filters: { [x: string]: DataRecordValue[] }) => {\n",
" if (!emitFilter) {\n",
" return;\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/plugin-chart-table/src/TableChart.tsx",
"type": "replace",
"edit_start_line_idx": 167
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import React, { CSSProperties, useCallback, useMemo, useState } from 'react';
import { ColumnInstance, ColumnWithLooseAccessor, DefaultSortTypes } from 'react-table';
import { extent as d3Extent, max as d3Max } from 'd3-array';
import { FaSort, FaSortDown as FaSortDesc, FaSortUp as FaSortAsc } from 'react-icons/fa';
import { DataRecord, DataRecordValue, GenericDataType, t, tn } from '@superset-ui/core';
import { DataColumnMeta, TableChartTransformedProps } from './types';
import DataTable, {
DataTableProps,
SearchInputProps,
SelectPageSizeRendererProps,
SizeOption,
} from './DataTable';
import Styles from './Styles';
import { formatColumnValue } from './utils/formatValue';
import { PAGE_SIZE_OPTIONS } from './consts';
import { updateExternalFormData } from './DataTable/utils/externalAPIs';
type ValueRange = [number, number];
/**
* Return sortType based on data type
*/
function getSortTypeByDataType(dataType: GenericDataType): DefaultSortTypes {
if (dataType === GenericDataType.TEMPORAL) {
return 'datetime';
}
if (dataType === GenericDataType.STRING) {
return 'alphanumeric';
}
return 'basic';
}
/**
* Cell background to render columns as horizontal bar chart
*/
function cellBar({
value,
valueRange,
colorPositiveNegative = false,
alignPositiveNegative,
}: {
value: number;
valueRange: ValueRange;
colorPositiveNegative: boolean;
alignPositiveNegative: boolean;
}) {
const [minValue, maxValue] = valueRange;
const r = colorPositiveNegative && value < 0 ? 150 : 0;
if (alignPositiveNegative) {
const perc = Math.abs(Math.round((value / maxValue) * 100));
// The 0.01 to 0.001 is a workaround for what appears to be a
// CSS rendering bug on flat, transparent colors
return (
`linear-gradient(to right, rgba(${r},0,0,0.2), rgba(${r},0,0,0.2) ${perc}%, ` +
`rgba(0,0,0,0.01) ${perc}%, rgba(0,0,0,0.001) 100%)`
);
}
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 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
return (
`linear-gradient(to right, rgba(0,0,0,0.01), rgba(0,0,0,0.001) ${perc1}%, ` +
`rgba(${r},0,0,0.2) ${perc1}%, rgba(${r},0,0,0.2) ${perc1 + perc2}%, ` +
`rgba(0,0,0,0.01) ${perc1 + perc2}%, rgba(0,0,0,0.001) 100%)`
);
}
function SortIcon<D extends object>({ column }: { column: ColumnInstance<D> }) {
const { isSorted, isSortedDesc } = column;
let sortIcon = <FaSort />;
if (isSorted) {
sortIcon = isSortedDesc ? <FaSortDesc /> : <FaSortAsc />;
}
return sortIcon;
}
function SearchInput({ count, value, onChange }: SearchInputProps) {
return (
<span className="dt-global-filter">
{t('Search')}{' '}
<input
className="form-control input-sm"
placeholder={tn('search.num_records', count)}
value={value}
onChange={onChange}
/>
</span>
);
}
function SelectPageSize({ options, current, onChange }: SelectPageSizeRendererProps) {
return (
<span className="dt-select-page-size form-inline">
{t('page_size.show')}{' '}
<select
className="form-control input-sm"
value={current}
onBlur={() => {}}
onChange={e => {
onChange(Number((e.target as HTMLSelectElement).value));
}}
>
{options.map(option => {
const [size, text] = Array.isArray(option) ? option : [option, option];
return (
<option key={size} value={size}>
{text}
</option>
);
})}
</select>{' '}
{t('page_size.entries')}
</span>
);
}
export default function TableChart<D extends DataRecord = DataRecord>(
props: TableChartTransformedProps<D> & {
sticky?: DataTableProps<D>['sticky'];
},
) {
const {
height,
width,
data,
totals,
isRawRecords,
rowCount = 0,
columns: columnsMeta,
alignPositiveNegative: defaultAlignPN = false,
colorPositiveNegative: defaultColorPN = false,
includeSearch = false,
pageSize = 0,
serverPagination = false,
serverPaginationData,
setDataMask,
showCellBars = true,
emitFilter = false,
sortDesc = false,
filters: initialFilters = {},
sticky = true, // whether to use sticky header
} = props;
const [filters, setFilters] = useState(initialFilters);
const handleChange = useCallback(
(filters: { [x: string]: DataRecordValue[] }) => {
if (!emitFilter) {
return;
}
const groupBy = Object.keys(filters);
const groupByValues = Object.values(filters);
setDataMask({
extraFormData: {
filters:
groupBy.length === 0
? []
: groupBy.map(col => {
const val = filters?.[col];
if (val === null || val === undefined)
return {
col,
op: 'IS NULL',
};
return {
col,
op: 'IN',
val: val as (string | number | boolean)[],
};
}),
},
filterState: {
value: groupByValues.length ? groupByValues : null,
},
});
},
[emitFilter, setDataMask],
);
// only take relevant page size options
const pageSizeOptions = useMemo(() => {
const getServerPagination = (n: number) => n <= rowCount;
return PAGE_SIZE_OPTIONS.filter(([n]) =>
serverPagination ? getServerPagination(n) : n <= 2 * data.length,
) as SizeOption[];
}, [data.length, rowCount, serverPagination]);
const getValueRange = useCallback(
function getValueRange(key: string, alignPositiveNegative: boolean) {
if (typeof data?.[0]?.[key] === 'number') {
const nums = data.map(row => row[key]) as number[];
return (alignPositiveNegative
? [0, d3Max(nums.map(Math.abs))]
: d3Extent(nums)) as ValueRange;
}
return null;
},
[data],
);
const isActiveFilterValue = useCallback(
function isActiveFilterValue(key: string, val: DataRecordValue) {
return !!filters && filters[key]?.includes(val);
},
[filters],
);
const toggleFilter = useCallback(
function toggleFilter(key: string, val: DataRecordValue) {
const updatedFilters = { ...(filters || {}) };
if (filters && isActiveFilterValue(key, val)) {
updatedFilters[key] = filters[key].filter((x: DataRecordValue) => x !== val);
} else {
updatedFilters[key] = [...(filters?.[key] || []), val];
}
if (Array.isArray(updatedFilters[key]) && updatedFilters[key].length === 0) {
delete updatedFilters[key];
}
setFilters(updatedFilters);
handleChange(updatedFilters);
},
[filters, handleChange, isActiveFilterValue],
);
const getSharedStyle = (column: DataColumnMeta): CSSProperties => {
const { isNumeric, config = {} } = column;
const textAlign = config.horizontalAlign
? config.horizontalAlign
: isNumeric
? 'right'
: 'left';
return {
textAlign,
};
};
const getColumnConfigs = useCallback(
(column: DataColumnMeta, i: number): ColumnWithLooseAccessor<D> => {
const { key, label, isNumeric, dataType, isMetric, config = {} } = column;
const isFilter = !isNumeric && emitFilter;
const columnWidth = Number.isNaN(Number(config.columnWidth))
? config.columnWidth
: Number(config.columnWidth);
// inline style for both th and td cell
const sharedStyle: CSSProperties = getSharedStyle(column);
const alignPositiveNegative =
config.alignPositiveNegative === undefined ? defaultAlignPN : config.alignPositiveNegative;
const colorPositiveNegative =
config.colorPositiveNegative === undefined ? defaultColorPN : config.colorPositiveNegative;
const valueRange =
(config.showCellBars === undefined ? showCellBars : config.showCellBars) &&
(isMetric || isRawRecords) &&
getValueRange(key, alignPositiveNegative);
let className = '';
if (isFilter) {
className += ' dt-is-filter';
}
return {
id: String(i), // to allow duplicate column keys
// must use custom accessor to allow `.` in column names
// typing is incorrect in current version of `@types/react-table`
// so we ask TS not to check.
accessor: ((datum: D) => datum[key]) as never,
Cell: ({ value }: { value: DataRecordValue }) => {
const [isHtml, text] = formatColumnValue(column, value);
const html = isHtml ? { __html: text } : undefined;
const cellProps = {
// show raw number in title in case of numeric values
title: typeof value === 'number' ? String(value) : undefined,
onClick: emitFilter && !valueRange ? () => toggleFilter(key, value) : undefined,
className: [
className,
value == null ? 'dt-is-null' : '',
isActiveFilterValue(key, value) ? ' dt-is-active-filter' : '',
].join(' '),
style: {
...sharedStyle,
background: valueRange
? cellBar({
value: value as number,
valueRange,
alignPositiveNegative,
colorPositiveNegative,
})
: undefined,
},
};
if (html) {
// eslint-disable-next-line react/no-danger
return <td {...cellProps} dangerouslySetInnerHTML={html} />;
}
// If cellProps renderes textContent already, then we don't have to
// render `Cell`. This saves some time for large tables.
return <td {...cellProps}>{text}</td>;
},
Header: ({ column: col, onClick, style }) => (
<th
title="Shift + Click to sort by multiple columns"
className={[className, col.isSorted ? 'is-sorted' : ''].join(' ')}
style={{
...sharedStyle,
...style,
}}
onClick={onClick}
>
{/* can't use `columnWidth &&` because it may also be zero */}
{config.columnWidth ? (
// column width hint
<div
style={{
width: columnWidth,
height: 0.01,
}}
/>
) : null}
{label}
<SortIcon column={col} />
</th>
),
Footer: totals ? (
i === 0 ? (
<th>{t('Totals')}</th>
) : (
<td style={sharedStyle}>
<strong>{formatColumnValue(column, totals[key])[1]}</strong>
</td>
)
) : undefined,
sortDescFirst: sortDesc,
sortType: getSortTypeByDataType(dataType),
};
},
[
defaultAlignPN,
defaultColorPN,
emitFilter,
getValueRange,
isActiveFilterValue,
isRawRecords,
showCellBars,
sortDesc,
toggleFilter,
totals,
],
);
const columns = useMemo(() => columnsMeta.map(getColumnConfigs), [columnsMeta, getColumnConfigs]);
const handleServerPaginationChange = (pageNumber: number, pageSize: number) => {
updateExternalFormData(setDataMask, pageNumber, pageSize);
};
return (
<Styles>
<DataTable<D>
columns={columns}
data={data}
rowCount={rowCount}
tableClassName="table table-striped table-condensed"
pageSize={pageSize}
serverPaginationData={serverPaginationData}
pageSizeOptions={pageSizeOptions}
width={width}
height={height}
serverPagination={serverPagination}
onServerPaginationChange={handleServerPaginationChange}
// 9 page items in > 340px works well even for 100+ pages
maxPageItemCount={width > 340 ? 9 : 7}
noResults={(filter: string) => t(filter ? 'No matching records found' : 'No records found')}
searchInput={includeSearch && SearchInput}
selectPageSize={pageSize !== null && SelectPageSize}
// not in use in Superset, but needed for unit tests
sticky={sticky}
/>
</Styles>
);
}
| superset-frontend/temporary_superset_ui/superset-ui/plugins/plugin-chart-table/src/TableChart.tsx | 1 | https://github.com/apache/superset/commit/4051fda671b8b6d4b0a4f2ba8266d61cda73b916 | [
0.9985753297805786,
0.126515194773674,
0.0001626996381673962,
0.00017613140516914427,
0.3220120072364807
] |
{
"id": 2,
"code_window": [
" sticky = true, // whether to use sticky header\n",
" } = props;\n",
"\n",
" const [filters, setFilters] = useState(initialFilters);\n",
"\n",
" const handleChange = useCallback(\n",
" (filters: { [x: string]: DataRecordValue[] }) => {\n",
" if (!emitFilter) {\n",
" return;\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/plugin-chart-table/src/TableChart.tsx",
"type": "replace",
"edit_start_line_idx": 167
} | <!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
<svg width="16" height="11" viewBox="0 0 16 11" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd" d="M4.82355 4.0072L3.96417 8.04041C3.81118 8.76307 3.48891 9.35388 2.99738 9.81287C2.50584 10.2719 1.99966 10.5013 1.47882 10.5013C1.19236 10.5013 0.981588 10.4468 0.846497 10.3378C0.711405 10.2287 0.64386 10.0912 0.64386 9.92517C0.64386 9.7852 0.686177 9.6615 0.770813 9.55408C0.855449 9.44666 0.977518 9.39295 1.13702 9.39295C1.23794 9.39295 1.32664 9.41573 1.40314 9.4613C1.47963 9.50688 1.54718 9.56384 1.60577 9.6322C1.65135 9.68754 1.70262 9.76241 1.75958 9.85681C1.81655 9.95121 1.86619 10.0326 1.90851 10.101C2.15916 10.0814 2.37319 9.91215 2.5506 9.59314C2.72801 9.27413 2.88181 8.8184 3.01202 8.22595L3.91046 4.0072H2.95831L3.06085 3.56287H4.00323L4.07159 3.23084C4.14972 2.85323 4.27342 2.51306 4.44269 2.21033C4.61196 1.90759 4.80402 1.65043 5.01886 1.43884C5.23045 1.23051 5.47052 1.06694 5.73907 0.94812C6.00763 0.829304 6.2656 0.769897 6.513 0.769897C6.79946 0.769897 7.01023 0.824422 7.14532 0.933472C7.28042 1.04252 7.34796 1.18005 7.34796 1.34607C7.34796 1.48604 7.30809 1.60974 7.22833 1.71716C7.14858 1.82459 7.02407 1.8783 6.8548 1.8783C6.75389 1.8783 6.666 1.85632 6.59113 1.81238C6.51626 1.76843 6.44952 1.71065 6.39093 1.63904C6.32583 1.55766 6.27374 1.48116 6.23468 1.40955C6.19562 1.33793 6.14679 1.25818 6.0882 1.17029C5.86358 1.18005 5.66502 1.32816 5.49249 1.61462C5.31997 1.90108 5.16372 2.37797 5.02374 3.04529L4.91632 3.56287H6.14191L6.03937 4.0072H4.82355ZM6.67739 5.89197C6.67739 4.42712 7.05174 3.23897 7.83299 2.20544H8.42706C7.84926 2.946 7.3976 4.51664 7.3976 5.89197C7.3976 7.27543 7.84519 8.842 8.42706 9.58256H7.83299C7.05174 8.54903 6.67739 7.36088 6.67739 5.89197ZM11.0841 6.68949H11.019L9.97736 8.34558H9.1839L10.6854 6.15239L9.16762 3.95919H10.0018L11.0434 5.59086H11.1085L12.138 3.95919H12.9315L11.4422 6.1239L12.9518 8.34558H12.1217L11.0841 6.68949ZM15.442 5.89604C15.442 7.36088 15.0677 8.54903 14.2864 9.58256H13.6924C14.2702 8.842 14.7218 7.27136 14.7218 5.89604C14.7218 4.51257 14.2742 2.946 13.6924 2.20544H14.2864C15.0677 3.23897 15.442 4.42712 15.442 5.89604Z" fill="#323232"/>
</svg>
| superset-frontend/src/assets/images/icons/function_x.svg | 0 | https://github.com/apache/superset/commit/4051fda671b8b6d4b0a4f2ba8266d61cda73b916 | [
0.0001781849714461714,
0.00017295543511863798,
0.00016477577446494251,
0.00017590551578905433,
0.000005858266831637593
] |
{
"id": 2,
"code_window": [
" sticky = true, // whether to use sticky header\n",
" } = props;\n",
"\n",
" const [filters, setFilters] = useState(initialFilters);\n",
"\n",
" const handleChange = useCallback(\n",
" (filters: { [x: string]: DataRecordValue[] }) => {\n",
" if (!emitFilter) {\n",
" return;\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/plugin-chart-table/src/TableChart.tsx",
"type": "replace",
"edit_start_line_idx": 167
} | import * as React from 'react';
import { SuperChart } from '@superset-ui/core';
import data from '../data/legacyData';
import { SCATTER_PLOT_PLUGIN_LEGACY_TYPE } from '../constants';
import dummyDatasource from '../../../../../shared/dummyDatasource';
export default () => (
<SuperChart
key="scatter-plot1"
chartType={SCATTER_PLOT_PLUGIN_LEGACY_TYPE}
width={400}
height={400}
datasource={dummyDatasource}
queriesData={[{ data }]}
formData={{
annotationData: {},
bottomMargin: 'auto',
colorScheme: 'd3Category10',
entity: 'country_name',
leftMargin: 'auto',
maxBubbleSize: '50',
series: 'region',
showLegend: true,
size: 'sum__SP_POP_TOTL',
vizType: 'bubble',
x: 'sum__SP_RUR_TOTL_ZS',
xAxisFormat: '.3s',
xAxisLabel: 'x-axis label test',
xAxisShowminmax: false,
xLogScale: false,
xTicksLayout: 'auto',
y: 'sum__SP_DYN_LE00_IN',
yAxisFormat: '.3s',
yAxisLabel: '',
yAxisShowminmax: false,
yLogScale: false,
}}
/>
);
| superset-frontend/temporary_superset_ui/superset-ui/packages/superset-ui-demo/storybook/stories/plugins/preset-chart-xy/ScatterPlot/stories/legacy.tsx | 0 | https://github.com/apache/superset/commit/4051fda671b8b6d4b0a4f2ba8266d61cda73b916 | [
0.00017961305275093764,
0.00017717404989525676,
0.0001737371931085363,
0.0001776729477569461,
0.0000021649257178069092
] |
{
"id": 2,
"code_window": [
" sticky = true, // whether to use sticky header\n",
" } = props;\n",
"\n",
" const [filters, setFilters] = useState(initialFilters);\n",
"\n",
" const handleChange = useCallback(\n",
" (filters: { [x: string]: DataRecordValue[] }) => {\n",
" if (!emitFilter) {\n",
" return;\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/plugin-chart-table/src/TableChart.tsx",
"type": "replace",
"edit_start_line_idx": 167
} | <!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd" d="M15 7H9V7.5C9 7.77614 8.77614 8 8.5 8C8.22386 8 8 7.77614 8 7.5V7H6.5C5.67157 7 5 7.67157 5 8.5V11H19V8.5C19 7.67157 18.3284 7 17.5 7H16V7.5C16 7.77614 15.7761 8 15.5 8C15.2239 8 15 7.77614 15 7.5V7ZM16 6H17.5C18.8807 6 20 7.11929 20 8.5V16.5074C20 17.8881 18.8807 19.0074 17.5 19.0074H6.5C5.11929 19.0074 4 17.8881 4 16.5074V8.5C4 7.11929 5.11929 6 6.5 6H8V5.5C8 5.22386 8.22386 5 8.5 5C8.77614 5 9 5.22386 9 5.5V6H15V5.5C15 5.22386 15.2239 5 15.5 5C15.7761 5 16 5.22386 16 5.5V6ZM5 12V16.5074C5 17.3358 5.67157 18.0074 6.5 18.0074H17.5C18.3284 18.0074 19 17.3358 19 16.5074V12H5Z" fill="currentColor"/>
</svg>
| superset-frontend/src/assets/images/icons/field_date.svg | 0 | https://github.com/apache/superset/commit/4051fda671b8b6d4b0a4f2ba8266d61cda73b916 | [
0.0001781849714461714,
0.00017610575014259666,
0.00017422674864064902,
0.00017590551578905433,
0.0000016221283658524044
] |
{
"id": 3,
"code_window": [
" },\n",
" filterState: {\n",
" value: groupByValues.length ? groupByValues : null,\n",
" },\n",
" });\n",
" },\n",
" [emitFilter, setDataMask],\n",
" );\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" filters: filters && Object.keys(filters).length ? filters : null,\n"
],
"file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/plugin-chart-table/src/TableChart.tsx",
"type": "add",
"edit_start_line_idx": 198
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import React, { CSSProperties, useCallback, useMemo, useState } from 'react';
import { ColumnInstance, ColumnWithLooseAccessor, DefaultSortTypes } from 'react-table';
import { extent as d3Extent, max as d3Max } from 'd3-array';
import { FaSort, FaSortDown as FaSortDesc, FaSortUp as FaSortAsc } from 'react-icons/fa';
import { DataRecord, DataRecordValue, GenericDataType, t, tn } from '@superset-ui/core';
import { DataColumnMeta, TableChartTransformedProps } from './types';
import DataTable, {
DataTableProps,
SearchInputProps,
SelectPageSizeRendererProps,
SizeOption,
} from './DataTable';
import Styles from './Styles';
import { formatColumnValue } from './utils/formatValue';
import { PAGE_SIZE_OPTIONS } from './consts';
import { updateExternalFormData } from './DataTable/utils/externalAPIs';
type ValueRange = [number, number];
/**
* Return sortType based on data type
*/
function getSortTypeByDataType(dataType: GenericDataType): DefaultSortTypes {
if (dataType === GenericDataType.TEMPORAL) {
return 'datetime';
}
if (dataType === GenericDataType.STRING) {
return 'alphanumeric';
}
return 'basic';
}
/**
* Cell background to render columns as horizontal bar chart
*/
function cellBar({
value,
valueRange,
colorPositiveNegative = false,
alignPositiveNegative,
}: {
value: number;
valueRange: ValueRange;
colorPositiveNegative: boolean;
alignPositiveNegative: boolean;
}) {
const [minValue, maxValue] = valueRange;
const r = colorPositiveNegative && value < 0 ? 150 : 0;
if (alignPositiveNegative) {
const perc = Math.abs(Math.round((value / maxValue) * 100));
// The 0.01 to 0.001 is a workaround for what appears to be a
// CSS rendering bug on flat, transparent colors
return (
`linear-gradient(to right, rgba(${r},0,0,0.2), rgba(${r},0,0,0.2) ${perc}%, ` +
`rgba(0,0,0,0.01) ${perc}%, rgba(0,0,0,0.001) 100%)`
);
}
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 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
return (
`linear-gradient(to right, rgba(0,0,0,0.01), rgba(0,0,0,0.001) ${perc1}%, ` +
`rgba(${r},0,0,0.2) ${perc1}%, rgba(${r},0,0,0.2) ${perc1 + perc2}%, ` +
`rgba(0,0,0,0.01) ${perc1 + perc2}%, rgba(0,0,0,0.001) 100%)`
);
}
function SortIcon<D extends object>({ column }: { column: ColumnInstance<D> }) {
const { isSorted, isSortedDesc } = column;
let sortIcon = <FaSort />;
if (isSorted) {
sortIcon = isSortedDesc ? <FaSortDesc /> : <FaSortAsc />;
}
return sortIcon;
}
function SearchInput({ count, value, onChange }: SearchInputProps) {
return (
<span className="dt-global-filter">
{t('Search')}{' '}
<input
className="form-control input-sm"
placeholder={tn('search.num_records', count)}
value={value}
onChange={onChange}
/>
</span>
);
}
function SelectPageSize({ options, current, onChange }: SelectPageSizeRendererProps) {
return (
<span className="dt-select-page-size form-inline">
{t('page_size.show')}{' '}
<select
className="form-control input-sm"
value={current}
onBlur={() => {}}
onChange={e => {
onChange(Number((e.target as HTMLSelectElement).value));
}}
>
{options.map(option => {
const [size, text] = Array.isArray(option) ? option : [option, option];
return (
<option key={size} value={size}>
{text}
</option>
);
})}
</select>{' '}
{t('page_size.entries')}
</span>
);
}
export default function TableChart<D extends DataRecord = DataRecord>(
props: TableChartTransformedProps<D> & {
sticky?: DataTableProps<D>['sticky'];
},
) {
const {
height,
width,
data,
totals,
isRawRecords,
rowCount = 0,
columns: columnsMeta,
alignPositiveNegative: defaultAlignPN = false,
colorPositiveNegative: defaultColorPN = false,
includeSearch = false,
pageSize = 0,
serverPagination = false,
serverPaginationData,
setDataMask,
showCellBars = true,
emitFilter = false,
sortDesc = false,
filters: initialFilters = {},
sticky = true, // whether to use sticky header
} = props;
const [filters, setFilters] = useState(initialFilters);
const handleChange = useCallback(
(filters: { [x: string]: DataRecordValue[] }) => {
if (!emitFilter) {
return;
}
const groupBy = Object.keys(filters);
const groupByValues = Object.values(filters);
setDataMask({
extraFormData: {
filters:
groupBy.length === 0
? []
: groupBy.map(col => {
const val = filters?.[col];
if (val === null || val === undefined)
return {
col,
op: 'IS NULL',
};
return {
col,
op: 'IN',
val: val as (string | number | boolean)[],
};
}),
},
filterState: {
value: groupByValues.length ? groupByValues : null,
},
});
},
[emitFilter, setDataMask],
);
// only take relevant page size options
const pageSizeOptions = useMemo(() => {
const getServerPagination = (n: number) => n <= rowCount;
return PAGE_SIZE_OPTIONS.filter(([n]) =>
serverPagination ? getServerPagination(n) : n <= 2 * data.length,
) as SizeOption[];
}, [data.length, rowCount, serverPagination]);
const getValueRange = useCallback(
function getValueRange(key: string, alignPositiveNegative: boolean) {
if (typeof data?.[0]?.[key] === 'number') {
const nums = data.map(row => row[key]) as number[];
return (alignPositiveNegative
? [0, d3Max(nums.map(Math.abs))]
: d3Extent(nums)) as ValueRange;
}
return null;
},
[data],
);
const isActiveFilterValue = useCallback(
function isActiveFilterValue(key: string, val: DataRecordValue) {
return !!filters && filters[key]?.includes(val);
},
[filters],
);
const toggleFilter = useCallback(
function toggleFilter(key: string, val: DataRecordValue) {
const updatedFilters = { ...(filters || {}) };
if (filters && isActiveFilterValue(key, val)) {
updatedFilters[key] = filters[key].filter((x: DataRecordValue) => x !== val);
} else {
updatedFilters[key] = [...(filters?.[key] || []), val];
}
if (Array.isArray(updatedFilters[key]) && updatedFilters[key].length === 0) {
delete updatedFilters[key];
}
setFilters(updatedFilters);
handleChange(updatedFilters);
},
[filters, handleChange, isActiveFilterValue],
);
const getSharedStyle = (column: DataColumnMeta): CSSProperties => {
const { isNumeric, config = {} } = column;
const textAlign = config.horizontalAlign
? config.horizontalAlign
: isNumeric
? 'right'
: 'left';
return {
textAlign,
};
};
const getColumnConfigs = useCallback(
(column: DataColumnMeta, i: number): ColumnWithLooseAccessor<D> => {
const { key, label, isNumeric, dataType, isMetric, config = {} } = column;
const isFilter = !isNumeric && emitFilter;
const columnWidth = Number.isNaN(Number(config.columnWidth))
? config.columnWidth
: Number(config.columnWidth);
// inline style for both th and td cell
const sharedStyle: CSSProperties = getSharedStyle(column);
const alignPositiveNegative =
config.alignPositiveNegative === undefined ? defaultAlignPN : config.alignPositiveNegative;
const colorPositiveNegative =
config.colorPositiveNegative === undefined ? defaultColorPN : config.colorPositiveNegative;
const valueRange =
(config.showCellBars === undefined ? showCellBars : config.showCellBars) &&
(isMetric || isRawRecords) &&
getValueRange(key, alignPositiveNegative);
let className = '';
if (isFilter) {
className += ' dt-is-filter';
}
return {
id: String(i), // to allow duplicate column keys
// must use custom accessor to allow `.` in column names
// typing is incorrect in current version of `@types/react-table`
// so we ask TS not to check.
accessor: ((datum: D) => datum[key]) as never,
Cell: ({ value }: { value: DataRecordValue }) => {
const [isHtml, text] = formatColumnValue(column, value);
const html = isHtml ? { __html: text } : undefined;
const cellProps = {
// show raw number in title in case of numeric values
title: typeof value === 'number' ? String(value) : undefined,
onClick: emitFilter && !valueRange ? () => toggleFilter(key, value) : undefined,
className: [
className,
value == null ? 'dt-is-null' : '',
isActiveFilterValue(key, value) ? ' dt-is-active-filter' : '',
].join(' '),
style: {
...sharedStyle,
background: valueRange
? cellBar({
value: value as number,
valueRange,
alignPositiveNegative,
colorPositiveNegative,
})
: undefined,
},
};
if (html) {
// eslint-disable-next-line react/no-danger
return <td {...cellProps} dangerouslySetInnerHTML={html} />;
}
// If cellProps renderes textContent already, then we don't have to
// render `Cell`. This saves some time for large tables.
return <td {...cellProps}>{text}</td>;
},
Header: ({ column: col, onClick, style }) => (
<th
title="Shift + Click to sort by multiple columns"
className={[className, col.isSorted ? 'is-sorted' : ''].join(' ')}
style={{
...sharedStyle,
...style,
}}
onClick={onClick}
>
{/* can't use `columnWidth &&` because it may also be zero */}
{config.columnWidth ? (
// column width hint
<div
style={{
width: columnWidth,
height: 0.01,
}}
/>
) : null}
{label}
<SortIcon column={col} />
</th>
),
Footer: totals ? (
i === 0 ? (
<th>{t('Totals')}</th>
) : (
<td style={sharedStyle}>
<strong>{formatColumnValue(column, totals[key])[1]}</strong>
</td>
)
) : undefined,
sortDescFirst: sortDesc,
sortType: getSortTypeByDataType(dataType),
};
},
[
defaultAlignPN,
defaultColorPN,
emitFilter,
getValueRange,
isActiveFilterValue,
isRawRecords,
showCellBars,
sortDesc,
toggleFilter,
totals,
],
);
const columns = useMemo(() => columnsMeta.map(getColumnConfigs), [columnsMeta, getColumnConfigs]);
const handleServerPaginationChange = (pageNumber: number, pageSize: number) => {
updateExternalFormData(setDataMask, pageNumber, pageSize);
};
return (
<Styles>
<DataTable<D>
columns={columns}
data={data}
rowCount={rowCount}
tableClassName="table table-striped table-condensed"
pageSize={pageSize}
serverPaginationData={serverPaginationData}
pageSizeOptions={pageSizeOptions}
width={width}
height={height}
serverPagination={serverPagination}
onServerPaginationChange={handleServerPaginationChange}
// 9 page items in > 340px works well even for 100+ pages
maxPageItemCount={width > 340 ? 9 : 7}
noResults={(filter: string) => t(filter ? 'No matching records found' : 'No records found')}
searchInput={includeSearch && SearchInput}
selectPageSize={pageSize !== null && SelectPageSize}
// not in use in Superset, but needed for unit tests
sticky={sticky}
/>
</Styles>
);
}
| superset-frontend/temporary_superset_ui/superset-ui/plugins/plugin-chart-table/src/TableChart.tsx | 1 | https://github.com/apache/superset/commit/4051fda671b8b6d4b0a4f2ba8266d61cda73b916 | [
0.9403024315834045,
0.023513346910476685,
0.00016616801440250129,
0.0001719057618174702,
0.14495974779129028
] |
{
"id": 3,
"code_window": [
" },\n",
" filterState: {\n",
" value: groupByValues.length ? groupByValues : null,\n",
" },\n",
" });\n",
" },\n",
" [emitFilter, setDataMask],\n",
" );\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" filters: filters && Object.keys(filters).length ? filters : null,\n"
],
"file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/plugin-chart-table/src/TableChart.tsx",
"type": "add",
"edit_start_line_idx": 198
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import React from 'react';
import { render, screen } from 'spec/helpers/testing-library';
import userEvent from '@testing-library/user-event';
import { Prev } from './Prev';
test('Prev - click when the button is enabled', () => {
const click = jest.fn();
render(<Prev onClick={click} />);
expect(click).toBeCalledTimes(0);
userEvent.click(screen.getByRole('button'));
expect(click).toBeCalledTimes(1);
});
test('Prev - click when the button is disabled', () => {
const click = jest.fn();
render(<Prev onClick={click} disabled />);
expect(click).toBeCalledTimes(0);
userEvent.click(screen.getByRole('button'));
expect(click).toBeCalledTimes(0);
});
| superset-frontend/src/components/Pagination/Prev.test.tsx | 0 | https://github.com/apache/superset/commit/4051fda671b8b6d4b0a4f2ba8266d61cda73b916 | [
0.00017266192298848182,
0.000171003513969481,
0.00016640967805869877,
0.00017247122013941407,
0.0000026533987238508416
] |
{
"id": 3,
"code_window": [
" },\n",
" filterState: {\n",
" value: groupByValues.length ? groupByValues : null,\n",
" },\n",
" });\n",
" },\n",
" [emitFilter, setDataMask],\n",
" );\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" filters: filters && Object.keys(filters).length ? filters : null,\n"
],
"file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/plugin-chart-table/src/TableChart.tsx",
"type": "add",
"edit_start_line_idx": 198
} | name: Docs
on:
push:
paths:
- "docs/**"
pull_request:
paths:
- "docs/**"
jobs:
build-deploy:
name: Build & Deploy
runs-on: ubuntu-20.04
steps:
- name: "Checkout ${{ github.ref }} ( ${{ github.sha }} )"
uses: actions/checkout@v2
with:
persist-credentials: false
submodules: recursive
- name: npm install
working-directory: ./docs
run: |
npm install
- name: lint
working-directory: ./docs
run: |
npm run lint
- name: gatsby build
working-directory: ./docs
run: |
npm run build
- name: deploy docs
if: github.ref == 'refs/heads/master'
uses: ./.github/actions/github-action-push-to-another-repository
env:
API_TOKEN_GITHUB: ${{ secrets.SUPERSET_SITE_BUILD }}
with:
source-directory: './docs/public'
destination-github-username: 'apache'
destination-repository-name: 'superset-site'
target-branch: 'asf-site'
commit-message: "deploying docs: ${{ github.event.head_commit.message }} (apache/superset@${{ github.sha }})"
user-email: [email protected]
| .github/workflows/superset-docs.yml | 0 | https://github.com/apache/superset/commit/4051fda671b8b6d4b0a4f2ba8266d61cda73b916 | [
0.00017368601402267814,
0.0001706907496554777,
0.0001687791955191642,
0.0001709966454654932,
0.0000018164382709073834
] |
{
"id": 3,
"code_window": [
" },\n",
" filterState: {\n",
" value: groupByValues.length ? groupByValues : null,\n",
" },\n",
" });\n",
" },\n",
" [emitFilter, setDataMask],\n",
" );\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" filters: filters && Object.keys(filters).length ? filters : null,\n"
],
"file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/plugin-chart-table/src/TableChart.tsx",
"type": "add",
"edit_start_line_idx": 198
} | <!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
## Superset Users in the Wild
Here's a list of organizations, broken down into broad industry categories, that have taken the time to send a PR to let
the world know they are using Apache Superset. If you are a user and want to be recognized,
all you have to do is file a simple PR [like this one](https://github.com/apache/superset/pull/10122). If you think
the categorization is inaccurate, please file a PR with your correction as well.
Join our growing community!
### Sharing Economy
- [Airbnb](https://github.com/airbnb)
- [Faasos](http://faasos.com/) [@shashanksingh]
- [Hostnfly](https://www.hostnfly.com/) [@alexisrosuel]
- [Lime](https://www.limebike.com/) [@cxmcc]
- [Lyft](https://www.lyft.com/)
- [Ontruck](https://www.ontruck.com/)
### Financial Services
- [Aktia Bank plc](https://www.aktia.com) [@villebro]
- [American Express](https://www.americanexpress.com) [@TheLastSultan]
- [Cape Crypto](https://capecrypto.com)
- [Capital Service S.A.](http://capitalservice.pl) [@pkonarzewski]
- [Clark.de](http://clark.de/)
- [Xendit](http://xendit.co/) [@LieAlbertTriAdrian]
### Gaming
- [Digit Game Studios](https://www.digitgaming.com/)
- [Popoko VM Games Studio](https://popoko.live)
### E-Commerce
- [AiHello](https://www.aihello.com) [@ganeshkrishnan1]
- [Dragonpass](https://www.dragonpass.com.cn/) [@zhxjdwh]
- [Fanatics](https://www.fanatics.com) [@coderfender]
- [Fordeal](http://www.fordeal.com) [@Renkai]
- [GFG - Global Fashion Group](https://global-fashion-group.com) [@ksaagariconic]
- [HuiShouBao](http://www.huishoubao.com/) [@Yukinoshita-Yukino]
- [Now](https://www.now.vn/) [@davidkohcw]
- [Qunar](https://www.qunar.com/) [@flametest]
- [Rakuten Viki](https://www.viki.com)
- [Shopee](https://shopee.sg) [@xiaohanyu]
- [Shopkick](https://www.shopkick.com) [@LAlbertalli]
- [Tails.com](https://tails.com) [@alanmcruickshank]
- [THE ICONIC](http://theiconic.com.au/) [@ksaagariconic]
- [Utair](https://www.utair.ru) [@utair-digital]
- [VkusVill](https://www.vkusvill.ru) [@ETselikov]
- [Zalando](https://www.zalando.com) [@dmigo]
- [Zalora](https://www.zalora.com) [@ksaagariconic]
### Enterprise Technology
- [A3Data](https://a3data.com.br) [@neylsoncrepalde]
- [Apollo GraphQL](https://www.apollographql.com/) [@evans]
- [Astronomer](https://www.astronomer.io) [@ryw]
- [Avesta Technologies](https://avestatechnologies.com/) [@TheRum]
- [Cloudsmith](https://cloudsmith.io) [@alancarson]
- [CnOvit](http://www.cnovit.com/) [@xieshaohu]
- [Deepomatic](https://deepomatic.com/) [@Zanoellia]
- [Dial Once](https://www.dial-once.com/)
- [Dremio](https://dremio.com) [@narendrans]
- [ELMO Cloud HR & Payroll](https://elmosoftware.com.au/)
- [Endress+Hauser](http://www.endress.com/) [@rumbin]
- [FBK - ICT center](http://ict.fbk.eu)
- [GfK Data Lab](http://datalab.gfk.com) [@mherr]
- [GrowthSimple](https://growthsimple.ai/)
- [Hydrolix](https://www.hydrolix.io/)
- [Intercom](https://www.intercom.com/) [@kate-gallo]
- [jampp](https://jampp.com/)
- [Konfío](http://konfio.mx) [@uis-rodriguez]
- [mishmash io](https://mishmash.io/)[@mishmash-io]
- [Myra Labs](http://www.myralabs.com/) [@viksit]
- [Nielsen](http://www.nielsen.com/) [@amitNielsen]
- [Ona](https://ona.io) [@pld]
- [Peak AI](https://www.peak.ai/) [@azhar22k]
- [PeopleDoc](https://www.people-doc.com) [@rodo]
- [Preset, Inc.](https://preset.io)
- [Pronto Tools](http://www.prontotools.io) [@zkan]
- [PubNub](https://pubnub.com) [@jzucker2]
- [Reward Gateway](https://www.rewardgateway.com)
- [ScopeAI](https://www.getscopeai.com) [@iloveluce]
- [Showmax](https://tech.showmax.com) [@bobek]
- [source{d}](https://www.sourced.tech) [@marnovo]
- [Steamroot](https://streamroot.io/)
- [TechAudit](https://www.techaudit.info) [@ETselikov]
- [Tenable](https://www.tenable.com) [@dflionis]
- [timbr.ai](https://timbr.ai/) [@semantiDan]
- [Tobii](http://www.tobii.com/) [@dwa]
- [Tooploox](https://www.tooploox.com/) [@jakubczaplicki]
- [Whale](http://whale.im)
- [Windsor.ai](https://www.windsor.ai/) [@octaviancorlade]
- [Zeta](https://www.zeta.tech/) [@shaikidris]
### Entertainment
- [6play](https://www.6play.fr) [@CoryChaplin]
- [bilibili](https://www.bilibili.com) [@Moinheart]
- [Douban](https://www.douban.com/) [@luchuan]
- [Kuaishou](https://www.kuaishou.com/) [@zhaoyu89730105]
- [Netflix](https://www.netflix.com/)
- [TME QQMUSIC/WESING](https://www.tencentmusic.com/)[@shenyuanli,@marklaw]
- [Xite](https://xite.com/) [@shashankkoppar]
- [Zaihang](http://www.zaih.com/)
### Education
- [Brilliant.org](https://brilliant.org/)
- [Udemy](https://www.udemy.com/) [@sungjuly]
- [VIPKID](https://www.vipkid.com.cn/) [@illpanda]
- [Sunbird](https://www.sunbird.org/) [@eksteporg]
### Energy
- [Airboxlab](https://foobot.io) [@antoine-galataud]
- [DouroECI](http://douroeci.com/en/) [@nunohelibeires]
- [Safaricom](https://www.safaricom.co.ke/) [@mmutiso]
- [Scoot](https://scoot.co/) [@haaspt]
### Healthcare
- [Amino](https://amino.com) [@shkr]
- [Care](https://www.getcare.io/)[@alandao2021]
- [Living Goods](https://www.livinggoods.org) [@chelule]
- [Maieutical Labs](https://maieuticallabs.it) [@xrmx]
- [QPID Health](http://www.qpidhealth.com/)
- [TrustMedis](https://trustmedis.com) [@famasya]
- [WeSure](https://www.wesure.cn/)
### HR / Staffing
- [Symmetrics](https://www.symmetrics.fyi)
### Others
- [Dropbox](https://www.dropbox.com/) [@bkyryliuk]
- [Grassroot](https://www.grassrootinstitute.org/)
- [komoot](https://www.komoot.com/) [@christophlingg]
- [Let's Roam](https://www.letsroam.com/)
- [Twitter](https://twitter.com/)
- [VLMedia](https://www.vlmedia.com.tr/) [@ibotheperfect]
- [Yahoo!](https://yahoo.com/)
| RESOURCES/INTHEWILD.md | 0 | https://github.com/apache/superset/commit/4051fda671b8b6d4b0a4f2ba8266d61cda73b916 | [
0.00017627389752306044,
0.00017088935419451445,
0.00016394813428632915,
0.00017082301201298833,
0.000002530034635128686
] |
{
"id": 4,
"code_window": [
" if (Array.isArray(updatedFilters[key]) && updatedFilters[key].length === 0) {\n",
" delete updatedFilters[key];\n",
" }\n",
" setFilters(updatedFilters);\n",
" handleChange(updatedFilters);\n",
" },\n",
" [filters, handleChange, isActiveFilterValue],\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/plugin-chart-table/src/TableChart.tsx",
"type": "replace",
"edit_start_line_idx": 243
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import React, { CSSProperties, useCallback, useMemo, useState } from 'react';
import { ColumnInstance, ColumnWithLooseAccessor, DefaultSortTypes } from 'react-table';
import { extent as d3Extent, max as d3Max } from 'd3-array';
import { FaSort, FaSortDown as FaSortDesc, FaSortUp as FaSortAsc } from 'react-icons/fa';
import { DataRecord, DataRecordValue, GenericDataType, t, tn } from '@superset-ui/core';
import { DataColumnMeta, TableChartTransformedProps } from './types';
import DataTable, {
DataTableProps,
SearchInputProps,
SelectPageSizeRendererProps,
SizeOption,
} from './DataTable';
import Styles from './Styles';
import { formatColumnValue } from './utils/formatValue';
import { PAGE_SIZE_OPTIONS } from './consts';
import { updateExternalFormData } from './DataTable/utils/externalAPIs';
type ValueRange = [number, number];
/**
* Return sortType based on data type
*/
function getSortTypeByDataType(dataType: GenericDataType): DefaultSortTypes {
if (dataType === GenericDataType.TEMPORAL) {
return 'datetime';
}
if (dataType === GenericDataType.STRING) {
return 'alphanumeric';
}
return 'basic';
}
/**
* Cell background to render columns as horizontal bar chart
*/
function cellBar({
value,
valueRange,
colorPositiveNegative = false,
alignPositiveNegative,
}: {
value: number;
valueRange: ValueRange;
colorPositiveNegative: boolean;
alignPositiveNegative: boolean;
}) {
const [minValue, maxValue] = valueRange;
const r = colorPositiveNegative && value < 0 ? 150 : 0;
if (alignPositiveNegative) {
const perc = Math.abs(Math.round((value / maxValue) * 100));
// The 0.01 to 0.001 is a workaround for what appears to be a
// CSS rendering bug on flat, transparent colors
return (
`linear-gradient(to right, rgba(${r},0,0,0.2), rgba(${r},0,0,0.2) ${perc}%, ` +
`rgba(0,0,0,0.01) ${perc}%, rgba(0,0,0,0.001) 100%)`
);
}
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 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
return (
`linear-gradient(to right, rgba(0,0,0,0.01), rgba(0,0,0,0.001) ${perc1}%, ` +
`rgba(${r},0,0,0.2) ${perc1}%, rgba(${r},0,0,0.2) ${perc1 + perc2}%, ` +
`rgba(0,0,0,0.01) ${perc1 + perc2}%, rgba(0,0,0,0.001) 100%)`
);
}
function SortIcon<D extends object>({ column }: { column: ColumnInstance<D> }) {
const { isSorted, isSortedDesc } = column;
let sortIcon = <FaSort />;
if (isSorted) {
sortIcon = isSortedDesc ? <FaSortDesc /> : <FaSortAsc />;
}
return sortIcon;
}
function SearchInput({ count, value, onChange }: SearchInputProps) {
return (
<span className="dt-global-filter">
{t('Search')}{' '}
<input
className="form-control input-sm"
placeholder={tn('search.num_records', count)}
value={value}
onChange={onChange}
/>
</span>
);
}
function SelectPageSize({ options, current, onChange }: SelectPageSizeRendererProps) {
return (
<span className="dt-select-page-size form-inline">
{t('page_size.show')}{' '}
<select
className="form-control input-sm"
value={current}
onBlur={() => {}}
onChange={e => {
onChange(Number((e.target as HTMLSelectElement).value));
}}
>
{options.map(option => {
const [size, text] = Array.isArray(option) ? option : [option, option];
return (
<option key={size} value={size}>
{text}
</option>
);
})}
</select>{' '}
{t('page_size.entries')}
</span>
);
}
export default function TableChart<D extends DataRecord = DataRecord>(
props: TableChartTransformedProps<D> & {
sticky?: DataTableProps<D>['sticky'];
},
) {
const {
height,
width,
data,
totals,
isRawRecords,
rowCount = 0,
columns: columnsMeta,
alignPositiveNegative: defaultAlignPN = false,
colorPositiveNegative: defaultColorPN = false,
includeSearch = false,
pageSize = 0,
serverPagination = false,
serverPaginationData,
setDataMask,
showCellBars = true,
emitFilter = false,
sortDesc = false,
filters: initialFilters = {},
sticky = true, // whether to use sticky header
} = props;
const [filters, setFilters] = useState(initialFilters);
const handleChange = useCallback(
(filters: { [x: string]: DataRecordValue[] }) => {
if (!emitFilter) {
return;
}
const groupBy = Object.keys(filters);
const groupByValues = Object.values(filters);
setDataMask({
extraFormData: {
filters:
groupBy.length === 0
? []
: groupBy.map(col => {
const val = filters?.[col];
if (val === null || val === undefined)
return {
col,
op: 'IS NULL',
};
return {
col,
op: 'IN',
val: val as (string | number | boolean)[],
};
}),
},
filterState: {
value: groupByValues.length ? groupByValues : null,
},
});
},
[emitFilter, setDataMask],
);
// only take relevant page size options
const pageSizeOptions = useMemo(() => {
const getServerPagination = (n: number) => n <= rowCount;
return PAGE_SIZE_OPTIONS.filter(([n]) =>
serverPagination ? getServerPagination(n) : n <= 2 * data.length,
) as SizeOption[];
}, [data.length, rowCount, serverPagination]);
const getValueRange = useCallback(
function getValueRange(key: string, alignPositiveNegative: boolean) {
if (typeof data?.[0]?.[key] === 'number') {
const nums = data.map(row => row[key]) as number[];
return (alignPositiveNegative
? [0, d3Max(nums.map(Math.abs))]
: d3Extent(nums)) as ValueRange;
}
return null;
},
[data],
);
const isActiveFilterValue = useCallback(
function isActiveFilterValue(key: string, val: DataRecordValue) {
return !!filters && filters[key]?.includes(val);
},
[filters],
);
const toggleFilter = useCallback(
function toggleFilter(key: string, val: DataRecordValue) {
const updatedFilters = { ...(filters || {}) };
if (filters && isActiveFilterValue(key, val)) {
updatedFilters[key] = filters[key].filter((x: DataRecordValue) => x !== val);
} else {
updatedFilters[key] = [...(filters?.[key] || []), val];
}
if (Array.isArray(updatedFilters[key]) && updatedFilters[key].length === 0) {
delete updatedFilters[key];
}
setFilters(updatedFilters);
handleChange(updatedFilters);
},
[filters, handleChange, isActiveFilterValue],
);
const getSharedStyle = (column: DataColumnMeta): CSSProperties => {
const { isNumeric, config = {} } = column;
const textAlign = config.horizontalAlign
? config.horizontalAlign
: isNumeric
? 'right'
: 'left';
return {
textAlign,
};
};
const getColumnConfigs = useCallback(
(column: DataColumnMeta, i: number): ColumnWithLooseAccessor<D> => {
const { key, label, isNumeric, dataType, isMetric, config = {} } = column;
const isFilter = !isNumeric && emitFilter;
const columnWidth = Number.isNaN(Number(config.columnWidth))
? config.columnWidth
: Number(config.columnWidth);
// inline style for both th and td cell
const sharedStyle: CSSProperties = getSharedStyle(column);
const alignPositiveNegative =
config.alignPositiveNegative === undefined ? defaultAlignPN : config.alignPositiveNegative;
const colorPositiveNegative =
config.colorPositiveNegative === undefined ? defaultColorPN : config.colorPositiveNegative;
const valueRange =
(config.showCellBars === undefined ? showCellBars : config.showCellBars) &&
(isMetric || isRawRecords) &&
getValueRange(key, alignPositiveNegative);
let className = '';
if (isFilter) {
className += ' dt-is-filter';
}
return {
id: String(i), // to allow duplicate column keys
// must use custom accessor to allow `.` in column names
// typing is incorrect in current version of `@types/react-table`
// so we ask TS not to check.
accessor: ((datum: D) => datum[key]) as never,
Cell: ({ value }: { value: DataRecordValue }) => {
const [isHtml, text] = formatColumnValue(column, value);
const html = isHtml ? { __html: text } : undefined;
const cellProps = {
// show raw number in title in case of numeric values
title: typeof value === 'number' ? String(value) : undefined,
onClick: emitFilter && !valueRange ? () => toggleFilter(key, value) : undefined,
className: [
className,
value == null ? 'dt-is-null' : '',
isActiveFilterValue(key, value) ? ' dt-is-active-filter' : '',
].join(' '),
style: {
...sharedStyle,
background: valueRange
? cellBar({
value: value as number,
valueRange,
alignPositiveNegative,
colorPositiveNegative,
})
: undefined,
},
};
if (html) {
// eslint-disable-next-line react/no-danger
return <td {...cellProps} dangerouslySetInnerHTML={html} />;
}
// If cellProps renderes textContent already, then we don't have to
// render `Cell`. This saves some time for large tables.
return <td {...cellProps}>{text}</td>;
},
Header: ({ column: col, onClick, style }) => (
<th
title="Shift + Click to sort by multiple columns"
className={[className, col.isSorted ? 'is-sorted' : ''].join(' ')}
style={{
...sharedStyle,
...style,
}}
onClick={onClick}
>
{/* can't use `columnWidth &&` because it may also be zero */}
{config.columnWidth ? (
// column width hint
<div
style={{
width: columnWidth,
height: 0.01,
}}
/>
) : null}
{label}
<SortIcon column={col} />
</th>
),
Footer: totals ? (
i === 0 ? (
<th>{t('Totals')}</th>
) : (
<td style={sharedStyle}>
<strong>{formatColumnValue(column, totals[key])[1]}</strong>
</td>
)
) : undefined,
sortDescFirst: sortDesc,
sortType: getSortTypeByDataType(dataType),
};
},
[
defaultAlignPN,
defaultColorPN,
emitFilter,
getValueRange,
isActiveFilterValue,
isRawRecords,
showCellBars,
sortDesc,
toggleFilter,
totals,
],
);
const columns = useMemo(() => columnsMeta.map(getColumnConfigs), [columnsMeta, getColumnConfigs]);
const handleServerPaginationChange = (pageNumber: number, pageSize: number) => {
updateExternalFormData(setDataMask, pageNumber, pageSize);
};
return (
<Styles>
<DataTable<D>
columns={columns}
data={data}
rowCount={rowCount}
tableClassName="table table-striped table-condensed"
pageSize={pageSize}
serverPaginationData={serverPaginationData}
pageSizeOptions={pageSizeOptions}
width={width}
height={height}
serverPagination={serverPagination}
onServerPaginationChange={handleServerPaginationChange}
// 9 page items in > 340px works well even for 100+ pages
maxPageItemCount={width > 340 ? 9 : 7}
noResults={(filter: string) => t(filter ? 'No matching records found' : 'No records found')}
searchInput={includeSearch && SearchInput}
selectPageSize={pageSize !== null && SelectPageSize}
// not in use in Superset, but needed for unit tests
sticky={sticky}
/>
</Styles>
);
}
| superset-frontend/temporary_superset_ui/superset-ui/plugins/plugin-chart-table/src/TableChart.tsx | 1 | https://github.com/apache/superset/commit/4051fda671b8b6d4b0a4f2ba8266d61cda73b916 | [
0.9975453019142151,
0.024929020553827286,
0.00016395984857808799,
0.00017416427726857364,
0.1537884771823883
] |
{
"id": 4,
"code_window": [
" if (Array.isArray(updatedFilters[key]) && updatedFilters[key].length === 0) {\n",
" delete updatedFilters[key];\n",
" }\n",
" setFilters(updatedFilters);\n",
" handleChange(updatedFilters);\n",
" },\n",
" [filters, handleChange, isActiveFilterValue],\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/plugin-chart-table/src/TableChart.tsx",
"type": "replace",
"edit_start_line_idx": 243
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import React from 'react';
import { render, screen, waitFor } from 'spec/helpers/testing-library';
import userEvent from '@testing-library/user-event';
import fetchMock from 'fetch-mock';
import { HeaderDropdownProps } from 'src/dashboard/components/Header/types';
import HeaderActionsDropdown from '.';
const createProps = () => ({
addSuccessToast: jest.fn(),
addDangerToast: jest.fn(),
customCss: '#save-dash-split-button{margin-left: 100px;}',
dashboardId: 1,
dashboardInfo: {
id: 1,
dash_edit_perm: true,
dash_save_perm: true,
userId: '1',
metadata: {},
common: {
conf: {},
},
},
dashboardTitle: 'Title',
editMode: false,
expandedSlices: {},
forceRefreshAllCharts: jest.fn(),
hasUnsavedChanges: false,
isLoading: false,
layout: {},
onChange: jest.fn(),
onSave: jest.fn(),
refreshFrequency: 200,
setRefreshFrequency: jest.fn(),
shouldPersistRefreshFrequency: false,
showPropertiesModal: jest.fn(),
startPeriodicRender: jest.fn(),
updateCss: jest.fn(),
userCanEdit: false,
userCanSave: false,
userCanShare: false,
lastModifiedTime: 0,
});
const editModeOnProps = {
...createProps(),
editMode: true,
};
function setup(props: HeaderDropdownProps) {
return (
<div className="dashboard-header">
<HeaderActionsDropdown {...props} />
</div>
);
}
fetchMock.get('glob:*/csstemplateasyncmodelview/api/read', {});
async function openDropdown() {
const btn = screen.getByRole('img', { name: 'more-horiz' });
userEvent.click(btn);
expect(await screen.findByRole('menu')).toBeInTheDocument();
}
test('should render', () => {
const mockedProps = createProps();
const { container } = render(setup(mockedProps));
expect(container).toBeInTheDocument();
});
test('should render the dropdown button', () => {
const mockedProps = createProps();
render(setup(mockedProps));
expect(screen.getByRole('button')).toBeInTheDocument();
});
test('should render the dropdown icon', () => {
const mockedProps = createProps();
render(setup(mockedProps));
expect(screen.getByRole('img', { name: 'more-horiz' })).toBeInTheDocument();
});
test('should open the dropdown', async () => {
const mockedProps = createProps();
render(setup(mockedProps));
await openDropdown();
expect(await screen.findByRole('menu')).toBeInTheDocument();
});
test('should render the menu items', async () => {
const mockedProps = createProps();
render(setup(mockedProps));
await openDropdown();
expect(screen.getAllByRole('menuitem')).toHaveLength(4);
expect(screen.getByText('Refresh dashboard')).toBeInTheDocument();
expect(screen.getByText('Set auto-refresh interval')).toBeInTheDocument();
expect(screen.getByText('Download as image')).toBeInTheDocument();
expect(screen.getByText('Enter fullscreen')).toBeInTheDocument();
});
test('should render the menu items in edit mode', async () => {
render(setup(editModeOnProps));
await openDropdown();
expect(screen.getAllByRole('menuitem')).toHaveLength(5);
expect(screen.getByText('Refresh dashboard')).toBeInTheDocument();
expect(screen.getByText('Set auto-refresh interval')).toBeInTheDocument();
expect(screen.getByText('Set filter mapping')).toBeInTheDocument();
expect(screen.getByText('Edit dashboard properties')).toBeInTheDocument();
expect(screen.getByText('Edit CSS')).toBeInTheDocument();
});
test('should show the share actions', async () => {
const mockedProps = createProps();
const canShareProps = {
...mockedProps,
userCanShare: true,
};
render(setup(canShareProps));
await openDropdown();
expect(screen.getByText('Copy dashboard URL')).toBeInTheDocument();
expect(screen.getByText('Share dashboard by email')).toBeInTheDocument();
});
test('should render the "Save Modal" when user can save', async () => {
const mockedProps = createProps();
const canSaveProps = {
...mockedProps,
userCanSave: true,
};
render(setup(canSaveProps));
await openDropdown();
expect(screen.getByText('Save as')).toBeInTheDocument();
});
test('should NOT render the "Save Modal" menu item when user cannot save', async () => {
const mockedProps = createProps();
render(setup(mockedProps));
await openDropdown();
expect(screen.queryByText('Save as')).not.toBeInTheDocument();
});
test('should render the "Refresh dashboard" menu item as disabled when loading', async () => {
const mockedProps = createProps();
const loadingProps = {
...mockedProps,
isLoading: true,
};
render(setup(loadingProps));
await openDropdown();
expect(screen.getByText('Refresh dashboard')).toHaveClass(
'ant-dropdown-menu-item-disabled',
);
});
test('should NOT render the "Refresh dashboard" menu item as disabled', async () => {
const mockedProps = createProps();
render(setup(mockedProps));
await openDropdown();
expect(screen.getByText('Refresh dashboard')).not.toHaveClass(
'ant-dropdown-menu-item-disabled',
);
});
test('should render with custom css', () => {
const mockedProps = createProps();
render(setup(mockedProps));
expect(screen.getByRole('button')).toHaveStyle('margin-left: 100px');
});
test('should refresh the charts', async () => {
const mockedProps = createProps();
render(setup(mockedProps));
await openDropdown();
userEvent.click(screen.getByText('Refresh dashboard'));
expect(mockedProps.forceRefreshAllCharts).toHaveBeenCalledTimes(1);
});
test('should show the properties modal', async () => {
render(setup(editModeOnProps));
await openDropdown();
userEvent.click(screen.getByText('Edit dashboard properties'));
expect(editModeOnProps.showPropertiesModal).toHaveBeenCalledTimes(1);
});
test('should display the Apply button when opening the modal', async () => {
render(setup(editModeOnProps));
await openDropdown();
userEvent.click(screen.getByText('Edit dashboard properties'));
waitFor(() => {
expect(screen.getByRole('button', { name: 'Apply' })).toBeInTheDocument();
});
});
| superset-frontend/src/dashboard/components/Header/HeaderActionsDropdown/HeaderActionsDropdown.test.tsx | 0 | https://github.com/apache/superset/commit/4051fda671b8b6d4b0a4f2ba8266d61cda73b916 | [
0.00026448434800840914,
0.00017918727826327085,
0.00016705911548342556,
0.00017536274390295148,
0.000019236080333939753
] |
{
"id": 4,
"code_window": [
" if (Array.isArray(updatedFilters[key]) && updatedFilters[key].length === 0) {\n",
" delete updatedFilters[key];\n",
" }\n",
" setFilters(updatedFilters);\n",
" handleChange(updatedFilters);\n",
" },\n",
" [filters, handleChange, isActiveFilterValue],\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/plugin-chart-table/src/TableChart.tsx",
"type": "replace",
"edit_start_line_idx": 243
} | {
"compilerOptions": {
"declarationDir": "lib",
"outDir": "lib",
"rootDir": "src"
},
"exclude": [
"lib",
"test"
],
"extends": "../../tsconfig.options.json",
"include": [
"src/**/*",
"types/**/*",
"../../types/**/*"
],
"references": [
{
"path": "../../packages/superset-ui-chart-controls"
},
{
"path": "../../packages/superset-ui-core"
}
]
} | superset-frontend/temporary_superset_ui/superset-ui/plugins/plugin-chart-word-cloud/tsconfig.json | 0 | https://github.com/apache/superset/commit/4051fda671b8b6d4b0a4f2ba8266d61cda73b916 | [
0.00017182349984068424,
0.00017154870147351176,
0.00017106530140154064,
0.00017175731773022562,
3.428850732234423e-7
] |
{
"id": 4,
"code_window": [
" if (Array.isArray(updatedFilters[key]) && updatedFilters[key].length === 0) {\n",
" delete updatedFilters[key];\n",
" }\n",
" setFilters(updatedFilters);\n",
" handleChange(updatedFilters);\n",
" },\n",
" [filters, handleChange, isActiveFilterValue],\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/plugin-chart-table/src/TableChart.tsx",
"type": "replace",
"edit_start_line_idx": 243
} | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# isort:skip_file
import json
import logging
import random
import string
from typing import Any, Dict, Iterator, Optional, Set, Tuple
import yaml
from werkzeug.utils import secure_filename
from superset.charts.commands.export import ExportChartsCommand
from superset.dashboards.commands.exceptions import DashboardNotFoundError
from superset.dashboards.commands.importers.v1.utils import find_chart_uuids
from superset.dashboards.dao import DashboardDAO
from superset.commands.export import ExportModelsCommand
from superset.datasets.commands.export import ExportDatasetsCommand
from superset.datasets.dao import DatasetDAO
from superset.models.dashboard import Dashboard
from superset.models.slice import Slice
from superset.utils.dict_import_export import EXPORT_VERSION
logger = logging.getLogger(__name__)
# keys stored as JSON are loaded and the prefix/suffix removed
JSON_KEYS = {"position_json": "position", "json_metadata": "metadata"}
DEFAULT_CHART_HEIGHT = 50
DEFAULT_CHART_WIDTH = 4
def suffix(length: int = 8) -> str:
return "".join(
random.SystemRandom().choice(string.ascii_uppercase + string.digits)
for _ in range(length)
)
def get_default_position(title: str) -> Dict[str, Any]:
return {
"DASHBOARD_VERSION_KEY": "v2",
"ROOT_ID": {"children": ["GRID_ID"], "id": "ROOT_ID", "type": "ROOT"},
"GRID_ID": {
"children": [],
"id": "GRID_ID",
"parents": ["ROOT_ID"],
"type": "GRID",
},
"HEADER_ID": {"id": "HEADER_ID", "meta": {"text": title}, "type": "HEADER"},
}
def append_charts(position: Dict[str, Any], charts: Set[Slice]) -> Dict[str, Any]:
chart_hashes = [f"CHART-{suffix()}" for _ in charts]
# if we have ROOT_ID/GRID_ID, append orphan charts to a new row inside the grid
row_hash = None
if "ROOT_ID" in position and "GRID_ID" in position["ROOT_ID"]["children"]:
row_hash = f"ROW-N-{suffix()}"
position["GRID_ID"]["children"].append(row_hash)
position[row_hash] = {
"children": chart_hashes,
"id": row_hash,
"meta": {"0": "ROOT_ID", "background": "BACKGROUND_TRANSPARENT"},
"type": "ROW",
"parents": ["ROOT_ID", "GRID_ID"],
}
for chart_hash, chart in zip(chart_hashes, charts):
position[chart_hash] = {
"children": [],
"id": chart_hash,
"meta": {
"chartId": chart.id,
"height": DEFAULT_CHART_HEIGHT,
"sliceName": chart.slice_name,
"uuid": str(chart.uuid),
"width": DEFAULT_CHART_WIDTH,
},
"type": "CHART",
}
if row_hash:
position[chart_hash]["parents"] = ["ROOT_ID", "GRID_ID", row_hash]
return position
class ExportDashboardsCommand(ExportModelsCommand):
dao = DashboardDAO
not_found = DashboardNotFoundError
@staticmethod
def _export(model: Dashboard) -> Iterator[Tuple[str, str]]:
dashboard_slug = secure_filename(model.dashboard_title)
file_name = f"dashboards/{dashboard_slug}.yaml"
payload = model.export_to_dict(
recursive=False,
include_parent_ref=False,
include_defaults=True,
export_uuids=True,
)
# TODO (betodealmeida): move this logic to export_to_dict once this
# becomes the default export endpoint
for key, new_name in JSON_KEYS.items():
value: Optional[str] = payload.pop(key, None)
if value:
try:
payload[new_name] = json.loads(value)
except (TypeError, json.decoder.JSONDecodeError):
logger.info("Unable to decode `%s` field: %s", key, value)
payload[new_name] = {}
# Extract all native filter datasets and replace native
# filter dataset references with uuid
for native_filter in payload.get("metadata", {}).get(
"native_filter_configuration", []
):
for target in native_filter.get("targets", []):
dataset_id = target.pop("datasetId", None)
if dataset_id is not None:
dataset = DatasetDAO.find_by_id(dataset_id)
target["datasetUuid"] = str(dataset.uuid)
yield from ExportDatasetsCommand([dataset_id]).run()
# the mapping between dashboard -> charts is inferred from the position
# attribute, so if it's not present we need to add a default config
if not payload.get("position"):
payload["position"] = get_default_position(model.dashboard_title)
# if any charts or not referenced in position, we need to add them
# in a new row
referenced_charts = find_chart_uuids(payload["position"])
orphan_charts = {
chart for chart in model.slices if str(chart.uuid) not in referenced_charts
}
if orphan_charts:
payload["position"] = append_charts(payload["position"], orphan_charts)
payload["version"] = EXPORT_VERSION
file_content = yaml.safe_dump(payload, sort_keys=False)
yield file_name, file_content
chart_ids = [chart.id for chart in model.slices]
yield from ExportChartsCommand(chart_ids).run()
| superset/dashboards/commands/export.py | 0 | https://github.com/apache/superset/commit/4051fda671b8b6d4b0a4f2ba8266d61cda73b916 | [
0.0003548794484231621,
0.00018996087601408362,
0.00016782963939476758,
0.00017476434004493058,
0.00004428221654961817
] |
{
"id": 5,
"code_window": [
" const {\n",
" height,\n",
" width,\n",
" rawFormData: formData,\n",
" queriesData = [],\n",
" initialValues: filters = {},\n",
" ownState: serverPaginationData = {},\n",
" hooks: { onAddFilter: onChangeFilter, setDataMask = () => {} },\n",
" } = chartProps;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" filterState,\n"
],
"file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/plugin-chart-table/src/transformProps.ts",
"type": "replace",
"edit_start_line_idx": 188
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import React, { CSSProperties, useCallback, useMemo, useState } from 'react';
import { ColumnInstance, ColumnWithLooseAccessor, DefaultSortTypes } from 'react-table';
import { extent as d3Extent, max as d3Max } from 'd3-array';
import { FaSort, FaSortDown as FaSortDesc, FaSortUp as FaSortAsc } from 'react-icons/fa';
import { DataRecord, DataRecordValue, GenericDataType, t, tn } from '@superset-ui/core';
import { DataColumnMeta, TableChartTransformedProps } from './types';
import DataTable, {
DataTableProps,
SearchInputProps,
SelectPageSizeRendererProps,
SizeOption,
} from './DataTable';
import Styles from './Styles';
import { formatColumnValue } from './utils/formatValue';
import { PAGE_SIZE_OPTIONS } from './consts';
import { updateExternalFormData } from './DataTable/utils/externalAPIs';
type ValueRange = [number, number];
/**
* Return sortType based on data type
*/
function getSortTypeByDataType(dataType: GenericDataType): DefaultSortTypes {
if (dataType === GenericDataType.TEMPORAL) {
return 'datetime';
}
if (dataType === GenericDataType.STRING) {
return 'alphanumeric';
}
return 'basic';
}
/**
* Cell background to render columns as horizontal bar chart
*/
function cellBar({
value,
valueRange,
colorPositiveNegative = false,
alignPositiveNegative,
}: {
value: number;
valueRange: ValueRange;
colorPositiveNegative: boolean;
alignPositiveNegative: boolean;
}) {
const [minValue, maxValue] = valueRange;
const r = colorPositiveNegative && value < 0 ? 150 : 0;
if (alignPositiveNegative) {
const perc = Math.abs(Math.round((value / maxValue) * 100));
// The 0.01 to 0.001 is a workaround for what appears to be a
// CSS rendering bug on flat, transparent colors
return (
`linear-gradient(to right, rgba(${r},0,0,0.2), rgba(${r},0,0,0.2) ${perc}%, ` +
`rgba(0,0,0,0.01) ${perc}%, rgba(0,0,0,0.001) 100%)`
);
}
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 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
return (
`linear-gradient(to right, rgba(0,0,0,0.01), rgba(0,0,0,0.001) ${perc1}%, ` +
`rgba(${r},0,0,0.2) ${perc1}%, rgba(${r},0,0,0.2) ${perc1 + perc2}%, ` +
`rgba(0,0,0,0.01) ${perc1 + perc2}%, rgba(0,0,0,0.001) 100%)`
);
}
function SortIcon<D extends object>({ column }: { column: ColumnInstance<D> }) {
const { isSorted, isSortedDesc } = column;
let sortIcon = <FaSort />;
if (isSorted) {
sortIcon = isSortedDesc ? <FaSortDesc /> : <FaSortAsc />;
}
return sortIcon;
}
function SearchInput({ count, value, onChange }: SearchInputProps) {
return (
<span className="dt-global-filter">
{t('Search')}{' '}
<input
className="form-control input-sm"
placeholder={tn('search.num_records', count)}
value={value}
onChange={onChange}
/>
</span>
);
}
function SelectPageSize({ options, current, onChange }: SelectPageSizeRendererProps) {
return (
<span className="dt-select-page-size form-inline">
{t('page_size.show')}{' '}
<select
className="form-control input-sm"
value={current}
onBlur={() => {}}
onChange={e => {
onChange(Number((e.target as HTMLSelectElement).value));
}}
>
{options.map(option => {
const [size, text] = Array.isArray(option) ? option : [option, option];
return (
<option key={size} value={size}>
{text}
</option>
);
})}
</select>{' '}
{t('page_size.entries')}
</span>
);
}
export default function TableChart<D extends DataRecord = DataRecord>(
props: TableChartTransformedProps<D> & {
sticky?: DataTableProps<D>['sticky'];
},
) {
const {
height,
width,
data,
totals,
isRawRecords,
rowCount = 0,
columns: columnsMeta,
alignPositiveNegative: defaultAlignPN = false,
colorPositiveNegative: defaultColorPN = false,
includeSearch = false,
pageSize = 0,
serverPagination = false,
serverPaginationData,
setDataMask,
showCellBars = true,
emitFilter = false,
sortDesc = false,
filters: initialFilters = {},
sticky = true, // whether to use sticky header
} = props;
const [filters, setFilters] = useState(initialFilters);
const handleChange = useCallback(
(filters: { [x: string]: DataRecordValue[] }) => {
if (!emitFilter) {
return;
}
const groupBy = Object.keys(filters);
const groupByValues = Object.values(filters);
setDataMask({
extraFormData: {
filters:
groupBy.length === 0
? []
: groupBy.map(col => {
const val = filters?.[col];
if (val === null || val === undefined)
return {
col,
op: 'IS NULL',
};
return {
col,
op: 'IN',
val: val as (string | number | boolean)[],
};
}),
},
filterState: {
value: groupByValues.length ? groupByValues : null,
},
});
},
[emitFilter, setDataMask],
);
// only take relevant page size options
const pageSizeOptions = useMemo(() => {
const getServerPagination = (n: number) => n <= rowCount;
return PAGE_SIZE_OPTIONS.filter(([n]) =>
serverPagination ? getServerPagination(n) : n <= 2 * data.length,
) as SizeOption[];
}, [data.length, rowCount, serverPagination]);
const getValueRange = useCallback(
function getValueRange(key: string, alignPositiveNegative: boolean) {
if (typeof data?.[0]?.[key] === 'number') {
const nums = data.map(row => row[key]) as number[];
return (alignPositiveNegative
? [0, d3Max(nums.map(Math.abs))]
: d3Extent(nums)) as ValueRange;
}
return null;
},
[data],
);
const isActiveFilterValue = useCallback(
function isActiveFilterValue(key: string, val: DataRecordValue) {
return !!filters && filters[key]?.includes(val);
},
[filters],
);
const toggleFilter = useCallback(
function toggleFilter(key: string, val: DataRecordValue) {
const updatedFilters = { ...(filters || {}) };
if (filters && isActiveFilterValue(key, val)) {
updatedFilters[key] = filters[key].filter((x: DataRecordValue) => x !== val);
} else {
updatedFilters[key] = [...(filters?.[key] || []), val];
}
if (Array.isArray(updatedFilters[key]) && updatedFilters[key].length === 0) {
delete updatedFilters[key];
}
setFilters(updatedFilters);
handleChange(updatedFilters);
},
[filters, handleChange, isActiveFilterValue],
);
const getSharedStyle = (column: DataColumnMeta): CSSProperties => {
const { isNumeric, config = {} } = column;
const textAlign = config.horizontalAlign
? config.horizontalAlign
: isNumeric
? 'right'
: 'left';
return {
textAlign,
};
};
const getColumnConfigs = useCallback(
(column: DataColumnMeta, i: number): ColumnWithLooseAccessor<D> => {
const { key, label, isNumeric, dataType, isMetric, config = {} } = column;
const isFilter = !isNumeric && emitFilter;
const columnWidth = Number.isNaN(Number(config.columnWidth))
? config.columnWidth
: Number(config.columnWidth);
// inline style for both th and td cell
const sharedStyle: CSSProperties = getSharedStyle(column);
const alignPositiveNegative =
config.alignPositiveNegative === undefined ? defaultAlignPN : config.alignPositiveNegative;
const colorPositiveNegative =
config.colorPositiveNegative === undefined ? defaultColorPN : config.colorPositiveNegative;
const valueRange =
(config.showCellBars === undefined ? showCellBars : config.showCellBars) &&
(isMetric || isRawRecords) &&
getValueRange(key, alignPositiveNegative);
let className = '';
if (isFilter) {
className += ' dt-is-filter';
}
return {
id: String(i), // to allow duplicate column keys
// must use custom accessor to allow `.` in column names
// typing is incorrect in current version of `@types/react-table`
// so we ask TS not to check.
accessor: ((datum: D) => datum[key]) as never,
Cell: ({ value }: { value: DataRecordValue }) => {
const [isHtml, text] = formatColumnValue(column, value);
const html = isHtml ? { __html: text } : undefined;
const cellProps = {
// show raw number in title in case of numeric values
title: typeof value === 'number' ? String(value) : undefined,
onClick: emitFilter && !valueRange ? () => toggleFilter(key, value) : undefined,
className: [
className,
value == null ? 'dt-is-null' : '',
isActiveFilterValue(key, value) ? ' dt-is-active-filter' : '',
].join(' '),
style: {
...sharedStyle,
background: valueRange
? cellBar({
value: value as number,
valueRange,
alignPositiveNegative,
colorPositiveNegative,
})
: undefined,
},
};
if (html) {
// eslint-disable-next-line react/no-danger
return <td {...cellProps} dangerouslySetInnerHTML={html} />;
}
// If cellProps renderes textContent already, then we don't have to
// render `Cell`. This saves some time for large tables.
return <td {...cellProps}>{text}</td>;
},
Header: ({ column: col, onClick, style }) => (
<th
title="Shift + Click to sort by multiple columns"
className={[className, col.isSorted ? 'is-sorted' : ''].join(' ')}
style={{
...sharedStyle,
...style,
}}
onClick={onClick}
>
{/* can't use `columnWidth &&` because it may also be zero */}
{config.columnWidth ? (
// column width hint
<div
style={{
width: columnWidth,
height: 0.01,
}}
/>
) : null}
{label}
<SortIcon column={col} />
</th>
),
Footer: totals ? (
i === 0 ? (
<th>{t('Totals')}</th>
) : (
<td style={sharedStyle}>
<strong>{formatColumnValue(column, totals[key])[1]}</strong>
</td>
)
) : undefined,
sortDescFirst: sortDesc,
sortType: getSortTypeByDataType(dataType),
};
},
[
defaultAlignPN,
defaultColorPN,
emitFilter,
getValueRange,
isActiveFilterValue,
isRawRecords,
showCellBars,
sortDesc,
toggleFilter,
totals,
],
);
const columns = useMemo(() => columnsMeta.map(getColumnConfigs), [columnsMeta, getColumnConfigs]);
const handleServerPaginationChange = (pageNumber: number, pageSize: number) => {
updateExternalFormData(setDataMask, pageNumber, pageSize);
};
return (
<Styles>
<DataTable<D>
columns={columns}
data={data}
rowCount={rowCount}
tableClassName="table table-striped table-condensed"
pageSize={pageSize}
serverPaginationData={serverPaginationData}
pageSizeOptions={pageSizeOptions}
width={width}
height={height}
serverPagination={serverPagination}
onServerPaginationChange={handleServerPaginationChange}
// 9 page items in > 340px works well even for 100+ pages
maxPageItemCount={width > 340 ? 9 : 7}
noResults={(filter: string) => t(filter ? 'No matching records found' : 'No records found')}
searchInput={includeSearch && SearchInput}
selectPageSize={pageSize !== null && SelectPageSize}
// not in use in Superset, but needed for unit tests
sticky={sticky}
/>
</Styles>
);
}
| superset-frontend/temporary_superset_ui/superset-ui/plugins/plugin-chart-table/src/TableChart.tsx | 1 | https://github.com/apache/superset/commit/4051fda671b8b6d4b0a4f2ba8266d61cda73b916 | [
0.9984108209609985,
0.13634155690670013,
0.00016590251470915973,
0.00017399515490978956,
0.3288304805755615
] |
{
"id": 5,
"code_window": [
" const {\n",
" height,\n",
" width,\n",
" rawFormData: formData,\n",
" queriesData = [],\n",
" initialValues: filters = {},\n",
" ownState: serverPaginationData = {},\n",
" hooks: { onAddFilter: onChangeFilter, setDataMask = () => {} },\n",
" } = chartProps;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" filterState,\n"
],
"file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/plugin-chart-table/src/transformProps.ts",
"type": "replace",
"edit_start_line_idx": 188
} | # -*- coding: utf-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
| superset/tasks/__init__.py | 0 | https://github.com/apache/superset/commit/4051fda671b8b6d4b0a4f2ba8266d61cda73b916 | [
0.00017847062554210424,
0.00017742790805641562,
0.000176385190570727,
0.00017742790805641562,
0.0000010427174856886268
] |
{
"id": 5,
"code_window": [
" const {\n",
" height,\n",
" width,\n",
" rawFormData: formData,\n",
" queriesData = [],\n",
" initialValues: filters = {},\n",
" ownState: serverPaginationData = {},\n",
" hooks: { onAddFilter: onChangeFilter, setDataMask = () => {} },\n",
" } = chartProps;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" filterState,\n"
],
"file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/plugin-chart-table/src/transformProps.ts",
"type": "replace",
"edit_start_line_idx": 188
} | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# isort:skip_file
"""Unit tests for Superset"""
from unittest import mock
import pytest
from marshmallow import ValidationError
from tests.integration_tests.test_app import app
from superset.charts.schemas import ChartDataQueryContextSchema
from tests.integration_tests.base_tests import SupersetTestCase
from tests.integration_tests.fixtures.birth_names_dashboard import (
load_birth_names_dashboard_with_slices,
)
from tests.integration_tests.fixtures.query_context import get_query_context
class TestSchema(SupersetTestCase):
@mock.patch(
"superset.common.query_context_factory.config",
{**app.config, "ROW_LIMIT": 5000},
)
@pytest.mark.usefixtures("load_birth_names_dashboard_with_slices")
def test_query_context_limit_and_offset(self):
self.login(username="admin")
payload = get_query_context("birth_names")
# too low limit and offset
payload["queries"][0]["row_limit"] = -1
payload["queries"][0]["row_offset"] = -1
with self.assertRaises(ValidationError) as context:
_ = ChartDataQueryContextSchema().load(payload)
self.assertIn("row_limit", context.exception.messages["queries"][0])
self.assertIn("row_offset", context.exception.messages["queries"][0])
@pytest.mark.usefixtures("load_birth_names_dashboard_with_slices")
def test_query_context_null_timegrain(self):
self.login(username="admin")
payload = get_query_context("birth_names")
payload["queries"][0]["extras"]["time_grain_sqla"] = None
_ = ChartDataQueryContextSchema().load(payload)
@pytest.mark.usefixtures("load_birth_names_dashboard_with_slices")
def test_query_context_series_limit(self):
self.login(username="admin")
payload = get_query_context("birth_names")
payload["queries"][0]["timeseries_limit"] = 2
payload["queries"][0]["timeseries_limit_metric"] = {
"expressionType": "SIMPLE",
"column": {
"id": 334,
"column_name": "gender",
"filterable": True,
"groupby": True,
"is_dttm": False,
"type": "VARCHAR(16)",
"optionName": "_col_gender",
},
"aggregate": "COUNT_DISTINCT",
"label": "COUNT_DISTINCT(gender)",
}
_ = ChartDataQueryContextSchema().load(payload)
| tests/integration_tests/charts/schema_tests.py | 0 | https://github.com/apache/superset/commit/4051fda671b8b6d4b0a4f2ba8266d61cda73b916 | [
0.0001770009839674458,
0.0001713637902867049,
0.000166381272720173,
0.00017080754332710057,
0.0000037111446999915643
] |
{
"id": 5,
"code_window": [
" const {\n",
" height,\n",
" width,\n",
" rawFormData: formData,\n",
" queriesData = [],\n",
" initialValues: filters = {},\n",
" ownState: serverPaginationData = {},\n",
" hooks: { onAddFilter: onChangeFilter, setDataMask = () => {} },\n",
" } = chartProps;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" filterState,\n"
],
"file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/plugin-chart-table/src/transformProps.ts",
"type": "replace",
"edit_start_line_idx": 188
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { User } from 'src/types/bootstrapTypes';
import Database from 'src/types/Database';
import Owner from 'src/types/Owner';
export type FavoriteStatus = {
[id: number]: boolean;
};
export enum TableTabTypes {
FAVORITE = 'Favorite',
MINE = 'Mine',
EXAMPLES = 'Examples',
}
export type Filters = {
col: string;
opr: string;
value: string | number;
};
export interface DashboardTableProps {
addDangerToast: (message: string) => void;
addSuccessToast: (message: string) => void;
search: string;
user?: User;
mine: Array<Dashboard>;
showThumbnails?: boolean;
featureFlag?: boolean;
examples: Array<Dashboard>;
}
export interface Dashboard {
certified_by?: string;
certification_details?: string;
changed_by_name: string;
changed_by_url: string;
changed_on_delta_humanized?: string;
changed_on_utc?: string;
changed_by: string;
dashboard_title: string;
slice_name?: string;
id: number;
published: boolean;
url: string;
thumbnail_url: string;
owners: Owner[];
loading?: boolean;
}
export type SavedQueryObject = {
id: number;
changed_on: string;
changed_on_delta_humanized: string;
database: {
database_name: string;
id: number;
};
db_id: number;
description?: string;
label: string;
schema: string;
sql: string | null;
sql_tables?: { catalog?: string; schema: string; table: string }[];
};
export interface QueryObject {
id: number;
changed_on: string;
database: {
database_name: string;
};
schema: string;
sql: string;
executed_sql: string | null;
sql_tables?: { catalog?: string; schema: string; table: string }[];
status:
| 'success'
| 'failed'
| 'stopped'
| 'running'
| 'timed_out'
| 'scheduled'
| 'pending';
tab_name: string;
user: {
first_name: string;
id: number;
last_name: string;
username: string;
};
start_time: number;
end_time: number;
rows: number;
tmp_table_name: string;
tracking_url: string;
}
export enum QueryObjectColumns {
id = 'id',
changed_on = 'changed_on',
database = 'database',
database_name = 'database.database_name',
schema = 'schema',
sql = 'sql',
executed_sql = 'exceuted_sql',
sql_tables = 'sql_tables',
status = 'status',
tab_name = 'tab_name',
user = 'user',
user_first_name = 'user.first_name',
start_time = 'start_time',
end_time = 'end_time',
rows = 'rows',
tmp_table_name = 'tmp_table_name',
tracking_url = 'tracking_url',
}
export type ImportResourceName =
| 'chart'
| 'dashboard'
| 'database'
| 'dataset'
| 'saved_query';
export type DatabaseObject = Partial<Database> &
Pick<Database, 'sqlalchemy_uri'>;
| superset-frontend/src/views/CRUD/types.ts | 0 | https://github.com/apache/superset/commit/4051fda671b8b6d4b0a4f2ba8266d61cda73b916 | [
0.0025574236642569304,
0.0003310780448373407,
0.00016771380614954978,
0.00017219613073393703,
0.0005950215854682028
] |
{
"id": 6,
"code_window": [
" includeSearch,\n",
" rowCount,\n",
" pageSize: serverPagination\n",
" ? serverPageLength\n",
" : getPageSize(pageLength, data.length, columns.length),\n",
" filters,\n",
" emitFilter: tableFilter,\n",
" onChangeFilter,\n",
" };\n",
"};\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" filters: filterState.filters,\n"
],
"file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/plugin-chart-table/src/transformProps.ts",
"type": "replace",
"edit_start_line_idx": 244
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import React, { CSSProperties, useCallback, useMemo, useState } from 'react';
import { ColumnInstance, ColumnWithLooseAccessor, DefaultSortTypes } from 'react-table';
import { extent as d3Extent, max as d3Max } from 'd3-array';
import { FaSort, FaSortDown as FaSortDesc, FaSortUp as FaSortAsc } from 'react-icons/fa';
import { DataRecord, DataRecordValue, GenericDataType, t, tn } from '@superset-ui/core';
import { DataColumnMeta, TableChartTransformedProps } from './types';
import DataTable, {
DataTableProps,
SearchInputProps,
SelectPageSizeRendererProps,
SizeOption,
} from './DataTable';
import Styles from './Styles';
import { formatColumnValue } from './utils/formatValue';
import { PAGE_SIZE_OPTIONS } from './consts';
import { updateExternalFormData } from './DataTable/utils/externalAPIs';
type ValueRange = [number, number];
/**
* Return sortType based on data type
*/
function getSortTypeByDataType(dataType: GenericDataType): DefaultSortTypes {
if (dataType === GenericDataType.TEMPORAL) {
return 'datetime';
}
if (dataType === GenericDataType.STRING) {
return 'alphanumeric';
}
return 'basic';
}
/**
* Cell background to render columns as horizontal bar chart
*/
function cellBar({
value,
valueRange,
colorPositiveNegative = false,
alignPositiveNegative,
}: {
value: number;
valueRange: ValueRange;
colorPositiveNegative: boolean;
alignPositiveNegative: boolean;
}) {
const [minValue, maxValue] = valueRange;
const r = colorPositiveNegative && value < 0 ? 150 : 0;
if (alignPositiveNegative) {
const perc = Math.abs(Math.round((value / maxValue) * 100));
// The 0.01 to 0.001 is a workaround for what appears to be a
// CSS rendering bug on flat, transparent colors
return (
`linear-gradient(to right, rgba(${r},0,0,0.2), rgba(${r},0,0,0.2) ${perc}%, ` +
`rgba(0,0,0,0.01) ${perc}%, rgba(0,0,0,0.001) 100%)`
);
}
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 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
return (
`linear-gradient(to right, rgba(0,0,0,0.01), rgba(0,0,0,0.001) ${perc1}%, ` +
`rgba(${r},0,0,0.2) ${perc1}%, rgba(${r},0,0,0.2) ${perc1 + perc2}%, ` +
`rgba(0,0,0,0.01) ${perc1 + perc2}%, rgba(0,0,0,0.001) 100%)`
);
}
function SortIcon<D extends object>({ column }: { column: ColumnInstance<D> }) {
const { isSorted, isSortedDesc } = column;
let sortIcon = <FaSort />;
if (isSorted) {
sortIcon = isSortedDesc ? <FaSortDesc /> : <FaSortAsc />;
}
return sortIcon;
}
function SearchInput({ count, value, onChange }: SearchInputProps) {
return (
<span className="dt-global-filter">
{t('Search')}{' '}
<input
className="form-control input-sm"
placeholder={tn('search.num_records', count)}
value={value}
onChange={onChange}
/>
</span>
);
}
function SelectPageSize({ options, current, onChange }: SelectPageSizeRendererProps) {
return (
<span className="dt-select-page-size form-inline">
{t('page_size.show')}{' '}
<select
className="form-control input-sm"
value={current}
onBlur={() => {}}
onChange={e => {
onChange(Number((e.target as HTMLSelectElement).value));
}}
>
{options.map(option => {
const [size, text] = Array.isArray(option) ? option : [option, option];
return (
<option key={size} value={size}>
{text}
</option>
);
})}
</select>{' '}
{t('page_size.entries')}
</span>
);
}
export default function TableChart<D extends DataRecord = DataRecord>(
props: TableChartTransformedProps<D> & {
sticky?: DataTableProps<D>['sticky'];
},
) {
const {
height,
width,
data,
totals,
isRawRecords,
rowCount = 0,
columns: columnsMeta,
alignPositiveNegative: defaultAlignPN = false,
colorPositiveNegative: defaultColorPN = false,
includeSearch = false,
pageSize = 0,
serverPagination = false,
serverPaginationData,
setDataMask,
showCellBars = true,
emitFilter = false,
sortDesc = false,
filters: initialFilters = {},
sticky = true, // whether to use sticky header
} = props;
const [filters, setFilters] = useState(initialFilters);
const handleChange = useCallback(
(filters: { [x: string]: DataRecordValue[] }) => {
if (!emitFilter) {
return;
}
const groupBy = Object.keys(filters);
const groupByValues = Object.values(filters);
setDataMask({
extraFormData: {
filters:
groupBy.length === 0
? []
: groupBy.map(col => {
const val = filters?.[col];
if (val === null || val === undefined)
return {
col,
op: 'IS NULL',
};
return {
col,
op: 'IN',
val: val as (string | number | boolean)[],
};
}),
},
filterState: {
value: groupByValues.length ? groupByValues : null,
},
});
},
[emitFilter, setDataMask],
);
// only take relevant page size options
const pageSizeOptions = useMemo(() => {
const getServerPagination = (n: number) => n <= rowCount;
return PAGE_SIZE_OPTIONS.filter(([n]) =>
serverPagination ? getServerPagination(n) : n <= 2 * data.length,
) as SizeOption[];
}, [data.length, rowCount, serverPagination]);
const getValueRange = useCallback(
function getValueRange(key: string, alignPositiveNegative: boolean) {
if (typeof data?.[0]?.[key] === 'number') {
const nums = data.map(row => row[key]) as number[];
return (alignPositiveNegative
? [0, d3Max(nums.map(Math.abs))]
: d3Extent(nums)) as ValueRange;
}
return null;
},
[data],
);
const isActiveFilterValue = useCallback(
function isActiveFilterValue(key: string, val: DataRecordValue) {
return !!filters && filters[key]?.includes(val);
},
[filters],
);
const toggleFilter = useCallback(
function toggleFilter(key: string, val: DataRecordValue) {
const updatedFilters = { ...(filters || {}) };
if (filters && isActiveFilterValue(key, val)) {
updatedFilters[key] = filters[key].filter((x: DataRecordValue) => x !== val);
} else {
updatedFilters[key] = [...(filters?.[key] || []), val];
}
if (Array.isArray(updatedFilters[key]) && updatedFilters[key].length === 0) {
delete updatedFilters[key];
}
setFilters(updatedFilters);
handleChange(updatedFilters);
},
[filters, handleChange, isActiveFilterValue],
);
const getSharedStyle = (column: DataColumnMeta): CSSProperties => {
const { isNumeric, config = {} } = column;
const textAlign = config.horizontalAlign
? config.horizontalAlign
: isNumeric
? 'right'
: 'left';
return {
textAlign,
};
};
const getColumnConfigs = useCallback(
(column: DataColumnMeta, i: number): ColumnWithLooseAccessor<D> => {
const { key, label, isNumeric, dataType, isMetric, config = {} } = column;
const isFilter = !isNumeric && emitFilter;
const columnWidth = Number.isNaN(Number(config.columnWidth))
? config.columnWidth
: Number(config.columnWidth);
// inline style for both th and td cell
const sharedStyle: CSSProperties = getSharedStyle(column);
const alignPositiveNegative =
config.alignPositiveNegative === undefined ? defaultAlignPN : config.alignPositiveNegative;
const colorPositiveNegative =
config.colorPositiveNegative === undefined ? defaultColorPN : config.colorPositiveNegative;
const valueRange =
(config.showCellBars === undefined ? showCellBars : config.showCellBars) &&
(isMetric || isRawRecords) &&
getValueRange(key, alignPositiveNegative);
let className = '';
if (isFilter) {
className += ' dt-is-filter';
}
return {
id: String(i), // to allow duplicate column keys
// must use custom accessor to allow `.` in column names
// typing is incorrect in current version of `@types/react-table`
// so we ask TS not to check.
accessor: ((datum: D) => datum[key]) as never,
Cell: ({ value }: { value: DataRecordValue }) => {
const [isHtml, text] = formatColumnValue(column, value);
const html = isHtml ? { __html: text } : undefined;
const cellProps = {
// show raw number in title in case of numeric values
title: typeof value === 'number' ? String(value) : undefined,
onClick: emitFilter && !valueRange ? () => toggleFilter(key, value) : undefined,
className: [
className,
value == null ? 'dt-is-null' : '',
isActiveFilterValue(key, value) ? ' dt-is-active-filter' : '',
].join(' '),
style: {
...sharedStyle,
background: valueRange
? cellBar({
value: value as number,
valueRange,
alignPositiveNegative,
colorPositiveNegative,
})
: undefined,
},
};
if (html) {
// eslint-disable-next-line react/no-danger
return <td {...cellProps} dangerouslySetInnerHTML={html} />;
}
// If cellProps renderes textContent already, then we don't have to
// render `Cell`. This saves some time for large tables.
return <td {...cellProps}>{text}</td>;
},
Header: ({ column: col, onClick, style }) => (
<th
title="Shift + Click to sort by multiple columns"
className={[className, col.isSorted ? 'is-sorted' : ''].join(' ')}
style={{
...sharedStyle,
...style,
}}
onClick={onClick}
>
{/* can't use `columnWidth &&` because it may also be zero */}
{config.columnWidth ? (
// column width hint
<div
style={{
width: columnWidth,
height: 0.01,
}}
/>
) : null}
{label}
<SortIcon column={col} />
</th>
),
Footer: totals ? (
i === 0 ? (
<th>{t('Totals')}</th>
) : (
<td style={sharedStyle}>
<strong>{formatColumnValue(column, totals[key])[1]}</strong>
</td>
)
) : undefined,
sortDescFirst: sortDesc,
sortType: getSortTypeByDataType(dataType),
};
},
[
defaultAlignPN,
defaultColorPN,
emitFilter,
getValueRange,
isActiveFilterValue,
isRawRecords,
showCellBars,
sortDesc,
toggleFilter,
totals,
],
);
const columns = useMemo(() => columnsMeta.map(getColumnConfigs), [columnsMeta, getColumnConfigs]);
const handleServerPaginationChange = (pageNumber: number, pageSize: number) => {
updateExternalFormData(setDataMask, pageNumber, pageSize);
};
return (
<Styles>
<DataTable<D>
columns={columns}
data={data}
rowCount={rowCount}
tableClassName="table table-striped table-condensed"
pageSize={pageSize}
serverPaginationData={serverPaginationData}
pageSizeOptions={pageSizeOptions}
width={width}
height={height}
serverPagination={serverPagination}
onServerPaginationChange={handleServerPaginationChange}
// 9 page items in > 340px works well even for 100+ pages
maxPageItemCount={width > 340 ? 9 : 7}
noResults={(filter: string) => t(filter ? 'No matching records found' : 'No records found')}
searchInput={includeSearch && SearchInput}
selectPageSize={pageSize !== null && SelectPageSize}
// not in use in Superset, but needed for unit tests
sticky={sticky}
/>
</Styles>
);
}
| superset-frontend/temporary_superset_ui/superset-ui/plugins/plugin-chart-table/src/TableChart.tsx | 1 | https://github.com/apache/superset/commit/4051fda671b8b6d4b0a4f2ba8266d61cda73b916 | [
0.08283797651529312,
0.003575481940060854,
0.00016411140677519143,
0.00017787551041692495,
0.0129896504804492
] |
{
"id": 6,
"code_window": [
" includeSearch,\n",
" rowCount,\n",
" pageSize: serverPagination\n",
" ? serverPageLength\n",
" : getPageSize(pageLength, data.length, columns.length),\n",
" filters,\n",
" emitFilter: tableFilter,\n",
" onChangeFilter,\n",
" };\n",
"};\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" filters: filterState.filters,\n"
],
"file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/plugin-chart-table/src/transformProps.ts",
"type": "replace",
"edit_start_line_idx": 244
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { ChartDataResponseResult } from '../../types';
export interface LegacyChartDataResponse extends Omit<ChartDataResponseResult, 'data'> {
data: Record<string, unknown>[] | Record<string, unknown>;
}
export default {};
| superset-frontend/temporary_superset_ui/superset-ui/packages/superset-ui-core/src/query/api/legacy/types.ts | 0 | https://github.com/apache/superset/commit/4051fda671b8b6d4b0a4f2ba8266d61cda73b916 | [
0.00021505579934455454,
0.0001892204600153491,
0.00017628548084758222,
0.00017632011440582573,
0.000018268345229444094
] |
{
"id": 6,
"code_window": [
" includeSearch,\n",
" rowCount,\n",
" pageSize: serverPagination\n",
" ? serverPageLength\n",
" : getPageSize(pageLength, data.length, columns.length),\n",
" filters,\n",
" emitFilter: tableFilter,\n",
" onChangeFilter,\n",
" };\n",
"};\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" filters: filterState.filters,\n"
],
"file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/plugin-chart-table/src/transformProps.ts",
"type": "replace",
"edit_start_line_idx": 244
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import shortid from 'shortid';
import { find, isEmpty } from 'lodash';
import {
Filter,
NativeFilterType,
} from 'src/dashboard/components/nativeFilters/types';
import {
FILTER_CONFIG_ATTRIBUTES,
TIME_FILTER_LABELS,
TIME_FILTER_MAP,
} from 'src/explore/constants';
import { DASHBOARD_FILTER_SCOPE_GLOBAL } from 'src/dashboard/reducers/dashboardFilters';
import { TimeGranularity } from '@superset-ui/core';
import { getChartIdsInFilterScope } from './activeDashboardFilters';
import getFilterConfigsFromFormdata from './getFilterConfigsFromFormdata';
interface FilterConfig {
asc: boolean;
clearable: boolean;
column: string;
defaultValue?: any;
key: string;
label?: string;
metric: string;
multiple: boolean;
}
interface SliceData {
slice_id: number;
form_data: {
adhoc_filters?: [];
datasource: string;
date_filter?: boolean;
filter_configs?: FilterConfig[];
granularity?: string;
granularity_sqla?: string;
time_grain_sqla?: string;
time_range?: string;
druid_time_origin?: string;
show_druid_time_granularity?: boolean;
show_druid_time_origin?: boolean;
show_sqla_time_column?: boolean;
show_sqla_time_granularity?: boolean;
viz_type: string;
};
}
interface FilterScopeType {
scope: string[];
immune: number[];
}
interface FilterScopesMetadata {
[key: string]: {
[key: string]: FilterScopeType;
};
}
interface PreselectedFilterColumn {
[key: string]: boolean | string | number | string[] | number[];
}
interface PreselectedFiltersMeatadata {
[key: string]: PreselectedFilterColumn;
}
interface FilterBoxToFilterComponentMap {
[key: string]: {
[key: string]: string;
};
}
interface FilterBoxDependencyMap {
[key: string]: {
[key: string]: number[];
};
}
enum FILTER_COMPONENT_FILTER_TYPES {
FILTER_TIME = 'filter_time',
FILTER_TIMEGRAIN = 'filter_timegrain',
FILTER_TIMECOLUMN = 'filter_timecolumn',
FILTER_SELECT = 'filter_select',
FILTER_RANGE = 'filter_range',
}
const getPreselectedValuesFromDashboard =
(preselectedFilters: PreselectedFiltersMeatadata) =>
(filterKey: string, column: string) => {
if (
preselectedFilters[filterKey] &&
preselectedFilters[filterKey][column]
) {
// overwrite default values by dashboard default_filters
return preselectedFilters[filterKey][column];
}
return null;
};
const getFilterBoxDefaultValues = (config: FilterConfig) => {
let defaultValues = config[FILTER_CONFIG_ATTRIBUTES.DEFAULT_VALUE];
// treat empty string as null (no default value)
if (defaultValues === '') {
defaultValues = null;
}
// defaultValue could be ; separated values,
// could be null or ''
if (defaultValues && config[FILTER_CONFIG_ATTRIBUTES.MULTIPLE]) {
defaultValues = config.defaultValue.split(';');
}
return defaultValues;
};
const setValuesInArray = (value1: any, value2: any) => {
if (!isEmpty(value1)) {
return [value1];
}
if (!isEmpty(value2)) {
return [value2];
}
return [];
};
const getFilterboxDependencies = (filterScopes: FilterScopesMetadata) => {
const filterFieldsDependencies: FilterBoxDependencyMap = {};
const filterChartIds: number[] = Object.keys(filterScopes).map(key =>
parseInt(key, 10),
);
Object.entries(filterScopes).forEach(([key, filterFields]) => {
filterFieldsDependencies[key] = {};
Object.entries(filterFields).forEach(([filterField, filterScope]) => {
filterFieldsDependencies[key][filterField] = getChartIdsInFilterScope({
filterScope,
}).filter(
chartId => filterChartIds.includes(chartId) && String(chartId) !== key,
);
});
});
return filterFieldsDependencies;
};
export default function getNativeFilterConfig(
chartData: SliceData[] = [],
filterScopes: FilterScopesMetadata = {},
preselectFilters: PreselectedFiltersMeatadata = {},
): Filter[] {
const filterConfig: Filter[] = [];
const filterBoxToFilterComponentMap: FilterBoxToFilterComponentMap = {};
chartData.forEach(slice => {
const key = String(slice.slice_id);
if (slice.form_data.viz_type === 'filter_box') {
filterBoxToFilterComponentMap[key] = {};
const configs = getFilterConfigsFromFormdata(slice.form_data);
let { columns } = configs;
if (preselectFilters[key]) {
Object.keys(columns).forEach(col => {
if (preselectFilters[key][col]) {
columns = {
...columns,
[col]: preselectFilters[key][col],
};
}
});
}
const scopesByChartId = Object.keys(columns).reduce((map, column) => {
const scopeSettings = {
...filterScopes[key],
};
const { scope, immune }: FilterScopeType = {
...DASHBOARD_FILTER_SCOPE_GLOBAL,
...scopeSettings[column],
};
return {
...map,
[column]: {
scope,
immune,
},
};
}, {});
const {
adhoc_filters = [],
datasource = '',
date_filter = false,
druid_time_origin,
filter_configs = [],
granularity,
granularity_sqla,
show_druid_time_granularity = false,
show_druid_time_origin = false,
show_sqla_time_column = false,
show_sqla_time_granularity = false,
time_grain_sqla,
time_range,
} = slice.form_data;
const getDashboardDefaultValues =
getPreselectedValuesFromDashboard(preselectFilters);
if (date_filter) {
const { scope, immune }: FilterScopeType =
scopesByChartId[TIME_FILTER_MAP.time_range] ||
DASHBOARD_FILTER_SCOPE_GLOBAL;
const timeRangeFilter: Filter = {
id: `NATIVE_FILTER-${shortid.generate()}`,
description: 'time range filter',
controlValues: {},
name: TIME_FILTER_LABELS.time_range,
filterType: FILTER_COMPONENT_FILTER_TYPES.FILTER_TIME,
targets: [{}],
cascadeParentIds: [],
defaultDataMask: {},
type: NativeFilterType.NATIVE_FILTER,
scope: {
rootPath: scope,
excluded: immune,
},
};
filterBoxToFilterComponentMap[key][TIME_FILTER_MAP.time_range] =
timeRangeFilter.id;
const dashboardDefaultValues =
getDashboardDefaultValues(key, TIME_FILTER_MAP.time_range) ||
time_range;
if (!isEmpty(dashboardDefaultValues)) {
timeRangeFilter.defaultDataMask = {
extraFormData: { time_range: dashboardDefaultValues as string },
filterState: { value: dashboardDefaultValues },
};
}
filterConfig.push(timeRangeFilter);
if (show_sqla_time_granularity) {
const { scope, immune }: FilterScopeType =
scopesByChartId[TIME_FILTER_MAP.time_grain_sqla] ||
DASHBOARD_FILTER_SCOPE_GLOBAL;
const timeGrainFilter: Filter = {
id: `NATIVE_FILTER-${shortid.generate()}`,
controlValues: {},
description: 'time grain filter',
name: TIME_FILTER_LABELS.time_grain_sqla,
filterType: FILTER_COMPONENT_FILTER_TYPES.FILTER_TIMEGRAIN,
targets: [
{
datasetId: parseInt(datasource.split('__')[0], 10),
},
],
cascadeParentIds: [],
defaultDataMask: {},
type: NativeFilterType.NATIVE_FILTER,
scope: {
rootPath: scope,
excluded: immune,
},
};
filterBoxToFilterComponentMap[key][TIME_FILTER_MAP.time_grain_sqla] =
timeGrainFilter.id;
const dashboardDefaultValues = getDashboardDefaultValues(
key,
TIME_FILTER_MAP.time_grain_sqla,
);
if (!isEmpty(dashboardDefaultValues)) {
timeGrainFilter.defaultDataMask = {
extraFormData: {
time_grain_sqla: (dashboardDefaultValues ||
time_grain_sqla) as TimeGranularity,
},
filterState: {
value: setValuesInArray(
dashboardDefaultValues,
time_grain_sqla,
),
},
};
}
filterConfig.push(timeGrainFilter);
}
if (show_sqla_time_column) {
const { scope, immune }: FilterScopeType =
scopesByChartId[TIME_FILTER_MAP.granularity_sqla] ||
DASHBOARD_FILTER_SCOPE_GLOBAL;
const timeColumnFilter: Filter = {
id: `NATIVE_FILTER-${shortid.generate()}`,
description: 'time column filter',
controlValues: {},
name: TIME_FILTER_LABELS.granularity_sqla,
filterType: FILTER_COMPONENT_FILTER_TYPES.FILTER_TIMECOLUMN,
targets: [
{
datasetId: parseInt(datasource.split('__')[0], 10),
},
],
cascadeParentIds: [],
defaultDataMask: {},
type: NativeFilterType.NATIVE_FILTER,
scope: {
rootPath: scope,
excluded: immune,
},
};
filterBoxToFilterComponentMap[key][TIME_FILTER_MAP.granularity_sqla] =
timeColumnFilter.id;
const dashboardDefaultValues = getDashboardDefaultValues(
key,
TIME_FILTER_MAP.granularity_sqla,
);
if (!isEmpty(dashboardDefaultValues)) {
timeColumnFilter.defaultDataMask = {
extraFormData: {
granularity_sqla: (dashboardDefaultValues ||
granularity_sqla) as string,
},
filterState: {
value: setValuesInArray(
dashboardDefaultValues,
granularity_sqla,
),
},
};
}
filterConfig.push(timeColumnFilter);
}
if (show_druid_time_granularity) {
const { scope, immune }: FilterScopeType =
scopesByChartId[TIME_FILTER_MAP.granularity] ||
DASHBOARD_FILTER_SCOPE_GLOBAL;
const druidGranularityFilter: Filter = {
id: `NATIVE_FILTER-${shortid.generate()}`,
description: 'time grain filter',
controlValues: {},
name: TIME_FILTER_LABELS.granularity,
filterType: FILTER_COMPONENT_FILTER_TYPES.FILTER_TIMEGRAIN,
targets: [
{
datasetId: parseInt(datasource.split('__')[0], 10),
},
],
cascadeParentIds: [],
defaultDataMask: {},
type: NativeFilterType.NATIVE_FILTER,
scope: {
rootPath: scope,
excluded: immune,
},
};
filterBoxToFilterComponentMap[key][TIME_FILTER_MAP.granularity] =
druidGranularityFilter.id;
const dashboardDefaultValues = getDashboardDefaultValues(
key,
TIME_FILTER_MAP.granularity,
);
if (!isEmpty(dashboardDefaultValues)) {
druidGranularityFilter.defaultDataMask = {
extraFormData: {
granularity_sqla: (dashboardDefaultValues ||
granularity) as string,
},
filterState: {
value: setValuesInArray(dashboardDefaultValues, granularity),
},
};
}
filterConfig.push(druidGranularityFilter);
}
if (show_druid_time_origin) {
const { scope, immune }: FilterScopeType =
scopesByChartId[TIME_FILTER_MAP.druid_time_origin] ||
DASHBOARD_FILTER_SCOPE_GLOBAL;
const druidOriginFilter: Filter = {
id: `NATIVE_FILTER-${shortid.generate()}`,
description: 'time column filter',
controlValues: {},
name: TIME_FILTER_LABELS.druid_time_origin,
filterType: FILTER_COMPONENT_FILTER_TYPES.FILTER_TIMECOLUMN,
targets: [
{
datasetId: parseInt(datasource.split('__')[0], 10),
},
],
cascadeParentIds: [],
defaultDataMask: {},
type: NativeFilterType.NATIVE_FILTER,
scope: {
rootPath: scope,
excluded: immune,
},
};
filterBoxToFilterComponentMap[key][
TIME_FILTER_MAP.druid_time_origin
] = druidOriginFilter.id;
const dashboardDefaultValues = getDashboardDefaultValues(
key,
TIME_FILTER_MAP.druid_time_origin,
);
if (!isEmpty(dashboardDefaultValues)) {
druidOriginFilter.defaultDataMask = {
extraFormData: {
granularity_sqla: (dashboardDefaultValues ||
druid_time_origin) as string,
},
filterState: {
value: setValuesInArray(
dashboardDefaultValues,
druid_time_origin,
),
},
};
}
filterConfig.push(druidOriginFilter);
}
}
filter_configs.forEach(config => {
const { scope, immune }: FilterScopeType =
scopesByChartId[config.column] || DASHBOARD_FILTER_SCOPE_GLOBAL;
const entry: Filter = {
id: `NATIVE_FILTER-${shortid.generate()}`,
description: '',
controlValues: {
enableEmptyFilter: !config[FILTER_CONFIG_ATTRIBUTES.CLEARABLE],
defaultToFirstItem: false,
inverseSelection: false,
multiSelect: config[FILTER_CONFIG_ATTRIBUTES.MULTIPLE],
sortAscending: config[FILTER_CONFIG_ATTRIBUTES.SORT_ASCENDING],
},
name: config.label || config.column,
filterType: FILTER_COMPONENT_FILTER_TYPES.FILTER_SELECT,
targets: [
{
datasetId: parseInt(datasource.split('__')[0], 10),
column: {
name: config.column,
},
},
],
cascadeParentIds: [],
defaultDataMask: {},
type: NativeFilterType.NATIVE_FILTER,
scope: {
rootPath: scope,
excluded: immune,
},
adhoc_filters,
sortMetric: config[FILTER_CONFIG_ATTRIBUTES.SORT_METRIC],
time_range,
};
filterBoxToFilterComponentMap[key][config.column] = entry.id;
const defaultValues =
getDashboardDefaultValues(key, config.column) ||
getFilterBoxDefaultValues(config);
if (!isEmpty(defaultValues)) {
entry.defaultDataMask = {
extraFormData: {
filters: [{ col: config.column, op: 'IN', val: defaultValues }],
},
filterState: { value: defaultValues },
};
}
filterConfig.push(entry);
});
}
});
const dependencies: FilterBoxDependencyMap =
getFilterboxDependencies(filterScopes);
Object.entries(dependencies).forEach(([key, filterFields]) => {
Object.entries(filterFields).forEach(([field, childrenChartIds]) => {
const parentComponentId = filterBoxToFilterComponentMap[key][field];
childrenChartIds.forEach(childrenChartId => {
const childComponentIds = Object.values(
filterBoxToFilterComponentMap[childrenChartId],
);
childComponentIds.forEach(childComponentId => {
const childComponent = find(
filterConfig,
({ id }) => id === childComponentId,
);
if (
childComponent &&
// time related filter components don't have parent
[
FILTER_COMPONENT_FILTER_TYPES.FILTER_SELECT,
FILTER_COMPONENT_FILTER_TYPES.FILTER_RANGE,
].includes(
childComponent.filterType as FILTER_COMPONENT_FILTER_TYPES,
)
) {
childComponent.cascadeParentIds ||= [];
childComponent.cascadeParentIds.push(parentComponentId);
}
});
});
});
});
return filterConfig;
}
| superset-frontend/src/dashboard/util/filterboxMigrationHelper.ts | 0 | https://github.com/apache/superset/commit/4051fda671b8b6d4b0a4f2ba8266d61cda73b916 | [
0.01172629464417696,
0.000528184522408992,
0.00016319511632900685,
0.0001730876974761486,
0.0016092561418190598
] |
{
"id": 6,
"code_window": [
" includeSearch,\n",
" rowCount,\n",
" pageSize: serverPagination\n",
" ? serverPageLength\n",
" : getPageSize(pageLength, data.length, columns.length),\n",
" filters,\n",
" emitFilter: tableFilter,\n",
" onChangeFilter,\n",
" };\n",
"};\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" filters: filterState.filters,\n"
],
"file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/plugin-chart-table/src/transformProps.ts",
"type": "replace",
"edit_start_line_idx": 244
} | ---
name: Oracle
menu: Connecting to Databases
route: /docs/databases/oracle
index: 20
version: 1
---
## Oracle
The recommended connector library is
[cx_Oracle](https://cx-oracle.readthedocs.io/en/latest/user_guide/installation.html).
The connection string is formatted as follows:
```
oracle://<username>:<password>@<hostname>:<port>
```
| docs/src/pages/docs/Connecting to Databases/oracle.mdx | 0 | https://github.com/apache/superset/commit/4051fda671b8b6d4b0a4f2ba8266d61cda73b916 | [
0.00016549693827982992,
0.00016533376765437424,
0.0001651706115808338,
0.00016533376765437424,
1.6316334949806333e-7
] |
{
"id": 0,
"code_window": [
"import { IRequestOptions, IRequestContext, IRequestFunction } from 'vs/base/node/request';\n",
"import { Readable } from 'stream';\n",
"import { RequestService as NodeRequestService } from 'vs/platform/request/node/requestService';\n",
"import { IHTTPConfiguration } from 'vs/platform/request/node/request';\n",
"\n",
"/**\n",
" * This service exposes the `request` API, while using the global\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/platform/request/electron-browser/requestService.ts",
"type": "replace",
"edit_start_line_idx": 10
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import { TPromise } from 'vs/base/common/winjs.base';
import { IRequestOptions, IRequestContext, IRequestFunction } from 'vs/base/node/request';
import { Readable } from 'stream';
import { RequestService as NodeRequestService } from 'vs/platform/request/node/requestService';
import { IHTTPConfiguration } from 'vs/platform/request/node/request';
/**
* This service exposes the `request` API, while using the global
* or configured proxy settings.
*/
export class RequestService extends NodeRequestService {
private _useXhrRequest = true;
protected configure(config: IHTTPConfiguration) {
this._useXhrRequest = !config.http.proxy;
}
request(options: IRequestOptions): TPromise<IRequestContext> {
if (this._useXhrRequest) {
return super.request(options, xhrRequest);
} else {
return super.request(options);
}
}
}
class ArryBufferStream extends Readable {
private _buffer: Buffer;
private _offset: number;
private _length: number;
constructor(arraybuffer: ArrayBuffer) {
super();
this._buffer = new Buffer(new Uint8Array(arraybuffer));
this._offset = 0;
this._length = this._buffer.length;
}
_read(size: number) {
if (this._offset < this._length) {
this.push(this._buffer.slice(this._offset, (this._offset + size)));
this._offset += size;
} else {
this.push(null);
}
}
}
export const xhrRequest: IRequestFunction = (options: IRequestOptions): TPromise<IRequestContext> => {
const xhr = new XMLHttpRequest();
return new TPromise<IRequestContext>((resolve, reject) => {
xhr.open(options.type, options.url, true, options.user, options.password);
setRequestHeaders(xhr, options);
xhr.responseType = 'arraybuffer';
xhr.onerror = reject;
xhr.onload = (e) => {
resolve({
res: {
statusCode: xhr.status,
headers: getResponseHeaders(xhr)
},
stream: new ArryBufferStream(xhr.response)
});
};
xhr.send(options.data);
return null;
}, () => {
// cancel
xhr.abort();
});
};
// --- header utils
const unsafeHeaders = Object.create(null);
unsafeHeaders['User-Agent'] = true;
unsafeHeaders['Content-Length'] = true;
unsafeHeaders['Accept-Encoding'] = true;
function setRequestHeaders(xhr: XMLHttpRequest, options: IRequestOptions): void {
if (options.headers) {
for (let k in options.headers) {
if (!unsafeHeaders[k]) {
xhr.setRequestHeader(k, options.headers[k]);
}
}
}
}
function getResponseHeaders(xhr: XMLHttpRequest): { [name: string]: string } {
const headers: { [name: string]: string } = Object.create(null);
for (const line of xhr.getAllResponseHeaders().split(/\r\n|\n|\r/g)) {
if (line) {
const idx = line.indexOf(':');
headers[line.substr(0, idx).trim().toLowerCase()] = line.substr(idx + 1).trim();
}
}
return headers;
}
| src/vs/platform/request/electron-browser/requestService.ts | 1 | https://github.com/microsoft/vscode/commit/10ae5b4b913b6b86351c43ebbd544a982643c5ac | [
0.014331931248307228,
0.001412307028658688,
0.00016736570978537202,
0.0001704902679193765,
0.0038978210650384426
] |
{
"id": 0,
"code_window": [
"import { IRequestOptions, IRequestContext, IRequestFunction } from 'vs/base/node/request';\n",
"import { Readable } from 'stream';\n",
"import { RequestService as NodeRequestService } from 'vs/platform/request/node/requestService';\n",
"import { IHTTPConfiguration } from 'vs/platform/request/node/request';\n",
"\n",
"/**\n",
" * This service exposes the `request` API, while using the global\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/platform/request/electron-browser/requestService.ts",
"type": "replace",
"edit_start_line_idx": 10
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import * as sinon from 'sinon';
import * as assert from 'assert';
import * as fs from 'fs';
import { assign } from 'vs/base/common/objects';
import { generateUuid } from 'vs/base/common/uuid';
import { IExtensionsWorkbenchService, ExtensionState } from 'vs/workbench/parts/extensions/common/extensions';
import { ExtensionsWorkbenchService } from 'vs/workbench/parts/extensions/node/extensionsWorkbenchService';
import {
IExtensionManagementService, IExtensionGalleryService, IExtensionEnablementService, IExtensionTipsService, ILocalExtension, LocalExtensionType, IGalleryExtension,
DidInstallExtensionEvent, DidUninstallExtensionEvent, InstallExtensionEvent
} from 'vs/platform/extensionManagement/common/extensionManagement';
import { ExtensionManagementService } from 'vs/platform/extensionManagement/node/extensionManagementService';
import { ExtensionTipsService } from 'vs/workbench/parts/extensions/browser/extensionTipsService';
import { TestExtensionEnablementService } from 'vs/platform/extensionManagement/test/common/extensionEnablementService.test';
import { ExtensionGalleryService } from 'vs/platform/extensionManagement/node/extensionGalleryService';
import { IURLService } from 'vs/platform/url/common/url';
import { TestInstantiationService } from 'vs/test/utils/instantiationTestUtils';
import Event, { Emitter } from 'vs/base/common/event';
import { IPager } from 'vs/base/common/paging';
import { ITelemetryService, NullTelemetryService } from 'vs/platform/telemetry/common/telemetry';
suite('ExtensionsWorkbenchService Test', () => {
let instantiationService: TestInstantiationService;
let testObject: IExtensionsWorkbenchService;
let installEvent: Emitter<InstallExtensionEvent>,
didInstallEvent: Emitter<DidInstallExtensionEvent>,
uninstallEvent: Emitter<string>,
didUninstallEvent: Emitter<DidUninstallExtensionEvent>;
suiteSetup(() => {
installEvent = new Emitter();
didInstallEvent = new Emitter();
uninstallEvent = new Emitter();
didUninstallEvent = new Emitter();
instantiationService = new TestInstantiationService();
instantiationService.stub(IURLService, { onOpenURL: new Emitter().event });
instantiationService.stub(ITelemetryService, NullTelemetryService);
instantiationService.stub(IExtensionGalleryService, ExtensionGalleryService);
instantiationService.stub(IExtensionManagementService, ExtensionManagementService);
instantiationService.stub(IExtensionManagementService, 'onInstallExtension', installEvent.event);
instantiationService.stub(IExtensionManagementService, 'onDidInstallExtension', didInstallEvent.event);
instantiationService.stub(IExtensionManagementService, 'onUninstallExtension', uninstallEvent.event);
instantiationService.stub(IExtensionManagementService, 'onDidUninstallExtension', didUninstallEvent.event);
instantiationService.stub(IExtensionEnablementService, new TestExtensionEnablementService(instantiationService));
instantiationService.stub(IExtensionTipsService, ExtensionTipsService);
instantiationService.stub(IExtensionTipsService, 'getKeymapRecommendations', () => []);
});
setup(() => {
instantiationService.stubPromise(IExtensionManagementService, 'getInstalled', []);
instantiationService.stubPromise(IExtensionGalleryService, 'query', aPage());
(<TestExtensionEnablementService>instantiationService.get(IExtensionEnablementService)).reset();
});
teardown(() => {
(<ExtensionsWorkbenchService>testObject).dispose();
});
test('test gallery extension', (done) => {
const expected = aGalleryExtension('expectedName', {
displayName: 'expectedDisplayName',
version: '1.5',
publisherId: 'expectedPublisherId',
publisher: 'expectedPublisher',
publisherDisplayName: 'expectedPublisherDisplayName',
description: 'expectedDescription',
installCount: 1000,
rating: 4,
ratingCount: 100
}, {
dependencies: ['pub.1', 'pub.2'],
}, {
manifest: 'expectedMainfest',
readme: 'expectedReadme',
changeLog: 'expectedChangelog',
download: 'expectedDownload',
icon: 'expectedIcon',
iconFallback: 'expectedIconFallback',
license: 'expectedLicense'
});
testObject = instantiationService.createInstance(ExtensionsWorkbenchService);
instantiationService.stubPromise(IExtensionGalleryService, 'query', aPage(expected));
testObject.queryGallery().done(pagedResponse => {
assert.equal(1, pagedResponse.firstPage.length);
const actual = pagedResponse.firstPage[0];
assert.equal(null, actual.type);
assert.equal('expectedName', actual.name);
assert.equal('expectedDisplayName', actual.displayName);
assert.equal('expectedPublisher.expectedName', actual.identifier);
assert.equal('expectedPublisher', actual.publisher);
assert.equal('expectedPublisherDisplayName', actual.publisherDisplayName);
assert.equal('1.5', actual.version);
assert.equal('1.5', actual.latestVersion);
assert.equal('expectedDescription', actual.description);
assert.equal('expectedIcon', actual.iconUrl);
assert.equal('expectedIconFallback', actual.iconUrlFallback);
assert.equal('expectedLicense', actual.licenseUrl);
assert.equal(ExtensionState.Uninstalled, actual.state);
assert.equal(1000, actual.installCount);
assert.equal(4, actual.rating);
assert.equal(100, actual.ratingCount);
assert.equal(false, actual.outdated);
assert.deepEqual(['pub.1', 'pub.2'], actual.dependencies);
done();
});
});
test('test for empty installed extensions', () => {
testObject = instantiationService.createInstance(ExtensionsWorkbenchService);
assert.deepEqual([], testObject.local);
});
test('test for installed extensions', () => {
const expected1 = aLocalExtension('local1', {
publisher: 'localPublisher1',
version: '1.1',
displayName: 'localDisplayName1',
description: 'localDescription1',
icon: 'localIcon1',
extensionDependencies: ['pub.1', 'pub.2'],
}, {
type: LocalExtensionType.User,
readmeUrl: 'localReadmeUrl1',
changelogUrl: 'localChangelogUrl1',
path: 'localPath1'
});
const expected2 = aLocalExtension('local2', {
publisher: 'localPublisher2',
version: '1.2',
displayName: 'localDisplayName2',
description: 'localDescription2',
}, {
type: LocalExtensionType.System,
readmeUrl: 'localReadmeUrl2',
changelogUrl: 'localChangelogUrl2',
});
instantiationService.stubPromise(IExtensionManagementService, 'getInstalled', [expected1, expected2]);
testObject = instantiationService.createInstance(ExtensionsWorkbenchService);
const actuals = testObject.local;
assert.equal(2, actuals.length);
let actual = actuals[0];
assert.equal(LocalExtensionType.User, actual.type);
assert.equal('local1', actual.name);
assert.equal('localDisplayName1', actual.displayName);
assert.equal('localPublisher1.local1', actual.identifier);
assert.equal('localPublisher1', actual.publisher);
assert.equal('1.1', actual.version);
assert.equal('1.1', actual.latestVersion);
assert.equal('localDescription1', actual.description);
assert.equal('file:///localPath1/localIcon1', actual.iconUrl);
assert.equal('file:///localPath1/localIcon1', actual.iconUrlFallback);
assert.equal(null, actual.licenseUrl);
assert.equal(ExtensionState.Installed, actual.state);
assert.equal(null, actual.installCount);
assert.equal(null, actual.rating);
assert.equal(null, actual.ratingCount);
assert.equal(false, actual.outdated);
assert.deepEqual(['pub.1', 'pub.2'], actual.dependencies);
actual = actuals[1];
assert.equal(LocalExtensionType.System, actual.type);
assert.equal('local2', actual.name);
assert.equal('localDisplayName2', actual.displayName);
assert.equal('localPublisher2.local2', actual.identifier);
assert.equal('localPublisher2', actual.publisher);
assert.equal('1.2', actual.version);
assert.equal('1.2', actual.latestVersion);
assert.equal('localDescription2', actual.description);
assert.ok(fs.existsSync(actual.iconUrl));
assert.equal(null, actual.licenseUrl);
assert.equal(ExtensionState.Installed, actual.state);
assert.equal(null, actual.installCount);
assert.equal(null, actual.rating);
assert.equal(null, actual.ratingCount);
assert.equal(false, actual.outdated);
assert.deepEqual([], actual.dependencies);
});
test('test installed extensions get syncs with gallery', (done) => {
const local1 = aLocalExtension('local1', {
publisher: 'localPublisher1',
version: '1.1.0',
displayName: 'localDisplayName1',
description: 'localDescription1',
icon: 'localIcon1',
extensionDependencies: ['pub.1', 'pub.2'],
}, {
type: LocalExtensionType.User,
readmeUrl: 'localReadmeUrl1',
changelogUrl: 'localChangelogUrl1',
path: 'localPath1'
});
const local2 = aLocalExtension('local2', {
publisher: 'localPublisher2',
version: '1.2.0',
displayName: 'localDisplayName2',
description: 'localDescription2',
}, {
type: LocalExtensionType.System,
readmeUrl: 'localReadmeUrl2',
changelogUrl: 'localChangelogUrl2',
});
const gallery1 = aGalleryExtension('expectedName', {
id: local1.id,
displayName: 'expectedDisplayName',
version: '1.5.0',
publisherId: 'expectedPublisherId',
publisher: 'expectedPublisher',
publisherDisplayName: 'expectedPublisherDisplayName',
description: 'expectedDescription',
installCount: 1000,
rating: 4,
ratingCount: 100
}, {
dependencies: ['pub.1'],
}, {
manifest: 'expectedMainfest',
readme: 'expectedReadme',
changeLog: 'expectedChangelog',
download: 'expectedDownload',
icon: 'expectedIcon',
iconFallback: 'expectedIconFallback',
license: 'expectedLicense'
});
instantiationService.stubPromise(IExtensionManagementService, 'getInstalled', [local1, local2]);
instantiationService.stubPromise(IExtensionGalleryService, 'query', aPage(gallery1));
testObject = instantiationService.createInstance(ExtensionsWorkbenchService);
listenAfter(testObject.onChange)(() => {
const actuals = testObject.local;
assert.equal(2, actuals.length);
let actual = actuals[0];
assert.equal(LocalExtensionType.User, actual.type);
assert.equal('local1', actual.name);
assert.equal('localDisplayName1', actual.displayName);
assert.equal('localPublisher1.local1', actual.identifier);
assert.equal('localPublisher1', actual.publisher);
assert.equal('1.1.0', actual.version);
assert.equal('1.5.0', actual.latestVersion);
assert.equal('localDescription1', actual.description);
assert.equal('file:///localPath1/localIcon1', actual.iconUrl);
assert.equal('file:///localPath1/localIcon1', actual.iconUrlFallback);
assert.equal(ExtensionState.Installed, actual.state);
assert.equal('expectedLicense', actual.licenseUrl);
assert.equal(1000, actual.installCount);
assert.equal(4, actual.rating);
assert.equal(100, actual.ratingCount);
assert.equal(true, actual.outdated);
assert.deepEqual(['pub.1', 'pub.2'], actual.dependencies);
actual = actuals[1];
assert.equal(LocalExtensionType.System, actual.type);
assert.equal('local2', actual.name);
assert.equal('localDisplayName2', actual.displayName);
assert.equal('localPublisher2.local2', actual.identifier);
assert.equal('localPublisher2', actual.publisher);
assert.equal('1.2.0', actual.version);
assert.equal('1.2.0', actual.latestVersion);
assert.equal('localDescription2', actual.description);
assert.ok(fs.existsSync(actual.iconUrl));
assert.equal(null, actual.licenseUrl);
assert.equal(ExtensionState.Installed, actual.state);
assert.equal(null, actual.installCount);
assert.equal(null, actual.rating);
assert.equal(null, actual.ratingCount);
assert.equal(false, actual.outdated);
assert.deepEqual([], actual.dependencies);
done();
});
});
test('test extension state computation', (done) => {
const gallery = aGalleryExtension('gallery1');
testObject = instantiationService.createInstance(ExtensionsWorkbenchService);
instantiationService.stubPromise(IExtensionGalleryService, 'query', aPage(gallery));
testObject.queryGallery().done(page => {
const extension = page.firstPage[0];
assert.equal(ExtensionState.Uninstalled, extension.state);
testObject.install(extension);
// Installing
installEvent.fire({ id: gallery.id, gallery });
let local = testObject.local;
assert.equal(1, local.length);
const actual = local[0];
assert.equal(`${gallery.publisher}.${gallery.name}`, actual.identifier);
assert.equal(ExtensionState.Installing, actual.state);
// Installed
didInstallEvent.fire({ id: gallery.id, gallery, local: aLocalExtension(gallery.name, gallery, gallery) });
assert.equal(ExtensionState.Installed, actual.state);
assert.equal(1, testObject.local.length);
testObject.uninstall(actual);
// Uninstalling
uninstallEvent.fire(gallery.id);
assert.equal(ExtensionState.Uninstalling, actual.state);
// Uninstalled
didUninstallEvent.fire({ id: gallery.id });
assert.equal(ExtensionState.Uninstalled, actual.state);
assert.equal(0, testObject.local.length);
done();
});
});
test('test extension doesnot show outdated for system extensions', () => {
const local = aLocalExtension('a', { version: '1.0.1' }, { type: LocalExtensionType.System });
instantiationService.stubPromise(IExtensionManagementService, 'getInstalled', [local]);
instantiationService.stubPromise(IExtensionGalleryService, 'query', aPage(aGalleryExtension(local.manifest.name, { id: local.id, version: '1.0.2' })));
testObject = instantiationService.createInstance(ExtensionsWorkbenchService);
assert.ok(!testObject.local[0].outdated);
});
test('test canInstall returns false for extensions with out gallery', () => {
const local = aLocalExtension('a', { version: '1.0.1' }, { type: LocalExtensionType.System });
instantiationService.stubPromise(IExtensionManagementService, 'getInstalled', [local]);
testObject = instantiationService.createInstance(ExtensionsWorkbenchService);
const target = testObject.local[0];
testObject.uninstall(target);
uninstallEvent.fire(local.id);
didUninstallEvent.fire({ id: local.id });
assert.ok(!testObject.canInstall(target));
});
test('test canInstall returns true for extensions with gallery', (done) => {
const local = aLocalExtension('a', { version: '1.0.1' }, { type: LocalExtensionType.System });
instantiationService.stubPromise(IExtensionManagementService, 'getInstalled', [local]);
instantiationService.stubPromise(IExtensionGalleryService, 'query', aPage(aGalleryExtension(local.manifest.name, { id: local.id })));
testObject = instantiationService.createInstance(ExtensionsWorkbenchService);
const target = testObject.local[0];
listenAfter(testObject.onChange)(() => {
assert.ok(testObject.canInstall(target));
done();
});
});
test('test onchange event is triggered while installing', (done) => {
const gallery = aGalleryExtension('gallery1');
testObject = instantiationService.createInstance(ExtensionsWorkbenchService);
instantiationService.stubPromise(IExtensionGalleryService, 'query', aPage(gallery));
const target = sinon.spy();
testObject.queryGallery().done(page => {
const extension = page.firstPage[0];
assert.equal(ExtensionState.Uninstalled, extension.state);
testObject.install(extension);
installEvent.fire({ id: gallery.id, gallery });
testObject.onChange(target);
// Installed
didInstallEvent.fire({ id: gallery.id, gallery, local: aLocalExtension(gallery.name, gallery, gallery) });
assert.ok(target.calledOnce);
done();
});
});
test('test onchange event is triggered when installation is finished', (done) => {
const gallery = aGalleryExtension('gallery1');
testObject = instantiationService.createInstance(ExtensionsWorkbenchService);
instantiationService.stubPromise(IExtensionGalleryService, 'query', aPage(gallery));
const target = sinon.spy();
testObject.queryGallery().done(page => {
const extension = page.firstPage[0];
assert.equal(ExtensionState.Uninstalled, extension.state);
testObject.install(extension);
testObject.onChange(target);
// Installing
installEvent.fire({ id: gallery.id, gallery });
assert.ok(target.calledOnce);
done();
});
});
test('test onchange event is triggered while uninstalling', () => {
const local = aLocalExtension('a', {}, { type: LocalExtensionType.System });
instantiationService.stubPromise(IExtensionManagementService, 'getInstalled', [local]);
testObject = instantiationService.createInstance(ExtensionsWorkbenchService);
const target = sinon.spy();
testObject.uninstall(testObject.local[0]);
testObject.onChange(target);
uninstallEvent.fire(local.id);
assert.ok(target.calledOnce);
});
test('test onchange event is triggered when uninstalling is finished', () => {
const local = aLocalExtension('a', {}, { type: LocalExtensionType.System });
instantiationService.stubPromise(IExtensionManagementService, 'getInstalled', [local]);
testObject = instantiationService.createInstance(ExtensionsWorkbenchService);
const target = sinon.spy();
testObject.uninstall(testObject.local[0]);
uninstallEvent.fire(local.id);
testObject.onChange(target);
didUninstallEvent.fire({ id: local.id });
assert.ok(target.calledOnce);
});
test('test extension dependencies when empty', (done) => {
testObject = instantiationService.createInstance(ExtensionsWorkbenchService);
instantiationService.stubPromise(IExtensionGalleryService, 'query', aPage(aGalleryExtension('a')));
testObject.queryGallery().done(page => {
testObject.loadDependencies(page.firstPage[0]).done(dependencies => {
assert.equal(null, dependencies);
done();
});
});
});
test('test one level extension dependencies without cycle', (done) => {
testObject = instantiationService.createInstance(ExtensionsWorkbenchService);
instantiationService.stubPromise(IExtensionGalleryService, 'query', aPage(aGalleryExtension('a', {}, { dependencies: ['pub.b', 'pub.c', 'pub.d'] })));
instantiationService.stubPromise(IExtensionGalleryService, 'getAllDependencies', [aGalleryExtension('b'), aGalleryExtension('c'), aGalleryExtension('d')]);
testObject.queryGallery().done(page => {
const extension = page.firstPage[0];
testObject.loadDependencies(extension).done(actual => {
assert.ok(actual.hasDependencies);
assert.equal(extension, actual.extension);
assert.equal(null, actual.dependent);
assert.equal(3, actual.dependencies.length);
assert.equal('pub.a', actual.identifier);
let dependent = actual;
actual = dependent.dependencies[0];
assert.ok(!actual.hasDependencies);
assert.equal('pub.b', actual.extension.identifier);
assert.equal('pub.b', actual.identifier);
assert.equal(dependent, actual.dependent);
assert.equal(0, actual.dependencies.length);
actual = dependent.dependencies[1];
assert.ok(!actual.hasDependencies);
assert.equal('pub.c', actual.extension.identifier);
assert.equal('pub.c', actual.identifier);
assert.equal(dependent, actual.dependent);
assert.equal(0, actual.dependencies.length);
actual = dependent.dependencies[2];
assert.ok(!actual.hasDependencies);
assert.equal('pub.d', actual.extension.identifier);
assert.equal('pub.d', actual.identifier);
assert.equal(dependent, actual.dependent);
assert.equal(0, actual.dependencies.length);
done();
});
});
});
test('test one level extension dependencies with cycle', (done) => {
testObject = instantiationService.createInstance(ExtensionsWorkbenchService);
instantiationService.stubPromise(IExtensionGalleryService, 'query', aPage(aGalleryExtension('a', {}, { dependencies: ['pub.b', 'pub.a'] })));
instantiationService.stubPromise(IExtensionGalleryService, 'getAllDependencies', [aGalleryExtension('b'), aGalleryExtension('a')]);
testObject.queryGallery().done(page => {
const extension = page.firstPage[0];
testObject.loadDependencies(extension).done(actual => {
assert.ok(actual.hasDependencies);
assert.equal(extension, actual.extension);
assert.equal(null, actual.dependent);
assert.equal(2, actual.dependencies.length);
assert.equal('pub.a', actual.identifier);
let dependent = actual;
actual = dependent.dependencies[0];
assert.ok(!actual.hasDependencies);
assert.equal('pub.b', actual.extension.identifier);
assert.equal('pub.b', actual.identifier);
assert.equal(dependent, actual.dependent);
assert.equal(0, actual.dependencies.length);
actual = dependent.dependencies[1];
assert.ok(!actual.hasDependencies);
assert.equal('pub.a', actual.extension.identifier);
assert.equal('pub.a', actual.identifier);
assert.equal(dependent, actual.dependent);
assert.equal(0, actual.dependencies.length);
done();
});
});
});
test('test one level extension dependencies with missing dependencies', (done) => {
testObject = instantiationService.createInstance(ExtensionsWorkbenchService);
instantiationService.stubPromise(IExtensionGalleryService, 'query', aPage(aGalleryExtension('a', {}, { dependencies: ['pub.b', 'pub.a'] })));
instantiationService.stubPromise(IExtensionGalleryService, 'getAllDependencies', [aGalleryExtension('a')]);
testObject.queryGallery().done(page => {
const extension = page.firstPage[0];
testObject.loadDependencies(extension).done(actual => {
assert.ok(actual.hasDependencies);
assert.equal(extension, actual.extension);
assert.equal(null, actual.dependent);
assert.equal(2, actual.dependencies.length);
assert.equal('pub.a', actual.identifier);
let dependent = actual;
actual = dependent.dependencies[0];
assert.ok(!actual.hasDependencies);
assert.equal(null, actual.extension);
assert.equal('pub.b', actual.identifier);
assert.equal(dependent, actual.dependent);
assert.equal(0, actual.dependencies.length);
actual = dependent.dependencies[1];
assert.ok(!actual.hasDependencies);
assert.equal('pub.a', actual.extension.identifier);
assert.equal('pub.a', actual.identifier);
assert.equal(dependent, actual.dependent);
assert.equal(0, actual.dependencies.length);
done();
});
});
});
test('test one level extension dependencies with in built dependencies', (done) => {
const local = aLocalExtension('inbuilt', {}, { type: LocalExtensionType.System });
instantiationService.stubPromise(IExtensionManagementService, 'getInstalled', [local]);
testObject = instantiationService.createInstance(ExtensionsWorkbenchService);
instantiationService.stubPromise(IExtensionGalleryService, 'query', aPage(aGalleryExtension('a', {}, { dependencies: ['pub.inbuilt', 'pub.a'] })));
instantiationService.stubPromise(IExtensionGalleryService, 'getAllDependencies', [aGalleryExtension('a')]);
testObject.queryGallery().done(page => {
const extension = page.firstPage[0];
testObject.loadDependencies(extension).done(actual => {
assert.ok(actual.hasDependencies);
assert.equal(extension, actual.extension);
assert.equal(null, actual.dependent);
assert.equal(2, actual.dependencies.length);
assert.equal('pub.a', actual.identifier);
let dependent = actual;
actual = dependent.dependencies[0];
assert.ok(!actual.hasDependencies);
assert.equal('pub.inbuilt', actual.extension.identifier);
assert.equal('pub.inbuilt', actual.identifier);
assert.equal(dependent, actual.dependent);
assert.equal(0, actual.dependencies.length);
actual = dependent.dependencies[1];
assert.ok(!actual.hasDependencies);
assert.equal('pub.a', actual.extension.identifier);
assert.equal('pub.a', actual.identifier);
assert.equal(dependent, actual.dependent);
assert.equal(0, actual.dependencies.length);
done();
});
});
});
test('test more than one level of extension dependencies', (done) => {
const local = aLocalExtension('c', { extensionDependencies: ['pub.d'] }, { type: LocalExtensionType.System });
instantiationService.stubPromise(IExtensionManagementService, 'getInstalled', [local]);
testObject = instantiationService.createInstance(ExtensionsWorkbenchService);
instantiationService.stubPromise(IExtensionGalleryService, 'query', aPage(aGalleryExtension('a', {}, { dependencies: ['pub.b', 'pub.c'] })));
instantiationService.stubPromise(IExtensionGalleryService, 'getAllDependencies', [
aGalleryExtension('b', {}, { dependencies: ['pub.d', 'pub.e'] }),
aGalleryExtension('d', {}, { dependencies: ['pub.f', 'pub.c'] }),
aGalleryExtension('e')]);
testObject.queryGallery().done(page => {
const extension = page.firstPage[0];
testObject.loadDependencies(extension).done(a => {
assert.ok(a.hasDependencies);
assert.equal(extension, a.extension);
assert.equal(null, a.dependent);
assert.equal(2, a.dependencies.length);
assert.equal('pub.a', a.identifier);
let b = a.dependencies[0];
assert.ok(b.hasDependencies);
assert.equal('pub.b', b.extension.identifier);
assert.equal('pub.b', b.identifier);
assert.equal(a, b.dependent);
assert.equal(2, b.dependencies.length);
let c = a.dependencies[1];
assert.ok(c.hasDependencies);
assert.equal('pub.c', c.extension.identifier);
assert.equal('pub.c', c.identifier);
assert.equal(a, c.dependent);
assert.equal(1, c.dependencies.length);
let d = b.dependencies[0];
assert.ok(d.hasDependencies);
assert.equal('pub.d', d.extension.identifier);
assert.equal('pub.d', d.identifier);
assert.equal(b, d.dependent);
assert.equal(2, d.dependencies.length);
let e = b.dependencies[1];
assert.ok(!e.hasDependencies);
assert.equal('pub.e', e.extension.identifier);
assert.equal('pub.e', e.identifier);
assert.equal(b, e.dependent);
assert.equal(0, e.dependencies.length);
let f = d.dependencies[0];
assert.ok(!f.hasDependencies);
assert.equal(null, f.extension);
assert.equal('pub.f', f.identifier);
assert.equal(d, f.dependent);
assert.equal(0, f.dependencies.length);
c = d.dependencies[1];
assert.ok(c.hasDependencies);
assert.equal('pub.c', c.extension.identifier);
assert.equal('pub.c', c.identifier);
assert.equal(d, c.dependent);
assert.equal(1, c.dependencies.length);
d = c.dependencies[0];
assert.ok(!d.hasDependencies);
assert.equal('pub.d', d.extension.identifier);
assert.equal('pub.d', d.identifier);
assert.equal(c, d.dependent);
assert.equal(0, d.dependencies.length);
c = a.dependencies[1];
d = c.dependencies[0];
assert.ok(d.hasDependencies);
assert.equal('pub.d', d.extension.identifier);
assert.equal('pub.d', d.identifier);
assert.equal(c, d.dependent);
assert.equal(2, d.dependencies.length);
f = d.dependencies[0];
assert.ok(!f.hasDependencies);
assert.equal(null, f.extension);
assert.equal('pub.f', f.identifier);
assert.equal(d, f.dependent);
assert.equal(0, f.dependencies.length);
c = d.dependencies[1];
assert.ok(!c.hasDependencies);
assert.equal('pub.c', c.extension.identifier);
assert.equal('pub.c', c.identifier);
assert.equal(d, c.dependent);
assert.equal(0, c.dependencies.length);
done();
});
});
});
test('test disabled flags are false for uninstalled extension', (done) => {
instantiationService.get(IExtensionEnablementService).setEnablement('pub.b', false);
instantiationService.get(IExtensionEnablementService).setEnablement('pub.c', false, true);
testObject = instantiationService.createInstance(ExtensionsWorkbenchService);
instantiationService.stubPromise(IExtensionGalleryService, 'query', aPage(aGalleryExtension('a')));
testObject.queryGallery().done(pagedResponse => {
const actual = pagedResponse.firstPage[0];
assert.ok(!actual.disabledForWorkspace);
assert.ok(!actual.disabledGlobally);
done();
});
});
test('test disabled flags are false for installed enabled extension', () => {
instantiationService.get(IExtensionEnablementService).setEnablement('pub.b', false);
instantiationService.get(IExtensionEnablementService).setEnablement('pub.c', false, true);
instantiationService.stubPromise(IExtensionManagementService, 'getInstalled', [aLocalExtension('a')]);
testObject = instantiationService.createInstance(ExtensionsWorkbenchService);
const actual = testObject.local[0];
assert.ok(!actual.disabledForWorkspace);
assert.ok(!actual.disabledGlobally);
});
test('test disabled for workspace is set', () => {
instantiationService.get(IExtensionEnablementService).setEnablement('pub.b', false);
instantiationService.get(IExtensionEnablementService).setEnablement('pub.d', false);
instantiationService.get(IExtensionEnablementService).setEnablement('pub.a', false, true);
instantiationService.get(IExtensionEnablementService).setEnablement('pub.e', false, true);
instantiationService.stubPromise(IExtensionManagementService, 'getInstalled', [aLocalExtension('a')]);
testObject = instantiationService.createInstance(ExtensionsWorkbenchService);
const actual = testObject.local[0];
assert.ok(actual.disabledForWorkspace);
assert.ok(!actual.disabledGlobally);
});
test('test disabled globally is set', () => {
instantiationService.get(IExtensionEnablementService).setEnablement('pub.a', false);
instantiationService.get(IExtensionEnablementService).setEnablement('pub.d', false);
instantiationService.get(IExtensionEnablementService).setEnablement('pub.c', false, true);
instantiationService.stubPromise(IExtensionManagementService, 'getInstalled', [aLocalExtension('a')]);
testObject = instantiationService.createInstance(ExtensionsWorkbenchService);
const actual = testObject.local[0];
assert.ok(!actual.disabledForWorkspace);
assert.ok(actual.disabledGlobally);
});
test('test disable flags are updated for user extensions', () => {
instantiationService.get(IExtensionEnablementService).setEnablement('pub.c', false);
instantiationService.get(IExtensionEnablementService).setEnablement('pub.b', false, true);
instantiationService.stubPromise(IExtensionManagementService, 'getInstalled', [aLocalExtension('a')]);
testObject = instantiationService.createInstance(ExtensionsWorkbenchService);
testObject.setEnablement(testObject.local[0], false, true);
const actual = testObject.local[0];
assert.ok(actual.disabledForWorkspace);
assert.ok(!actual.disabledGlobally);
});
test('test enable extension globally when extension is disabled for workspace', () => {
instantiationService.get(IExtensionEnablementService).setEnablement('pub.a', false, true);
instantiationService.stubPromise(IExtensionManagementService, 'getInstalled', [aLocalExtension('a')]);
testObject = instantiationService.createInstance(ExtensionsWorkbenchService);
testObject.setEnablement(testObject.local[0], true);
const actual = testObject.local[0];
assert.ok(!actual.disabledForWorkspace);
assert.ok(!actual.disabledGlobally);
});
test('test disable extension globally should not disable for workspace', () => {
instantiationService.stubPromise(IExtensionManagementService, 'getInstalled', [aLocalExtension('a')]);
testObject = instantiationService.createInstance(ExtensionsWorkbenchService);
testObject.setEnablement(testObject.local[0], false);
const actual = testObject.local[0];
assert.ok(!actual.disabledForWorkspace);
assert.ok(actual.disabledGlobally);
});
test('test disabled flags are not updated for system extensions', () => {
instantiationService.stubPromise(IExtensionManagementService, 'getInstalled', [aLocalExtension('a', {}, { type: LocalExtensionType.System })]);
testObject = instantiationService.createInstance(ExtensionsWorkbenchService);
testObject.setEnablement(testObject.local[0], false);
const actual = testObject.local[0];
assert.ok(!actual.disabledForWorkspace);
assert.ok(!actual.disabledGlobally);
});
test('test disabled flags are updated on change from outside', () => {
instantiationService.get(IExtensionEnablementService).setEnablement('pub.c', false);
instantiationService.get(IExtensionEnablementService).setEnablement('pub.b', false, true);
instantiationService.stubPromise(IExtensionManagementService, 'getInstalled', [aLocalExtension('a')]);
testObject = instantiationService.createInstance(ExtensionsWorkbenchService);
instantiationService.get(IExtensionEnablementService).setEnablement('pub.a', false);
const actual = testObject.local[0];
assert.ok(!actual.disabledForWorkspace);
assert.ok(actual.disabledGlobally);
});
test('test change event is fired when disablement flags are changed', () => {
instantiationService.get(IExtensionEnablementService).setEnablement('pub.c', false);
instantiationService.get(IExtensionEnablementService).setEnablement('pub.b', false, true);
instantiationService.stubPromise(IExtensionManagementService, 'getInstalled', [aLocalExtension('a')]);
testObject = instantiationService.createInstance(ExtensionsWorkbenchService);
const target = sinon.spy();
testObject.onChange(target);
testObject.setEnablement(testObject.local[0], false);
assert.ok(target.calledOnce);
});
test('test change event is fired when disablement flags are changed from outside', () => {
instantiationService.get(IExtensionEnablementService).setEnablement('pub.c', false);
instantiationService.get(IExtensionEnablementService).setEnablement('pub.b', false, true);
instantiationService.stubPromise(IExtensionManagementService, 'getInstalled', [aLocalExtension('a')]);
testObject = instantiationService.createInstance(ExtensionsWorkbenchService);
const target = sinon.spy();
testObject.onChange(target);
instantiationService.get(IExtensionEnablementService).setEnablement('pub.a', false);
assert.ok(target.calledOnce);
});
function aLocalExtension(name: string = 'someext', manifest: any = {}, properties: any = {}): ILocalExtension {
const localExtension = <ILocalExtension>Object.create({ manifest: {} });
assign(localExtension, { type: LocalExtensionType.User, id: generateUuid() }, properties);
assign(localExtension.manifest, { name, publisher: 'pub' }, manifest);
localExtension.metadata = { id: localExtension.id, publisherId: localExtension.manifest.publisher, publisherDisplayName: 'somename' };
return localExtension;
}
function aGalleryExtension(name: string, properties: any = {}, galleryExtensionProperties: any = {}, assets: any = {}): IGalleryExtension {
const galleryExtension = <IGalleryExtension>Object.create({});
assign(galleryExtension, { name, publisher: 'pub', id: generateUuid(), properties: {}, assets: {} }, properties);
assign(galleryExtension.properties, { dependencies: [] }, galleryExtensionProperties);
assign(galleryExtension.assets, assets);
return <IGalleryExtension>galleryExtension;
}
function aPage<T>(...objects: T[]): IPager<T> {
return { firstPage: objects, total: objects.length, pageSize: objects.length, getPage: () => null };
}
function listenAfter(event: Event<any>, count: number = 1): Event<any> {
let counter = 0;
const emitter = new Emitter<any>();
event(() => {
if (++counter === count) {
emitter.fire();
emitter.dispose();
}
});
return emitter.event;
}
}); | src/vs/workbench/parts/extensions/test/electron-browser/extensionsWorkbenchService.test.ts | 0 | https://github.com/microsoft/vscode/commit/10ae5b4b913b6b86351c43ebbd544a982643c5ac | [
0.00017558109539095312,
0.00017109222244471312,
0.00016562528617214411,
0.0001714374520815909,
0.0000025285107767558657
] |
{
"id": 0,
"code_window": [
"import { IRequestOptions, IRequestContext, IRequestFunction } from 'vs/base/node/request';\n",
"import { Readable } from 'stream';\n",
"import { RequestService as NodeRequestService } from 'vs/platform/request/node/requestService';\n",
"import { IHTTPConfiguration } from 'vs/platform/request/node/request';\n",
"\n",
"/**\n",
" * This service exposes the `request` API, while using the global\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/platform/request/electron-browser/requestService.ts",
"type": "replace",
"edit_start_line_idx": 10
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"fileBinaryError": "Похоже, файл является двоичным, и его нельзя открыть как текстовый.",
"fileInvalidPath": "Недопустимый ресурс файла ({0})",
"fileIsDirectoryError": "Файл является каталогом ({0})",
"fileNotFoundError": "Файл не найден ({0})",
"fileReadOnlyError": "Файл доступен только для чтения",
"foldersCopyError": "Папки нельзя копировать в рабочую область. Выберите отдельные файлы, чтобы скопировать их.",
"unableToMoveCopyError": "Невозможно переместить или скопировать файл, так как он заменил бы папку, в которой содержится."
} | i18n/rus/src/vs/workbench/services/files/node/fileService.i18n.json | 0 | https://github.com/microsoft/vscode/commit/10ae5b4b913b6b86351c43ebbd544a982643c5ac | [
0.00016882555792108178,
0.0001662823196966201,
0.00016373909602407366,
0.0001662823196966201,
0.0000025432309485040605
] |
{
"id": 0,
"code_window": [
"import { IRequestOptions, IRequestContext, IRequestFunction } from 'vs/base/node/request';\n",
"import { Readable } from 'stream';\n",
"import { RequestService as NodeRequestService } from 'vs/platform/request/node/requestService';\n",
"import { IHTTPConfiguration } from 'vs/platform/request/node/request';\n",
"\n",
"/**\n",
" * This service exposes the `request` API, while using the global\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/platform/request/electron-browser/requestService.ts",
"type": "replace",
"edit_start_line_idx": 10
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"invalid": "无效的“contributes.{0}”。应为数组。",
"invalid.empty": "“contributes.{0}”的值为空",
"opt.aliases": "属性“{0}”可以省略,其类型必须是 \"string[]\"",
"opt.configuration": "属性“{0}”可以省略,其类型必须是“字符串”",
"opt.extensions": "属性“{0}”可以省略,其类型必须是 \"string[]\"",
"opt.filenames": "属性“{0}”可以省略,其类型必须是 \"string[]\"",
"opt.firstLine": "属性“{0}”可以省略,其类型必须是“字符串”",
"opt.mimetypes": "属性“{0}”可以省略,其类型必须是 \"string[]\"",
"require.id": "属性“{0}”是必需的,其类型必须是“字符串”",
"vscode.extension.contributes.languages": "有助于语言声明。",
"vscode.extension.contributes.languages.aliases": "语言的别名。",
"vscode.extension.contributes.languages.configuration": "包含语言配置选项的文件的相对路径。",
"vscode.extension.contributes.languages.extensions": "与语言关联的文件扩展名。",
"vscode.extension.contributes.languages.filenamePatterns": "与语言关联的文件名 glob 模式。",
"vscode.extension.contributes.languages.filenames": "与语言关联的文件名。",
"vscode.extension.contributes.languages.firstLine": "与语言文件的第一行匹配的正则表达式。",
"vscode.extension.contributes.languages.id": "语言 ID。",
"vscode.extension.contributes.languages.mimetypes": "与语言关联的 Mime 类型。"
} | i18n/chs/src/vs/editor/common/services/modeServiceImpl.i18n.json | 0 | https://github.com/microsoft/vscode/commit/10ae5b4b913b6b86351c43ebbd544a982643c5ac | [
0.00017067167209461331,
0.00016775990661699325,
0.00016327013145200908,
0.00016933791630435735,
0.0000032211062261922052
] |
{
"id": 1,
"code_window": [
" * This service exposes the `request` API, while using the global\n",
" * or configured proxy settings.\n",
" */\n",
"export class RequestService extends NodeRequestService {\n",
"\n",
"\tprivate _useXhrRequest = true;\n",
"\n",
"\tprotected configure(config: IHTTPConfiguration) {\n",
"\t\tthis._useXhrRequest = !config.http.proxy;\n",
"\t}\n",
"\n",
"\trequest(options: IRequestOptions): TPromise<IRequestContext> {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [],
"file_path": "src/vs/platform/request/electron-browser/requestService.ts",
"type": "replace",
"edit_start_line_idx": 17
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import { TPromise } from 'vs/base/common/winjs.base';
import { IRequestOptions, IRequestContext, IRequestFunction } from 'vs/base/node/request';
import { Readable } from 'stream';
import { RequestService as NodeRequestService } from 'vs/platform/request/node/requestService';
import { IHTTPConfiguration } from 'vs/platform/request/node/request';
/**
* This service exposes the `request` API, while using the global
* or configured proxy settings.
*/
export class RequestService extends NodeRequestService {
private _useXhrRequest = true;
protected configure(config: IHTTPConfiguration) {
this._useXhrRequest = !config.http.proxy;
}
request(options: IRequestOptions): TPromise<IRequestContext> {
if (this._useXhrRequest) {
return super.request(options, xhrRequest);
} else {
return super.request(options);
}
}
}
class ArryBufferStream extends Readable {
private _buffer: Buffer;
private _offset: number;
private _length: number;
constructor(arraybuffer: ArrayBuffer) {
super();
this._buffer = new Buffer(new Uint8Array(arraybuffer));
this._offset = 0;
this._length = this._buffer.length;
}
_read(size: number) {
if (this._offset < this._length) {
this.push(this._buffer.slice(this._offset, (this._offset + size)));
this._offset += size;
} else {
this.push(null);
}
}
}
export const xhrRequest: IRequestFunction = (options: IRequestOptions): TPromise<IRequestContext> => {
const xhr = new XMLHttpRequest();
return new TPromise<IRequestContext>((resolve, reject) => {
xhr.open(options.type, options.url, true, options.user, options.password);
setRequestHeaders(xhr, options);
xhr.responseType = 'arraybuffer';
xhr.onerror = reject;
xhr.onload = (e) => {
resolve({
res: {
statusCode: xhr.status,
headers: getResponseHeaders(xhr)
},
stream: new ArryBufferStream(xhr.response)
});
};
xhr.send(options.data);
return null;
}, () => {
// cancel
xhr.abort();
});
};
// --- header utils
const unsafeHeaders = Object.create(null);
unsafeHeaders['User-Agent'] = true;
unsafeHeaders['Content-Length'] = true;
unsafeHeaders['Accept-Encoding'] = true;
function setRequestHeaders(xhr: XMLHttpRequest, options: IRequestOptions): void {
if (options.headers) {
for (let k in options.headers) {
if (!unsafeHeaders[k]) {
xhr.setRequestHeader(k, options.headers[k]);
}
}
}
}
function getResponseHeaders(xhr: XMLHttpRequest): { [name: string]: string } {
const headers: { [name: string]: string } = Object.create(null);
for (const line of xhr.getAllResponseHeaders().split(/\r\n|\n|\r/g)) {
if (line) {
const idx = line.indexOf(':');
headers[line.substr(0, idx).trim().toLowerCase()] = line.substr(idx + 1).trim();
}
}
return headers;
}
| src/vs/platform/request/electron-browser/requestService.ts | 1 | https://github.com/microsoft/vscode/commit/10ae5b4b913b6b86351c43ebbd544a982643c5ac | [
0.9968786239624023,
0.1849546581506729,
0.00016776692064013332,
0.00020447405404411256,
0.3667047619819641
] |
{
"id": 1,
"code_window": [
" * This service exposes the `request` API, while using the global\n",
" * or configured proxy settings.\n",
" */\n",
"export class RequestService extends NodeRequestService {\n",
"\n",
"\tprivate _useXhrRequest = true;\n",
"\n",
"\tprotected configure(config: IHTTPConfiguration) {\n",
"\t\tthis._useXhrRequest = !config.http.proxy;\n",
"\t}\n",
"\n",
"\trequest(options: IRequestOptions): TPromise<IRequestContext> {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [],
"file_path": "src/vs/platform/request/electron-browser/requestService.ts",
"type": "replace",
"edit_start_line_idx": 17
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"added-char": "A",
"allChanges": "변경 내용",
"ariaLabelChanges": "변경, Git",
"ariaLabelMerge": "병합, Git",
"ariaLabelStagedChanges": "스테이징된 변경 내용, Git",
"copied-char": "C",
"deleted-char": "D",
"fileStatusAriaLabel": "{1} 폴더에 있는 {0} 파일의 상태는 {2}입니다. Git",
"ignored-char": "!",
"mergeChanges": "변경 내용 병합",
"modified-char": "M",
"outsideOfWorkspace": "이 파일은 현재 작업 영역의 외부에 있습니다.",
"renamed-char": "R",
"stagedChanges": "스테이징된 변경 내용",
"title-conflict-added-by-them": "충돌: 타인이 추가",
"title-conflict-added-by-us": "충돌: 자체 추가",
"title-conflict-both-added": "충돌: 양쪽에서 추가",
"title-conflict-both-deleted": "충돌: 양쪽에서 삭제",
"title-conflict-both-modified": "충돌: 양쪽에서 수정",
"title-conflict-deleted-by-them": "충돌: 타인이 삭제",
"title-conflict-deleted-by-us": "충돌: 자체 삭제",
"title-deleted": "삭제됨",
"title-ignored": "무시됨",
"title-index-added": "인덱스에 추가",
"title-index-copied": "인덱스에 복사",
"title-index-deleted": "인덱스에서 삭제",
"title-index-modified": "인덱스에서 수정",
"title-index-renamed": "인덱스에서 이름 변경",
"title-modified": "수정됨",
"title-untracked": "추적되지 않음",
"untracked-char": "U"
} | i18n/kor/src/vs/workbench/parts/git/browser/views/changes/changesViewer.i18n.json | 0 | https://github.com/microsoft/vscode/commit/10ae5b4b913b6b86351c43ebbd544a982643c5ac | [
0.00017663832113612443,
0.0001712714583845809,
0.00016810157103464007,
0.00017017296340782195,
0.0000032118853141582804
] |
{
"id": 1,
"code_window": [
" * This service exposes the `request` API, while using the global\n",
" * or configured proxy settings.\n",
" */\n",
"export class RequestService extends NodeRequestService {\n",
"\n",
"\tprivate _useXhrRequest = true;\n",
"\n",
"\tprotected configure(config: IHTTPConfiguration) {\n",
"\t\tthis._useXhrRequest = !config.http.proxy;\n",
"\t}\n",
"\n",
"\trequest(options: IRequestOptions): TPromise<IRequestContext> {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [],
"file_path": "src/vs/platform/request/electron-browser/requestService.ts",
"type": "replace",
"edit_start_line_idx": 17
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"explorerSection": "Раздел проводника",
"treeAriaLabel": "Проводник"
} | i18n/rus/src/vs/workbench/parts/files/browser/views/explorerView.i18n.json | 0 | https://github.com/microsoft/vscode/commit/10ae5b4b913b6b86351c43ebbd544a982643c5ac | [
0.00017609614587854594,
0.00017609614587854594,
0.00017609614587854594,
0.00017609614587854594,
0
] |
{
"id": 1,
"code_window": [
" * This service exposes the `request` API, while using the global\n",
" * or configured proxy settings.\n",
" */\n",
"export class RequestService extends NodeRequestService {\n",
"\n",
"\tprivate _useXhrRequest = true;\n",
"\n",
"\tprotected configure(config: IHTTPConfiguration) {\n",
"\t\tthis._useXhrRequest = !config.http.proxy;\n",
"\t}\n",
"\n",
"\trequest(options: IRequestOptions): TPromise<IRequestContext> {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [],
"file_path": "src/vs/platform/request/electron-browser/requestService.ts",
"type": "replace",
"edit_start_line_idx": 17
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"array": "tableaux",
"boolean": "booléens",
"number": "nombres",
"object": "objets",
"string": "chaînes",
"undefined": "non défini"
} | i18n/fra/src/vs/languages/json/common/json.i18n.json | 0 | https://github.com/microsoft/vscode/commit/10ae5b4b913b6b86351c43ebbd544a982643c5ac | [
0.00017725632642395794,
0.0001730251678964123,
0.00016879400936886668,
0.0001730251678964123,
0.000004231158527545631
] |
{
"id": 2,
"code_window": [
"\trequest(options: IRequestOptions): TPromise<IRequestContext> {\n",
"\t\tif (this._useXhrRequest) {\n",
"\t\t\treturn super.request(options, xhrRequest);\n",
"\t\t} else {\n",
"\t\t\treturn super.request(options);\n",
"\t\t}\n",
"\t}\n",
"}\n",
"\n",
"class ArryBufferStream extends Readable {\n"
],
"labels": [
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\treturn super.request(options, xhrRequest);\n"
],
"file_path": "src/vs/platform/request/electron-browser/requestService.ts",
"type": "replace",
"edit_start_line_idx": 25
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import { TPromise } from 'vs/base/common/winjs.base';
import { IRequestOptions, IRequestContext, IRequestFunction } from 'vs/base/node/request';
import { Readable } from 'stream';
import { RequestService as NodeRequestService } from 'vs/platform/request/node/requestService';
import { IHTTPConfiguration } from 'vs/platform/request/node/request';
/**
* This service exposes the `request` API, while using the global
* or configured proxy settings.
*/
export class RequestService extends NodeRequestService {
private _useXhrRequest = true;
protected configure(config: IHTTPConfiguration) {
this._useXhrRequest = !config.http.proxy;
}
request(options: IRequestOptions): TPromise<IRequestContext> {
if (this._useXhrRequest) {
return super.request(options, xhrRequest);
} else {
return super.request(options);
}
}
}
class ArryBufferStream extends Readable {
private _buffer: Buffer;
private _offset: number;
private _length: number;
constructor(arraybuffer: ArrayBuffer) {
super();
this._buffer = new Buffer(new Uint8Array(arraybuffer));
this._offset = 0;
this._length = this._buffer.length;
}
_read(size: number) {
if (this._offset < this._length) {
this.push(this._buffer.slice(this._offset, (this._offset + size)));
this._offset += size;
} else {
this.push(null);
}
}
}
export const xhrRequest: IRequestFunction = (options: IRequestOptions): TPromise<IRequestContext> => {
const xhr = new XMLHttpRequest();
return new TPromise<IRequestContext>((resolve, reject) => {
xhr.open(options.type, options.url, true, options.user, options.password);
setRequestHeaders(xhr, options);
xhr.responseType = 'arraybuffer';
xhr.onerror = reject;
xhr.onload = (e) => {
resolve({
res: {
statusCode: xhr.status,
headers: getResponseHeaders(xhr)
},
stream: new ArryBufferStream(xhr.response)
});
};
xhr.send(options.data);
return null;
}, () => {
// cancel
xhr.abort();
});
};
// --- header utils
const unsafeHeaders = Object.create(null);
unsafeHeaders['User-Agent'] = true;
unsafeHeaders['Content-Length'] = true;
unsafeHeaders['Accept-Encoding'] = true;
function setRequestHeaders(xhr: XMLHttpRequest, options: IRequestOptions): void {
if (options.headers) {
for (let k in options.headers) {
if (!unsafeHeaders[k]) {
xhr.setRequestHeader(k, options.headers[k]);
}
}
}
}
function getResponseHeaders(xhr: XMLHttpRequest): { [name: string]: string } {
const headers: { [name: string]: string } = Object.create(null);
for (const line of xhr.getAllResponseHeaders().split(/\r\n|\n|\r/g)) {
if (line) {
const idx = line.indexOf(':');
headers[line.substr(0, idx).trim().toLowerCase()] = line.substr(idx + 1).trim();
}
}
return headers;
}
| src/vs/platform/request/electron-browser/requestService.ts | 1 | https://github.com/microsoft/vscode/commit/10ae5b4b913b6b86351c43ebbd544a982643c5ac | [
0.9992270469665527,
0.19568593800067902,
0.00016300739662256092,
0.00026258203433826566,
0.37056824564933777
] |
{
"id": 2,
"code_window": [
"\trequest(options: IRequestOptions): TPromise<IRequestContext> {\n",
"\t\tif (this._useXhrRequest) {\n",
"\t\t\treturn super.request(options, xhrRequest);\n",
"\t\t} else {\n",
"\t\t\treturn super.request(options);\n",
"\t\t}\n",
"\t}\n",
"}\n",
"\n",
"class ArryBufferStream extends Readable {\n"
],
"labels": [
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\treturn super.request(options, xhrRequest);\n"
],
"file_path": "src/vs/platform/request/electron-browser/requestService.ts",
"type": "replace",
"edit_start_line_idx": 25
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"copy": "复制",
"cut": "剪切",
"developer": "开发人员",
"file": "文件",
"paste": "粘贴",
"redo": "恢复",
"selectAll": "全选",
"undo": "撤消"
} | i18n/chs/src/vs/workbench/electron-browser/integration.i18n.json | 0 | https://github.com/microsoft/vscode/commit/10ae5b4b913b6b86351c43ebbd544a982643c5ac | [
0.0001784231571946293,
0.00017608216148801148,
0.00017374116578139365,
0.00017608216148801148,
0.000002340995706617832
] |
{
"id": 2,
"code_window": [
"\trequest(options: IRequestOptions): TPromise<IRequestContext> {\n",
"\t\tif (this._useXhrRequest) {\n",
"\t\t\treturn super.request(options, xhrRequest);\n",
"\t\t} else {\n",
"\t\t\treturn super.request(options);\n",
"\t\t}\n",
"\t}\n",
"}\n",
"\n",
"class ArryBufferStream extends Readable {\n"
],
"labels": [
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\treturn super.request(options, xhrRequest);\n"
],
"file_path": "src/vs/platform/request/electron-browser/requestService.ts",
"type": "replace",
"edit_start_line_idx": 25
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"abbreviation": "Сокращение",
"enterAbbreviation": "Ввод сокращения",
"wrapWithAbbreviationAction": "Emmet: перенос с сокращением"
} | i18n/rus/src/vs/workbench/parts/emmet/node/actions/wrapWithAbbreviation.i18n.json | 0 | https://github.com/microsoft/vscode/commit/10ae5b4b913b6b86351c43ebbd544a982643c5ac | [
0.0001745558256516233,
0.00017199444118887186,
0.00016943304217420518,
0.00017199444118887186,
0.0000025613917387090623
] |
{
"id": 2,
"code_window": [
"\trequest(options: IRequestOptions): TPromise<IRequestContext> {\n",
"\t\tif (this._useXhrRequest) {\n",
"\t\t\treturn super.request(options, xhrRequest);\n",
"\t\t} else {\n",
"\t\t\treturn super.request(options);\n",
"\t\t}\n",
"\t}\n",
"}\n",
"\n",
"class ArryBufferStream extends Readable {\n"
],
"labels": [
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\treturn super.request(options, xhrRequest);\n"
],
"file_path": "src/vs/platform/request/electron-browser/requestService.ts",
"type": "replace",
"edit_start_line_idx": 25
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"editableEditorAriaLabel": "Textdateivergleichs-Editor",
"editableEditorWithInputAriaLabel": "{0}. Textdateivergleichs-Editor.",
"inlineDiffLabel": "Zur Inlineansicht wechseln",
"navigate.next.label": "Nächste Änderung",
"navigate.prev.label": "Vorherige Änderung",
"readonlyEditorAriaLabel": "Schreibgeschützter Textvergleichs-Editor.",
"readonlyEditorWithInputAriaLabel": "{0}. Schreibgeschützter Textvergleichs-Editor.",
"sideBySideDiffLabel": "Zur Parallelansicht wechseln",
"textDiffEditor": "Textdiff-Editor"
} | i18n/deu/src/vs/workbench/browser/parts/editor/textDiffEditor.i18n.json | 0 | https://github.com/microsoft/vscode/commit/10ae5b4b913b6b86351c43ebbd544a982643c5ac | [
0.00017599979764781892,
0.00017496288637630641,
0.0001739259751047939,
0.00017496288637630641,
0.0000010369112715125084
] |
{
"id": 3,
"code_window": [
"\t\t// cancel\n",
"\t\txhr.abort();\n",
"\t});\n",
"};\n",
"\n",
"// --- header utils\n",
"\n",
"const unsafeHeaders = Object.create(null);\n",
"unsafeHeaders['User-Agent'] = true;\n",
"unsafeHeaders['Content-Length'] = true;\n",
"unsafeHeaders['Accept-Encoding'] = true;\n",
"\n",
"function setRequestHeaders(xhr: XMLHttpRequest, options: IRequestOptions): void {\n",
"\tif (options.headers) {\n",
"\t\tfor (let k in options.headers) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/platform/request/electron-browser/requestService.ts",
"type": "replace",
"edit_start_line_idx": 85
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import { TPromise } from 'vs/base/common/winjs.base';
import { IRequestOptions, IRequestContext, IRequestFunction } from 'vs/base/node/request';
import { Readable } from 'stream';
import { RequestService as NodeRequestService } from 'vs/platform/request/node/requestService';
import { IHTTPConfiguration } from 'vs/platform/request/node/request';
/**
* This service exposes the `request` API, while using the global
* or configured proxy settings.
*/
export class RequestService extends NodeRequestService {
private _useXhrRequest = true;
protected configure(config: IHTTPConfiguration) {
this._useXhrRequest = !config.http.proxy;
}
request(options: IRequestOptions): TPromise<IRequestContext> {
if (this._useXhrRequest) {
return super.request(options, xhrRequest);
} else {
return super.request(options);
}
}
}
class ArryBufferStream extends Readable {
private _buffer: Buffer;
private _offset: number;
private _length: number;
constructor(arraybuffer: ArrayBuffer) {
super();
this._buffer = new Buffer(new Uint8Array(arraybuffer));
this._offset = 0;
this._length = this._buffer.length;
}
_read(size: number) {
if (this._offset < this._length) {
this.push(this._buffer.slice(this._offset, (this._offset + size)));
this._offset += size;
} else {
this.push(null);
}
}
}
export const xhrRequest: IRequestFunction = (options: IRequestOptions): TPromise<IRequestContext> => {
const xhr = new XMLHttpRequest();
return new TPromise<IRequestContext>((resolve, reject) => {
xhr.open(options.type, options.url, true, options.user, options.password);
setRequestHeaders(xhr, options);
xhr.responseType = 'arraybuffer';
xhr.onerror = reject;
xhr.onload = (e) => {
resolve({
res: {
statusCode: xhr.status,
headers: getResponseHeaders(xhr)
},
stream: new ArryBufferStream(xhr.response)
});
};
xhr.send(options.data);
return null;
}, () => {
// cancel
xhr.abort();
});
};
// --- header utils
const unsafeHeaders = Object.create(null);
unsafeHeaders['User-Agent'] = true;
unsafeHeaders['Content-Length'] = true;
unsafeHeaders['Accept-Encoding'] = true;
function setRequestHeaders(xhr: XMLHttpRequest, options: IRequestOptions): void {
if (options.headers) {
for (let k in options.headers) {
if (!unsafeHeaders[k]) {
xhr.setRequestHeader(k, options.headers[k]);
}
}
}
}
function getResponseHeaders(xhr: XMLHttpRequest): { [name: string]: string } {
const headers: { [name: string]: string } = Object.create(null);
for (const line of xhr.getAllResponseHeaders().split(/\r\n|\n|\r/g)) {
if (line) {
const idx = line.indexOf(':');
headers[line.substr(0, idx).trim().toLowerCase()] = line.substr(idx + 1).trim();
}
}
return headers;
}
| src/vs/platform/request/electron-browser/requestService.ts | 1 | https://github.com/microsoft/vscode/commit/10ae5b4b913b6b86351c43ebbd544a982643c5ac | [
0.9985806941986084,
0.25062495470046997,
0.00016892860003281385,
0.001102981623262167,
0.43173280358314514
] |
{
"id": 3,
"code_window": [
"\t\t// cancel\n",
"\t\txhr.abort();\n",
"\t});\n",
"};\n",
"\n",
"// --- header utils\n",
"\n",
"const unsafeHeaders = Object.create(null);\n",
"unsafeHeaders['User-Agent'] = true;\n",
"unsafeHeaders['Content-Length'] = true;\n",
"unsafeHeaders['Accept-Encoding'] = true;\n",
"\n",
"function setRequestHeaders(xhr: XMLHttpRequest, options: IRequestOptions): void {\n",
"\tif (options.headers) {\n",
"\t\tfor (let k in options.headers) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/platform/request/electron-browser/requestService.ts",
"type": "replace",
"edit_start_line_idx": 85
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"jsonserver.name": "JSON 言語サーバー"
} | i18n/jpn/extensions/json/client/out/jsonMain.i18n.json | 0 | https://github.com/microsoft/vscode/commit/10ae5b4b913b6b86351c43ebbd544a982643c5ac | [
0.00017590803327038884,
0.00017590803327038884,
0.00017590803327038884,
0.00017590803327038884,
0
] |
{
"id": 3,
"code_window": [
"\t\t// cancel\n",
"\t\txhr.abort();\n",
"\t});\n",
"};\n",
"\n",
"// --- header utils\n",
"\n",
"const unsafeHeaders = Object.create(null);\n",
"unsafeHeaders['User-Agent'] = true;\n",
"unsafeHeaders['Content-Length'] = true;\n",
"unsafeHeaders['Accept-Encoding'] = true;\n",
"\n",
"function setRequestHeaders(xhr: XMLHttpRequest, options: IRequestOptions): void {\n",
"\tif (options.headers) {\n",
"\t\tfor (let k in options.headers) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/platform/request/electron-browser/requestService.ts",
"type": "replace",
"edit_start_line_idx": 85
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import * as assert from 'assert';
import { DiffComputer } from 'vs/editor/common/diff/diffComputer';
import { IChange, ICharChange, ILineChange } from 'vs/editor/common/editorCommon';
function extractCharChangeRepresentation(change, expectedChange): ICharChange {
var hasOriginal = expectedChange && expectedChange.originalStartLineNumber > 0;
var hasModified = expectedChange && expectedChange.modifiedStartLineNumber > 0;
return {
originalStartLineNumber: hasOriginal ? change.originalStartLineNumber : 0,
originalStartColumn: hasOriginal ? change.originalStartColumn : 0,
originalEndLineNumber: hasOriginal ? change.originalEndLineNumber : 0,
originalEndColumn: hasOriginal ? change.originalEndColumn : 0,
modifiedStartLineNumber: hasModified ? change.modifiedStartLineNumber : 0,
modifiedStartColumn: hasModified ? change.modifiedStartColumn : 0,
modifiedEndLineNumber: hasModified ? change.modifiedEndLineNumber : 0,
modifiedEndColumn: hasModified ? change.modifiedEndColumn : 0,
};
}
function extractLineChangeRepresentation(change, expectedChange): IChange | ILineChange {
if (change.charChanges) {
let charChanges: ICharChange[] = [];
for (let i = 0; i < change.charChanges.length; i++) {
charChanges.push(
extractCharChangeRepresentation(
change.charChanges[i],
expectedChange && expectedChange.charChanges && i < expectedChange.charChanges.length ? expectedChange.charChanges[i] : null
)
);
}
return {
originalStartLineNumber: change.originalStartLineNumber,
originalEndLineNumber: change.originalEndLineNumber,
modifiedStartLineNumber: change.modifiedStartLineNumber,
modifiedEndLineNumber: change.modifiedEndLineNumber,
charChanges: charChanges
};
}
return {
originalStartLineNumber: change.originalStartLineNumber,
originalEndLineNumber: change.originalEndLineNumber,
modifiedStartLineNumber: change.modifiedStartLineNumber,
modifiedEndLineNumber: change.modifiedEndLineNumber
};
}
function assertDiff(originalLines: string[], modifiedLines: string[], expectedChanges: IChange[], shouldPostProcessCharChanges: boolean = false, shouldIgnoreTrimWhitespace: boolean = false) {
var diffComputer = new DiffComputer(originalLines, modifiedLines, {
shouldPostProcessCharChanges: shouldPostProcessCharChanges || false,
shouldIgnoreTrimWhitespace: shouldIgnoreTrimWhitespace || false,
shouldConsiderTrimWhitespaceInEmptyCase: true
});
var changes = diffComputer.computeDiff();
var extracted = [];
for (var i = 0; i < changes.length; i++) {
extracted.push(extractLineChangeRepresentation(changes[i], i < expectedChanges.length ? expectedChanges[i] : null));
}
assert.deepEqual(extracted, expectedChanges);
}
function createLineDeletion(startLineNumber, endLineNumber, modifiedLineNumber): IChange {
return {
originalStartLineNumber: startLineNumber,
originalEndLineNumber: endLineNumber,
modifiedStartLineNumber: modifiedLineNumber,
modifiedEndLineNumber: 0
};
}
function createLineInsertion(startLineNumber, endLineNumber, originalLineNumber): IChange {
return {
originalStartLineNumber: originalLineNumber,
originalEndLineNumber: 0,
modifiedStartLineNumber: startLineNumber,
modifiedEndLineNumber: endLineNumber
};
}
function createLineChange(originalStartLineNumber, originalEndLineNumber, modifiedStartLineNumber, modifiedEndLineNumber, charChanges): ILineChange {
return {
originalStartLineNumber: originalStartLineNumber,
originalEndLineNumber: originalEndLineNumber,
modifiedStartLineNumber: modifiedStartLineNumber,
modifiedEndLineNumber: modifiedEndLineNumber,
charChanges: charChanges
};
}
function createCharInsertion(startLineNumber, startColumn, endLineNumber, endColumn) {
return {
originalStartLineNumber: 0,
originalStartColumn: 0,
originalEndLineNumber: 0,
originalEndColumn: 0,
modifiedStartLineNumber: startLineNumber,
modifiedStartColumn: startColumn,
modifiedEndLineNumber: endLineNumber,
modifiedEndColumn: endColumn
};
}
function createCharDeletion(startLineNumber, startColumn, endLineNumber, endColumn) {
return {
originalStartLineNumber: startLineNumber,
originalStartColumn: startColumn,
originalEndLineNumber: endLineNumber,
originalEndColumn: endColumn,
modifiedStartLineNumber: 0,
modifiedStartColumn: 0,
modifiedEndLineNumber: 0,
modifiedEndColumn: 0
};
}
function createCharChange(originalStartLineNumber, originalStartColumn, originalEndLineNumber, originalEndColumn,
modifiedStartLineNumber, modifiedStartColumn, modifiedEndLineNumber, modifiedEndColumn) {
return {
originalStartLineNumber: originalStartLineNumber,
originalStartColumn: originalStartColumn,
originalEndLineNumber: originalEndLineNumber,
originalEndColumn: originalEndColumn,
modifiedStartLineNumber: modifiedStartLineNumber,
modifiedStartColumn: modifiedStartColumn,
modifiedEndLineNumber: modifiedEndLineNumber,
modifiedEndColumn: modifiedEndColumn
};
}
suite('Editor Diff - DiffComputer', () => {
// ---- insertions
test('one inserted line below', () => {
var original = ['line'];
var modified = ['line', 'new line'];
var expected = [createLineInsertion(2, 2, 1)];
assertDiff(original, modified, expected);
});
test('two inserted lines below', () => {
var original = ['line'];
var modified = ['line', 'new line', 'another new line'];
var expected = [createLineInsertion(2, 3, 1)];
assertDiff(original, modified, expected);
});
test('one inserted line above', () => {
var original = ['line'];
var modified = ['new line', 'line'];
var expected = [createLineInsertion(1, 1, 0)];
assertDiff(original, modified, expected);
});
test('two inserted lines above', () => {
var original = ['line'];
var modified = ['new line', 'another new line', 'line'];
var expected = [createLineInsertion(1, 2, 0)];
assertDiff(original, modified, expected);
});
test('one inserted line in middle', () => {
var original = ['line1', 'line2', 'line3', 'line4'];
var modified = ['line1', 'line2', 'new line', 'line3', 'line4'];
var expected = [createLineInsertion(3, 3, 2)];
assertDiff(original, modified, expected);
});
test('two inserted lines in middle', () => {
var original = ['line1', 'line2', 'line3', 'line4'];
var modified = ['line1', 'line2', 'new line', 'another new line', 'line3', 'line4'];
var expected = [createLineInsertion(3, 4, 2)];
assertDiff(original, modified, expected);
});
test('two inserted lines in middle interrupted', () => {
var original = ['line1', 'line2', 'line3', 'line4'];
var modified = ['line1', 'line2', 'new line', 'line3', 'another new line', 'line4'];
var expected = [createLineInsertion(3, 3, 2), createLineInsertion(5, 5, 3)];
assertDiff(original, modified, expected);
});
// ---- deletions
test('one deleted line below', () => {
var original = ['line', 'new line'];
var modified = ['line'];
var expected = [createLineDeletion(2, 2, 1)];
assertDiff(original, modified, expected);
});
test('two deleted lines below', () => {
var original = ['line', 'new line', 'another new line'];
var modified = ['line'];
var expected = [createLineDeletion(2, 3, 1)];
assertDiff(original, modified, expected);
});
test('one deleted lines above', () => {
var original = ['new line', 'line'];
var modified = ['line'];
var expected = [createLineDeletion(1, 1, 0)];
assertDiff(original, modified, expected);
});
test('two deleted lines above', () => {
var original = ['new line', 'another new line', 'line'];
var modified = ['line'];
var expected = [createLineDeletion(1, 2, 0)];
assertDiff(original, modified, expected);
});
test('one deleted line in middle', () => {
var original = ['line1', 'line2', 'new line', 'line3', 'line4'];
var modified = ['line1', 'line2', 'line3', 'line4'];
var expected = [createLineDeletion(3, 3, 2)];
assertDiff(original, modified, expected);
});
test('two deleted lines in middle', () => {
var original = ['line1', 'line2', 'new line', 'another new line', 'line3', 'line4'];
var modified = ['line1', 'line2', 'line3', 'line4'];
var expected = [createLineDeletion(3, 4, 2)];
assertDiff(original, modified, expected);
});
test('two deleted lines in middle interrupted', () => {
var original = ['line1', 'line2', 'new line', 'line3', 'another new line', 'line4'];
var modified = ['line1', 'line2', 'line3', 'line4'];
var expected = [createLineDeletion(3, 3, 2), createLineDeletion(5, 5, 3)];
assertDiff(original, modified, expected);
});
// ---- changes
test('one line changed: chars inserted at the end', () => {
var original = ['line'];
var modified = ['line changed'];
var expected = [
createLineChange(1, 1, 1, 1, [
createCharInsertion(1, 5, 1, 13)
])
];
assertDiff(original, modified, expected);
});
test('one line changed: chars inserted at the beginning', () => {
var original = ['line'];
var modified = ['my line'];
var expected = [
createLineChange(1, 1, 1, 1, [
createCharInsertion(1, 1, 1, 4)
])
];
assertDiff(original, modified, expected);
});
test('one line changed: chars inserted in the middle', () => {
var original = ['abba'];
var modified = ['abzzba'];
var expected = [
createLineChange(1, 1, 1, 1, [
createCharInsertion(1, 3, 1, 5)
])
];
assertDiff(original, modified, expected);
});
test('one line changed: chars inserted in the middle (two spots)', () => {
var original = ['abba'];
var modified = ['abzzbzza'];
var expected = [
createLineChange(1, 1, 1, 1, [
createCharInsertion(1, 3, 1, 5),
createCharInsertion(1, 6, 1, 8)
])
];
assertDiff(original, modified, expected);
});
test('one line changed: chars deleted 1', () => {
var original = ['abcdefg'];
var modified = ['abcfg'];
var expected = [
createLineChange(1, 1, 1, 1, [
createCharDeletion(1, 4, 1, 6)
])
];
assertDiff(original, modified, expected);
});
test('one line changed: chars deleted 2', () => {
var original = ['abcdefg'];
var modified = ['acfg'];
var expected = [
createLineChange(1, 1, 1, 1, [
createCharDeletion(1, 2, 1, 3),
createCharDeletion(1, 4, 1, 6)
])
];
assertDiff(original, modified, expected);
});
test('two lines changed 1', () => {
var original = ['abcd', 'efgh'];
var modified = ['abcz'];
var expected = [
createLineChange(1, 2, 1, 1, [
createCharChange(1, 4, 2, 5, 1, 4, 1, 5)
])
];
assertDiff(original, modified, expected);
});
test('two lines changed 2', () => {
var original = ['foo', 'abcd', 'efgh', 'BAR'];
var modified = ['foo', 'abcz', 'BAR'];
var expected = [
createLineChange(2, 3, 2, 2, [
createCharChange(2, 4, 3, 5, 2, 4, 2, 5)
])
];
assertDiff(original, modified, expected);
});
test('two lines changed 3', () => {
var original = ['foo', 'abcd', 'efgh', 'BAR'];
var modified = ['foo', 'abcz', 'zzzzefgh', 'BAR'];
var expected = [
createLineChange(2, 3, 2, 3, [
createCharChange(2, 4, 2, 5, 2, 4, 3, 5)
])
];
assertDiff(original, modified, expected);
});
test('three lines changed', () => {
var original = ['foo', 'abcd', 'efgh', 'BAR'];
var modified = ['foo', 'zzzefgh', 'xxx', 'BAR'];
var expected = [
createLineChange(2, 3, 2, 3, [
createCharChange(2, 1, 2, 5, 2, 1, 2, 4),
createCharInsertion(3, 1, 3, 4)
])
];
assertDiff(original, modified, expected);
});
test('big change part 1', () => {
var original = ['foo', 'abcd', 'efgh', 'BAR'];
var modified = ['hello', 'foo', 'zzzefgh', 'xxx', 'BAR'];
var expected = [
createLineInsertion(1, 1, 0),
createLineChange(2, 3, 3, 4, [
createCharChange(2, 1, 2, 5, 3, 1, 3, 4),
createCharInsertion(4, 1, 4, 4)
])
];
assertDiff(original, modified, expected);
});
test('big change part 2', () => {
var original = ['foo', 'abcd', 'efgh', 'BAR', 'RAB'];
var modified = ['hello', 'foo', 'zzzefgh', 'xxx', 'BAR'];
var expected = [
createLineInsertion(1, 1, 0),
createLineChange(2, 3, 3, 4, [
createCharChange(2, 1, 2, 5, 3, 1, 3, 4),
createCharInsertion(4, 1, 4, 4)
]),
createLineDeletion(5, 5, 5)
];
assertDiff(original, modified, expected);
});
test('char change postprocessing merges', () => {
var original = ['abba'];
var modified = ['azzzbzzzbzzza'];
var expected = [
createLineChange(1, 1, 1, 1, [
createCharChange(1, 2, 1, 4, 1, 2, 1, 13)
])
];
assertDiff(original, modified, expected, true);
});
test('ignore trim whitespace', () => {
var original = ['\t\t foo ', 'abcd', 'efgh', '\t\t BAR\t\t'];
var modified = [' hello\t', '\t foo \t', 'zzzefgh', 'xxx', ' BAR \t'];
var expected = [
createLineInsertion(1, 1, 0),
createLineChange(2, 3, 3, 4, [
createCharChange(2, 1, 2, 5, 3, 1, 3, 4),
createCharInsertion(4, 1, 4, 4)
])
];
assertDiff(original, modified, expected, false, true);
});
test('issue #12122 r.hasOwnProperty is not a function', () => {
var original = ['hasOwnProperty'];
var modified = ['hasOwnProperty', 'and another line'];
var expected = [
createLineInsertion(2, 2, 1)
];
assertDiff(original, modified, expected);
});
});
| src/vs/editor/test/common/diff/diffComputer.test.ts | 0 | https://github.com/microsoft/vscode/commit/10ae5b4b913b6b86351c43ebbd544a982643c5ac | [
0.00017633139214012772,
0.00017236138228327036,
0.00016637031512800604,
0.00017264182679355145,
0.0000021218634174147155
] |
{
"id": 3,
"code_window": [
"\t\t// cancel\n",
"\t\txhr.abort();\n",
"\t});\n",
"};\n",
"\n",
"// --- header utils\n",
"\n",
"const unsafeHeaders = Object.create(null);\n",
"unsafeHeaders['User-Agent'] = true;\n",
"unsafeHeaders['Content-Length'] = true;\n",
"unsafeHeaders['Accept-Encoding'] = true;\n",
"\n",
"function setRequestHeaders(xhr: XMLHttpRequest, options: IRequestOptions): void {\n",
"\tif (options.headers) {\n",
"\t\tfor (let k in options.headers) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/platform/request/electron-browser/requestService.ts",
"type": "replace",
"edit_start_line_idx": 85
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"JsonSchema.locale": "Linguaggio dell'interfaccia utente da usare.",
"configureLocale": "Configura lingua",
"displayLanguage": "Definisce la lingua visualizzata di VSCode.",
"doc": "Per un elenco delle lingue supportate, vedere {0}.",
"fail.createSettings": "Non è possibile creare '{0}' ({1}).",
"restart": "Se si modifica il valore, è necessario riavviare VSCode."
} | i18n/ita/src/vs/workbench/browser/actions/configureLocale.i18n.json | 0 | https://github.com/microsoft/vscode/commit/10ae5b4b913b6b86351c43ebbd544a982643c5ac | [
0.00017303637287113816,
0.0001723887398838997,
0.00017174110689666122,
0.0001723887398838997,
6.476329872384667e-7
] |
{
"id": 4,
"code_window": [
"function setRequestHeaders(xhr: XMLHttpRequest, options: IRequestOptions): void {\n",
"\tif (options.headers) {\n",
"\t\tfor (let k in options.headers) {\n",
"\t\t\tif (!unsafeHeaders[k]) {\n",
"\t\t\t\txhr.setRequestHeader(k, options.headers[k]);\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\t\t\ttry {\n"
],
"file_path": "src/vs/platform/request/electron-browser/requestService.ts",
"type": "replace",
"edit_start_line_idx": 95
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import { TPromise } from 'vs/base/common/winjs.base';
import { IRequestOptions, IRequestContext, IRequestFunction } from 'vs/base/node/request';
import { Readable } from 'stream';
import { RequestService as NodeRequestService } from 'vs/platform/request/node/requestService';
import { IHTTPConfiguration } from 'vs/platform/request/node/request';
/**
* This service exposes the `request` API, while using the global
* or configured proxy settings.
*/
export class RequestService extends NodeRequestService {
private _useXhrRequest = true;
protected configure(config: IHTTPConfiguration) {
this._useXhrRequest = !config.http.proxy;
}
request(options: IRequestOptions): TPromise<IRequestContext> {
if (this._useXhrRequest) {
return super.request(options, xhrRequest);
} else {
return super.request(options);
}
}
}
class ArryBufferStream extends Readable {
private _buffer: Buffer;
private _offset: number;
private _length: number;
constructor(arraybuffer: ArrayBuffer) {
super();
this._buffer = new Buffer(new Uint8Array(arraybuffer));
this._offset = 0;
this._length = this._buffer.length;
}
_read(size: number) {
if (this._offset < this._length) {
this.push(this._buffer.slice(this._offset, (this._offset + size)));
this._offset += size;
} else {
this.push(null);
}
}
}
export const xhrRequest: IRequestFunction = (options: IRequestOptions): TPromise<IRequestContext> => {
const xhr = new XMLHttpRequest();
return new TPromise<IRequestContext>((resolve, reject) => {
xhr.open(options.type, options.url, true, options.user, options.password);
setRequestHeaders(xhr, options);
xhr.responseType = 'arraybuffer';
xhr.onerror = reject;
xhr.onload = (e) => {
resolve({
res: {
statusCode: xhr.status,
headers: getResponseHeaders(xhr)
},
stream: new ArryBufferStream(xhr.response)
});
};
xhr.send(options.data);
return null;
}, () => {
// cancel
xhr.abort();
});
};
// --- header utils
const unsafeHeaders = Object.create(null);
unsafeHeaders['User-Agent'] = true;
unsafeHeaders['Content-Length'] = true;
unsafeHeaders['Accept-Encoding'] = true;
function setRequestHeaders(xhr: XMLHttpRequest, options: IRequestOptions): void {
if (options.headers) {
for (let k in options.headers) {
if (!unsafeHeaders[k]) {
xhr.setRequestHeader(k, options.headers[k]);
}
}
}
}
function getResponseHeaders(xhr: XMLHttpRequest): { [name: string]: string } {
const headers: { [name: string]: string } = Object.create(null);
for (const line of xhr.getAllResponseHeaders().split(/\r\n|\n|\r/g)) {
if (line) {
const idx = line.indexOf(':');
headers[line.substr(0, idx).trim().toLowerCase()] = line.substr(idx + 1).trim();
}
}
return headers;
}
| src/vs/platform/request/electron-browser/requestService.ts | 1 | https://github.com/microsoft/vscode/commit/10ae5b4b913b6b86351c43ebbd544a982643c5ac | [
0.9987624883651733,
0.24288195371627808,
0.00016443048662040383,
0.0040639895014464855,
0.40122970938682556
] |
{
"id": 4,
"code_window": [
"function setRequestHeaders(xhr: XMLHttpRequest, options: IRequestOptions): void {\n",
"\tif (options.headers) {\n",
"\t\tfor (let k in options.headers) {\n",
"\t\t\tif (!unsafeHeaders[k]) {\n",
"\t\t\t\txhr.setRequestHeader(k, options.headers[k]);\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\t\t\ttry {\n"
],
"file_path": "src/vs/platform/request/electron-browser/requestService.ts",
"type": "replace",
"edit_start_line_idx": 95
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import { IDiffChange, ISequence, LcsDiff } from 'vs/base/common/diff/diff';
import * as strings from 'vs/base/common/strings';
import { ICharChange, ILineChange } from 'vs/editor/common/editorCommon';
var MAXIMUM_RUN_TIME = 5000; // 5 seconds
var MINIMUM_MATCHING_CHARACTER_LENGTH = 3;
interface IMarker {
lineNumber: number;
column: number;
offset: number;
}
function computeDiff(originalSequence: ISequence, modifiedSequence: ISequence, continueProcessingPredicate: () => boolean): IDiffChange[] {
var diffAlgo = new LcsDiff(originalSequence, modifiedSequence, continueProcessingPredicate);
return diffAlgo.ComputeDiff();
}
class MarkerSequence implements ISequence {
public buffer: string;
public startMarkers: IMarker[];
public endMarkers: IMarker[];
constructor(buffer: string, startMarkers: IMarker[], endMarkers: IMarker[]) {
this.buffer = buffer;
this.startMarkers = startMarkers;
this.endMarkers = endMarkers;
}
public equals(other: any): boolean {
if (!(other instanceof MarkerSequence)) {
return false;
}
var otherMarkerSequence = <MarkerSequence>other;
if (this.getLength() !== otherMarkerSequence.getLength()) {
return false;
}
for (var i = 0, len = this.getLength(); i < len; i++) {
var myElement = this.getElementHash(i);
var otherElement = otherMarkerSequence.getElementHash(i);
if (myElement !== otherElement) {
return false;
}
}
return true;
}
public getLength(): number {
return this.startMarkers.length;
}
public getElementHash(i: number): string {
return this.buffer.substring(this.startMarkers[i].offset, this.endMarkers[i].offset);
}
public getStartLineNumber(i: number): number {
if (i === this.startMarkers.length) {
// This is the special case where a change happened after the last marker
return this.startMarkers[i - 1].lineNumber + 1;
}
return this.startMarkers[i].lineNumber;
}
public getStartColumn(i: number): number {
return this.startMarkers[i].column;
}
public getEndLineNumber(i: number): number {
return this.endMarkers[i].lineNumber;
}
public getEndColumn(i: number): number {
return this.endMarkers[i].column;
}
}
class LineMarkerSequence extends MarkerSequence {
constructor(lines: string[], shouldIgnoreTrimWhitespace: boolean) {
var i: number, length: number, pos: number;
var buffer = '';
var startMarkers: IMarker[] = [], endMarkers: IMarker[] = [], startColumn: number, endColumn: number;
for (pos = 0, i = 0, length = lines.length; i < length; i++) {
buffer += lines[i];
startColumn = 1;
endColumn = lines[i].length + 1;
if (shouldIgnoreTrimWhitespace) {
startColumn = LineMarkerSequence._getFirstNonBlankColumn(lines[i], 1);
endColumn = LineMarkerSequence._getLastNonBlankColumn(lines[i], 1);
}
startMarkers.push({
offset: pos + startColumn - 1,
lineNumber: i + 1,
column: startColumn
});
endMarkers.push({
offset: pos + endColumn - 1,
lineNumber: i + 1,
column: endColumn
});
pos += lines[i].length;
}
super(buffer, startMarkers, endMarkers);
}
private static _getFirstNonBlankColumn(txt: string, defaultValue: number): number {
var r = strings.firstNonWhitespaceIndex(txt);
if (r === -1) {
return defaultValue;
}
return r + 1;
}
private static _getLastNonBlankColumn(txt: string, defaultValue: number): number {
var r = strings.lastNonWhitespaceIndex(txt);
if (r === -1) {
return defaultValue;
}
return r + 2;
}
public getCharSequence(startIndex: number, endIndex: number): MarkerSequence {
var startMarkers: IMarker[] = [], endMarkers: IMarker[] = [], index: number, i: number, startMarker: IMarker, endMarker: IMarker;
for (index = startIndex; index <= endIndex; index++) {
startMarker = this.startMarkers[index];
endMarker = this.endMarkers[index];
for (i = startMarker.offset; i < endMarker.offset; i++) {
startMarkers.push({
offset: i,
lineNumber: startMarker.lineNumber,
column: startMarker.column + (i - startMarker.offset)
});
endMarkers.push({
offset: i + 1,
lineNumber: startMarker.lineNumber,
column: startMarker.column + (i - startMarker.offset) + 1
});
}
}
return new MarkerSequence(this.buffer, startMarkers, endMarkers);
}
}
class CharChange implements ICharChange {
public originalStartLineNumber: number;
public originalStartColumn: number;
public originalEndLineNumber: number;
public originalEndColumn: number;
public modifiedStartLineNumber: number;
public modifiedStartColumn: number;
public modifiedEndLineNumber: number;
public modifiedEndColumn: number;
constructor(diffChange: IDiffChange, originalCharSequence: MarkerSequence, modifiedCharSequence: MarkerSequence) {
if (diffChange.originalLength === 0) {
this.originalStartLineNumber = 0;
this.originalStartColumn = 0;
this.originalEndLineNumber = 0;
this.originalEndColumn = 0;
} else {
this.originalStartLineNumber = originalCharSequence.getStartLineNumber(diffChange.originalStart);
this.originalStartColumn = originalCharSequence.getStartColumn(diffChange.originalStart);
this.originalEndLineNumber = originalCharSequence.getEndLineNumber(diffChange.originalStart + diffChange.originalLength - 1);
this.originalEndColumn = originalCharSequence.getEndColumn(diffChange.originalStart + diffChange.originalLength - 1);
}
if (diffChange.modifiedLength === 0) {
this.modifiedStartLineNumber = 0;
this.modifiedStartColumn = 0;
this.modifiedEndLineNumber = 0;
this.modifiedEndColumn = 0;
} else {
this.modifiedStartLineNumber = modifiedCharSequence.getStartLineNumber(diffChange.modifiedStart);
this.modifiedStartColumn = modifiedCharSequence.getStartColumn(diffChange.modifiedStart);
this.modifiedEndLineNumber = modifiedCharSequence.getEndLineNumber(diffChange.modifiedStart + diffChange.modifiedLength - 1);
this.modifiedEndColumn = modifiedCharSequence.getEndColumn(diffChange.modifiedStart + diffChange.modifiedLength - 1);
}
}
}
function postProcessCharChanges(rawChanges: IDiffChange[]): IDiffChange[] {
if (rawChanges.length <= 1) {
return rawChanges;
}
var result = [rawChanges[0]];
var i: number, len: number, originalMatchingLength: number, modifiedMatchingLength: number, matchingLength: number, prevChange = result[0], currChange: IDiffChange;
for (i = 1, len = rawChanges.length; i < len; i++) {
currChange = rawChanges[i];
originalMatchingLength = currChange.originalStart - (prevChange.originalStart + prevChange.originalLength);
modifiedMatchingLength = currChange.modifiedStart - (prevChange.modifiedStart + prevChange.modifiedLength);
// Both of the above should be equal, but the continueProcessingPredicate may prevent this from being true
matchingLength = Math.min(originalMatchingLength, modifiedMatchingLength);
if (matchingLength < MINIMUM_MATCHING_CHARACTER_LENGTH) {
// Merge the current change into the previous one
prevChange.originalLength = (currChange.originalStart + currChange.originalLength) - prevChange.originalStart;
prevChange.modifiedLength = (currChange.modifiedStart + currChange.modifiedLength) - prevChange.modifiedStart;
} else {
// Add the current change
result.push(currChange);
prevChange = currChange;
}
}
return result;
}
class LineChange implements ILineChange {
public originalStartLineNumber: number;
public originalEndLineNumber: number;
public modifiedStartLineNumber: number;
public modifiedEndLineNumber: number;
public charChanges: CharChange[];
constructor(diffChange: IDiffChange, originalLineSequence: LineMarkerSequence, modifiedLineSequence: LineMarkerSequence, continueProcessingPredicate: () => boolean, shouldPostProcessCharChanges: boolean) {
if (diffChange.originalLength === 0) {
this.originalStartLineNumber = originalLineSequence.getStartLineNumber(diffChange.originalStart) - 1;
this.originalEndLineNumber = 0;
} else {
this.originalStartLineNumber = originalLineSequence.getStartLineNumber(diffChange.originalStart);
this.originalEndLineNumber = originalLineSequence.getEndLineNumber(diffChange.originalStart + diffChange.originalLength - 1);
}
if (diffChange.modifiedLength === 0) {
this.modifiedStartLineNumber = modifiedLineSequence.getStartLineNumber(diffChange.modifiedStart) - 1;
this.modifiedEndLineNumber = 0;
} else {
this.modifiedStartLineNumber = modifiedLineSequence.getStartLineNumber(diffChange.modifiedStart);
this.modifiedEndLineNumber = modifiedLineSequence.getEndLineNumber(diffChange.modifiedStart + diffChange.modifiedLength - 1);
}
if (diffChange.originalLength !== 0 && diffChange.modifiedLength !== 0 && continueProcessingPredicate()) {
var originalCharSequence = originalLineSequence.getCharSequence(diffChange.originalStart, diffChange.originalStart + diffChange.originalLength - 1);
var modifiedCharSequence = modifiedLineSequence.getCharSequence(diffChange.modifiedStart, diffChange.modifiedStart + diffChange.modifiedLength - 1);
var rawChanges = computeDiff(originalCharSequence, modifiedCharSequence, continueProcessingPredicate);
if (shouldPostProcessCharChanges) {
rawChanges = postProcessCharChanges(rawChanges);
}
this.charChanges = [];
for (var i = 0, length = rawChanges.length; i < length; i++) {
this.charChanges.push(new CharChange(rawChanges[i], originalCharSequence, modifiedCharSequence));
}
}
}
}
export interface IDiffComputerOpts {
shouldPostProcessCharChanges: boolean;
shouldIgnoreTrimWhitespace: boolean;
shouldConsiderTrimWhitespaceInEmptyCase: boolean;
}
export class DiffComputer {
private shouldPostProcessCharChanges: boolean;
private shouldIgnoreTrimWhitespace: boolean;
private maximumRunTimeMs: number;
private original: LineMarkerSequence;
private modified: LineMarkerSequence;
private computationStartTime: number;
constructor(originalLines: string[], modifiedLines: string[], opts: IDiffComputerOpts) {
this.shouldPostProcessCharChanges = opts.shouldPostProcessCharChanges;
this.shouldIgnoreTrimWhitespace = opts.shouldIgnoreTrimWhitespace;
this.maximumRunTimeMs = MAXIMUM_RUN_TIME;
this.original = new LineMarkerSequence(originalLines, this.shouldIgnoreTrimWhitespace);
this.modified = new LineMarkerSequence(modifiedLines, this.shouldIgnoreTrimWhitespace);
if (opts.shouldConsiderTrimWhitespaceInEmptyCase && this.shouldIgnoreTrimWhitespace && this.original.equals(this.modified)) {
// Diff would be empty with `shouldIgnoreTrimWhitespace`
this.shouldIgnoreTrimWhitespace = false;
this.original = new LineMarkerSequence(originalLines, this.shouldIgnoreTrimWhitespace);
this.modified = new LineMarkerSequence(modifiedLines, this.shouldIgnoreTrimWhitespace);
}
}
public computeDiff(): ILineChange[] {
this.computationStartTime = (new Date()).getTime();
var rawChanges = computeDiff(this.original, this.modified, this._continueProcessingPredicate.bind(this));
var lineChanges: ILineChange[] = [];
for (var i = 0, length = rawChanges.length; i < length; i++) {
lineChanges.push(new LineChange(rawChanges[i], this.original, this.modified, this._continueProcessingPredicate.bind(this), this.shouldPostProcessCharChanges));
}
return lineChanges;
}
private _continueProcessingPredicate(): boolean {
if (this.maximumRunTimeMs === 0) {
return true;
}
var now = (new Date()).getTime();
return now - this.computationStartTime < this.maximumRunTimeMs;
}
}
| src/vs/editor/common/diff/diffComputer.ts | 0 | https://github.com/microsoft/vscode/commit/10ae5b4b913b6b86351c43ebbd544a982643c5ac | [
0.00030827749287709594,
0.0001835076982388273,
0.00016722535656299442,
0.00017177533300127834,
0.00003131630001007579
] |
{
"id": 4,
"code_window": [
"function setRequestHeaders(xhr: XMLHttpRequest, options: IRequestOptions): void {\n",
"\tif (options.headers) {\n",
"\t\tfor (let k in options.headers) {\n",
"\t\t\tif (!unsafeHeaders[k]) {\n",
"\t\t\t\txhr.setRequestHeader(k, options.headers[k]);\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\t\t\ttry {\n"
],
"file_path": "src/vs/platform/request/electron-browser/requestService.ts",
"type": "replace",
"edit_start_line_idx": 95
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import { IRemoteCom } from 'vs/base/common/remote';
import { TPromise } from 'vs/base/common/winjs.base';
import { AbstractThreadService } from 'vs/workbench/services/thread/common/abstractThreadService';
import { IThreadService } from 'vs/workbench/services/thread/common/threadService';
export class ExtHostThreadService extends AbstractThreadService implements IThreadService {
public _serviceBrand: any;
protected _remoteCom: IRemoteCom;
constructor(remoteCom: IRemoteCom) {
super(false);
this._remoteCom = remoteCom;
this._remoteCom.setManyHandler(this);
}
protected _callOnRemote(proxyId: string, path: string, args: any[]): TPromise<any> {
return this._remoteCom.callOnRemote(proxyId, path, args);
}
}
| src/vs/workbench/services/thread/common/extHostThreadService.ts | 0 | https://github.com/microsoft/vscode/commit/10ae5b4b913b6b86351c43ebbd544a982643c5ac | [
0.0001811353286029771,
0.00017616110562812537,
0.0001732680102577433,
0.00017407993436791003,
0.0000035329007914697286
] |
{
"id": 4,
"code_window": [
"function setRequestHeaders(xhr: XMLHttpRequest, options: IRequestOptions): void {\n",
"\tif (options.headers) {\n",
"\t\tfor (let k in options.headers) {\n",
"\t\t\tif (!unsafeHeaders[k]) {\n",
"\t\t\t\txhr.setRequestHeader(k, options.headers[k]);\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\t\t\ttry {\n"
],
"file_path": "src/vs/platform/request/electron-browser/requestService.ts",
"type": "replace",
"edit_start_line_idx": 95
} | <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"><style type="text/css">.icon-canvas-transparent{opacity:0;fill:#F6F6F6;} .icon-vs-out{fill:#F6F6F6;} .icon-vs-bg{fill:#424242;} .icon-vs-fg{fill:#F0EFF1;}</style><path class="icon-canvas-transparent" d="M32 32h-32v-32h32v32z" id="canvas"/><path class="icon-vs-out" d="M32 28h-32v-24h32v24z" id="outline"/><path class="icon-vs-bg" d="M2 6v20h28v-20h-28zm26 18h-24v-16h24v16zm-13-8l-5.25 5.5-1.75-1.833 3.5-3.667-3.5-3.667 1.75-1.833 5.25 5.5z" id="iconBg"/><g id="iconFg"><path class="icon-vs-fg" d="M4 8v16h24v-16h-24zm5.75 13.5l-1.75-1.833 3.5-3.667-3.5-3.667 1.75-1.833 5.25 5.5-5.25 5.5z"/></g></svg> | src/vs/workbench/parts/debug/browser/media/repl.svg | 0 | https://github.com/microsoft/vscode/commit/10ae5b4b913b6b86351c43ebbd544a982643c5ac | [
0.00016675943334121257,
0.00016675943334121257,
0.00016675943334121257,
0.00016675943334121257,
0
] |
{
"id": 5,
"code_window": [
"\t\t\t\txhr.setRequestHeader(k, options.headers[k]);\n",
"\t\t\t}\n",
"\t\t}\n",
"\t}\n",
"}\n",
"\n"
],
"labels": [
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t} catch (e) {\n",
"\t\t\t\tconsole.warn(e);\n"
],
"file_path": "src/vs/platform/request/electron-browser/requestService.ts",
"type": "add",
"edit_start_line_idx": 97
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import { TPromise } from 'vs/base/common/winjs.base';
import { IRequestOptions, IRequestContext, IRequestFunction } from 'vs/base/node/request';
import { Readable } from 'stream';
import { RequestService as NodeRequestService } from 'vs/platform/request/node/requestService';
import { IHTTPConfiguration } from 'vs/platform/request/node/request';
/**
* This service exposes the `request` API, while using the global
* or configured proxy settings.
*/
export class RequestService extends NodeRequestService {
private _useXhrRequest = true;
protected configure(config: IHTTPConfiguration) {
this._useXhrRequest = !config.http.proxy;
}
request(options: IRequestOptions): TPromise<IRequestContext> {
if (this._useXhrRequest) {
return super.request(options, xhrRequest);
} else {
return super.request(options);
}
}
}
class ArryBufferStream extends Readable {
private _buffer: Buffer;
private _offset: number;
private _length: number;
constructor(arraybuffer: ArrayBuffer) {
super();
this._buffer = new Buffer(new Uint8Array(arraybuffer));
this._offset = 0;
this._length = this._buffer.length;
}
_read(size: number) {
if (this._offset < this._length) {
this.push(this._buffer.slice(this._offset, (this._offset + size)));
this._offset += size;
} else {
this.push(null);
}
}
}
export const xhrRequest: IRequestFunction = (options: IRequestOptions): TPromise<IRequestContext> => {
const xhr = new XMLHttpRequest();
return new TPromise<IRequestContext>((resolve, reject) => {
xhr.open(options.type, options.url, true, options.user, options.password);
setRequestHeaders(xhr, options);
xhr.responseType = 'arraybuffer';
xhr.onerror = reject;
xhr.onload = (e) => {
resolve({
res: {
statusCode: xhr.status,
headers: getResponseHeaders(xhr)
},
stream: new ArryBufferStream(xhr.response)
});
};
xhr.send(options.data);
return null;
}, () => {
// cancel
xhr.abort();
});
};
// --- header utils
const unsafeHeaders = Object.create(null);
unsafeHeaders['User-Agent'] = true;
unsafeHeaders['Content-Length'] = true;
unsafeHeaders['Accept-Encoding'] = true;
function setRequestHeaders(xhr: XMLHttpRequest, options: IRequestOptions): void {
if (options.headers) {
for (let k in options.headers) {
if (!unsafeHeaders[k]) {
xhr.setRequestHeader(k, options.headers[k]);
}
}
}
}
function getResponseHeaders(xhr: XMLHttpRequest): { [name: string]: string } {
const headers: { [name: string]: string } = Object.create(null);
for (const line of xhr.getAllResponseHeaders().split(/\r\n|\n|\r/g)) {
if (line) {
const idx = line.indexOf(':');
headers[line.substr(0, idx).trim().toLowerCase()] = line.substr(idx + 1).trim();
}
}
return headers;
}
| src/vs/platform/request/electron-browser/requestService.ts | 1 | https://github.com/microsoft/vscode/commit/10ae5b4b913b6b86351c43ebbd544a982643c5ac | [
0.04240158572793007,
0.004864221904426813,
0.0001687061449047178,
0.001031855819746852,
0.011429981328547001
] |
{
"id": 5,
"code_window": [
"\t\t\t\txhr.setRequestHeader(k, options.headers[k]);\n",
"\t\t\t}\n",
"\t\t}\n",
"\t}\n",
"}\n",
"\n"
],
"labels": [
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t} catch (e) {\n",
"\t\t\t\tconsole.warn(e);\n"
],
"file_path": "src/vs/platform/request/electron-browser/requestService.ts",
"type": "add",
"edit_start_line_idx": 97
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
/* Title Container */
.vs .monaco-workbench > .part.editor > .content > .one-editor-silo > .container > .title.tabs {
background: #F3F3F3;
}
.vs-dark .monaco-workbench > .part.editor > .content > .one-editor-silo > .container > .title.tabs {
background: #252526;
}
.monaco-workbench > .part.editor > .content > .one-editor-silo > .container > .title.tabs::before {
display: block;
content: '';
position: absolute;
top: 34px;
width: 100%;
z-index: 1; /* on top of tabs */
}
.vs .monaco-workbench > .part.editor > .content > .one-editor-silo > .container > .title.tabs::before {
border-top: 1px solid #DDDDDD;
}
.vs-dark .monaco-workbench > .part.editor > .content > .one-editor-silo > .container > .title.tabs::before {
border-top: 1px solid #403F3F;
}
.hc-black .monaco-workbench > .part.editor > .content > .one-editor-silo > .container > .title.tabs::before {
border-top: 1px solid #6FC3DF;
}
.monaco-workbench > .part.editor > .content > .one-editor-silo > .container > .title.tabs > .monaco-scrollable-element {
flex: 1;
}
.monaco-workbench > .part.editor > .content > .one-editor-silo > .container > .title.tabs > .monaco-scrollable-element .scrollbar {
z-index: 3; /* on top of tabs */
cursor: default;
}
/* Tabs Container */
.monaco-workbench > .part.editor > .content > .one-editor-silo > .container > .title .tabs-container {
display: flex;
height: 35px;
}
.monaco-workbench > .part.editor > .content > .one-editor-silo > .container > .title .tabs-container.scroll {
overflow: scroll !important;
}
.monaco-workbench > .part.editor > .content > .one-editor-silo > .container > .title .tabs-container::-webkit-scrollbar {
display: none;
}
/* Tab */
.monaco-workbench > .part.editor > .content > .one-editor-silo > .container > .title .tabs-container > .tab {
display: flex;
width: 120px;
min-width: fit-content;
white-space: nowrap;
cursor: pointer;
height: 35px;
box-sizing: border-box;
border: 1px solid transparent;
padding-left: 10px;
}
.monaco-workbench > .part.editor > .content > .one-editor-silo > .container > .title .tabs-container > .tab.active {
z-index: 2; /* on top of the horizontal border of the title */
}
.monaco-workbench > .part.editor > .content > .one-editor-silo.dragged-over > .container > .title .tabs-container > .tab.active {
z-index: auto;
}
.vs .monaco-workbench > .part.editor > .content > .one-editor-silo > .container > .title .tabs-container > .tab:not(.active) {
background-color: #ECECEC;
}
.vs-dark .monaco-workbench > .part.editor > .content > .one-editor-silo > .container > .title .tabs-container > .tab:not(.active) {
background-color: #2D2D2D;
}
.vs .monaco-workbench > .part.editor > .content > .one-editor-silo > .container > .title .tabs-container > .tab {
border-left-color: #DDDDDD;
}
.vs .monaco-workbench > .part.editor > .content > .one-editor-silo > .container > .title .tabs-container > .tab.active:last-child {
border-right-color: #DDDDDD;
}
.vs-dark .monaco-workbench > .part.editor > .content > .one-editor-silo > .container > .title .tabs-container > .tab {
border-left-color: #403F3F;
}
.vs-dark .monaco-workbench > .part.editor > .content > .one-editor-silo > .container > .title .tabs-container > .tab.active:last-child {
border-right-color: #403F3F;
}
.vs-dark .monaco-workbench > .part.editor > .content > .one-editor-silo > .container > .title .tabs-container > .tab:first-child,
.vs .monaco-workbench > .part.editor > .content > .one-editor-silo > .container > .title .tabs-container > .tab:first-child {
border-left-color: transparent;
}
.hc-black .monaco-workbench > .part.editor > .content > .one-editor-silo > .container > .title .tabs-container > .tab {
border-left-color: #6FC3DF;
}
.hc-black .monaco-workbench > .part.editor > .content > .one-editor-silo > .container > .title .tabs-container > .tab.active {
outline: 2px solid #f38518;
outline-offset: -1px;
}
.vs .monaco-workbench > .part.editor > .content > .one-editor-silo > .container > .title .tabs-container.dropfeedback,
.vs .monaco-workbench > .part.editor > .content > .one-editor-silo > .container > .title .tabs-container > .tab.dropfeedback {
background-color: #DDECFF;
}
.vs-dark .monaco-workbench > .part.editor > .content > .one-editor-silo > .container > .title .tabs-container.dropfeedback,
.vs-dark .monaco-workbench > .part.editor > .content > .one-editor-silo > .container > .title .tabs-container > .tab.dropfeedback {
background-color: #383B3D;
}
.hc-black .monaco-workbench > .part.editor > .content > .one-editor-silo > .container > .title .tabs-container.dropfeedback,
.hc-black .monaco-workbench > .part.editor > .content > .one-editor-silo > .container > .title .tabs-container > .tab.dropfeedback {
background: none !important;
outline: 2px dashed #f38518;
outline-offset: -2px;
}
/* Tab Label */
.monaco-workbench > .part.editor > .content > .one-editor-silo > .container > .title .tabs-container > .tab .tab-label {
margin-top: auto;
margin-bottom: auto;
}
.monaco-workbench > .part.editor > .content > .one-editor-silo > .container > .title .tabs-container > .tab .monaco-icon-label::before {
height: 16px; /* tweak the icon size of the editor labels when icons are enabled */
}
.vs .monaco-workbench > .part.editor > .content > .one-editor-silo > .container > .title .tabs-container > .tab .tab-label {
opacity: 0.7 !important;
}
.vs-dark .monaco-workbench > .part.editor > .content > .one-editor-silo > .container > .title .tabs-container > .tab .tab-label {
opacity: 0.5 !important;
}
.vs-dark .monaco-workbench > .part.editor > .content > .one-editor-silo > .container > .title .tabs-container > .tab.active .tab-label,
.monaco-workbench > .part.editor > .content > .one-editor-silo > .container > .title .tabs-container > .tab.dropfeedback .tab-label {
opacity: 1 !important;
}
.hc-black .monaco-workbench > .part.editor > .content > .one-editor-silo > .container > .title .tabs-container > .tab .tab-label {
opacity: 1 !important;
}
/* Tab Close */
.monaco-workbench > .part.editor > .content > .one-editor-silo > .container > .title .tabs-container > .tab > .tab-close {
margin-top: auto;
margin-bottom: auto;
width: 28px;
}
.monaco-workbench > .part.editor > .content > .one-editor-silo > .container > .title .tabs-container > .tab.no-close-button > .tab-close {
display: none; /* hide the close action bar when we are configured to hide it */
}
.monaco-workbench > .part.editor > .content > .one-editor-silo > .container > .title.active .tabs-container > .tab.active > .tab-close .action-label, /* always show it for active tab */
.monaco-workbench > .part.editor > .content > .one-editor-silo > .container > .title.active .tabs-container > .tab > .tab-close .action-label:focus, /* always show it on focus */
.monaco-workbench > .part.editor > .content > .one-editor-silo > .container > .title.active .tabs-container > .tab:hover > .tab-close .action-label, /* always show it on hover */
.monaco-workbench > .part.editor > .content > .one-editor-silo > .container > .title.active .tabs-container > .tab.active:hover > .tab-close .action-label, /* always show it on hover */
.monaco-workbench > .part.editor > .content > .one-editor-silo > .container > .title.active .tabs-container > .tab.dirty > .tab-close .action-label { /* always show it for dirty tabs */
opacity: 1;
}
.monaco-workbench > .part.editor > .content > .one-editor-silo > .container > .title .tabs-container > .tab.active > .tab-close .action-label, /* show dimmed for inactive group */
.monaco-workbench > .part.editor > .content > .one-editor-silo > .container > .title .tabs-container > .tab.active:hover > .tab-close .action-label, /* show dimmed for inactive group */
.monaco-workbench > .part.editor > .content > .one-editor-silo > .container > .title .tabs-container > .tab.dirty > .tab-close .action-label, /* show dimmed for inactive group */
.monaco-workbench > .part.editor > .content > .one-editor-silo > .container > .title .tabs-container > .tab:hover > .tab-close .action-label { /* show dimmed for inactive group */
opacity: 0.5;
}
.monaco-workbench > .part.editor > .content > .one-editor-silo > .container > .title .tabs-container > .tab > .tab-close .action-label {
opacity: 0;
display: block;
height: 16px;
width: 16px;
background-size: 16px;
background-position: center center;
background-repeat: no-repeat;
margin-right: 0.5em;
}
.vs .monaco-workbench > .part.editor > .content > .one-editor-silo > .container > .title .tabs-container > .tab.dirty .close-editor-action {
background: url('close-dirty.svg') center center no-repeat;
}
.vs-dark .monaco-workbench > .part.editor > .content > .one-editor-silo > .container > .title .tabs-container > .tab.dirty .close-editor-action,
.hc-black .monaco-workbench > .part.editor > .content > .one-editor-silo > .container > .title .tabs-container > .tab.dirty .close-editor-action {
background: url('close-dirty-inverse.svg') center center no-repeat;
}
.vs .monaco-workbench > .part.editor > .content > .one-editor-silo > .container > .title .tabs-container > .tab.dirty .close-editor-action:hover {
background: url('close.svg') center center no-repeat;
}
.vs-dark .monaco-workbench > .part.editor > .content > .one-editor-silo > .container > .title .tabs-container > .tab.dirty .close-editor-action:hover,
.hc-black .monaco-workbench > .part.editor > .content > .one-editor-silo > .container > .title .tabs-container > .tab.dirty .close-editor-action:hover {
background: url('close-inverse.svg') center center no-repeat;
}
/* No Tab Close Button */
.monaco-workbench > .part.editor > .content > .one-editor-silo > .container > .title .tabs-container > .tab.no-close-button {
padding-right: 28px; /* make room for dirty indication when we are running without close button */
}
.monaco-workbench > .part.editor > .content > .one-editor-silo > .container > .title .tabs-container > .tab.no-close-button.dirty {
background-repeat: no-repeat;
background-position-y: center;
background-position-x: calc(100% - 6px); /* to the right of the tab label */
}
.vs .monaco-workbench > .part.editor > .content > .one-editor-silo > .container > .title .tabs-container > .tab.no-close-button.dirty {
background-image: url('close-dirty.svg');
}
.vs-dark .monaco-workbench > .part.editor > .content > .one-editor-silo > .container > .title .tabs-container > .tab.no-close-button.dirty,
.hc-black .monaco-workbench > .part.editor > .content > .one-editor-silo > .container > .title .tabs-container > .tab.no-close-button.dirty {
background-image: url('close-dirty-inverse.svg');
}
/* Editor Actions */
.monaco-workbench > .part.editor > .content > .one-editor-silo > .container > .title .editor-actions {
cursor: default;
flex: initial;
padding-left: 4px;
} | src/vs/workbench/browser/parts/editor/media/tabstitle.css | 0 | https://github.com/microsoft/vscode/commit/10ae5b4b913b6b86351c43ebbd544a982643c5ac | [
0.00017599257989786565,
0.00016856970614753664,
0.0001635292574064806,
0.00016810190572869033,
0.0000027835249056806788
] |
{
"id": 5,
"code_window": [
"\t\t\t\txhr.setRequestHeader(k, options.headers[k]);\n",
"\t\t\t}\n",
"\t\t}\n",
"\t}\n",
"}\n",
"\n"
],
"labels": [
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t} catch (e) {\n",
"\t\t\t\tconsole.warn(e);\n"
],
"file_path": "src/vs/platform/request/electron-browser/requestService.ts",
"type": "add",
"edit_start_line_idx": 97
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"json.bower.default": "Standarddatei \"bower.json\"",
"json.bower.error.repoaccess": "Fehler bei der Anforderung des Bower-Repositorys: {0}",
"json.bower.latest.version": "Neueste",
"json.bower.package.hover": "{0}"
} | i18n/deu/extensions/javascript/out/features/bowerJSONContribution.i18n.json | 0 | https://github.com/microsoft/vscode/commit/10ae5b4b913b6b86351c43ebbd544a982643c5ac | [
0.0001776192511897534,
0.0001761937019182369,
0.0001747681526467204,
0.0001761937019182369,
0.000001425549271516502
] |
{
"id": 5,
"code_window": [
"\t\t\t\txhr.setRequestHeader(k, options.headers[k]);\n",
"\t\t\t}\n",
"\t\t}\n",
"\t}\n",
"}\n",
"\n"
],
"labels": [
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t} catch (e) {\n",
"\t\t\t\tconsole.warn(e);\n"
],
"file_path": "src/vs/platform/request/electron-browser/requestService.ts",
"type": "add",
"edit_start_line_idx": 97
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"label.closeButton": "Chiudi",
"label.find": "Trova",
"label.matchesLocation": "{0} di {1}",
"label.nextMatchButton": "Risultato successivo",
"label.noResults": "Nessun risultato",
"label.previousMatchButton": "Risultato precedente",
"label.replace": "Sostituisci",
"label.replaceAllButton": "Sostituisci tutto",
"label.replaceButton": "Sostituisci",
"label.toggleReplaceButton": "Attiva/Disattiva modalità sostituzione",
"label.toggleSelectionFind": "Trova nella selezione",
"placeholder.find": "Trova",
"placeholder.replace": "Sostituisci",
"title.matchesCountLimit": "Vengono evidenziati solo i primi 999 risultati, ma tutte le operazioni di ricerca funzionano sull'intero testo."
} | i18n/ita/src/vs/editor/contrib/find/browser/findWidget.i18n.json | 0 | https://github.com/microsoft/vscode/commit/10ae5b4b913b6b86351c43ebbd544a982643c5ac | [
0.0001776192511897534,
0.00017429709259886295,
0.0001702911249594763,
0.00017498091619927436,
0.0000030305186555779073
] |
{
"id": 6,
"code_window": [
"\n",
"\tprivate onDidUpdateConfiguration(e: IConfigurationServiceEvent) {\n",
"\t\tthis.configure(e.config);\n",
"\t}\n",
"\n",
"\tprotected configure(config: IHTTPConfiguration) {\n",
"\t\tthis.proxyUrl = config.http && config.http.proxy;\n",
"\t\tthis.strictSSL = config.http && config.http.proxyStrictSSL;\n",
"\t\tthis.authorization = config.http && config.http.proxyAuthorization;\n",
"\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tprivate configure(config: IHTTPConfiguration) {\n"
],
"file_path": "src/vs/platform/request/node/requestService.ts",
"type": "replace",
"edit_start_line_idx": 38
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import { TPromise } from 'vs/base/common/winjs.base';
import { IRequestOptions, IRequestContext, IRequestFunction } from 'vs/base/node/request';
import { Readable } from 'stream';
import { RequestService as NodeRequestService } from 'vs/platform/request/node/requestService';
import { IHTTPConfiguration } from 'vs/platform/request/node/request';
/**
* This service exposes the `request` API, while using the global
* or configured proxy settings.
*/
export class RequestService extends NodeRequestService {
private _useXhrRequest = true;
protected configure(config: IHTTPConfiguration) {
this._useXhrRequest = !config.http.proxy;
}
request(options: IRequestOptions): TPromise<IRequestContext> {
if (this._useXhrRequest) {
return super.request(options, xhrRequest);
} else {
return super.request(options);
}
}
}
class ArryBufferStream extends Readable {
private _buffer: Buffer;
private _offset: number;
private _length: number;
constructor(arraybuffer: ArrayBuffer) {
super();
this._buffer = new Buffer(new Uint8Array(arraybuffer));
this._offset = 0;
this._length = this._buffer.length;
}
_read(size: number) {
if (this._offset < this._length) {
this.push(this._buffer.slice(this._offset, (this._offset + size)));
this._offset += size;
} else {
this.push(null);
}
}
}
export const xhrRequest: IRequestFunction = (options: IRequestOptions): TPromise<IRequestContext> => {
const xhr = new XMLHttpRequest();
return new TPromise<IRequestContext>((resolve, reject) => {
xhr.open(options.type, options.url, true, options.user, options.password);
setRequestHeaders(xhr, options);
xhr.responseType = 'arraybuffer';
xhr.onerror = reject;
xhr.onload = (e) => {
resolve({
res: {
statusCode: xhr.status,
headers: getResponseHeaders(xhr)
},
stream: new ArryBufferStream(xhr.response)
});
};
xhr.send(options.data);
return null;
}, () => {
// cancel
xhr.abort();
});
};
// --- header utils
const unsafeHeaders = Object.create(null);
unsafeHeaders['User-Agent'] = true;
unsafeHeaders['Content-Length'] = true;
unsafeHeaders['Accept-Encoding'] = true;
function setRequestHeaders(xhr: XMLHttpRequest, options: IRequestOptions): void {
if (options.headers) {
for (let k in options.headers) {
if (!unsafeHeaders[k]) {
xhr.setRequestHeader(k, options.headers[k]);
}
}
}
}
function getResponseHeaders(xhr: XMLHttpRequest): { [name: string]: string } {
const headers: { [name: string]: string } = Object.create(null);
for (const line of xhr.getAllResponseHeaders().split(/\r\n|\n|\r/g)) {
if (line) {
const idx = line.indexOf(':');
headers[line.substr(0, idx).trim().toLowerCase()] = line.substr(idx + 1).trim();
}
}
return headers;
}
| src/vs/platform/request/electron-browser/requestService.ts | 1 | https://github.com/microsoft/vscode/commit/10ae5b4b913b6b86351c43ebbd544a982643c5ac | [
0.5637249946594238,
0.04718905687332153,
0.00016680380213074386,
0.00017323551583103836,
0.15574154257774353
] |
{
"id": 6,
"code_window": [
"\n",
"\tprivate onDidUpdateConfiguration(e: IConfigurationServiceEvent) {\n",
"\t\tthis.configure(e.config);\n",
"\t}\n",
"\n",
"\tprotected configure(config: IHTTPConfiguration) {\n",
"\t\tthis.proxyUrl = config.http && config.http.proxy;\n",
"\t\tthis.strictSSL = config.http && config.http.proxyStrictSSL;\n",
"\t\tthis.authorization = config.http && config.http.proxyAuthorization;\n",
"\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tprivate configure(config: IHTTPConfiguration) {\n"
],
"file_path": "src/vs/platform/request/node/requestService.ts",
"type": "replace",
"edit_start_line_idx": 38
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"telemetry.enableTelemetry": "Consente l'invio di errori e dati sull'utilizzo a Microsoft.",
"telemetryConfigurationTitle": "Configurazione della telemetria"
} | i18n/ita/src/vs/platform/telemetry/electron-browser/electronTelemetryService.i18n.json | 0 | https://github.com/microsoft/vscode/commit/10ae5b4b913b6b86351c43ebbd544a982643c5ac | [
0.00017531760386191308,
0.00017531760386191308,
0.00017531760386191308,
0.00017531760386191308,
0
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.