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": 3,
"code_window": [
"import {\n",
" Alert,\n",
" Button,\n",
" FormControl,\n",
" FormGroup,\n",
" ControlLabel,\n",
" Modal,\n",
" Radio,\n",
"} from 'react-bootstrap';\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "superset-frontend/src/explore/components/SaveModal.jsx",
"type": "replace",
"edit_start_line_idx": 27
} | {#
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.
#}
{% macro js_bundle(filename) %}
{# HTML comment is needed for webpack-dev-server to replace assets
with development version #}
<!-- Bundle js {{ filename }} START -->
{% for entry in js_manifest(filename) %}
<script src="{{ entry }}"></script>
{% endfor %}
<!-- Bundle js {{ filename }} END -->
{% endmacro %}
{% macro css_bundle(filename) %}
<!-- Bundle css {{ filename }} START -->
{% for entry in css_manifest(filename) %}
<link rel="stylesheet" type="text/css" href="{{ entry }}" />
{% endfor %}
<!-- Bundle css {{ filename }} END -->
{% endmacro %}
| superset/templates/superset/partials/asset_bundle.html | 0 | https://github.com/apache/superset/commit/9eab29aeaacc9e7346649ca46730d49f2fe0b4ef | [
0.00017736133304424584,
0.0001753221731632948,
0.0001731028751237318,
0.00017541224951855838,
0.0000018688432419367018
] |
{
"id": 3,
"code_window": [
"import {\n",
" Alert,\n",
" Button,\n",
" FormControl,\n",
" FormGroup,\n",
" ControlLabel,\n",
" Modal,\n",
" Radio,\n",
"} from 'react-bootstrap';\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "superset-frontend/src/explore/components/SaveModal.jsx",
"type": "replace",
"edit_start_line_idx": 27
} | /**
* 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 moment from 'moment';
import React from 'react';
import PropTypes from 'prop-types';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { Alert } from 'react-bootstrap';
import Dialog from 'react-bootstrap-dialog';
import { t } from '@superset-ui/translation';
import { InfoTooltipWithTrigger } from '@superset-ui/chart-controls';
import shortid from 'shortid';
import { exploreChart } from '../../explore/exploreUtils';
import * as actions from '../actions/sqlLab';
import Button from '../../components/Button';
const propTypes = {
actions: PropTypes.object.isRequired,
query: PropTypes.object,
errorMessage: PropTypes.string,
timeout: PropTypes.number,
database: PropTypes.object.isRequired,
};
const defaultProps = {
query: {},
};
class ExploreResultsButton extends React.PureComponent {
constructor(props) {
super(props);
this.visualize = this.visualize.bind(this);
this.onClick = this.onClick.bind(this);
this.getInvalidColumns = this.getInvalidColumns.bind(this);
this.renderInvalidColumnMessage = this.renderInvalidColumnMessage.bind(
this,
);
}
onClick() {
const timeout = this.props.timeout;
const msg = this.renderInvalidColumnMessage();
if (Math.round(this.getQueryDuration()) > timeout) {
this.dialog.show({
title: t('Explore'),
body: this.renderTimeoutWarning(),
actions: [
Dialog.CancelAction(),
Dialog.OKAction(() => {
this.visualize();
}),
],
bsSize: 'large',
onHide: dialog => {
dialog.hide();
},
});
} else if (msg) {
this.dialog.show({
title: t('Explore'),
body: msg,
actions: [Dialog.DefaultAction('Ok', () => {}, 'btn-primary')],
bsSize: 'large',
bsStyle: 'warning',
onHide: dialog => {
dialog.hide();
},
});
} else {
this.visualize();
}
}
getColumns() {
const props = this.props;
if (
props.query &&
props.query.results &&
props.query.results.selected_columns
) {
return props.query.results.selected_columns;
}
return [];
}
getQueryDuration() {
return moment
.duration(this.props.query.endDttm - this.props.query.startDttm)
.asSeconds();
}
getInvalidColumns() {
const re1 = /^[A-Za-z_]\w*$/; // starts with char or _, then only alphanum
const re2 = /__\d+$/; // does not finish with __ and then a number which screams dup col name
const re3 = /^__timestamp/i; // is not a reserved temporal column alias
return this.props.query.results.selected_columns
.map(col => col.name)
.filter(col => !re1.test(col) || re2.test(col) || re3.test(col));
}
datasourceName() {
const { query } = this.props;
const uniqueId = shortid.generate();
let datasourceName = uniqueId;
if (query) {
datasourceName = query.user ? `${query.user}-` : '';
datasourceName += `${query.tab}-${uniqueId}`;
}
return datasourceName;
}
buildVizOptions() {
const { schema, sql, dbId, templateParams } = this.props.query;
return {
dbId,
schema,
sql,
templateParams,
datasourceName: this.datasourceName(),
columns: this.getColumns(),
};
}
visualize() {
this.props.actions
.createDatasource(this.buildVizOptions())
.then(data => {
const columns = this.getColumns();
const formData = {
datasource: `${data.table_id}__table`,
metrics: [],
groupby: [],
time_range: 'No filter',
viz_type: 'table',
all_columns: columns.map(c => c.name),
row_limit: 1000,
};
this.props.actions.addInfoToast(
t('Creating a data source and creating a new tab'),
);
// open new window for data visualization
exploreChart(formData);
})
.catch(() => {
this.props.actions.addDangerToast(
this.props.errorMessage || t('An error occurred'),
);
});
}
renderTimeoutWarning() {
return (
<Alert bsStyle="warning">
{t(
'This query took %s seconds to run, ',
Math.round(this.getQueryDuration()),
) +
t(
'and the explore view times out at %s seconds ',
this.props.timeout,
) +
t(
'following this flow will most likely lead to your query timing out. ',
) +
t(
'We recommend your summarize your data further before following that flow. ',
) +
t('If activated you can use the ')}
<strong>CREATE TABLE AS </strong>
{t('feature to store a summarized data set that you can then explore.')}
</Alert>
);
}
renderInvalidColumnMessage() {
const invalidColumns = this.getInvalidColumns();
if (invalidColumns.length === 0) {
return null;
}
return (
<div>
{t('Column name(s) ')}
<code>
<strong>{invalidColumns.join(', ')} </strong>
</code>
{t('cannot be used as a column name. Please use aliases (as in ')}
<code>
SELECT count(*)
<strong>AS my_alias</strong>
</code>
){' '}
{t(`limited to alphanumeric characters and underscores. The alias "__timestamp"
used as for the temporal expression and column aliases ending with
double underscores followed by a numeric value are not allowed for reasons
discussed in Github issue #5739.
`)}
</div>
);
}
render() {
const allowsSubquery =
this.props.database && this.props.database.allows_subquery;
return (
<>
<Button
bsSize="small"
onClick={this.onClick}
disabled={!allowsSubquery}
tooltip={t('Explore the result set in the data exploration view')}
>
<InfoTooltipWithTrigger
icon="line-chart"
placement="top"
label="explore"
/>{' '}
{t('Explore')}
</Button>
<Dialog
ref={el => {
this.dialog = el;
}}
/>
</>
);
}
}
ExploreResultsButton.propTypes = propTypes;
ExploreResultsButton.defaultProps = defaultProps;
function mapStateToProps({ sqlLab, common }) {
return {
errorMessage: sqlLab.errorMessage,
timeout: common.conf ? common.conf.SUPERSET_WEBSERVER_TIMEOUT : null,
};
}
function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators(actions, dispatch),
};
}
export { ExploreResultsButton };
export default connect(
mapStateToProps,
mapDispatchToProps,
)(ExploreResultsButton);
| superset-frontend/src/SqlLab/components/ExploreResultsButton.jsx | 0 | https://github.com/apache/superset/commit/9eab29aeaacc9e7346649ca46730d49f2fe0b4ef | [
0.0009242235100828111,
0.00022513417934533209,
0.00016418388986494392,
0.0001708168856566772,
0.00015649078704882413
] |
{
"id": 4,
"code_window": [
" Modal,\n",
" Radio,\n",
"} from 'react-bootstrap';\n",
"import { CreatableSelect } from 'src/components/Select/SupersetStyledSelect';\n",
"import { t } from '@superset-ui/translation';\n",
"import ReactMarkdown from 'react-markdown';\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import FormLabel from 'src/components/FormLabel';\n"
],
"file_path": "superset-frontend/src/explore/components/SaveModal.jsx",
"type": "add",
"edit_start_line_idx": 31
} | /**
* 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, { useState, useEffect, useRef } from 'react';
import {
Button,
Modal,
Row,
Col,
FormControl,
FormGroup,
// @ts-ignore
} from 'react-bootstrap';
// @ts-ignore
import Dialog from 'react-bootstrap-dialog';
import { OptionsType } from 'react-select/src/types';
import { AsyncSelect } from 'src/components/Select';
import rison from 'rison';
import { t } from '@superset-ui/translation';
import { SupersetClient } from '@superset-ui/connection';
import Chart from 'src/types/Chart';
import FormLabel from 'src/components/FormLabel';
import getClientErrorObject from '../../utils/getClientErrorObject';
export type Slice = {
slice_id: number;
slice_name: string;
description: string | null;
cache_timeout: number | null;
};
type InternalProps = {
slice: Slice;
onHide: () => void;
onSave: (chart: Chart) => void;
};
type OwnerOption = {
label: string;
value: number;
};
export type WrapperProps = InternalProps & {
show: boolean;
animation?: boolean; // for the modal
};
export default function PropertiesModalWrapper({
show,
onHide,
animation,
slice,
onSave,
}: WrapperProps) {
// The wrapper is a separate component so that hooks only run when the modal opens
return (
<Modal show={show} onHide={onHide} animation={animation} bsSize="large">
<PropertiesModal slice={slice} onHide={onHide} onSave={onSave} />
</Modal>
);
}
function PropertiesModal({ slice, onHide, onSave }: InternalProps) {
const [submitting, setSubmitting] = useState(false);
const errorDialog = useRef<any>(null);
// values of form inputs
const [name, setName] = useState(slice.slice_name || '');
const [description, setDescription] = useState(slice.description || '');
const [cacheTimeout, setCacheTimeout] = useState(
slice.cache_timeout != null ? slice.cache_timeout : '',
);
const [owners, setOwners] = useState<OptionsType<OwnerOption> | null>(null);
function showError({ error, statusText }: any) {
errorDialog.current.show({
title: 'Error',
bsSize: 'medium',
bsStyle: 'danger',
actions: [Dialog.DefaultAction('Ok', () => {}, 'btn-danger')],
body: error || statusText || t('An error has occurred'),
});
}
async function fetchChartData() {
try {
const response = await SupersetClient.get({
endpoint: `/api/v1/chart/${slice.slice_id}`,
});
const chart = response.json.result;
setOwners(
chart.owners.map((owner: any) => ({
value: owner.id,
label: `${owner.first_name} ${owner.last_name}`,
})),
);
} catch (response) {
const clientError = await getClientErrorObject(response);
showError(clientError);
}
}
// get the owners of this slice
useEffect(() => {
fetchChartData();
}, []);
const loadOptions = (input = '') => {
const query = rison.encode({
filter: input,
});
return SupersetClient.get({
endpoint: `/api/v1/chart/related/owners?q=${query}`,
}).then(
response => {
const { result } = response.json;
return result.map((item: any) => ({
value: item.value,
label: item.text,
}));
},
badResponse => {
getClientErrorObject(badResponse).then(showError);
return [];
},
);
};
const onSubmit = async (event: React.FormEvent) => {
event.stopPropagation();
event.preventDefault();
setSubmitting(true);
const payload: { [key: string]: any } = {
slice_name: name || null,
description: description || null,
cache_timeout: cacheTimeout || null,
};
if (owners) {
payload.owners = owners.map(o => o.value);
}
try {
const res = await SupersetClient.put({
endpoint: `/api/v1/chart/${slice.slice_id}`,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
});
// update the redux state
const updatedChart = {
...res.json.result,
id: slice.slice_id,
};
onSave(updatedChart);
onHide();
} catch (res) {
const clientError = await getClientErrorObject(res);
showError(clientError);
}
setSubmitting(false);
};
return (
<form onSubmit={onSubmit}>
<Modal.Header closeButton>
<Modal.Title>Edit Chart Properties</Modal.Title>
</Modal.Header>
<Modal.Body>
<Row>
<Col md={6}>
<h3>{t('Basic Information')}</h3>
<FormGroup>
<FormLabel htmlFor="name" required>
{t('Name')}
</FormLabel>
<FormControl
name="name"
type="text"
bsSize="sm"
value={name}
// @ts-ignore
onChange={(event: React.ChangeEvent<HTMLInputElement>) =>
setName(event.target.value)
}
/>
</FormGroup>
<FormGroup>
<FormLabel htmlFor="description">{t('Description')}</FormLabel>
<FormControl
name="description"
type="text"
componentClass="textarea"
bsSize="sm"
value={description}
// @ts-ignore
onChange={(event: React.ChangeEvent<HTMLInputElement>) =>
setDescription(event.target.value)
}
style={{ maxWidth: '100%' }}
/>
<p className="help-block">
{t(
'The description can be displayed as widget headers in the dashboard view. Supports markdown.',
)}
</p>
</FormGroup>
</Col>
<Col md={6}>
<h3>{t('Configuration')}</h3>
<FormGroup>
<FormLabel htmlFor="cacheTimeout">{t('Cache Timeout')}</FormLabel>
<FormControl
name="cacheTimeout"
type="text"
bsSize="sm"
value={cacheTimeout}
// @ts-ignore
onChange={(event: React.ChangeEvent<HTMLInputElement>) =>
setCacheTimeout(event.target.value.replace(/[^0-9]/, ''))
}
/>
<p className="help-block">
{t(
'Duration (in seconds) of the caching timeout for this chart. Note this defaults to the datasource/table timeout if undefined.',
)}
</p>
</FormGroup>
<h3 style={{ marginTop: '1em' }}>{t('Access')}</h3>
<FormGroup>
<FormLabel htmlFor="owners">{t('Owners')}</FormLabel>
<AsyncSelect
isMulti
name="owners"
value={owners || []}
loadOptions={loadOptions}
defaultOptions // load options on render
cacheOptions
onChange={setOwners}
disabled={!owners}
filterOption={null} // options are filtered at the api
/>
<p className="help-block">
{t(
'A list of users who can alter the chart. Searchable by name or username.',
)}
</p>
</FormGroup>
</Col>
</Row>
</Modal.Body>
<Modal.Footer>
<Button
type="submit"
bsSize="sm"
bsStyle="primary"
className="m-r-5"
disabled={!owners || submitting}
>
{t('Save')}
</Button>
<Button type="button" bsSize="sm" onClick={onHide}>
{t('Cancel')}
</Button>
<Dialog ref={errorDialog} />
</Modal.Footer>
</form>
);
}
| superset-frontend/src/explore/components/PropertiesModal.tsx | 1 | https://github.com/apache/superset/commit/9eab29aeaacc9e7346649ca46730d49f2fe0b4ef | [
0.009181166999042034,
0.0004879121552221477,
0.0001631868799449876,
0.0001731150841806084,
0.0016429449897259474
] |
{
"id": 4,
"code_window": [
" Modal,\n",
" Radio,\n",
"} from 'react-bootstrap';\n",
"import { CreatableSelect } from 'src/components/Select/SupersetStyledSelect';\n",
"import { t } from '@superset-ui/translation';\n",
"import ReactMarkdown from 'react-markdown';\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import FormLabel from 'src/components/FormLabel';\n"
],
"file_path": "superset-frontend/src/explore/components/SaveModal.jsx",
"type": "add",
"edit_start_line_idx": 31
} | /**
* 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 sinon from 'sinon';
import { ActionCreators as UndoActionCreators } from 'redux-undo';
import {
UPDATE_COMPONENTS,
updateComponents,
DELETE_COMPONENT,
deleteComponent,
CREATE_COMPONENT,
CREATE_TOP_LEVEL_TABS,
createTopLevelTabs,
DELETE_TOP_LEVEL_TABS,
deleteTopLevelTabs,
resizeComponent,
MOVE_COMPONENT,
handleComponentDrop,
updateDashboardTitle,
undoLayoutAction,
redoLayoutAction,
} from 'src/dashboard/actions/dashboardLayout';
import { setUnsavedChanges } from 'src/dashboard/actions/dashboardState';
import * as dashboardFilters from 'src/dashboard/actions/dashboardFilters';
import { addWarningToast, ADD_TOAST } from 'src/messageToasts/actions';
import {
DASHBOARD_GRID_TYPE,
ROW_TYPE,
CHART_TYPE,
TABS_TYPE,
TAB_TYPE,
} from 'src/dashboard/util/componentTypes';
import {
DASHBOARD_HEADER_ID,
DASHBOARD_GRID_ID,
DASHBOARD_ROOT_ID,
NEW_COMPONENTS_SOURCE_ID,
NEW_ROW_ID,
} from 'src/dashboard/util/constants';
describe('dashboardLayout actions', () => {
const mockState = {
dashboardState: {
hasUnsavedChanges: true, // don't dispatch setUnsavedChanges() after every action
},
dashboardInfo: {},
dashboardLayout: {
past: [],
present: {},
future: {},
},
};
function setup(stateOverrides) {
const state = { ...mockState, ...stateOverrides };
const getState = sinon.spy(() => state);
const dispatch = sinon.spy();
return { getState, dispatch, state };
}
beforeEach(() => {
sinon.spy(dashboardFilters, 'updateLayoutComponents');
});
afterEach(() => {
dashboardFilters.updateLayoutComponents.restore();
});
describe('updateComponents', () => {
it('should dispatch an updateLayout action', () => {
const { getState, dispatch } = setup();
const nextComponents = { 1: {} };
const thunk = updateComponents(nextComponents);
thunk(dispatch, getState);
expect(dispatch.callCount).toBe(1);
expect(dispatch.getCall(0).args[0]).toEqual({
type: UPDATE_COMPONENTS,
payload: { nextComponents },
});
// update component should not trigger action for dashboardFilters
expect(dashboardFilters.updateLayoutComponents.callCount).toEqual(0);
});
it('should dispatch a setUnsavedChanges action if hasUnsavedChanges=false', () => {
const { getState, dispatch } = setup({
dashboardState: { hasUnsavedChanges: false },
});
const nextComponents = { 1: {} };
const thunk = updateComponents(nextComponents);
thunk(dispatch, getState);
expect(dispatch.getCall(1).args[0]).toEqual(setUnsavedChanges(true));
// update component should not trigger action for dashboardFilters
expect(dashboardFilters.updateLayoutComponents.callCount).toEqual(0);
});
});
describe('deleteComponents', () => {
it('should dispatch an deleteComponent action', () => {
const { getState, dispatch } = setup();
const thunk = deleteComponent('id', 'parentId');
thunk(dispatch, getState);
expect(dispatch.getCall(0).args[0]).toEqual({
type: DELETE_COMPONENT,
payload: { id: 'id', parentId: 'parentId' },
});
// delete components should trigger action for dashboardFilters
expect(dashboardFilters.updateLayoutComponents.callCount).toEqual(1);
});
it('should dispatch a setUnsavedChanges action if hasUnsavedChanges=false', () => {
const { getState, dispatch } = setup({
dashboardState: { hasUnsavedChanges: false },
});
const thunk = deleteComponent('id', 'parentId');
thunk(dispatch, getState);
expect(dispatch.getCall(2).args[0]).toEqual(setUnsavedChanges(true));
// delete components should trigger action for dashboardFilters
expect(dashboardFilters.updateLayoutComponents.callCount).toEqual(1);
});
});
describe('updateDashboardTitle', () => {
it('should dispatch an updateComponent action for the header component', () => {
const { getState, dispatch } = setup();
const thunk1 = updateDashboardTitle('new text');
thunk1(dispatch, getState);
const thunk2 = dispatch.getCall(0).args[0];
thunk2(dispatch, getState);
expect(dispatch.getCall(1).args[0]).toEqual({
type: UPDATE_COMPONENTS,
payload: {
nextComponents: {
[DASHBOARD_HEADER_ID]: {
meta: { text: 'new text' },
},
},
},
});
// update dashboard title should not trigger action for dashboardFilters
expect(dashboardFilters.updateLayoutComponents.callCount).toEqual(0);
});
});
describe('createTopLevelTabs', () => {
it('should dispatch a createTopLevelTabs action', () => {
const { getState, dispatch } = setup();
const dropResult = {};
const thunk = createTopLevelTabs(dropResult);
thunk(dispatch, getState);
expect(dispatch.getCall(0).args[0]).toEqual({
type: CREATE_TOP_LEVEL_TABS,
payload: { dropResult },
});
// create top level tabs should trigger action for dashboardFilters
expect(dashboardFilters.updateLayoutComponents.callCount).toEqual(1);
});
it('should dispatch a setUnsavedChanges action if hasUnsavedChanges=false', () => {
const { getState, dispatch } = setup({
dashboardState: { hasUnsavedChanges: false },
});
const dropResult = {};
const thunk = createTopLevelTabs(dropResult);
thunk(dispatch, getState);
expect(dispatch.getCall(2).args[0]).toEqual(setUnsavedChanges(true));
// create top level tabs should trigger action for dashboardFilters
expect(dashboardFilters.updateLayoutComponents.callCount).toEqual(1);
});
});
describe('deleteTopLevelTabs', () => {
it('should dispatch a deleteTopLevelTabs action', () => {
const { getState, dispatch } = setup();
const dropResult = {};
const thunk = deleteTopLevelTabs(dropResult);
thunk(dispatch, getState);
expect(dispatch.getCall(0).args[0]).toEqual({
type: DELETE_TOP_LEVEL_TABS,
payload: {},
});
// delete top level tabs should trigger action for dashboardFilters
expect(dashboardFilters.updateLayoutComponents.callCount).toEqual(1);
});
it('should dispatch a setUnsavedChanges action if hasUnsavedChanges=false', () => {
const { getState, dispatch } = setup({
dashboardState: { hasUnsavedChanges: false },
});
const dropResult = {};
const thunk = deleteTopLevelTabs(dropResult);
thunk(dispatch, getState);
expect(dispatch.getCall(2).args[0]).toEqual(setUnsavedChanges(true));
// delete top level tabs should trigger action for dashboardFilters
expect(dashboardFilters.updateLayoutComponents.callCount).toEqual(1);
});
});
describe('resizeComponent', () => {
const dashboardLayout = {
...mockState.dashboardLayout,
present: {
1: {
id: 1,
children: [],
meta: {
width: 1,
height: 1,
},
},
},
};
it('should update the size of the component', () => {
const { getState, dispatch } = setup({
dashboardLayout,
});
const thunk1 = resizeComponent({ id: 1, width: 10, height: 3 });
thunk1(dispatch, getState);
const thunk2 = dispatch.getCall(0).args[0];
thunk2(dispatch, getState);
expect(dispatch.callCount).toBe(2);
expect(dispatch.getCall(1).args[0]).toEqual({
type: UPDATE_COMPONENTS,
payload: {
nextComponents: {
1: {
id: 1,
children: [],
meta: {
width: 10,
height: 3,
},
},
},
},
});
expect(dispatch.callCount).toBe(2);
});
it('should dispatch a setUnsavedChanges action if hasUnsavedChanges=false', () => {
const { getState, dispatch } = setup({
dashboardState: { hasUnsavedChanges: false },
dashboardLayout,
});
const thunk1 = resizeComponent({ id: 1, width: 10, height: 3 });
thunk1(dispatch, getState);
const thunk2 = dispatch.getCall(0).args[0];
thunk2(dispatch, getState);
expect(dispatch.callCount).toBe(3);
// resize components should not trigger action for dashboardFilters
expect(dashboardFilters.updateLayoutComponents.callCount).toEqual(0);
});
});
describe('handleComponentDrop', () => {
it('should create a component if it is new', () => {
const { getState, dispatch } = setup();
const dropResult = {
source: { id: NEW_COMPONENTS_SOURCE_ID },
destination: { id: DASHBOARD_GRID_ID, type: DASHBOARD_GRID_TYPE },
dragging: { id: NEW_ROW_ID, type: ROW_TYPE },
};
const handleComponentDropThunk = handleComponentDrop(dropResult);
handleComponentDropThunk(dispatch, getState);
const createComponentThunk = dispatch.getCall(0).args[0];
createComponentThunk(dispatch, getState);
expect(dispatch.getCall(1).args[0]).toEqual({
type: CREATE_COMPONENT,
payload: {
dropResult,
},
});
// create components should trigger action for dashboardFilters
expect(dashboardFilters.updateLayoutComponents.callCount).toEqual(1);
});
it('should move a component if the component is not new', () => {
const { getState, dispatch } = setup({
dashboardLayout: {
// if 'dragging' is not only child will dispatch deleteComponent thunk
present: { id: { type: ROW_TYPE, children: ['_'] } },
},
});
const dropResult = {
source: { id: 'id', index: 0, type: ROW_TYPE },
destination: { id: DASHBOARD_GRID_ID, type: DASHBOARD_GRID_TYPE },
dragging: { id: 'dragging', type: ROW_TYPE },
};
const handleComponentDropThunk = handleComponentDrop(dropResult);
handleComponentDropThunk(dispatch, getState);
const moveComponentThunk = dispatch.getCall(0).args[0];
moveComponentThunk(dispatch, getState);
expect(dispatch.getCall(1).args[0]).toEqual({
type: MOVE_COMPONENT,
payload: {
dropResult,
},
});
// create components should trigger action for dashboardFilters
expect(dashboardFilters.updateLayoutComponents.callCount).toEqual(1);
});
it('should dispatch a toast if the drop overflows the destination', () => {
const { getState, dispatch } = setup({
dashboardLayout: {
present: {
source: { type: ROW_TYPE },
destination: { type: ROW_TYPE, children: ['rowChild'] },
dragging: { type: CHART_TYPE, meta: { width: 1 } },
rowChild: { type: CHART_TYPE, meta: { width: 12 } },
},
},
});
const dropResult = {
source: { id: 'source', type: ROW_TYPE },
destination: { id: 'destination', type: ROW_TYPE },
dragging: { id: 'dragging', type: CHART_TYPE },
};
const thunk = handleComponentDrop(dropResult);
thunk(dispatch, getState);
expect(dispatch.getCall(0).args[0].type).toEqual(
addWarningToast('').type,
);
expect(dispatch.callCount).toBe(1);
});
it('should delete a parent Row or Tabs if the moved child was the only child', () => {
const { getState, dispatch } = setup({
dashboardLayout: {
present: {
parentId: { id: 'parentId', children: ['tabsId'] },
tabsId: { id: 'tabsId', type: TABS_TYPE, children: [] },
[DASHBOARD_GRID_ID]: {
id: DASHBOARD_GRID_ID,
type: DASHBOARD_GRID_TYPE,
},
tabId: { id: 'tabId', type: TAB_TYPE },
},
},
});
const dropResult = {
source: { id: 'tabsId', type: TABS_TYPE },
destination: { id: DASHBOARD_GRID_ID, type: DASHBOARD_GRID_TYPE },
dragging: { id: 'tabId', type: TAB_TYPE },
};
const moveThunk = handleComponentDrop(dropResult);
moveThunk(dispatch, getState);
// first call is move action which is not a thunk
const deleteThunk = dispatch.getCall(1).args[0];
deleteThunk(dispatch, getState);
expect(dispatch.getCall(2).args[0]).toEqual({
type: DELETE_COMPONENT,
payload: {
id: 'tabsId',
parentId: 'parentId',
},
});
});
it('should create top-level tabs if dropped on root', () => {
const { getState, dispatch } = setup();
const dropResult = {
source: { id: NEW_COMPONENTS_SOURCE_ID },
destination: { id: DASHBOARD_ROOT_ID },
dragging: { id: NEW_ROW_ID, type: ROW_TYPE },
};
const thunk1 = handleComponentDrop(dropResult);
thunk1(dispatch, getState);
const thunk2 = dispatch.getCall(0).args[0];
thunk2(dispatch, getState);
expect(dispatch.getCall(1).args[0]).toEqual({
type: CREATE_TOP_LEVEL_TABS,
payload: {
dropResult,
},
});
});
it('should dispatch a toast if drop top-level tab into nested tab', () => {
const { getState, dispatch } = setup({
dashboardLayout: {
present: {
[DASHBOARD_ROOT_ID]: {
children: ['TABS-ROOT_TABS'],
id: DASHBOARD_ROOT_ID,
type: 'ROOT',
},
'TABS-ROOT_TABS': {
children: ['TAB-iMppmTOQy', 'TAB-rt1y8cQ6K9', 'TAB-X_pnCIwPN'],
id: 'TABS-ROOT_TABS',
meta: {},
parents: ['ROOT_ID'],
type: TABS_TYPE,
},
'TABS-ROW_TABS': {
children: [
'TAB-dKIDBT03bQ',
'TAB-PtxY5bbTe',
'TAB-Wc2P-yGMz',
'TAB-U-xe_si7i',
],
id: 'TABS-ROW_TABS',
meta: {},
parents: ['ROOT_ID', 'TABS-ROOT_TABS', 'TAB-X_pnCIwPN'],
type: TABS_TYPE,
},
},
},
});
const dropResult = {
source: {
id: 'TABS-ROOT_TABS',
index: 1,
type: TABS_TYPE,
},
destination: {
id: 'TABS-ROW_TABS',
index: 1,
type: TABS_TYPE,
},
dragging: {
id: 'TAB-rt1y8cQ6K9',
meta: { text: 'New Tab' },
type: 'TAB',
},
};
const thunk1 = handleComponentDrop(dropResult);
thunk1(dispatch, getState);
const thunk2 = dispatch.getCall(0).args[0];
thunk2(dispatch, getState);
expect(dispatch.getCall(1).args[0].type).toEqual(ADD_TOAST);
});
});
describe('undoLayoutAction', () => {
it('should dispatch a redux-undo .undo() action ', () => {
const { getState, dispatch } = setup({
dashboardLayout: { past: ['non-empty'] },
});
const thunk = undoLayoutAction();
thunk(dispatch, getState);
expect(dispatch.callCount).toBe(1);
expect(dispatch.getCall(0).args[0]).toEqual(UndoActionCreators.undo());
});
it('should dispatch a setUnsavedChanges(false) action history length is zero', () => {
const { getState, dispatch } = setup({
dashboardLayout: { past: [] },
});
const thunk = undoLayoutAction();
thunk(dispatch, getState);
expect(dispatch.callCount).toBe(2);
expect(dispatch.getCall(1).args[0]).toEqual(setUnsavedChanges(false));
});
});
describe('redoLayoutAction', () => {
it('should dispatch a redux-undo .redo() action ', () => {
const { getState, dispatch } = setup();
const thunk = redoLayoutAction();
thunk(dispatch, getState);
expect(dispatch.getCall(0).args[0]).toEqual(UndoActionCreators.redo());
// redo/undo should trigger action for dashboardFilters
expect(dashboardFilters.updateLayoutComponents.callCount).toEqual(1);
});
it('should dispatch a setUnsavedChanges(true) action if hasUnsavedChanges=false', () => {
const { getState, dispatch } = setup({
dashboardState: { hasUnsavedChanges: false },
});
const thunk = redoLayoutAction();
thunk(dispatch, getState);
expect(dispatch.getCall(2).args[0]).toEqual(setUnsavedChanges(true));
// redo/undo should trigger action for dashboardFilters
expect(dashboardFilters.updateLayoutComponents.callCount).toEqual(1);
});
});
});
| superset-frontend/spec/javascripts/dashboard/actions/dashboardLayout_spec.js | 0 | https://github.com/apache/superset/commit/9eab29aeaacc9e7346649ca46730d49f2fe0b4ef | [
0.00017838232452049851,
0.00017288843810092658,
0.0001640884147491306,
0.00017333673895336688,
0.000003174843186570797
] |
{
"id": 4,
"code_window": [
" Modal,\n",
" Radio,\n",
"} from 'react-bootstrap';\n",
"import { CreatableSelect } from 'src/components/Select/SupersetStyledSelect';\n",
"import { t } from '@superset-ui/translation';\n",
"import ReactMarkdown from 'react-markdown';\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import FormLabel from 'src/components/FormLabel';\n"
],
"file_path": "superset-frontend/src/explore/components/SaveModal.jsx",
"type": "add",
"edit_start_line_idx": 31
} | # 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.
"""Time grain SQLA
Revision ID: c5756bec8b47
Revises: e502db2af7be
Create Date: 2018-06-04 11:12:59.878742
"""
# revision identifiers, used by Alembic.
revision = "c5756bec8b47"
down_revision = "e502db2af7be"
import json
from alembic import op
from sqlalchemy import Column, Integer, Text
from sqlalchemy.ext.declarative import declarative_base
from superset import db
Base = declarative_base()
class Slice(Base):
__tablename__ = "slices"
id = Column(Integer, primary_key=True)
params = Column(Text)
def upgrade():
bind = op.get_bind()
session = db.Session(bind=bind)
for slc in session.query(Slice).all():
try:
params = json.loads(slc.params)
if params.get("time_grain_sqla") == "Time Column":
params["time_grain_sqla"] = None
slc.params = json.dumps(params, sort_keys=True)
except Exception:
pass
session.commit()
session.close()
def downgrade():
bind = op.get_bind()
session = db.Session(bind=bind)
for slc in session.query(Slice).all():
try:
params = json.loads(slc.params)
if params.get("time_grain_sqla") is None:
params["time_grain_sqla"] = "Time Column"
slc.params = json.dumps(params, sort_keys=True)
except Exception:
pass
session.commit()
session.close()
| superset/migrations/versions/c5756bec8b47_time_grain_sqla.py | 0 | https://github.com/apache/superset/commit/9eab29aeaacc9e7346649ca46730d49f2fe0b4ef | [
0.00017828558338806033,
0.00017431427841074765,
0.0001676177344052121,
0.00017531041521579027,
0.000003431335017012316
] |
{
"id": 4,
"code_window": [
" Modal,\n",
" Radio,\n",
"} from 'react-bootstrap';\n",
"import { CreatableSelect } from 'src/components/Select/SupersetStyledSelect';\n",
"import { t } from '@superset-ui/translation';\n",
"import ReactMarkdown from 'react-markdown';\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import FormLabel from 'src/components/FormLabel';\n"
],
"file_path": "superset-frontend/src/explore/components/SaveModal.jsx",
"type": "add",
"edit_start_line_idx": 31
} | /**
* 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 { shallow } from 'enzyme';
import { Table, Thead, Td, Th, Tr } from 'reactable-arc';
import { getChartControlPanelRegistry } from '@superset-ui/chart';
import AlteredSliceTag from 'src/components/AlteredSliceTag';
import ModalTrigger from 'src/components/ModalTrigger';
import TooltipWrapper from 'src/components/TooltipWrapper';
const defaultProps = {
origFormData: {
viz_type: 'altered_slice_tag_spec',
adhoc_filters: [
{
clause: 'WHERE',
comparator: 'hello',
expressionType: 'SIMPLE',
operator: '==',
subject: 'a',
},
],
y_axis_bounds: [10, 20],
column_collection: [{ 1: 'a', b: ['6', 'g'] }],
bool: false,
alpha: undefined,
gucci: [1, 2, 3, 4],
never: 5,
ever: { a: 'b', c: 'd' },
},
currentFormData: {
adhoc_filters: [
{
clause: 'WHERE',
comparator: ['hello', 'my', 'name'],
expressionType: 'SIMPLE',
operator: 'in',
subject: 'b',
},
],
y_axis_bounds: [15, 16],
column_collection: [{ 1: 'a', b: [9, '15'], t: 'gggg' }],
bool: true,
alpha: null,
gucci: ['a', 'b', 'c', 'd'],
never: 10,
ever: { x: 'y', z: 'z' },
},
};
const expectedDiffs = {
adhoc_filters: {
before: [
{
clause: 'WHERE',
comparator: 'hello',
expressionType: 'SIMPLE',
operator: '==',
subject: 'a',
},
],
after: [
{
clause: 'WHERE',
comparator: ['hello', 'my', 'name'],
expressionType: 'SIMPLE',
operator: 'in',
subject: 'b',
},
],
},
y_axis_bounds: {
before: [10, 20],
after: [15, 16],
},
column_collection: {
before: [{ 1: 'a', b: ['6', 'g'] }],
after: [{ 1: 'a', b: [9, '15'], t: 'gggg' }],
},
bool: {
before: false,
after: true,
},
gucci: {
before: [1, 2, 3, 4],
after: ['a', 'b', 'c', 'd'],
},
never: {
before: 5,
after: 10,
},
ever: {
before: { a: 'b', c: 'd' },
after: { x: 'y', z: 'z' },
},
};
const fakePluginControls = {
controlPanelSections: [
{
label: 'Fake Control Panel Sections',
expanded: true,
controlSetRows: [
[
{
name: 'y_axis_bounds',
config: {
type: 'BoundsControl',
label: 'Value bounds',
default: [null, null],
description: 'Value bounds for the y axis',
},
},
{
name: 'column_collection',
config: {
type: 'CollectionControl',
label: 'Fake Collection Control',
},
},
{
name: 'adhoc_filters',
config: {
type: 'AdhocFilterControl',
label: 'Fake Filters',
default: null,
},
},
],
],
},
],
};
describe('AlteredSliceTag', () => {
let wrapper;
let props;
beforeEach(() => {
getChartControlPanelRegistry().registerValue(
'altered_slice_tag_spec',
fakePluginControls,
);
props = { ...defaultProps };
wrapper = shallow(<AlteredSliceTag {...props} />);
});
it('correctly determines form data differences', () => {
const diffs = wrapper.instance().getDiffs(props);
expect(diffs).toEqual(expectedDiffs);
expect(wrapper.instance().state.diffs).toEqual(expectedDiffs);
expect(wrapper.instance().state.hasDiffs).toBe(true);
});
it('does not run when there are no differences', () => {
props = {
origFormData: props.origFormData,
currentFormData: props.origFormData,
};
wrapper = shallow(<AlteredSliceTag {...props} />);
expect(wrapper.instance().state.diffs).toEqual({});
expect(wrapper.instance().state.hasDiffs).toBe(false);
expect(wrapper.instance().render()).toBeNull();
});
it('sets new diffs when receiving new props', () => {
const newProps = {
currentFormData: { ...props.currentFormData },
origFormData: { ...props.origFormData },
};
newProps.currentFormData.beta = 10;
wrapper = shallow(<AlteredSliceTag {...props} />);
wrapper.instance().UNSAFE_componentWillReceiveProps(newProps);
const newDiffs = wrapper.instance().state.diffs;
const expectedBeta = { before: undefined, after: 10 };
expect(newDiffs.beta).toEqual(expectedBeta);
});
it('does not set new state when props are the same', () => {
const currentDiff = wrapper.instance().state.diffs;
wrapper.instance().UNSAFE_componentWillReceiveProps(props);
// Check equal references
expect(wrapper.instance().state.diffs).toBe(currentDiff);
});
it('renders a ModalTrigger', () => {
expect(wrapper.find(ModalTrigger)).toExist();
});
describe('renderTriggerNode', () => {
it('renders a TooltipWrapper', () => {
const triggerNode = shallow(
<div>{wrapper.instance().renderTriggerNode()}</div>,
);
expect(triggerNode.find(TooltipWrapper)).toHaveLength(1);
});
});
describe('renderModalBody', () => {
it('renders a Table', () => {
const modalBody = shallow(
<div>{wrapper.instance().renderModalBody()}</div>,
);
expect(modalBody.find(Table)).toHaveLength(1);
});
it('renders a Thead', () => {
const modalBody = shallow(
<div>{wrapper.instance().renderModalBody()}</div>,
);
expect(modalBody.find(Thead)).toHaveLength(1);
});
it('renders Th', () => {
const modalBody = shallow(
<div>{wrapper.instance().renderModalBody()}</div>,
);
const th = modalBody.find(Th);
expect(th).toHaveLength(3);
['control', 'before', 'after'].forEach((v, i) => {
expect(th.get(i).props.column).toBe(v);
});
});
it('renders the correct number of Tr', () => {
const modalBody = shallow(
<div>{wrapper.instance().renderModalBody()}</div>,
);
const tr = modalBody.find(Tr);
expect(tr).toHaveLength(7);
});
it('renders the correct number of Td', () => {
const modalBody = shallow(
<div>{wrapper.instance().renderModalBody()}</div>,
);
const td = modalBody.find(Td);
expect(td).toHaveLength(21);
['control', 'before', 'after'].forEach((v, i) => {
expect(td.get(i).props.column).toBe(v);
});
});
});
describe('renderRows', () => {
it('returns an array of rows with one Tr and three Td', () => {
const rows = wrapper.instance().renderRows();
expect(rows).toHaveLength(7);
const fakeRow = shallow(<div>{rows[0]}</div>);
expect(fakeRow.find(Tr)).toHaveLength(1);
expect(fakeRow.find(Td)).toHaveLength(3);
});
});
describe('formatValue', () => {
it('returns "N/A" for undefined values', () => {
expect(wrapper.instance().formatValue(undefined, 'b')).toBe('N/A');
});
it('returns "null" for null values', () => {
expect(wrapper.instance().formatValue(null, 'b')).toBe('null');
});
it('returns "Max" and "Min" for BoundsControl', () => {
// need to pass the viz type to the wrapper
expect(wrapper.instance().formatValue([5, 6], 'y_axis_bounds')).toBe(
'Min: 5, Max: 6',
);
});
it('returns stringified objects for CollectionControl', () => {
const value = [
{ 1: 2, alpha: 'bravo' },
{ sent: 'imental', w0ke: 5 },
];
const expected = '{"1":2,"alpha":"bravo"}, {"sent":"imental","w0ke":5}';
expect(wrapper.instance().formatValue(value, 'column_collection')).toBe(
expected,
);
});
it('returns boolean values as string', () => {
expect(wrapper.instance().formatValue(true, 'b')).toBe('true');
expect(wrapper.instance().formatValue(false, 'b')).toBe('false');
});
it('returns Array joined by commas', () => {
const value = [5, 6, 7, 8, 'hello', 'goodbye'];
const expected = '5, 6, 7, 8, hello, goodbye';
expect(wrapper.instance().formatValue(value)).toBe(expected);
});
it('stringifies objects', () => {
const value = { 1: 2, alpha: 'bravo' };
const expected = '{"1":2,"alpha":"bravo"}';
expect(wrapper.instance().formatValue(value)).toBe(expected);
});
it('does nothing to strings and numbers', () => {
expect(wrapper.instance().formatValue(5)).toBe(5);
expect(wrapper.instance().formatValue('hello')).toBe('hello');
});
it('returns "[]" for empty filters', () => {
expect(wrapper.instance().formatValue([], 'adhoc_filters')).toBe('[]');
});
it('correctly formats filters with array values', () => {
const filters = [
{
clause: 'WHERE',
comparator: ['1', 'g', '7', 'ho'],
expressionType: 'SIMPLE',
operator: 'in',
subject: 'a',
},
{
clause: 'WHERE',
comparator: ['hu', 'ho', 'ha'],
expressionType: 'SIMPLE',
operator: 'not in',
subject: 'b',
},
];
const expected = 'a in [1, g, 7, ho], b not in [hu, ho, ha]';
expect(wrapper.instance().formatValue(filters, 'adhoc_filters')).toBe(
expected,
);
});
it('correctly formats filters with string values', () => {
const filters = [
{
clause: 'WHERE',
comparator: 'gucci',
expressionType: 'SIMPLE',
operator: '==',
subject: 'a',
},
{
clause: 'WHERE',
comparator: 'moshi moshi',
expressionType: 'SIMPLE',
operator: 'LIKE',
subject: 'b',
},
];
const expected = 'a == gucci, b LIKE moshi moshi';
expect(wrapper.instance().formatValue(filters, 'adhoc_filters')).toBe(
expected,
);
});
});
describe('isEqualish', () => {
it('considers null, undefined, {} and [] as equal', () => {
const inst = wrapper.instance();
expect(inst.isEqualish(null, undefined)).toBe(true);
expect(inst.isEqualish(null, [])).toBe(true);
expect(inst.isEqualish(null, {})).toBe(true);
expect(inst.isEqualish(undefined, {})).toBe(true);
});
it('considers empty strings are the same as null', () => {
const inst = wrapper.instance();
expect(inst.isEqualish(undefined, '')).toBe(true);
expect(inst.isEqualish(null, '')).toBe(true);
});
it('considers deeply equal objects as equal', () => {
const inst = wrapper.instance();
expect(inst.isEqualish('', '')).toBe(true);
expect(inst.isEqualish({ a: 1, b: 2, c: 3 }, { a: 1, b: 2, c: 3 })).toBe(
true,
);
// Out of order
expect(inst.isEqualish({ a: 1, b: 2, c: 3 }, { b: 2, a: 1, c: 3 })).toBe(
true,
);
// Actually not equal
expect(inst.isEqualish({ a: 1, b: 2, z: 9 }, { a: 1, b: 2, c: 3 })).toBe(
false,
);
});
});
});
| superset-frontend/spec/javascripts/components/AlteredSliceTag_spec.jsx | 0 | https://github.com/apache/superset/commit/9eab29aeaacc9e7346649ca46730d49f2fe0b4ef | [
0.0005342605873011053,
0.0001827445230446756,
0.00016478236648254097,
0.00017484500131104141,
0.00005565828178077936
] |
{
"id": 5,
"code_window": [
" {t('Save as ...')} \n",
" </Radio>\n",
" </FormGroup>\n",
" <hr />\n",
" <FormGroup>\n",
" <ControlLabel>{t('Chart name')}</ControlLabel>\n",
" <FormControl\n",
" name=\"new_slice_name\"\n",
" type=\"text\"\n",
" bsSize=\"sm\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <FormLabel required>{t('Chart name')}</FormLabel>\n"
],
"file_path": "superset-frontend/src/explore/components/SaveModal.jsx",
"type": "replace",
"edit_start_line_idx": 178
} | /**
* 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.
*/
/* eslint camelcase: 0 */
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import {
Alert,
Button,
FormControl,
FormGroup,
ControlLabel,
Modal,
Radio,
} from 'react-bootstrap';
import { CreatableSelect } from 'src/components/Select/SupersetStyledSelect';
import { t } from '@superset-ui/translation';
import ReactMarkdown from 'react-markdown';
import { EXPLORE_ONLY_VIZ_TYPE } from '../constants';
const propTypes = {
can_overwrite: PropTypes.bool,
onHide: PropTypes.func.isRequired,
actions: PropTypes.object.isRequired,
form_data: PropTypes.object,
userId: PropTypes.string.isRequired,
dashboards: PropTypes.array.isRequired,
alert: PropTypes.string,
slice: PropTypes.object,
datasource: PropTypes.object,
};
// Session storage key for recent dashboard
const SK_DASHBOARD_ID = 'save_chart_recent_dashboard';
const SELECT_PLACEHOLDER = t('**Select** a dashboard OR **create** a new one');
class SaveModal extends React.Component {
constructor(props) {
super(props);
this.state = {
saveToDashboardId: null,
newSliceName: props.sliceName,
dashboards: [],
alert: null,
action: props.can_overwrite ? 'overwrite' : 'saveas',
vizType: props.form_data.viz_type,
};
this.onDashboardSelectChange = this.onDashboardSelectChange.bind(this);
this.onSliceNameChange = this.onSliceNameChange.bind(this);
}
componentDidMount() {
this.props.actions.fetchDashboards(this.props.userId).then(() => {
const dashboardIds = this.props.dashboards.map(
dashboard => dashboard.value,
);
let recentDashboard = sessionStorage.getItem(SK_DASHBOARD_ID);
recentDashboard = recentDashboard && parseInt(recentDashboard, 10);
if (
recentDashboard !== null &&
dashboardIds.indexOf(recentDashboard) !== -1
) {
this.setState({
saveToDashboardId: recentDashboard,
});
}
});
}
onSliceNameChange(event) {
this.setState({ newSliceName: event.target.value });
}
onDashboardSelectChange(event) {
const newDashboardName = event ? event.label : null;
const saveToDashboardId =
event && typeof event.value === 'number' ? event.value : null;
this.setState({ saveToDashboardId, newDashboardName });
}
changeAction(action) {
this.setState({ action });
}
saveOrOverwrite(gotodash) {
this.setState({ alert: null });
this.props.actions.removeSaveModalAlert();
const sliceParams = {};
if (this.props.slice && this.props.slice.slice_id) {
sliceParams.slice_id = this.props.slice.slice_id;
}
if (sliceParams.action === 'saveas') {
if (this.state.newSliceName === '') {
this.setState({ alert: t('Please enter a chart name') });
return;
}
}
sliceParams.action = this.state.action;
sliceParams.slice_name = this.state.newSliceName;
sliceParams.save_to_dashboard_id = this.state.saveToDashboardId;
sliceParams.new_dashboard_name = this.state.newDashboardName;
this.props.actions
.saveSlice(this.props.form_data, sliceParams)
.then(({ data }) => {
if (data.dashboard_id === null) {
sessionStorage.removeItem(SK_DASHBOARD_ID);
} else {
sessionStorage.setItem(SK_DASHBOARD_ID, data.dashboard_id);
}
// Go to new slice url or dashboard url
const url = gotodash ? data.dashboard_url : data.slice.slice_url;
window.location.assign(url);
});
this.props.onHide();
}
removeAlert() {
if (this.props.alert) {
this.props.actions.removeSaveModalAlert();
}
this.setState({ alert: null });
}
render() {
const canNotSaveToDash =
EXPLORE_ONLY_VIZ_TYPE.indexOf(this.state.vizType) > -1;
return (
<Modal show onHide={this.props.onHide}>
<Modal.Header closeButton>
<Modal.Title>{t('Save Chart')}</Modal.Title>
</Modal.Header>
<Modal.Body>
{(this.state.alert || this.props.alert) && (
<Alert>
{this.state.alert ? this.state.alert : this.props.alert}
<i
role="button"
tabIndex={0}
className="fa fa-close pull-right"
onClick={this.removeAlert.bind(this)}
style={{ cursor: 'pointer' }}
/>
</Alert>
)}
<FormGroup>
<Radio
id="overwrite-radio"
inline
disabled={!(this.props.can_overwrite && this.props.slice)}
checked={this.state.action === 'overwrite'}
onChange={this.changeAction.bind(this, 'overwrite')}
>
{t('Save (Overwrite)')}
</Radio>
<Radio
id="saveas-radio"
inline
checked={this.state.action === 'saveas'}
onChange={this.changeAction.bind(this, 'saveas')}
>
{' '}
{t('Save as ...')}
</Radio>
</FormGroup>
<hr />
<FormGroup>
<ControlLabel>{t('Chart name')}</ControlLabel>
<FormControl
name="new_slice_name"
type="text"
bsSize="sm"
placeholder="Name"
value={this.state.newSliceName}
onChange={this.onSliceNameChange}
/>
</FormGroup>
<FormGroup>
<ControlLabel>{t('Add to dashboard')}</ControlLabel>
<CreatableSelect
id="dashboard-creatable-select"
className="save-modal-selector"
options={this.props.dashboards}
clearable
creatable
onChange={this.onDashboardSelectChange}
autoSize={false}
value={
this.state.saveToDashboardId || this.state.newDashboardName
}
placeholder={
// Using markdown to allow for good i18n
<ReactMarkdown
source={SELECT_PLACEHOLDER}
renderers={{ paragraph: 'span' }}
/>
}
/>
</FormGroup>
</Modal.Body>
<Modal.Footer>
<div className="float-right">
<Button
type="button"
id="btn_cancel"
bsSize="sm"
onClick={this.props.onHide}
>
{t('Cancel')}
</Button>
<Button
type="button"
id="btn_modal_save_goto_dash"
bsSize="sm"
disabled={canNotSaveToDash || !this.state.newDashboardName}
onClick={this.saveOrOverwrite.bind(this, true)}
>
{t('Save & go to dashboard')}
</Button>
<Button
type="button"
id="btn_modal_save"
bsSize="sm"
bsStyle="primary"
onClick={this.saveOrOverwrite.bind(this, false)}
>
{t('Save')}
</Button>
</div>
</Modal.Footer>
</Modal>
);
}
}
SaveModal.propTypes = propTypes;
function mapStateToProps({ explore, saveModal }) {
return {
datasource: explore.datasource,
slice: explore.slice,
can_overwrite: explore.can_overwrite,
userId: explore.user_id,
dashboards: saveModal.dashboards,
alert: saveModal.saveModalAlert,
};
}
export { SaveModal };
export default connect(mapStateToProps, () => ({}))(SaveModal);
| superset-frontend/src/explore/components/SaveModal.jsx | 1 | https://github.com/apache/superset/commit/9eab29aeaacc9e7346649ca46730d49f2fe0b4ef | [
0.9890263676643372,
0.037774309515953064,
0.00016267015598714352,
0.00017449291772209108,
0.18658317625522614
] |
{
"id": 5,
"code_window": [
" {t('Save as ...')} \n",
" </Radio>\n",
" </FormGroup>\n",
" <hr />\n",
" <FormGroup>\n",
" <ControlLabel>{t('Chart name')}</ControlLabel>\n",
" <FormControl\n",
" name=\"new_slice_name\"\n",
" type=\"text\"\n",
" bsSize=\"sm\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <FormLabel required>{t('Chart name')}</FormLabel>\n"
],
"file_path": "superset-frontend/src/explore/components/SaveModal.jsx",
"type": "replace",
"edit_start_line_idx": 178
} | /**
* 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 ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(<App />, document.getElementById('app'));
| superset-frontend/src/profile/index.tsx | 0 | https://github.com/apache/superset/commit/9eab29aeaacc9e7346649ca46730d49f2fe0b4ef | [
0.00017427773855160922,
0.00017126568127423525,
0.00016560476797167212,
0.0001739145372994244,
0.000004005615664937068
] |
{
"id": 5,
"code_window": [
" {t('Save as ...')} \n",
" </Radio>\n",
" </FormGroup>\n",
" <hr />\n",
" <FormGroup>\n",
" <ControlLabel>{t('Chart name')}</ControlLabel>\n",
" <FormControl\n",
" name=\"new_slice_name\"\n",
" type=\"text\"\n",
" bsSize=\"sm\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <FormLabel required>{t('Chart name')}</FormLabel>\n"
],
"file_path": "superset-frontend/src/explore/components/SaveModal.jsx",
"type": "replace",
"edit_start_line_idx": 178
} | # 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.
from typing import Optional, Type
from flask_babel import lazy_gettext as _
from marshmallow import ValidationError
from sqlalchemy.engine.url import make_url
from sqlalchemy.exc import ArgumentError
from superset import security_manager
from superset.models.core import Database
def sqlalchemy_uri_validator(
uri: str, exception: Type[ValidationError] = ValidationError
) -> None:
"""
Check if a user has submitted a valid SQLAlchemy URI
"""
try:
make_url(uri.strip())
except (ArgumentError, AttributeError):
raise exception(
_(
"Invalid connection string, a valid string usually follows:"
"'DRIVER://USER:PASSWORD@DB-HOST/DATABASE-NAME'"
"<p>Example:'postgresql://user:password@your-postgres-db/database'</p>"
)
)
def schema_allows_csv_upload(database: Database, schema: Optional[str]) -> bool:
if not database.allow_csv_upload:
return False
schemas = database.get_schema_access_for_csv_upload()
if schemas:
return schema in schemas
return security_manager.can_access_database(database)
| superset/views/database/validators.py | 0 | https://github.com/apache/superset/commit/9eab29aeaacc9e7346649ca46730d49f2fe0b4ef | [
0.000179816284799017,
0.00017292324628215283,
0.0001651756465435028,
0.00017310454859398305,
0.000004593899575411342
] |
{
"id": 5,
"code_window": [
" {t('Save as ...')} \n",
" </Radio>\n",
" </FormGroup>\n",
" <hr />\n",
" <FormGroup>\n",
" <ControlLabel>{t('Chart name')}</ControlLabel>\n",
" <FormControl\n",
" name=\"new_slice_name\"\n",
" type=\"text\"\n",
" bsSize=\"sm\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <FormLabel required>{t('Chart name')}</FormLabel>\n"
],
"file_path": "superset-frontend/src/explore/components/SaveModal.jsx",
"type": "replace",
"edit_start_line_idx": 178
} | # 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.
"""add_sql_string_to_table
Revision ID: 3c3ffe173e4f
Revises: ad82a75afd82
Create Date: 2016-08-18 14:06:28.784699
"""
# revision identifiers, used by Alembic.
revision = "3c3ffe173e4f"
down_revision = "ad82a75afd82"
import sqlalchemy as sa
from alembic import op
def upgrade():
op.add_column("tables", sa.Column("sql", sa.Text(), nullable=True))
def downgrade():
op.drop_column("tables", "sql")
| superset/migrations/versions/3c3ffe173e4f_add_sql_string_to_table.py | 0 | https://github.com/apache/superset/commit/9eab29aeaacc9e7346649ca46730d49f2fe0b4ef | [
0.00017491869220975786,
0.00017234428378287703,
0.0001695474493317306,
0.00017245547496713698,
0.0000022178853669174714
] |
{
"id": 6,
"code_window": [
" onChange={this.onSliceNameChange}\n",
" />\n",
" </FormGroup>\n",
" <FormGroup>\n",
" <ControlLabel>{t('Add to dashboard')}</ControlLabel>\n",
" <CreatableSelect\n",
" id=\"dashboard-creatable-select\"\n",
" className=\"save-modal-selector\"\n",
" options={this.props.dashboards}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <FormLabel required>{t('Add to dashboard')}</FormLabel>\n"
],
"file_path": "superset-frontend/src/explore/components/SaveModal.jsx",
"type": "replace",
"edit_start_line_idx": 189
} | /**
* 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.
*/
/* eslint camelcase: 0 */
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import {
Alert,
Button,
FormControl,
FormGroup,
ControlLabel,
Modal,
Radio,
} from 'react-bootstrap';
import { CreatableSelect } from 'src/components/Select/SupersetStyledSelect';
import { t } from '@superset-ui/translation';
import ReactMarkdown from 'react-markdown';
import { EXPLORE_ONLY_VIZ_TYPE } from '../constants';
const propTypes = {
can_overwrite: PropTypes.bool,
onHide: PropTypes.func.isRequired,
actions: PropTypes.object.isRequired,
form_data: PropTypes.object,
userId: PropTypes.string.isRequired,
dashboards: PropTypes.array.isRequired,
alert: PropTypes.string,
slice: PropTypes.object,
datasource: PropTypes.object,
};
// Session storage key for recent dashboard
const SK_DASHBOARD_ID = 'save_chart_recent_dashboard';
const SELECT_PLACEHOLDER = t('**Select** a dashboard OR **create** a new one');
class SaveModal extends React.Component {
constructor(props) {
super(props);
this.state = {
saveToDashboardId: null,
newSliceName: props.sliceName,
dashboards: [],
alert: null,
action: props.can_overwrite ? 'overwrite' : 'saveas',
vizType: props.form_data.viz_type,
};
this.onDashboardSelectChange = this.onDashboardSelectChange.bind(this);
this.onSliceNameChange = this.onSliceNameChange.bind(this);
}
componentDidMount() {
this.props.actions.fetchDashboards(this.props.userId).then(() => {
const dashboardIds = this.props.dashboards.map(
dashboard => dashboard.value,
);
let recentDashboard = sessionStorage.getItem(SK_DASHBOARD_ID);
recentDashboard = recentDashboard && parseInt(recentDashboard, 10);
if (
recentDashboard !== null &&
dashboardIds.indexOf(recentDashboard) !== -1
) {
this.setState({
saveToDashboardId: recentDashboard,
});
}
});
}
onSliceNameChange(event) {
this.setState({ newSliceName: event.target.value });
}
onDashboardSelectChange(event) {
const newDashboardName = event ? event.label : null;
const saveToDashboardId =
event && typeof event.value === 'number' ? event.value : null;
this.setState({ saveToDashboardId, newDashboardName });
}
changeAction(action) {
this.setState({ action });
}
saveOrOverwrite(gotodash) {
this.setState({ alert: null });
this.props.actions.removeSaveModalAlert();
const sliceParams = {};
if (this.props.slice && this.props.slice.slice_id) {
sliceParams.slice_id = this.props.slice.slice_id;
}
if (sliceParams.action === 'saveas') {
if (this.state.newSliceName === '') {
this.setState({ alert: t('Please enter a chart name') });
return;
}
}
sliceParams.action = this.state.action;
sliceParams.slice_name = this.state.newSliceName;
sliceParams.save_to_dashboard_id = this.state.saveToDashboardId;
sliceParams.new_dashboard_name = this.state.newDashboardName;
this.props.actions
.saveSlice(this.props.form_data, sliceParams)
.then(({ data }) => {
if (data.dashboard_id === null) {
sessionStorage.removeItem(SK_DASHBOARD_ID);
} else {
sessionStorage.setItem(SK_DASHBOARD_ID, data.dashboard_id);
}
// Go to new slice url or dashboard url
const url = gotodash ? data.dashboard_url : data.slice.slice_url;
window.location.assign(url);
});
this.props.onHide();
}
removeAlert() {
if (this.props.alert) {
this.props.actions.removeSaveModalAlert();
}
this.setState({ alert: null });
}
render() {
const canNotSaveToDash =
EXPLORE_ONLY_VIZ_TYPE.indexOf(this.state.vizType) > -1;
return (
<Modal show onHide={this.props.onHide}>
<Modal.Header closeButton>
<Modal.Title>{t('Save Chart')}</Modal.Title>
</Modal.Header>
<Modal.Body>
{(this.state.alert || this.props.alert) && (
<Alert>
{this.state.alert ? this.state.alert : this.props.alert}
<i
role="button"
tabIndex={0}
className="fa fa-close pull-right"
onClick={this.removeAlert.bind(this)}
style={{ cursor: 'pointer' }}
/>
</Alert>
)}
<FormGroup>
<Radio
id="overwrite-radio"
inline
disabled={!(this.props.can_overwrite && this.props.slice)}
checked={this.state.action === 'overwrite'}
onChange={this.changeAction.bind(this, 'overwrite')}
>
{t('Save (Overwrite)')}
</Radio>
<Radio
id="saveas-radio"
inline
checked={this.state.action === 'saveas'}
onChange={this.changeAction.bind(this, 'saveas')}
>
{' '}
{t('Save as ...')}
</Radio>
</FormGroup>
<hr />
<FormGroup>
<ControlLabel>{t('Chart name')}</ControlLabel>
<FormControl
name="new_slice_name"
type="text"
bsSize="sm"
placeholder="Name"
value={this.state.newSliceName}
onChange={this.onSliceNameChange}
/>
</FormGroup>
<FormGroup>
<ControlLabel>{t('Add to dashboard')}</ControlLabel>
<CreatableSelect
id="dashboard-creatable-select"
className="save-modal-selector"
options={this.props.dashboards}
clearable
creatable
onChange={this.onDashboardSelectChange}
autoSize={false}
value={
this.state.saveToDashboardId || this.state.newDashboardName
}
placeholder={
// Using markdown to allow for good i18n
<ReactMarkdown
source={SELECT_PLACEHOLDER}
renderers={{ paragraph: 'span' }}
/>
}
/>
</FormGroup>
</Modal.Body>
<Modal.Footer>
<div className="float-right">
<Button
type="button"
id="btn_cancel"
bsSize="sm"
onClick={this.props.onHide}
>
{t('Cancel')}
</Button>
<Button
type="button"
id="btn_modal_save_goto_dash"
bsSize="sm"
disabled={canNotSaveToDash || !this.state.newDashboardName}
onClick={this.saveOrOverwrite.bind(this, true)}
>
{t('Save & go to dashboard')}
</Button>
<Button
type="button"
id="btn_modal_save"
bsSize="sm"
bsStyle="primary"
onClick={this.saveOrOverwrite.bind(this, false)}
>
{t('Save')}
</Button>
</div>
</Modal.Footer>
</Modal>
);
}
}
SaveModal.propTypes = propTypes;
function mapStateToProps({ explore, saveModal }) {
return {
datasource: explore.datasource,
slice: explore.slice,
can_overwrite: explore.can_overwrite,
userId: explore.user_id,
dashboards: saveModal.dashboards,
alert: saveModal.saveModalAlert,
};
}
export { SaveModal };
export default connect(mapStateToProps, () => ({}))(SaveModal);
| superset-frontend/src/explore/components/SaveModal.jsx | 1 | https://github.com/apache/superset/commit/9eab29aeaacc9e7346649ca46730d49f2fe0b4ef | [
0.9964357614517212,
0.03952748328447342,
0.0001628744212212041,
0.00029152733623050153,
0.1877923309803009
] |
{
"id": 6,
"code_window": [
" onChange={this.onSliceNameChange}\n",
" />\n",
" </FormGroup>\n",
" <FormGroup>\n",
" <ControlLabel>{t('Add to dashboard')}</ControlLabel>\n",
" <CreatableSelect\n",
" id=\"dashboard-creatable-select\"\n",
" className=\"save-modal-selector\"\n",
" options={this.props.dashboards}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <FormLabel required>{t('Add to dashboard')}</FormLabel>\n"
],
"file_path": "superset-frontend/src/explore/components/SaveModal.jsx",
"type": "replace",
"edit_start_line_idx": 189
} | /**
* 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.
*/
.resizable-container {
background-color: transparent;
position: relative;
/* re-resizable sets an empty div to 100% width and height, which doesn't
play well with many 100% height containers we need
*/
& ~ div {
width: auto !important;
height: auto !important;
}
}
.resizable-container--resizing {
/* after ensures border visibility on top of any children */
&:after {
content: '';
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
box-shadow: inset 0 0 0 2px @indicator-color;
}
& > span .resize-handle {
border-color: @indicator-color;
}
}
.resize-handle {
opacity: 0;
z-index: @z-index-above-dashboard-charts;
&--bottom-right {
position: absolute;
border: solid;
border-width: 0 1.5px 1.5px 0;
border-right-color: @gray;
border-bottom-color: @gray;
right: 16px;
bottom: 16px;
width: 8px;
height: 8px;
}
&--right {
width: 2px;
height: 20px;
right: 4px;
top: 50%;
transform: translate(0, -50%);
position: absolute;
border-left: 1px solid @gray;
border-right: 1px solid @gray;
}
&--bottom {
height: 2px;
width: 20px;
bottom: 4px;
left: 50%;
transform: translate(-50%);
position: absolute;
border-top: 1px solid @gray;
border-bottom: 1px solid @gray;
}
}
.resizable-container:hover .resize-handle,
.resizable-container--resizing .resize-handle {
opacity: 1;
}
.dragdroppable-column .resizable-container-handle--right {
/* override the default because the inner column's handle's mouse target is very small */
right: -10px !important;
}
.dragdroppable-column .dragdroppable-column .resizable-container-handle--right {
/* override the default because the inner column's handle's mouse target is very small */
right: 0px !important;
}
.resizable-container-handle--bottom {
bottom: 0 !important;
}
| superset-frontend/src/dashboard/stylesheets/resizable.less | 0 | https://github.com/apache/superset/commit/9eab29aeaacc9e7346649ca46730d49f2fe0b4ef | [
0.00017515502986498177,
0.0001713754318188876,
0.00016103505913633853,
0.00017356150783598423,
0.000004801899194717407
] |
{
"id": 6,
"code_window": [
" onChange={this.onSliceNameChange}\n",
" />\n",
" </FormGroup>\n",
" <FormGroup>\n",
" <ControlLabel>{t('Add to dashboard')}</ControlLabel>\n",
" <CreatableSelect\n",
" id=\"dashboard-creatable-select\"\n",
" className=\"save-modal-selector\"\n",
" options={this.props.dashboards}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <FormLabel required>{t('Add to dashboard')}</FormLabel>\n"
],
"file_path": "superset-frontend/src/explore/components/SaveModal.jsx",
"type": "replace",
"edit_start_line_idx": 189
} | # 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/views/dashboard/__init__.py | 0 | https://github.com/apache/superset/commit/9eab29aeaacc9e7346649ca46730d49f2fe0b4ef | [
0.000177890105987899,
0.000176784917130135,
0.000175679728272371,
0.000176784917130135,
0.0000011051888577640057
] |
{
"id": 6,
"code_window": [
" onChange={this.onSliceNameChange}\n",
" />\n",
" </FormGroup>\n",
" <FormGroup>\n",
" <ControlLabel>{t('Add to dashboard')}</ControlLabel>\n",
" <CreatableSelect\n",
" id=\"dashboard-creatable-select\"\n",
" className=\"save-modal-selector\"\n",
" options={this.props.dashboards}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <FormLabel required>{t('Add to dashboard')}</FormLabel>\n"
],
"file_path": "superset-frontend/src/explore/components/SaveModal.jsx",
"type": "replace",
"edit_start_line_idx": 189
} | /**
* 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 { ErrorTypeEnum } from 'src/components/ErrorMessage/types';
import getClientErrorObject from 'src/utils/getClientErrorObject';
describe('getClientErrorObject()', () => {
it('Returns a Promise', () => {
const response = getClientErrorObject('error');
expect(response instanceof Promise).toBe(true);
});
it('Returns a Promise that resolves to an object with an error key', () => {
const error = 'error';
return getClientErrorObject(error).then(errorObj => {
expect(errorObj).toMatchObject({ error });
});
});
it('Handles Response that can be parsed as json', () => {
const jsonError = { something: 'something', error: 'Error message' };
const jsonErrorString = JSON.stringify(jsonError);
return getClientErrorObject(new Response(jsonErrorString)).then(
errorObj => {
expect(errorObj).toMatchObject(jsonError);
},
);
});
it('Handles backwards compatibility between old error messages and the new SIP-40 errors format', () => {
const jsonError = {
errors: [
{
error_type: ErrorTypeEnum.GENERIC_DB_ENGINE_ERROR,
extra: { engine: 'presto', link: 'https://www.google.com' },
level: 'error',
message: 'presto error: test error',
},
],
};
const jsonErrorString = JSON.stringify(jsonError);
return getClientErrorObject(new Response(jsonErrorString)).then(
errorObj => {
expect(errorObj.error).toEqual(jsonError.errors[0].message);
expect(errorObj.link).toEqual(jsonError.errors[0].extra.link);
},
);
});
it('Handles Response that can be parsed as text', () => {
const textError = 'Hello I am a text error';
return getClientErrorObject(new Response(textError)).then(errorObj => {
expect(errorObj).toMatchObject({ error: textError });
});
});
it('Handles plain text as input', () => {
const error = 'error';
return getClientErrorObject(error).then(errorObj => {
expect(errorObj).toMatchObject({ error });
});
});
});
| superset-frontend/spec/javascripts/utils/getClientErrorObject_spec.ts | 0 | https://github.com/apache/superset/commit/9eab29aeaacc9e7346649ca46730d49f2fe0b4ef | [
0.0001761142921168357,
0.0001738246064633131,
0.00017116498202085495,
0.00017419287178199738,
0.0000016138222918016254
] |
{
"id": 7,
"code_window": [
" type=\"button\"\n",
" id=\"btn_modal_save_goto_dash\"\n",
" bsSize=\"sm\"\n",
" disabled={canNotSaveToDash || !this.state.newDashboardName}\n",
" onClick={this.saveOrOverwrite.bind(this, true)}\n",
" >\n",
" {t('Save & go to dashboard')}\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" disabled={\n",
" canNotSaveToDash ||\n",
" !this.state.newSliceName ||\n",
" !this.state.newDashboardName\n",
" }\n"
],
"file_path": "superset-frontend/src/explore/components/SaveModal.jsx",
"type": "replace",
"edit_start_line_idx": 226
} | /**
* 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.
*/
/* eslint camelcase: 0 */
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import {
Alert,
Button,
FormControl,
FormGroup,
ControlLabel,
Modal,
Radio,
} from 'react-bootstrap';
import { CreatableSelect } from 'src/components/Select/SupersetStyledSelect';
import { t } from '@superset-ui/translation';
import ReactMarkdown from 'react-markdown';
import { EXPLORE_ONLY_VIZ_TYPE } from '../constants';
const propTypes = {
can_overwrite: PropTypes.bool,
onHide: PropTypes.func.isRequired,
actions: PropTypes.object.isRequired,
form_data: PropTypes.object,
userId: PropTypes.string.isRequired,
dashboards: PropTypes.array.isRequired,
alert: PropTypes.string,
slice: PropTypes.object,
datasource: PropTypes.object,
};
// Session storage key for recent dashboard
const SK_DASHBOARD_ID = 'save_chart_recent_dashboard';
const SELECT_PLACEHOLDER = t('**Select** a dashboard OR **create** a new one');
class SaveModal extends React.Component {
constructor(props) {
super(props);
this.state = {
saveToDashboardId: null,
newSliceName: props.sliceName,
dashboards: [],
alert: null,
action: props.can_overwrite ? 'overwrite' : 'saveas',
vizType: props.form_data.viz_type,
};
this.onDashboardSelectChange = this.onDashboardSelectChange.bind(this);
this.onSliceNameChange = this.onSliceNameChange.bind(this);
}
componentDidMount() {
this.props.actions.fetchDashboards(this.props.userId).then(() => {
const dashboardIds = this.props.dashboards.map(
dashboard => dashboard.value,
);
let recentDashboard = sessionStorage.getItem(SK_DASHBOARD_ID);
recentDashboard = recentDashboard && parseInt(recentDashboard, 10);
if (
recentDashboard !== null &&
dashboardIds.indexOf(recentDashboard) !== -1
) {
this.setState({
saveToDashboardId: recentDashboard,
});
}
});
}
onSliceNameChange(event) {
this.setState({ newSliceName: event.target.value });
}
onDashboardSelectChange(event) {
const newDashboardName = event ? event.label : null;
const saveToDashboardId =
event && typeof event.value === 'number' ? event.value : null;
this.setState({ saveToDashboardId, newDashboardName });
}
changeAction(action) {
this.setState({ action });
}
saveOrOverwrite(gotodash) {
this.setState({ alert: null });
this.props.actions.removeSaveModalAlert();
const sliceParams = {};
if (this.props.slice && this.props.slice.slice_id) {
sliceParams.slice_id = this.props.slice.slice_id;
}
if (sliceParams.action === 'saveas') {
if (this.state.newSliceName === '') {
this.setState({ alert: t('Please enter a chart name') });
return;
}
}
sliceParams.action = this.state.action;
sliceParams.slice_name = this.state.newSliceName;
sliceParams.save_to_dashboard_id = this.state.saveToDashboardId;
sliceParams.new_dashboard_name = this.state.newDashboardName;
this.props.actions
.saveSlice(this.props.form_data, sliceParams)
.then(({ data }) => {
if (data.dashboard_id === null) {
sessionStorage.removeItem(SK_DASHBOARD_ID);
} else {
sessionStorage.setItem(SK_DASHBOARD_ID, data.dashboard_id);
}
// Go to new slice url or dashboard url
const url = gotodash ? data.dashboard_url : data.slice.slice_url;
window.location.assign(url);
});
this.props.onHide();
}
removeAlert() {
if (this.props.alert) {
this.props.actions.removeSaveModalAlert();
}
this.setState({ alert: null });
}
render() {
const canNotSaveToDash =
EXPLORE_ONLY_VIZ_TYPE.indexOf(this.state.vizType) > -1;
return (
<Modal show onHide={this.props.onHide}>
<Modal.Header closeButton>
<Modal.Title>{t('Save Chart')}</Modal.Title>
</Modal.Header>
<Modal.Body>
{(this.state.alert || this.props.alert) && (
<Alert>
{this.state.alert ? this.state.alert : this.props.alert}
<i
role="button"
tabIndex={0}
className="fa fa-close pull-right"
onClick={this.removeAlert.bind(this)}
style={{ cursor: 'pointer' }}
/>
</Alert>
)}
<FormGroup>
<Radio
id="overwrite-radio"
inline
disabled={!(this.props.can_overwrite && this.props.slice)}
checked={this.state.action === 'overwrite'}
onChange={this.changeAction.bind(this, 'overwrite')}
>
{t('Save (Overwrite)')}
</Radio>
<Radio
id="saveas-radio"
inline
checked={this.state.action === 'saveas'}
onChange={this.changeAction.bind(this, 'saveas')}
>
{' '}
{t('Save as ...')}
</Radio>
</FormGroup>
<hr />
<FormGroup>
<ControlLabel>{t('Chart name')}</ControlLabel>
<FormControl
name="new_slice_name"
type="text"
bsSize="sm"
placeholder="Name"
value={this.state.newSliceName}
onChange={this.onSliceNameChange}
/>
</FormGroup>
<FormGroup>
<ControlLabel>{t('Add to dashboard')}</ControlLabel>
<CreatableSelect
id="dashboard-creatable-select"
className="save-modal-selector"
options={this.props.dashboards}
clearable
creatable
onChange={this.onDashboardSelectChange}
autoSize={false}
value={
this.state.saveToDashboardId || this.state.newDashboardName
}
placeholder={
// Using markdown to allow for good i18n
<ReactMarkdown
source={SELECT_PLACEHOLDER}
renderers={{ paragraph: 'span' }}
/>
}
/>
</FormGroup>
</Modal.Body>
<Modal.Footer>
<div className="float-right">
<Button
type="button"
id="btn_cancel"
bsSize="sm"
onClick={this.props.onHide}
>
{t('Cancel')}
</Button>
<Button
type="button"
id="btn_modal_save_goto_dash"
bsSize="sm"
disabled={canNotSaveToDash || !this.state.newDashboardName}
onClick={this.saveOrOverwrite.bind(this, true)}
>
{t('Save & go to dashboard')}
</Button>
<Button
type="button"
id="btn_modal_save"
bsSize="sm"
bsStyle="primary"
onClick={this.saveOrOverwrite.bind(this, false)}
>
{t('Save')}
</Button>
</div>
</Modal.Footer>
</Modal>
);
}
}
SaveModal.propTypes = propTypes;
function mapStateToProps({ explore, saveModal }) {
return {
datasource: explore.datasource,
slice: explore.slice,
can_overwrite: explore.can_overwrite,
userId: explore.user_id,
dashboards: saveModal.dashboards,
alert: saveModal.saveModalAlert,
};
}
export { SaveModal };
export default connect(mapStateToProps, () => ({}))(SaveModal);
| superset-frontend/src/explore/components/SaveModal.jsx | 1 | https://github.com/apache/superset/commit/9eab29aeaacc9e7346649ca46730d49f2fe0b4ef | [
0.9928761720657349,
0.03876987099647522,
0.00016391888493672013,
0.00036840219399891794,
0.1871640980243683
] |
{
"id": 7,
"code_window": [
" type=\"button\"\n",
" id=\"btn_modal_save_goto_dash\"\n",
" bsSize=\"sm\"\n",
" disabled={canNotSaveToDash || !this.state.newDashboardName}\n",
" onClick={this.saveOrOverwrite.bind(this, true)}\n",
" >\n",
" {t('Save & go to dashboard')}\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" disabled={\n",
" canNotSaveToDash ||\n",
" !this.state.newSliceName ||\n",
" !this.state.newDashboardName\n",
" }\n"
],
"file_path": "superset-frontend/src/explore/components/SaveModal.jsx",
"type": "replace",
"edit_start_line_idx": 226
} | # 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.
from datetime import date, datetime
from pandas import DataFrame, to_datetime
names_df = DataFrame(
[
{
"dt": date(2020, 1, 2),
"name": "John",
"country": "United Kingdom",
"cars": 3,
"bikes": 1,
"seconds": 30,
},
{
"dt": date(2020, 1, 2),
"name": "Peter",
"country": "Sweden",
"cars": 4,
"bikes": 2,
"seconds": 1,
},
{
"dt": date(2020, 1, 3),
"name": "Mary",
"country": "Finland",
"cars": 5,
"bikes": 3,
"seconds": None,
},
{
"dt": date(2020, 1, 3),
"name": "Peter",
"country": "India",
"cars": 6,
"bikes": 4,
"seconds": 12,
},
{
"dt": date(2020, 1, 4),
"name": "John",
"country": "Portugal",
"cars": 7,
"bikes": None,
"seconds": 75,
},
{
"dt": date(2020, 1, 4),
"name": "Peter",
"country": "Italy",
"cars": None,
"bikes": 5,
"seconds": 600,
},
{
"dt": date(2020, 1, 4),
"name": "Mary",
"country": None,
"cars": 9,
"bikes": 6,
"seconds": 2,
},
{
"dt": date(2020, 1, 4),
"name": None,
"country": "Australia",
"cars": 10,
"bikes": 7,
"seconds": 99,
},
{
"dt": date(2020, 1, 1),
"name": "John",
"country": "USA",
"cars": 1,
"bikes": 8,
"seconds": None,
},
{
"dt": date(2020, 1, 1),
"name": "Mary",
"country": "Fiji",
"cars": 2,
"bikes": 9,
"seconds": 50,
},
]
)
categories_df = DataFrame(
{
"constant": ["dummy" for _ in range(0, 101)],
"category": [f"cat{i%3}" for i in range(0, 101)],
"dept": [f"dept{i%5}" for i in range(0, 101)],
"name": [f"person{i}" for i in range(0, 101)],
"asc_idx": [i for i in range(0, 101)],
"desc_idx": [i for i in range(100, -1, -1)],
"idx_nulls": [i if i % 5 == 0 else None for i in range(0, 101)],
}
)
timeseries_df = DataFrame(
index=to_datetime(["2019-01-01", "2019-01-02", "2019-01-05", "2019-01-07"]),
data={"label": ["x", "y", "z", "q"], "y": [1.0, 2.0, 3.0, 4.0]},
)
lonlat_df = DataFrame(
{
"city": ["New York City", "Sydney"],
"geohash": ["dr5regw3pg6f", "r3gx2u9qdevk"],
"latitude": [40.71277496, -33.85598011],
"longitude": [-74.00597306, 151.20666526],
"altitude": [5.5, 0.012],
"geodetic": [
"40.71277496, -74.00597306, 5.5km",
"-33.85598011, 151.20666526, 12m",
],
}
)
prophet_df = DataFrame(
{
"__timestamp": [
datetime(2018, 12, 31),
datetime(2019, 12, 31),
datetime(2020, 12, 31),
datetime(2021, 12, 31),
],
"a": [1.1, 1, 1.9, 3.15],
"b": [4, 3, 4.1, 3.95],
}
)
| tests/fixtures/dataframes.py | 0 | https://github.com/apache/superset/commit/9eab29aeaacc9e7346649ca46730d49f2fe0b4ef | [
0.00017666762869339436,
0.00017191945516970009,
0.00016758001584094018,
0.00017187430057674646,
0.0000021349035250750603
] |
{
"id": 7,
"code_window": [
" type=\"button\"\n",
" id=\"btn_modal_save_goto_dash\"\n",
" bsSize=\"sm\"\n",
" disabled={canNotSaveToDash || !this.state.newDashboardName}\n",
" onClick={this.saveOrOverwrite.bind(this, true)}\n",
" >\n",
" {t('Save & go to dashboard')}\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" disabled={\n",
" canNotSaveToDash ||\n",
" !this.state.newSliceName ||\n",
" !this.state.newDashboardName\n",
" }\n"
],
"file_path": "superset-frontend/src/explore/components/SaveModal.jsx",
"type": "replace",
"edit_start_line_idx": 226
} | /**
* 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 { TABBED_DASHBOARD } from './dashboard.helper';
describe('Dashboard tabs', () => {
let filterId;
let treemapId;
let linechartId;
let boxplotId;
let dashboardId;
// cypress can not handle window.scrollTo
// https://github.com/cypress-io/cypress/issues/2761
// add this exception handler to pass test
const handleException = () => {
// return false to prevent the error from
// failing this test
cy.on('uncaught:exception', () => false);
};
beforeEach(() => {
cy.server();
cy.login();
cy.visit(TABBED_DASHBOARD);
cy.get('#app').then(data => {
const bootstrapData = JSON.parse(data[0].dataset.bootstrap);
const dashboard = bootstrapData.dashboard_data;
dashboardId = dashboard.id;
filterId = dashboard.slices.find(
slice => slice.form_data.viz_type === 'filter_box',
).slice_id;
boxplotId = dashboard.slices.find(
slice => slice.form_data.viz_type === 'box_plot',
).slice_id;
treemapId = dashboard.slices.find(
slice => slice.form_data.viz_type === 'treemap',
).slice_id;
linechartId = dashboard.slices.find(
slice => slice.form_data.viz_type === 'line',
).slice_id;
const filterFormdata = {
slice_id: filterId,
};
const filterRequest = `/superset/explore_json/?form_data=${JSON.stringify(
filterFormdata,
)}&dashboard_id=${dashboardId}`;
cy.route('POST', filterRequest).as('filterRequest');
const treemapFormdata = {
slice_id: treemapId,
};
const treemapRequest = `/superset/explore_json/?form_data=${JSON.stringify(
treemapFormdata,
)}&dashboard_id=${dashboardId}`;
cy.route('POST', treemapRequest).as('treemapRequest');
const linechartFormdata = {
slice_id: linechartId,
};
const linechartRequest = `/superset/explore_json/?form_data=${JSON.stringify(
linechartFormdata,
)}&dashboard_id=${dashboardId}`;
cy.route('POST', linechartRequest).as('linechartRequest');
const boxplotFormdata = {
slice_id: boxplotId,
};
const boxplotRequest = `/superset/explore_json/?form_data=${JSON.stringify(
boxplotFormdata,
)}&dashboard_id=${dashboardId}`;
cy.route('POST', boxplotRequest).as('boxplotRequest');
});
});
it('should load charts when tab is visible', () => {
// landing in first tab, should see 2 charts
cy.wait('@filterRequest');
cy.get('.grid-container .filter_box').should('be.exist');
cy.wait('@treemapRequest');
cy.get('.grid-container .treemap').should('be.exist');
cy.get('.grid-container .box_plot').should('not.be.exist');
cy.get('.grid-container .line').should('not.be.exist');
// click row level tab, see 1 more chart
cy.get('.tab-content ul.nav.nav-tabs li')
.last()
.find('.editable-title input')
.click();
cy.wait('@linechartRequest');
cy.get('.grid-container .line').should('be.exist');
// click top level tab, see 1 more chart
handleException();
cy.get('.dashboard-component-tabs')
.first()
.find('ul.nav.nav-tabs li')
.last()
.find('.editable-title input')
.click();
// should exist a visible box_plot element
cy.get('.grid-container .box_plot');
});
it('should send new queries when tab becomes visible', () => {
// landing in first tab
cy.wait('@filterRequest');
cy.wait('@treemapRequest');
// apply filter
cy.get('.Select__control').first().should('be.visible');
cy.get('.Select__control').first().click({ force: true });
cy.get('.Select__control input[type=text]')
.first()
.should('be.visible')
.type('South Asia{enter}', { force: true });
// send new query from same tab
cy.wait('@treemapRequest').then(xhr => {
const requestFormData = xhr.request.body;
const requestParams = JSON.parse(requestFormData.get('form_data'));
expect(requestParams.extra_filters[0]).deep.eq({
col: 'region',
op: 'in',
val: ['South Asia'],
});
});
// click row level tab, send 1 more query
cy.get('.tab-content ul.nav.nav-tabs li').last().click();
cy.wait('@linechartRequest').then(xhr => {
const requestFormData = xhr.request.body;
const requestParams = JSON.parse(requestFormData.get('form_data'));
expect(requestParams.extra_filters[0]).deep.eq({
col: 'region',
op: 'in',
val: ['South Asia'],
});
});
// click top level tab, send 1 more query
handleException();
cy.get('.dashboard-component-tabs')
.first()
.find('ul.nav.nav-tabs li')
.last()
.find('.editable-title input')
.click();
cy.wait('@boxplotRequest').then(xhr => {
const requestFormData = xhr.request.body;
const requestParams = JSON.parse(requestFormData.get('form_data'));
expect(requestParams.extra_filters[0]).deep.eq({
col: 'region',
op: 'in',
val: ['South Asia'],
});
});
// navigate to filter and clear filter
cy.get('.dashboard-component-tabs')
.first()
.find('ul.nav.nav-tabs li')
.first()
.click();
cy.get('.tab-content ul.nav.nav-tabs li')
.first()
.should('be.visible')
.click();
cy.get('.Select__clear-indicator').click();
// trigger 1 new query
cy.wait('@treemapRequest');
// make sure query API not requested multiple times
cy.on('fail', err => {
expect(err.message).to.include('timed out waiting');
return false;
});
cy.wait('@boxplotRequest', { timeout: 1000 }).then(() => {
throw new Error('Unexpected API call.');
});
});
});
| superset-frontend/cypress-base/cypress/integration/dashboard/tabs.test.js | 0 | https://github.com/apache/superset/commit/9eab29aeaacc9e7346649ca46730d49f2fe0b4ef | [
0.0012336875079199672,
0.00025964187807403505,
0.00016720971325412393,
0.0001710830838419497,
0.00023453225730918348
] |
{
"id": 7,
"code_window": [
" type=\"button\"\n",
" id=\"btn_modal_save_goto_dash\"\n",
" bsSize=\"sm\"\n",
" disabled={canNotSaveToDash || !this.state.newDashboardName}\n",
" onClick={this.saveOrOverwrite.bind(this, true)}\n",
" >\n",
" {t('Save & go to dashboard')}\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" disabled={\n",
" canNotSaveToDash ||\n",
" !this.state.newSliceName ||\n",
" !this.state.newDashboardName\n",
" }\n"
],
"file_path": "superset-frontend/src/explore/components/SaveModal.jsx",
"type": "replace",
"edit_start_line_idx": 226
} | # 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.
"""Materializing permission
Revision ID: c3a8f8611885
Revises: 4fa88fe24e94
Create Date: 2016-04-25 08:54:04.303859
"""
import sqlalchemy as sa
from alembic import op
from sqlalchemy import Column, ForeignKey, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from superset import db
# revision identifiers, used by Alembic.
revision = "c3a8f8611885"
down_revision = "4fa88fe24e94"
Base = declarative_base()
class Slice(Base):
"""Declarative class to do query in upgrade"""
__tablename__ = "slices"
id = Column(Integer, primary_key=True)
slice_name = Column(String(250))
druid_datasource_id = Column(Integer, ForeignKey("datasources.id"))
table_id = Column(Integer, ForeignKey("tables.id"))
perm = Column(String(2000))
def upgrade():
bind = op.get_bind()
op.add_column("slices", sa.Column("perm", sa.String(length=2000), nullable=True))
session = db.Session(bind=bind)
# Use Slice class defined here instead of models.Slice
for slc in session.query(Slice).all():
if slc.datasource:
slc.perm = slc.datasource.perm
session.merge(slc)
session.commit()
db.session.close()
def downgrade():
# Use batch_alter_table because dropping columns is not supported in SQLite
with op.batch_alter_table("slices") as batch_op:
batch_op.drop_column("perm")
| superset/migrations/versions/c3a8f8611885_materializing_permission.py | 0 | https://github.com/apache/superset/commit/9eab29aeaacc9e7346649ca46730d49f2fe0b4ef | [
0.00018482384621165693,
0.00017283372289966792,
0.00016566335398238152,
0.00017178713460452855,
0.000006163599209685344
] |
{
"id": 8,
"code_window": [
" bsSize=\"sm\"\n",
" bsStyle=\"primary\"\n",
" onClick={this.saveOrOverwrite.bind(this, false)}\n",
" >\n",
" {t('Save')}\n",
" </Button>\n",
" </div>\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" disabled={!this.state.newSliceName}\n"
],
"file_path": "superset-frontend/src/explore/components/SaveModal.jsx",
"type": "add",
"edit_start_line_idx": 237
} | /**
* 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.
*/
/* eslint camelcase: 0 */
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import {
Alert,
Button,
FormControl,
FormGroup,
ControlLabel,
Modal,
Radio,
} from 'react-bootstrap';
import { CreatableSelect } from 'src/components/Select/SupersetStyledSelect';
import { t } from '@superset-ui/translation';
import ReactMarkdown from 'react-markdown';
import { EXPLORE_ONLY_VIZ_TYPE } from '../constants';
const propTypes = {
can_overwrite: PropTypes.bool,
onHide: PropTypes.func.isRequired,
actions: PropTypes.object.isRequired,
form_data: PropTypes.object,
userId: PropTypes.string.isRequired,
dashboards: PropTypes.array.isRequired,
alert: PropTypes.string,
slice: PropTypes.object,
datasource: PropTypes.object,
};
// Session storage key for recent dashboard
const SK_DASHBOARD_ID = 'save_chart_recent_dashboard';
const SELECT_PLACEHOLDER = t('**Select** a dashboard OR **create** a new one');
class SaveModal extends React.Component {
constructor(props) {
super(props);
this.state = {
saveToDashboardId: null,
newSliceName: props.sliceName,
dashboards: [],
alert: null,
action: props.can_overwrite ? 'overwrite' : 'saveas',
vizType: props.form_data.viz_type,
};
this.onDashboardSelectChange = this.onDashboardSelectChange.bind(this);
this.onSliceNameChange = this.onSliceNameChange.bind(this);
}
componentDidMount() {
this.props.actions.fetchDashboards(this.props.userId).then(() => {
const dashboardIds = this.props.dashboards.map(
dashboard => dashboard.value,
);
let recentDashboard = sessionStorage.getItem(SK_DASHBOARD_ID);
recentDashboard = recentDashboard && parseInt(recentDashboard, 10);
if (
recentDashboard !== null &&
dashboardIds.indexOf(recentDashboard) !== -1
) {
this.setState({
saveToDashboardId: recentDashboard,
});
}
});
}
onSliceNameChange(event) {
this.setState({ newSliceName: event.target.value });
}
onDashboardSelectChange(event) {
const newDashboardName = event ? event.label : null;
const saveToDashboardId =
event && typeof event.value === 'number' ? event.value : null;
this.setState({ saveToDashboardId, newDashboardName });
}
changeAction(action) {
this.setState({ action });
}
saveOrOverwrite(gotodash) {
this.setState({ alert: null });
this.props.actions.removeSaveModalAlert();
const sliceParams = {};
if (this.props.slice && this.props.slice.slice_id) {
sliceParams.slice_id = this.props.slice.slice_id;
}
if (sliceParams.action === 'saveas') {
if (this.state.newSliceName === '') {
this.setState({ alert: t('Please enter a chart name') });
return;
}
}
sliceParams.action = this.state.action;
sliceParams.slice_name = this.state.newSliceName;
sliceParams.save_to_dashboard_id = this.state.saveToDashboardId;
sliceParams.new_dashboard_name = this.state.newDashboardName;
this.props.actions
.saveSlice(this.props.form_data, sliceParams)
.then(({ data }) => {
if (data.dashboard_id === null) {
sessionStorage.removeItem(SK_DASHBOARD_ID);
} else {
sessionStorage.setItem(SK_DASHBOARD_ID, data.dashboard_id);
}
// Go to new slice url or dashboard url
const url = gotodash ? data.dashboard_url : data.slice.slice_url;
window.location.assign(url);
});
this.props.onHide();
}
removeAlert() {
if (this.props.alert) {
this.props.actions.removeSaveModalAlert();
}
this.setState({ alert: null });
}
render() {
const canNotSaveToDash =
EXPLORE_ONLY_VIZ_TYPE.indexOf(this.state.vizType) > -1;
return (
<Modal show onHide={this.props.onHide}>
<Modal.Header closeButton>
<Modal.Title>{t('Save Chart')}</Modal.Title>
</Modal.Header>
<Modal.Body>
{(this.state.alert || this.props.alert) && (
<Alert>
{this.state.alert ? this.state.alert : this.props.alert}
<i
role="button"
tabIndex={0}
className="fa fa-close pull-right"
onClick={this.removeAlert.bind(this)}
style={{ cursor: 'pointer' }}
/>
</Alert>
)}
<FormGroup>
<Radio
id="overwrite-radio"
inline
disabled={!(this.props.can_overwrite && this.props.slice)}
checked={this.state.action === 'overwrite'}
onChange={this.changeAction.bind(this, 'overwrite')}
>
{t('Save (Overwrite)')}
</Radio>
<Radio
id="saveas-radio"
inline
checked={this.state.action === 'saveas'}
onChange={this.changeAction.bind(this, 'saveas')}
>
{' '}
{t('Save as ...')}
</Radio>
</FormGroup>
<hr />
<FormGroup>
<ControlLabel>{t('Chart name')}</ControlLabel>
<FormControl
name="new_slice_name"
type="text"
bsSize="sm"
placeholder="Name"
value={this.state.newSliceName}
onChange={this.onSliceNameChange}
/>
</FormGroup>
<FormGroup>
<ControlLabel>{t('Add to dashboard')}</ControlLabel>
<CreatableSelect
id="dashboard-creatable-select"
className="save-modal-selector"
options={this.props.dashboards}
clearable
creatable
onChange={this.onDashboardSelectChange}
autoSize={false}
value={
this.state.saveToDashboardId || this.state.newDashboardName
}
placeholder={
// Using markdown to allow for good i18n
<ReactMarkdown
source={SELECT_PLACEHOLDER}
renderers={{ paragraph: 'span' }}
/>
}
/>
</FormGroup>
</Modal.Body>
<Modal.Footer>
<div className="float-right">
<Button
type="button"
id="btn_cancel"
bsSize="sm"
onClick={this.props.onHide}
>
{t('Cancel')}
</Button>
<Button
type="button"
id="btn_modal_save_goto_dash"
bsSize="sm"
disabled={canNotSaveToDash || !this.state.newDashboardName}
onClick={this.saveOrOverwrite.bind(this, true)}
>
{t('Save & go to dashboard')}
</Button>
<Button
type="button"
id="btn_modal_save"
bsSize="sm"
bsStyle="primary"
onClick={this.saveOrOverwrite.bind(this, false)}
>
{t('Save')}
</Button>
</div>
</Modal.Footer>
</Modal>
);
}
}
SaveModal.propTypes = propTypes;
function mapStateToProps({ explore, saveModal }) {
return {
datasource: explore.datasource,
slice: explore.slice,
can_overwrite: explore.can_overwrite,
userId: explore.user_id,
dashboards: saveModal.dashboards,
alert: saveModal.saveModalAlert,
};
}
export { SaveModal };
export default connect(mapStateToProps, () => ({}))(SaveModal);
| superset-frontend/src/explore/components/SaveModal.jsx | 1 | https://github.com/apache/superset/commit/9eab29aeaacc9e7346649ca46730d49f2fe0b4ef | [
0.9976525902748108,
0.038500092923641205,
0.00016440352192148566,
0.00017218365974258631,
0.18814264237880707
] |
{
"id": 8,
"code_window": [
" bsSize=\"sm\"\n",
" bsStyle=\"primary\"\n",
" onClick={this.saveOrOverwrite.bind(this, false)}\n",
" >\n",
" {t('Save')}\n",
" </Button>\n",
" </div>\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" disabled={!this.state.newSliceName}\n"
],
"file_path": "superset-frontend/src/explore/components/SaveModal.jsx",
"type": "add",
"edit_start_line_idx": 237
} | /**
* 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 { Button, Panel } from 'react-bootstrap';
import Select from 'src/components/Select';
import { t } from '@superset-ui/translation';
import VizTypeControl from '../explore/components/controls/VizTypeControl';
interface Datasource {
label: string;
value: string;
}
export type AddSliceContainerProps = {
datasources: Datasource[];
};
export type AddSliceContainerState = {
datasourceId?: string;
datasourceType?: string;
datasourceValue?: string;
visType: string;
};
const styleSelectWidth = { width: 600 };
export default class AddSliceContainer extends React.PureComponent<
AddSliceContainerProps,
AddSliceContainerState
> {
constructor(props: AddSliceContainerProps) {
super(props);
this.state = {
visType: 'table',
};
this.changeDatasource = this.changeDatasource.bind(this);
this.changeVisType = this.changeVisType.bind(this);
this.gotoSlice = this.gotoSlice.bind(this);
}
exploreUrl() {
const formData = encodeURIComponent(
JSON.stringify({
viz_type: this.state.visType,
datasource: this.state.datasourceValue,
}),
);
return `/superset/explore/?form_data=${formData}`;
}
gotoSlice() {
window.location.href = this.exploreUrl();
}
changeDatasource(option: { value: string }) {
this.setState({
datasourceValue: option.value,
datasourceId: option.value.split('__')[0],
datasourceType: option.value.split('__')[1],
});
}
changeVisType(visType: string) {
this.setState({ visType });
}
isBtnDisabled() {
return !(this.state.datasourceId && this.state.visType);
}
render() {
return (
<div className="container">
<Panel>
<Panel.Heading>
<h3>{t('Create a new chart')}</h3>
</Panel.Heading>
<Panel.Body>
<div>
<p>{t('Choose a datasource')}</p>
<p>
<div style={styleSelectWidth}>
<Select
clearable={false}
ignoreAccents={false}
name="select-datasource"
onChange={this.changeDatasource}
options={this.props.datasources}
placeholder={t('Choose a datasource')}
style={styleSelectWidth}
value={
this.state.datasourceValue
? {
value: this.state.datasourceValue,
}
: undefined
}
width={600}
/>
</div>
</p>
<span className="text-muted">
{t(
'If the datasource you are looking for is not available in the list, follow the instructions on how to add it in the Superset tutorial.',
)}{' '}
<a
href="https://superset.apache.org/tutorial.html#adding-a-new-table"
rel="noopener noreferrer"
target="_blank"
>
<i className="fa fa-external-link" />
</a>
</span>
</div>
<br />
<div>
<p>{t('Choose a visualization type')}</p>
<VizTypeControl
name="select-vis-type"
onChange={this.changeVisType}
value={this.state.visType}
/>
</div>
<br />
<hr />
<Button
bsStyle="primary"
disabled={this.isBtnDisabled()}
onClick={this.gotoSlice}
>
{t('Create new chart')}
</Button>
<br />
<br />
</Panel.Body>
</Panel>
</div>
);
}
}
| superset-frontend/src/addSlice/AddSliceContainer.tsx | 0 | https://github.com/apache/superset/commit/9eab29aeaacc9e7346649ca46730d49f2fe0b4ef | [
0.02091057598590851,
0.0014855802292004228,
0.00016385468188673258,
0.00016939880151767284,
0.005015715956687927
] |
{
"id": 8,
"code_window": [
" bsSize=\"sm\"\n",
" bsStyle=\"primary\"\n",
" onClick={this.saveOrOverwrite.bind(this, false)}\n",
" >\n",
" {t('Save')}\n",
" </Button>\n",
" </div>\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" disabled={!this.state.newSliceName}\n"
],
"file_path": "superset-frontend/src/explore/components/SaveModal.jsx",
"type": "add",
"edit_start_line_idx": 237
} | /**
* 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.
*/
// Variables ported from "src/stylesheets/less/variables.less"
// TODO: move to `@superset-ui/style`
// Keep it here to make PRs easier for review.
export const supersetColors = {
primary: '#00a699',
danger: '#fe4a49',
warning: '#ffab00',
indicator: '#44c0ff',
almostBlack: '#263238',
grayDark: '#484848',
grayLight: '#cfd8dc',
gray: '#879399',
grayBg: '#f5f5f5',
grayBgDarker: '#e8e8e8', // select option menu hover
grayBgDarkest: '#d2d2d2', // table cell bar chart
grayHeading: '#a3a3a3',
menuHover: '#f2f3f5',
lightest: '#fff',
darkest: '#000',
// addition most common colors
grayBorder: '#ccc',
grayBorderLight: '#d9d9d9',
grayBorderDark: '#b3b3b3',
textDefault: '#333',
textDarkest: '#111',
};
| superset-frontend/src/components/styles.ts | 0 | https://github.com/apache/superset/commit/9eab29aeaacc9e7346649ca46730d49f2fe0b4ef | [
0.0003818359109573066,
0.00021491595543920994,
0.0001714049285510555,
0.0001732815580908209,
0.00008346841059392318
] |
{
"id": 8,
"code_window": [
" bsSize=\"sm\"\n",
" bsStyle=\"primary\"\n",
" onClick={this.saveOrOverwrite.bind(this, false)}\n",
" >\n",
" {t('Save')}\n",
" </Button>\n",
" </div>\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" disabled={!this.state.newSliceName}\n"
],
"file_path": "superset-frontend/src/explore/components/SaveModal.jsx",
"type": "add",
"edit_start_line_idx": 237
} | # 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.
| tests/datasets/__init__.py | 0 | https://github.com/apache/superset/commit/9eab29aeaacc9e7346649ca46730d49f2fe0b4ef | [
0.00017557540559209883,
0.00017529819160699844,
0.00017502096306998283,
0.00017529819160699844,
2.772212610580027e-7
] |
{
"id": 0,
"code_window": [
" playerOptions['easing'] = easing;\n",
" }\n",
"\n",
" return new WebAnimationsPlayer(\n",
" element, formattedSteps, playerOptions, <WebAnimationsPlayer[]>previousPlayers);\n",
" }\n",
"}\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" // there may be a chance a NoOp player is returned depending\n",
" // on when the previous animation was cancelled\n",
" previousPlayers = previousPlayers.filter(filterWebAnimationPlayerFn);\n"
],
"file_path": "modules/@angular/platform-browser/src/dom/web_animations_driver.ts",
"type": "add",
"edit_start_line_idx": 56
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {AnimationPlayer} from '@angular/core';
import {isPresent} from '../facade/lang';
import {AnimationKeyframe, AnimationStyles} from '../private_import_core';
import {AnimationDriver} from './animation_driver';
import {WebAnimationsPlayer} from './web_animations_player';
export class WebAnimationsDriver implements AnimationDriver {
animate(
element: any, startingStyles: AnimationStyles, keyframes: AnimationKeyframe[],
duration: number, delay: number, easing: string,
previousPlayers: AnimationPlayer[] = []): WebAnimationsPlayer {
let formattedSteps: {[key: string]: string | number}[] = [];
let startingStyleLookup: {[key: string]: string | number} = {};
if (isPresent(startingStyles) && startingStyles.styles.length > 0) {
startingStyleLookup = _populateStyles(startingStyles, {});
startingStyleLookup['offset'] = 0;
formattedSteps.push(startingStyleLookup);
}
keyframes.forEach((keyframe: AnimationKeyframe) => {
const data = _populateStyles(keyframe.styles, startingStyleLookup);
data['offset'] = keyframe.offset;
formattedSteps.push(data);
});
// this is a special case when only styles are applied as an
// animation. When this occurs we want to animate from start to
// end with the same values. Removing the offset and having only
// start/end values is suitable enough for the web-animations API
if (formattedSteps.length == 1) {
const start = formattedSteps[0];
start['offset'] = null;
formattedSteps = [start, start];
}
const playerOptions: {[key: string]: string | number} = {
'duration': duration,
'delay': delay,
'fill': 'both' // we use `both` because it allows for styling at 0% to work with `delay`
};
// we check for this to avoid having a null|undefined value be present
// for the easing (which results in an error for certain browsers #9752)
if (easing) {
playerOptions['easing'] = easing;
}
return new WebAnimationsPlayer(
element, formattedSteps, playerOptions, <WebAnimationsPlayer[]>previousPlayers);
}
}
function _populateStyles(styles: AnimationStyles, defaultStyles: {[key: string]: string | number}):
{[key: string]: string | number} {
const data: {[key: string]: string | number} = {};
styles.styles.forEach(
(entry) => { Object.keys(entry).forEach(prop => { data[prop] = entry[prop]; }); });
Object.keys(defaultStyles).forEach(prop => {
if (!isPresent(data[prop])) {
data[prop] = defaultStyles[prop];
}
});
return data;
}
| modules/@angular/platform-browser/src/dom/web_animations_driver.ts | 1 | https://github.com/angular/angular/commit/be010a292a2f349b8fc54afff3f0d1e8323b67a2 | [
0.9960458874702454,
0.13173578679561615,
0.0001742378663038835,
0.0012210665736347437,
0.32709455490112305
] |
{
"id": 0,
"code_window": [
" playerOptions['easing'] = easing;\n",
" }\n",
"\n",
" return new WebAnimationsPlayer(\n",
" element, formattedSteps, playerOptions, <WebAnimationsPlayer[]>previousPlayers);\n",
" }\n",
"}\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" // there may be a chance a NoOp player is returned depending\n",
" // on when the previous animation was cancelled\n",
" previousPlayers = previousPlayers.filter(filterWebAnimationPlayerFn);\n"
],
"file_path": "modules/@angular/platform-browser/src/dom/web_animations_driver.ts",
"type": "add",
"edit_start_line_idx": 56
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {enableProdMode} from '@angular/core';
import {platformBrowser} from '@angular/platform-browser';
import {init} from './init';
import {AppModuleNgFactory} from './tree.ngfactory';
enableProdMode();
platformBrowser().bootstrapModuleFactory(AppModuleNgFactory).then(init);
| modules/benchmarks/src/tree/ng2_switch/index_aot.ts | 0 | https://github.com/angular/angular/commit/be010a292a2f349b8fc54afff3f0d1e8323b67a2 | [
0.00017828830459620804,
0.00017765932716429234,
0.00017703034973237664,
0.00017765932716429234,
6.289774319157004e-7
] |
{
"id": 0,
"code_window": [
" playerOptions['easing'] = easing;\n",
" }\n",
"\n",
" return new WebAnimationsPlayer(\n",
" element, formattedSteps, playerOptions, <WebAnimationsPlayer[]>previousPlayers);\n",
" }\n",
"}\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" // there may be a chance a NoOp player is returned depending\n",
" // on when the previous animation was cancelled\n",
" previousPlayers = previousPlayers.filter(filterWebAnimationPlayerFn);\n"
],
"file_path": "modules/@angular/platform-browser/src/dom/web_animations_driver.ts",
"type": "add",
"edit_start_line_idx": 56
} | #!/usr/bin/env node
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Extract i18n messages from source code
*/
// Must be imported first, because angular2 decorators throws on load.
import 'reflect-metadata';
import * as compiler from '@angular/compiler';
import * as tsc from '@angular/tsc-wrapped';
import * as path from 'path';
import * as ts from 'typescript';
import {Extractor} from './extractor';
function extract(
ngOptions: tsc.AngularCompilerOptions, cliOptions: tsc.I18nExtractionCliOptions,
program: ts.Program, host: ts.CompilerHost) {
const resourceLoader: compiler.ResourceLoader = {
get: (s: string) => {
if (!host.fileExists(s)) {
// TODO: We should really have a test for error cases like this!
throw new Error(`Compilation failed. Resource file not found: ${s}`);
}
return Promise.resolve(host.readFile(s));
}
};
const extractor =
Extractor.create(ngOptions, cliOptions.i18nFormat, program, host, resourceLoader);
const bundlePromise: Promise<compiler.MessageBundle> = extractor.extract();
return (bundlePromise).then(messageBundle => {
let ext: string;
let serializer: compiler.Serializer;
const format = (cliOptions.i18nFormat || 'xlf').toLowerCase();
switch (format) {
case 'xmb':
ext = 'xmb';
serializer = new compiler.Xmb();
break;
case 'xliff':
case 'xlf':
default:
ext = 'xlf';
serializer = new compiler.Xliff();
break;
}
const dstPath = path.join(ngOptions.genDir, `messages.${ext}`);
host.writeFile(dstPath, messageBundle.write(serializer), false);
});
}
// Entry point
if (require.main === module) {
const args = require('minimist')(process.argv.slice(2));
const project = args.p || args.project || '.';
const cliOptions = new tsc.I18nExtractionCliOptions(args);
tsc.main(project, cliOptions, extract)
.then((exitCode: any) => process.exit(exitCode))
.catch((e: any) => {
console.error(e.stack);
console.error('Extraction failed');
process.exit(1);
});
}
| modules/@angular/compiler-cli/src/extract_i18n.ts | 0 | https://github.com/angular/angular/commit/be010a292a2f349b8fc54afff3f0d1e8323b67a2 | [
0.000179295486304909,
0.00017574275261722505,
0.00017302168998867273,
0.00017540549742989242,
0.0000020471952666412108
] |
{
"id": 0,
"code_window": [
" playerOptions['easing'] = easing;\n",
" }\n",
"\n",
" return new WebAnimationsPlayer(\n",
" element, formattedSteps, playerOptions, <WebAnimationsPlayer[]>previousPlayers);\n",
" }\n",
"}\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" // there may be a chance a NoOp player is returned depending\n",
" // on when the previous animation was cancelled\n",
" previousPlayers = previousPlayers.filter(filterWebAnimationPlayerFn);\n"
],
"file_path": "modules/@angular/platform-browser/src/dom/web_animations_driver.ts",
"type": "add",
"edit_start_line_idx": 56
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
export {BrowserXhr} from './backends/browser_xhr';
export {JSONPBackend, JSONPConnection} from './backends/jsonp_backend';
export {CookieXSRFStrategy, XHRBackend, XHRConnection} from './backends/xhr_backend';
export {BaseRequestOptions, RequestOptions} from './base_request_options';
export {BaseResponseOptions, ResponseOptions} from './base_response_options';
export {ReadyState, RequestMethod, ResponseContentType, ResponseType} from './enums';
export {Headers} from './headers';
export {Http, Jsonp} from './http';
export {HttpModule, JsonpModule} from './http_module';
export {Connection, ConnectionBackend, RequestOptionsArgs, ResponseOptionsArgs, XSRFStrategy} from './interfaces';
export {Request} from './static_request';
export {Response} from './static_response';
export {QueryEncoder, URLSearchParams} from './url_search_params';
| modules/@angular/http/src/index.ts | 0 | https://github.com/angular/angular/commit/be010a292a2f349b8fc54afff3f0d1e8323b67a2 | [
0.0001754135882947594,
0.00017439539078623056,
0.00017251365352422,
0.00017525894509162754,
0.000001332089482275478
] |
{
"id": 1,
"code_window": [
" data[prop] = defaultStyles[prop];\n",
" }\n",
" });\n",
" return data;\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add"
],
"after_edit": [
"\n",
"function filterWebAnimationPlayerFn(player: AnimationPlayer) {\n",
" return player instanceof WebAnimationsPlayer;\n",
"}"
],
"file_path": "modules/@angular/platform-browser/src/dom/web_animations_driver.ts",
"type": "add",
"edit_start_line_idx": 73
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {el} from '@angular/platform-browser/testing/browser_util';
import {DomAnimatePlayer} from '../../src/dom/dom_animate_player';
import {WebAnimationsDriver} from '../../src/dom/web_animations_driver';
import {WebAnimationsPlayer} from '../../src/dom/web_animations_player';
import {AnimationKeyframe, AnimationStyles} from '../../src/private_import_core';
import {MockDomAnimatePlayer} from '../../testing/mock_dom_animate_player';
class ExtendedWebAnimationsDriver extends WebAnimationsDriver {
public log: {[key: string]: any}[] = [];
constructor() { super(); }
/** @internal */
_triggerWebAnimation(elm: any, keyframes: any[], options: any): DomAnimatePlayer {
this.log.push({'elm': elm, 'keyframes': keyframes, 'options': options});
return new MockDomAnimatePlayer();
}
}
function _makeStyles(styles: {[key: string]: string | number}): AnimationStyles {
return new AnimationStyles([styles]);
}
function _makeKeyframe(
offset: number, styles: {[key: string]: string | number}): AnimationKeyframe {
return new AnimationKeyframe(offset, _makeStyles(styles));
}
export function main() {
describe('WebAnimationsDriver', () => {
let driver: ExtendedWebAnimationsDriver;
let elm: HTMLElement;
beforeEach(() => {
driver = new ExtendedWebAnimationsDriver();
elm = el('<div></div>');
});
it('should use a fill mode of `both`', () => {
const startingStyles = _makeStyles({});
const styles = [_makeKeyframe(0, {'color': 'green'}), _makeKeyframe(1, {'color': 'red'})];
const player = driver.animate(elm, startingStyles, styles, 1000, 1000, 'linear', []);
const details = _formatOptions(player);
const options = details['options'];
expect(options['fill']).toEqual('both');
});
it('should apply the provided easing', () => {
const startingStyles = _makeStyles({});
const styles = [_makeKeyframe(0, {'color': 'green'}), _makeKeyframe(1, {'color': 'red'})];
const player = driver.animate(elm, startingStyles, styles, 1000, 1000, 'ease-out', []);
const details = _formatOptions(player);
const options = details['options'];
expect(options['easing']).toEqual('ease-out');
});
it('should only apply the provided easing if present', () => {
const startingStyles = _makeStyles({});
const styles = [_makeKeyframe(0, {'color': 'green'}), _makeKeyframe(1, {'color': 'red'})];
const player = driver.animate(elm, startingStyles, styles, 1000, 1000, null, []);
const details = _formatOptions(player);
const options = details['options'];
const keys = Object.keys(options);
expect(keys.indexOf('easing')).toEqual(-1);
});
});
}
function _formatOptions(player: WebAnimationsPlayer): {[key: string]: any} {
return {'element': player.element, 'keyframes': player.keyframes, 'options': player.options};
}
| modules/@angular/platform-browser/test/dom/web_animations_driver_spec.ts | 1 | https://github.com/angular/angular/commit/be010a292a2f349b8fc54afff3f0d1e8323b67a2 | [
0.00020930814207531512,
0.00017935568757820874,
0.00016970741853583604,
0.00017629488138481975,
0.000012247030099388212
] |
{
"id": 1,
"code_window": [
" data[prop] = defaultStyles[prop];\n",
" }\n",
" });\n",
" return data;\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add"
],
"after_edit": [
"\n",
"function filterWebAnimationPlayerFn(player: AnimationPlayer) {\n",
" return player instanceof WebAnimationsPlayer;\n",
"}"
],
"file_path": "modules/@angular/platform-browser/src/dom/web_animations_driver.ts",
"type": "add",
"edit_start_line_idx": 73
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {CommonModule} from '@angular/common';
import {Component, ContentChildren, Directive, NO_ERRORS_SCHEMA, QueryList, TemplateRef} from '@angular/core';
import {ComponentFixture, TestBed, async} from '@angular/core/testing';
import {expect} from '@angular/platform-browser/testing/matchers';
export function main() {
describe('NgTemplateOutlet', () => {
let fixture: ComponentFixture<any>;
function setTplRef(value: any): void { fixture.componentInstance.currentTplRef = value; }
function detectChangesAndExpectText(text: string): void {
fixture.detectChanges();
expect(fixture.debugElement.nativeElement).toHaveText(text);
}
afterEach(() => { fixture = null; });
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [
TestComponent,
CaptureTplRefs,
],
imports: [CommonModule],
});
});
it('should do nothing if templateRef is null', async(() => {
const template = `<template [ngTemplateOutlet]="null"></template>`;
fixture = createTestComponent(template);
detectChangesAndExpectText('');
}));
it('should insert content specified by TemplateRef', async(() => {
const template =
`<tpl-refs #refs="tplRefs"><template>foo</template></tpl-refs><template [ngTemplateOutlet]="currentTplRef"></template>`;
fixture = createTestComponent(template);
detectChangesAndExpectText('');
const refs = fixture.debugElement.children[0].references['refs'];
setTplRef(refs.tplRefs.first);
detectChangesAndExpectText('foo');
}));
it('should clear content if TemplateRef becomes null', async(() => {
const template =
`<tpl-refs #refs="tplRefs"><template>foo</template></tpl-refs><template [ngTemplateOutlet]="currentTplRef"></template>`;
fixture = createTestComponent(template);
fixture.detectChanges();
const refs = fixture.debugElement.children[0].references['refs'];
setTplRef(refs.tplRefs.first);
detectChangesAndExpectText('foo');
setTplRef(null);
detectChangesAndExpectText('');
}));
it('should swap content if TemplateRef changes', async(() => {
const template =
`<tpl-refs #refs="tplRefs"><template>foo</template><template>bar</template></tpl-refs><template [ngTemplateOutlet]="currentTplRef"></template>`;
fixture = createTestComponent(template);
fixture.detectChanges();
const refs = fixture.debugElement.children[0].references['refs'];
setTplRef(refs.tplRefs.first);
detectChangesAndExpectText('foo');
setTplRef(refs.tplRefs.last);
detectChangesAndExpectText('bar');
}));
it('should display template if context is null', async(() => {
const template =
`<tpl-refs #refs="tplRefs"><template>foo</template></tpl-refs><template [ngTemplateOutlet]="currentTplRef" [ngOutletContext]="null"></template>`;
fixture = createTestComponent(template);
detectChangesAndExpectText('');
const refs = fixture.debugElement.children[0].references['refs'];
setTplRef(refs.tplRefs.first);
detectChangesAndExpectText('foo');
}));
it('should reflect initial context and changes', async(() => {
const template =
`<tpl-refs #refs="tplRefs"><template let-foo="foo"><span>{{foo}}</span></template></tpl-refs><template [ngTemplateOutlet]="currentTplRef" [ngOutletContext]="context"></template>`;
fixture = createTestComponent(template);
fixture.detectChanges();
const refs = fixture.debugElement.children[0].references['refs'];
setTplRef(refs.tplRefs.first);
detectChangesAndExpectText('bar');
fixture.componentInstance.context.foo = 'alter-bar';
detectChangesAndExpectText('alter-bar');
}));
it('should reflect user defined $implicit property in the context', async(() => {
const template =
`<tpl-refs #refs="tplRefs"><template let-ctx><span>{{ctx.foo}}</span></template></tpl-refs><template [ngTemplateOutlet]="currentTplRef" [ngOutletContext]="context"></template>`;
fixture = createTestComponent(template);
fixture.detectChanges();
const refs = fixture.debugElement.children[0].references['refs'];
setTplRef(refs.tplRefs.first);
fixture.componentInstance.context = {$implicit: fixture.componentInstance.context};
detectChangesAndExpectText('bar');
}));
it('should reflect context re-binding', async(() => {
const template =
`<tpl-refs #refs="tplRefs"><template let-shawshank="shawshank"><span>{{shawshank}}</span></template></tpl-refs><template [ngTemplateOutlet]="currentTplRef" [ngOutletContext]="context"></template>`;
fixture = createTestComponent(template);
fixture.detectChanges();
const refs = fixture.debugElement.children[0].references['refs'];
setTplRef(refs.tplRefs.first);
fixture.componentInstance.context = {shawshank: 'brooks'};
detectChangesAndExpectText('brooks');
fixture.componentInstance.context = {shawshank: 'was here'};
detectChangesAndExpectText('was here');
}));
});
}
@Directive({selector: 'tpl-refs', exportAs: 'tplRefs'})
class CaptureTplRefs {
@ContentChildren(TemplateRef) tplRefs: QueryList<TemplateRef<any>>;
}
@Component({selector: 'test-cmp', template: ''})
class TestComponent {
currentTplRef: TemplateRef<any>;
context: any = {foo: 'bar'};
}
function createTestComponent(template: string): ComponentFixture<TestComponent> {
return TestBed.overrideComponent(TestComponent, {set: {template: template}})
.configureTestingModule({schemas: [NO_ERRORS_SCHEMA]})
.createComponent(TestComponent);
} | modules/@angular/common/test/directives/ng_template_outlet_spec.ts | 0 | https://github.com/angular/angular/commit/be010a292a2f349b8fc54afff3f0d1e8323b67a2 | [
0.0001777454890543595,
0.00017220994050148875,
0.00016789861547295004,
0.00017150056373793632,
0.0000030121809686534107
] |
{
"id": 1,
"code_window": [
" data[prop] = defaultStyles[prop];\n",
" }\n",
" });\n",
" return data;\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add"
],
"after_edit": [
"\n",
"function filterWebAnimationPlayerFn(player: AnimationPlayer) {\n",
" return player instanceof WebAnimationsPlayer;\n",
"}"
],
"file_path": "modules/@angular/platform-browser/src/dom/web_animations_driver.ts",
"type": "add",
"edit_start_line_idx": 73
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {CommonModule, NgLocalization} from '@angular/common';
import {Component, Injectable} from '@angular/core';
import {ComponentFixture, TestBed, async} from '@angular/core/testing';
import {expect} from '@angular/platform-browser/testing/matchers';
export function main() {
describe('switch', () => {
let fixture: ComponentFixture<any>;
function getComponent(): TestComponent { return fixture.componentInstance; }
function detectChangesAndExpectText<T>(text: string): void {
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText(text);
}
afterEach(() => { fixture = null; });
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [TestComponent],
providers: [{provide: NgLocalization, useClass: TestLocalization}],
imports: [CommonModule]
});
});
it('should display the template according to the exact value', async(() => {
const template = '<div>' +
'<ul [ngPlural]="switchValue">' +
'<template ngPluralCase="=0"><li>you have no messages.</li></template>' +
'<template ngPluralCase="=1"><li>you have one message.</li></template>' +
'</ul></div>';
fixture = createTestComponent(template);
getComponent().switchValue = 0;
detectChangesAndExpectText('you have no messages.');
getComponent().switchValue = 1;
detectChangesAndExpectText('you have one message.');
}));
// https://github.com/angular/angular/issues/9868
// https://github.com/angular/angular/issues/9882
it('should not throw when ngPluralCase contains expressions', async(() => {
const template = '<div>' +
'<ul [ngPlural]="switchValue">' +
'<template ngPluralCase="=0"><li>{{ switchValue }}</li></template>' +
'</ul></div>';
fixture = createTestComponent(template);
getComponent().switchValue = 0;
expect(() => fixture.detectChanges()).not.toThrow();
}));
it('should be applicable to <ng-container> elements', async(() => {
const template = '<div>' +
'<ng-container [ngPlural]="switchValue">' +
'<template ngPluralCase="=0">you have no messages.</template>' +
'<template ngPluralCase="=1">you have one message.</template>' +
'</ng-container></div>';
fixture = createTestComponent(template);
getComponent().switchValue = 0;
detectChangesAndExpectText('you have no messages.');
getComponent().switchValue = 1;
detectChangesAndExpectText('you have one message.');
}));
it('should display the template according to the category', async(() => {
const template = '<div>' +
'<ul [ngPlural]="switchValue">' +
'<template ngPluralCase="few"><li>you have a few messages.</li></template>' +
'<template ngPluralCase="many"><li>you have many messages.</li></template>' +
'</ul></div>';
fixture = createTestComponent(template);
getComponent().switchValue = 2;
detectChangesAndExpectText('you have a few messages.');
getComponent().switchValue = 8;
detectChangesAndExpectText('you have many messages.');
}));
it('should default to other when no matches are found', async(() => {
const template = '<div>' +
'<ul [ngPlural]="switchValue">' +
'<template ngPluralCase="few"><li>you have a few messages.</li></template>' +
'<template ngPluralCase="other"><li>default message.</li></template>' +
'</ul></div>';
fixture = createTestComponent(template);
getComponent().switchValue = 100;
detectChangesAndExpectText('default message.');
}));
it('should prioritize value matches over category matches', async(() => {
const template = '<div>' +
'<ul [ngPlural]="switchValue">' +
'<template ngPluralCase="few"><li>you have a few messages.</li></template>' +
'<template ngPluralCase="=2">you have two messages.</template>' +
'</ul></div>';
fixture = createTestComponent(template);
getComponent().switchValue = 2;
detectChangesAndExpectText('you have two messages.');
getComponent().switchValue = 3;
detectChangesAndExpectText('you have a few messages.');
}));
});
}
@Injectable()
class TestLocalization extends NgLocalization {
getPluralCategory(value: number): string {
if (value > 1 && value < 4) {
return 'few';
}
if (value >= 4 && value < 10) {
return 'many';
}
return 'other';
}
}
@Component({selector: 'test-cmp', template: ''})
class TestComponent {
switchValue: number = null;
}
function createTestComponent(template: string): ComponentFixture<TestComponent> {
return TestBed.overrideComponent(TestComponent, {set: {template: template}})
.createComponent(TestComponent);
}
| modules/@angular/common/test/directives/ng_plural_spec.ts | 0 | https://github.com/angular/angular/commit/be010a292a2f349b8fc54afff3f0d1e8323b67a2 | [
0.00017818294872995466,
0.00017282669432461262,
0.00016577269707340747,
0.0001725954352878034,
0.000003077249402849702
] |
{
"id": 1,
"code_window": [
" data[prop] = defaultStyles[prop];\n",
" }\n",
" });\n",
" return data;\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add"
],
"after_edit": [
"\n",
"function filterWebAnimationPlayerFn(player: AnimationPlayer) {\n",
" return player instanceof WebAnimationsPlayer;\n",
"}"
],
"file_path": "modules/@angular/platform-browser/src/dom/web_animations_driver.ts",
"type": "add",
"edit_start_line_idx": 73
} | <div>
<div id="scrollDiv"
ng-style="scrollDivStyle"
ng-scroll="onScroll()">
<div ng-style="paddingStyle"></div>
<div ng-style="innerStyle">
<scroll-item
ng-repeat="item in visibleItems"
offering="item">
</scroll-item>
</div>
</div>
</div>
| modules/benchmarks_external/src/naive_infinite_scroll/scroll_area.html | 0 | https://github.com/angular/angular/commit/be010a292a2f349b8fc54afff3f0d1e8323b67a2 | [
0.00017717269656714052,
0.00017051625763997436,
0.00016385983326472342,
0.00017051625763997436,
0.00000665643165120855
] |
{
"id": 2,
"code_window": [
" * found in the LICENSE file at https://angular.io/license\n",
" */\n",
"\n",
"import {el} from '@angular/platform-browser/testing/browser_util';\n",
"\n",
"import {DomAnimatePlayer} from '../../src/dom/dom_animate_player';\n",
"import {WebAnimationsDriver} from '../../src/dom/web_animations_driver';\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import {AnimationPlayer} from '@angular/core';\n"
],
"file_path": "modules/@angular/platform-browser/test/dom/web_animations_driver_spec.ts",
"type": "add",
"edit_start_line_idx": 8
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {el} from '@angular/platform-browser/testing/browser_util';
import {DomAnimatePlayer} from '../../src/dom/dom_animate_player';
import {WebAnimationsDriver} from '../../src/dom/web_animations_driver';
import {WebAnimationsPlayer} from '../../src/dom/web_animations_player';
import {AnimationKeyframe, AnimationStyles} from '../../src/private_import_core';
import {MockDomAnimatePlayer} from '../../testing/mock_dom_animate_player';
class ExtendedWebAnimationsDriver extends WebAnimationsDriver {
public log: {[key: string]: any}[] = [];
constructor() { super(); }
/** @internal */
_triggerWebAnimation(elm: any, keyframes: any[], options: any): DomAnimatePlayer {
this.log.push({'elm': elm, 'keyframes': keyframes, 'options': options});
return new MockDomAnimatePlayer();
}
}
function _makeStyles(styles: {[key: string]: string | number}): AnimationStyles {
return new AnimationStyles([styles]);
}
function _makeKeyframe(
offset: number, styles: {[key: string]: string | number}): AnimationKeyframe {
return new AnimationKeyframe(offset, _makeStyles(styles));
}
export function main() {
describe('WebAnimationsDriver', () => {
let driver: ExtendedWebAnimationsDriver;
let elm: HTMLElement;
beforeEach(() => {
driver = new ExtendedWebAnimationsDriver();
elm = el('<div></div>');
});
it('should use a fill mode of `both`', () => {
const startingStyles = _makeStyles({});
const styles = [_makeKeyframe(0, {'color': 'green'}), _makeKeyframe(1, {'color': 'red'})];
const player = driver.animate(elm, startingStyles, styles, 1000, 1000, 'linear', []);
const details = _formatOptions(player);
const options = details['options'];
expect(options['fill']).toEqual('both');
});
it('should apply the provided easing', () => {
const startingStyles = _makeStyles({});
const styles = [_makeKeyframe(0, {'color': 'green'}), _makeKeyframe(1, {'color': 'red'})];
const player = driver.animate(elm, startingStyles, styles, 1000, 1000, 'ease-out', []);
const details = _formatOptions(player);
const options = details['options'];
expect(options['easing']).toEqual('ease-out');
});
it('should only apply the provided easing if present', () => {
const startingStyles = _makeStyles({});
const styles = [_makeKeyframe(0, {'color': 'green'}), _makeKeyframe(1, {'color': 'red'})];
const player = driver.animate(elm, startingStyles, styles, 1000, 1000, null, []);
const details = _formatOptions(player);
const options = details['options'];
const keys = Object.keys(options);
expect(keys.indexOf('easing')).toEqual(-1);
});
});
}
function _formatOptions(player: WebAnimationsPlayer): {[key: string]: any} {
return {'element': player.element, 'keyframes': player.keyframes, 'options': player.options};
}
| modules/@angular/platform-browser/test/dom/web_animations_driver_spec.ts | 1 | https://github.com/angular/angular/commit/be010a292a2f349b8fc54afff3f0d1e8323b67a2 | [
0.0007249197224155068,
0.00026328928652219474,
0.00016860049800015986,
0.00019099467317573726,
0.00017746095545589924
] |
{
"id": 2,
"code_window": [
" * found in the LICENSE file at https://angular.io/license\n",
" */\n",
"\n",
"import {el} from '@angular/platform-browser/testing/browser_util';\n",
"\n",
"import {DomAnimatePlayer} from '../../src/dom/dom_animate_player';\n",
"import {WebAnimationsDriver} from '../../src/dom/web_animations_driver';\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import {AnimationPlayer} from '@angular/core';\n"
],
"file_path": "modules/@angular/platform-browser/test/dom/web_animations_driver_spec.ts",
"type": "add",
"edit_start_line_idx": 8
} | #!/usr/bin/env bash
cd `dirname $0`
while read RAW_PACKAGE || [[ -n "$RAW_PACKAGE" ]]
do
PACKAGE=${RAW_PACKAGE%$'\r'}
DESTDIR=./../../modules/\@angular/${PACKAGE}
mv ${DESTDIR}/facade ${DESTDIR}/facade.old
cmd <<< "mklink \"..\\..\\modules\\\@angular\\"${PACKAGE}"\\facade\" \"..\\..\\facade\\src\\\""
done < packages.txt
| scripts/windows/create-symlinks.sh | 0 | https://github.com/angular/angular/commit/be010a292a2f349b8fc54afff3f0d1e8323b67a2 | [
0.00017414950707461685,
0.000169150807778351,
0.00016415210848208517,
0.000169150807778351,
0.0000049986992962658405
] |
{
"id": 2,
"code_window": [
" * found in the LICENSE file at https://angular.io/license\n",
" */\n",
"\n",
"import {el} from '@angular/platform-browser/testing/browser_util';\n",
"\n",
"import {DomAnimatePlayer} from '../../src/dom/dom_animate_player';\n",
"import {WebAnimationsDriver} from '../../src/dom/web_animations_driver';\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import {AnimationPlayer} from '@angular/core';\n"
],
"file_path": "modules/@angular/platform-browser/test/dom/web_animations_driver_spec.ts",
"type": "add",
"edit_start_line_idx": 8
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @module
* @description
* Entry point for all public APIs of the platform-browser-dynamic package.
*/
export * from './src/platform-webworker-dynamic';
// This file only reexports content of the `src` folder. Keep it that way.
| modules/@angular/platform-webworker-dynamic/index.ts | 0 | https://github.com/angular/angular/commit/be010a292a2f349b8fc54afff3f0d1e8323b67a2 | [
0.00016848092491272837,
0.00016827306535560638,
0.00016806520579848439,
0.00016827306535560638,
2.078595571219921e-7
] |
{
"id": 2,
"code_window": [
" * found in the LICENSE file at https://angular.io/license\n",
" */\n",
"\n",
"import {el} from '@angular/platform-browser/testing/browser_util';\n",
"\n",
"import {DomAnimatePlayer} from '../../src/dom/dom_animate_player';\n",
"import {WebAnimationsDriver} from '../../src/dom/web_animations_driver';\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import {AnimationPlayer} from '@angular/core';\n"
],
"file_path": "modules/@angular/platform-browser/test/dom/web_animations_driver_spec.ts",
"type": "add",
"edit_start_line_idx": 8
} | #!/bin/sh
cd `dirname $0`
./build.sh
gulp serve-examples &
(cd ../../../ && NODE_PATH=$NODE_PATH:dist/all $(npm bin)/protractor protractor-examples-e2e.conf.js --bundles=true)
| modules/@angular/examples/test.sh | 0 | https://github.com/angular/angular/commit/be010a292a2f349b8fc54afff3f0d1e8323b67a2 | [
0.00017397258488927037,
0.00017397258488927037,
0.00017397258488927037,
0.00017397258488927037,
0
] |
{
"id": 3,
"code_window": [
"import {DomAnimatePlayer} from '../../src/dom/dom_animate_player';\n",
"import {WebAnimationsDriver} from '../../src/dom/web_animations_driver';\n",
"import {WebAnimationsPlayer} from '../../src/dom/web_animations_player';\n",
"import {AnimationKeyframe, AnimationStyles} from '../../src/private_import_core';\n",
"import {MockDomAnimatePlayer} from '../../testing/mock_dom_animate_player';\n",
"\n",
"class ExtendedWebAnimationsDriver extends WebAnimationsDriver {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"import {AnimationKeyframe, AnimationStyles, NoOpAnimationPlayer} from '../../src/private_import_core';\n"
],
"file_path": "modules/@angular/platform-browser/test/dom/web_animations_driver_spec.ts",
"type": "replace",
"edit_start_line_idx": 13
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {el} from '@angular/platform-browser/testing/browser_util';
import {DomAnimatePlayer} from '../../src/dom/dom_animate_player';
import {WebAnimationsDriver} from '../../src/dom/web_animations_driver';
import {WebAnimationsPlayer} from '../../src/dom/web_animations_player';
import {AnimationKeyframe, AnimationStyles} from '../../src/private_import_core';
import {MockDomAnimatePlayer} from '../../testing/mock_dom_animate_player';
class ExtendedWebAnimationsDriver extends WebAnimationsDriver {
public log: {[key: string]: any}[] = [];
constructor() { super(); }
/** @internal */
_triggerWebAnimation(elm: any, keyframes: any[], options: any): DomAnimatePlayer {
this.log.push({'elm': elm, 'keyframes': keyframes, 'options': options});
return new MockDomAnimatePlayer();
}
}
function _makeStyles(styles: {[key: string]: string | number}): AnimationStyles {
return new AnimationStyles([styles]);
}
function _makeKeyframe(
offset: number, styles: {[key: string]: string | number}): AnimationKeyframe {
return new AnimationKeyframe(offset, _makeStyles(styles));
}
export function main() {
describe('WebAnimationsDriver', () => {
let driver: ExtendedWebAnimationsDriver;
let elm: HTMLElement;
beforeEach(() => {
driver = new ExtendedWebAnimationsDriver();
elm = el('<div></div>');
});
it('should use a fill mode of `both`', () => {
const startingStyles = _makeStyles({});
const styles = [_makeKeyframe(0, {'color': 'green'}), _makeKeyframe(1, {'color': 'red'})];
const player = driver.animate(elm, startingStyles, styles, 1000, 1000, 'linear', []);
const details = _formatOptions(player);
const options = details['options'];
expect(options['fill']).toEqual('both');
});
it('should apply the provided easing', () => {
const startingStyles = _makeStyles({});
const styles = [_makeKeyframe(0, {'color': 'green'}), _makeKeyframe(1, {'color': 'red'})];
const player = driver.animate(elm, startingStyles, styles, 1000, 1000, 'ease-out', []);
const details = _formatOptions(player);
const options = details['options'];
expect(options['easing']).toEqual('ease-out');
});
it('should only apply the provided easing if present', () => {
const startingStyles = _makeStyles({});
const styles = [_makeKeyframe(0, {'color': 'green'}), _makeKeyframe(1, {'color': 'red'})];
const player = driver.animate(elm, startingStyles, styles, 1000, 1000, null, []);
const details = _formatOptions(player);
const options = details['options'];
const keys = Object.keys(options);
expect(keys.indexOf('easing')).toEqual(-1);
});
});
}
function _formatOptions(player: WebAnimationsPlayer): {[key: string]: any} {
return {'element': player.element, 'keyframes': player.keyframes, 'options': player.options};
}
| modules/@angular/platform-browser/test/dom/web_animations_driver_spec.ts | 1 | https://github.com/angular/angular/commit/be010a292a2f349b8fc54afff3f0d1e8323b67a2 | [
0.9991070628166199,
0.37153100967407227,
0.00016624187992420048,
0.0008543758885934949,
0.47913414239883423
] |
{
"id": 3,
"code_window": [
"import {DomAnimatePlayer} from '../../src/dom/dom_animate_player';\n",
"import {WebAnimationsDriver} from '../../src/dom/web_animations_driver';\n",
"import {WebAnimationsPlayer} from '../../src/dom/web_animations_player';\n",
"import {AnimationKeyframe, AnimationStyles} from '../../src/private_import_core';\n",
"import {MockDomAnimatePlayer} from '../../testing/mock_dom_animate_player';\n",
"\n",
"class ExtendedWebAnimationsDriver extends WebAnimationsDriver {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"import {AnimationKeyframe, AnimationStyles, NoOpAnimationPlayer} from '../../src/private_import_core';\n"
],
"file_path": "modules/@angular/platform-browser/test/dom/web_animations_driver_spec.ts",
"type": "replace",
"edit_start_line_idx": 13
} | /** @stable */
export declare function async(fn: Function): (done: any) => any;
/** @stable */
export declare class ComponentFixture<T> {
changeDetectorRef: ChangeDetectorRef;
componentInstance: T;
componentRef: ComponentRef<T>;
debugElement: DebugElement;
elementRef: ElementRef;
nativeElement: any;
ngZone: NgZone;
constructor(componentRef: ComponentRef<T>, ngZone: NgZone, _autoDetect: boolean);
autoDetectChanges(autoDetect?: boolean): void;
checkNoChanges(): void;
destroy(): void;
detectChanges(checkNoChanges?: boolean): void;
isStable(): boolean;
whenStable(): Promise<any>;
}
/** @experimental */
export declare const ComponentFixtureAutoDetect: OpaqueToken;
/** @experimental */
export declare const ComponentFixtureNoNgZone: OpaqueToken;
/** @experimental */
export declare function discardPeriodicTasks(): void;
/** @experimental */
export declare function fakeAsync(fn: Function): (...args: any[]) => any;
/** @experimental */
export declare function flushMicrotasks(): void;
/** @experimental */
export declare function getTestBed(): TestBed;
/** @stable */
export declare function inject(tokens: any[], fn: Function): () => any;
/** @experimental */
export declare class InjectSetupWrapper {
constructor(_moduleDef: () => TestModuleMetadata);
inject(tokens: any[], fn: Function): () => any;
}
/** @experimental */
export declare type MetadataOverride<T> = {
add?: T;
remove?: T;
set?: T;
};
/** @experimental */
export declare function resetFakeAsyncZone(): void;
/** @stable */
export declare class TestBed implements Injector {
ngModule: Type<any>;
platform: PlatformRef;
compileComponents(): Promise<any>;
configureCompiler(config: {
providers?: any[];
useJit?: boolean;
}): void;
configureTestingModule(moduleDef: TestModuleMetadata): void;
createComponent<T>(component: Type<T>): ComponentFixture<T>;
execute(tokens: any[], fn: Function): any;
get(token: any, notFoundValue?: any): any;
/** @experimental */ initTestEnvironment(ngModule: Type<any>, platform: PlatformRef): void;
overrideComponent(component: Type<any>, override: MetadataOverride<Component>): void;
overrideDirective(directive: Type<any>, override: MetadataOverride<Directive>): void;
overrideModule(ngModule: Type<any>, override: MetadataOverride<NgModule>): void;
overridePipe(pipe: Type<any>, override: MetadataOverride<Pipe>): void;
/** @experimental */ resetTestEnvironment(): void;
resetTestingModule(): void;
static compileComponents(): Promise<any>;
static configureCompiler(config: {
providers?: any[];
useJit?: boolean;
}): typeof TestBed;
static configureTestingModule(moduleDef: TestModuleMetadata): typeof TestBed;
static createComponent<T>(component: Type<T>): ComponentFixture<T>;
static get(token: any, notFoundValue?: any): any;
/** @experimental */ static initTestEnvironment(ngModule: Type<any>, platform: PlatformRef): TestBed;
static overrideComponent(component: Type<any>, override: MetadataOverride<Component>): typeof TestBed;
static overrideDirective(directive: Type<any>, override: MetadataOverride<Directive>): typeof TestBed;
static overrideModule(ngModule: Type<any>, override: MetadataOverride<NgModule>): typeof TestBed;
static overridePipe(pipe: Type<any>, override: MetadataOverride<Pipe>): typeof TestBed;
/** @experimental */ static resetTestEnvironment(): void;
static resetTestingModule(): typeof TestBed;
}
/** @experimental */
export declare class TestComponentRenderer {
insertRootElement(rootElementId: string): void;
}
/** @experimental */
export declare type TestModuleMetadata = {
providers?: any[];
declarations?: any[];
imports?: any[];
schemas?: Array<SchemaMetadata | any[]>;
};
/** @experimental */
export declare function tick(millis?: number): void;
/** @experimental */
export declare function withModule(moduleDef: TestModuleMetadata): InjectSetupWrapper;
| tools/public_api_guard/core/testing/index.d.ts | 0 | https://github.com/angular/angular/commit/be010a292a2f349b8fc54afff3f0d1e8323b67a2 | [
0.00017728591046761721,
0.0001737039565341547,
0.00016977345512714237,
0.00017440650844946504,
0.00000224981067731278
] |
{
"id": 3,
"code_window": [
"import {DomAnimatePlayer} from '../../src/dom/dom_animate_player';\n",
"import {WebAnimationsDriver} from '../../src/dom/web_animations_driver';\n",
"import {WebAnimationsPlayer} from '../../src/dom/web_animations_player';\n",
"import {AnimationKeyframe, AnimationStyles} from '../../src/private_import_core';\n",
"import {MockDomAnimatePlayer} from '../../testing/mock_dom_animate_player';\n",
"\n",
"class ExtendedWebAnimationsDriver extends WebAnimationsDriver {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"import {AnimationKeyframe, AnimationStyles, NoOpAnimationPlayer} from '../../src/private_import_core';\n"
],
"file_path": "modules/@angular/platform-browser/test/dom/web_animations_driver_spec.ts",
"type": "replace",
"edit_start_line_idx": 13
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// Public API for Zone
export {NgZone} from './zone/ng_zone';
| modules/@angular/core/src/zone.ts | 0 | https://github.com/angular/angular/commit/be010a292a2f349b8fc54afff3f0d1e8323b67a2 | [
0.0001749373768689111,
0.00017175052198581398,
0.0001685636816546321,
0.00017175052198581398,
0.000003186847607139498
] |
{
"id": 3,
"code_window": [
"import {DomAnimatePlayer} from '../../src/dom/dom_animate_player';\n",
"import {WebAnimationsDriver} from '../../src/dom/web_animations_driver';\n",
"import {WebAnimationsPlayer} from '../../src/dom/web_animations_player';\n",
"import {AnimationKeyframe, AnimationStyles} from '../../src/private_import_core';\n",
"import {MockDomAnimatePlayer} from '../../testing/mock_dom_animate_player';\n",
"\n",
"class ExtendedWebAnimationsDriver extends WebAnimationsDriver {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"import {AnimationKeyframe, AnimationStyles, NoOpAnimationPlayer} from '../../src/private_import_core';\n"
],
"file_path": "modules/@angular/platform-browser/test/dom/web_animations_driver_spec.ts",
"type": "replace",
"edit_start_line_idx": 13
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/*
DO NOT DELETE THIS FILE
=======================
The purpose of this file is to allow `main-dynamic.ts` to be tsc-compiled
BEFORE it is copied over to each of the associated example directories
within `dist/examples`.
*/
export class AppModule {};
| modules/@angular/examples/_common/module.d.ts | 0 | https://github.com/angular/angular/commit/be010a292a2f349b8fc54afff3f0d1e8323b67a2 | [
0.00017512546037323773,
0.00017228482465725392,
0.0001694441889412701,
0.00017228482465725392,
0.000002840635715983808
] |
{
"id": 4,
"code_window": [
" const details = _formatOptions(player);\n",
" const options = details['options'];\n",
" const keys = Object.keys(options);\n",
" expect(keys.indexOf('easing')).toEqual(-1);\n",
" });\n",
" });\n",
"}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
" it('should only apply the provided easing if present', () => {\n",
" const previousPlayers = [\n",
" new NoOpAnimationPlayerWithStyles(),\n",
" new NoOpAnimationPlayerWithStyles(),\n",
" new NoOpAnimationPlayerWithStyles(),\n",
" ];\n",
" const startingStyles = _makeStyles({});\n",
" const styles = [_makeKeyframe(0, {}), _makeKeyframe(1, {})];\n",
" const player = driver.animate(\n",
" elm, startingStyles, styles, 1000, 1000, null, <AnimationPlayer[]>previousPlayers);\n",
" expect(player.previousStyles).toEqual({});\n",
" });\n"
],
"file_path": "modules/@angular/platform-browser/test/dom/web_animations_driver_spec.ts",
"type": "add",
"edit_start_line_idx": 73
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {el} from '@angular/platform-browser/testing/browser_util';
import {DomAnimatePlayer} from '../../src/dom/dom_animate_player';
import {WebAnimationsDriver} from '../../src/dom/web_animations_driver';
import {WebAnimationsPlayer} from '../../src/dom/web_animations_player';
import {AnimationKeyframe, AnimationStyles} from '../../src/private_import_core';
import {MockDomAnimatePlayer} from '../../testing/mock_dom_animate_player';
class ExtendedWebAnimationsDriver extends WebAnimationsDriver {
public log: {[key: string]: any}[] = [];
constructor() { super(); }
/** @internal */
_triggerWebAnimation(elm: any, keyframes: any[], options: any): DomAnimatePlayer {
this.log.push({'elm': elm, 'keyframes': keyframes, 'options': options});
return new MockDomAnimatePlayer();
}
}
function _makeStyles(styles: {[key: string]: string | number}): AnimationStyles {
return new AnimationStyles([styles]);
}
function _makeKeyframe(
offset: number, styles: {[key: string]: string | number}): AnimationKeyframe {
return new AnimationKeyframe(offset, _makeStyles(styles));
}
export function main() {
describe('WebAnimationsDriver', () => {
let driver: ExtendedWebAnimationsDriver;
let elm: HTMLElement;
beforeEach(() => {
driver = new ExtendedWebAnimationsDriver();
elm = el('<div></div>');
});
it('should use a fill mode of `both`', () => {
const startingStyles = _makeStyles({});
const styles = [_makeKeyframe(0, {'color': 'green'}), _makeKeyframe(1, {'color': 'red'})];
const player = driver.animate(elm, startingStyles, styles, 1000, 1000, 'linear', []);
const details = _formatOptions(player);
const options = details['options'];
expect(options['fill']).toEqual('both');
});
it('should apply the provided easing', () => {
const startingStyles = _makeStyles({});
const styles = [_makeKeyframe(0, {'color': 'green'}), _makeKeyframe(1, {'color': 'red'})];
const player = driver.animate(elm, startingStyles, styles, 1000, 1000, 'ease-out', []);
const details = _formatOptions(player);
const options = details['options'];
expect(options['easing']).toEqual('ease-out');
});
it('should only apply the provided easing if present', () => {
const startingStyles = _makeStyles({});
const styles = [_makeKeyframe(0, {'color': 'green'}), _makeKeyframe(1, {'color': 'red'})];
const player = driver.animate(elm, startingStyles, styles, 1000, 1000, null, []);
const details = _formatOptions(player);
const options = details['options'];
const keys = Object.keys(options);
expect(keys.indexOf('easing')).toEqual(-1);
});
});
}
function _formatOptions(player: WebAnimationsPlayer): {[key: string]: any} {
return {'element': player.element, 'keyframes': player.keyframes, 'options': player.options};
}
| modules/@angular/platform-browser/test/dom/web_animations_driver_spec.ts | 1 | https://github.com/angular/angular/commit/be010a292a2f349b8fc54afff3f0d1e8323b67a2 | [
0.9966781139373779,
0.37369632720947266,
0.00017336684686597437,
0.0010997651843354106,
0.4817371964454651
] |
{
"id": 4,
"code_window": [
" const details = _formatOptions(player);\n",
" const options = details['options'];\n",
" const keys = Object.keys(options);\n",
" expect(keys.indexOf('easing')).toEqual(-1);\n",
" });\n",
" });\n",
"}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
" it('should only apply the provided easing if present', () => {\n",
" const previousPlayers = [\n",
" new NoOpAnimationPlayerWithStyles(),\n",
" new NoOpAnimationPlayerWithStyles(),\n",
" new NoOpAnimationPlayerWithStyles(),\n",
" ];\n",
" const startingStyles = _makeStyles({});\n",
" const styles = [_makeKeyframe(0, {}), _makeKeyframe(1, {})];\n",
" const player = driver.animate(\n",
" elm, startingStyles, styles, 1000, 1000, null, <AnimationPlayer[]>previousPlayers);\n",
" expect(player.previousStyles).toEqual({});\n",
" });\n"
],
"file_path": "modules/@angular/platform-browser/test/dom/web_animations_driver_spec.ts",
"type": "add",
"edit_start_line_idx": 73
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
(function(global: any) {
writeScriptTag('/vendor/zone.js');
writeScriptTag('/vendor/system.js');
writeScriptTag('/vendor/Reflect.js');
writeScriptTag('/_common/system-config.js');
function writeScriptTag(scriptUrl: string, onload: string = '') {
document.write('<script src="' + scriptUrl + '" onload="' + onload + '"></script>');
}
}(window));
| modules/@angular/examples/_common/bootstrap.ts | 0 | https://github.com/angular/angular/commit/be010a292a2f349b8fc54afff3f0d1e8323b67a2 | [
0.00017542229034006596,
0.0001750378287397325,
0.00017465338169131428,
0.0001750378287397325,
3.8445432437583804e-7
] |
{
"id": 4,
"code_window": [
" const details = _formatOptions(player);\n",
" const options = details['options'];\n",
" const keys = Object.keys(options);\n",
" expect(keys.indexOf('easing')).toEqual(-1);\n",
" });\n",
" });\n",
"}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
" it('should only apply the provided easing if present', () => {\n",
" const previousPlayers = [\n",
" new NoOpAnimationPlayerWithStyles(),\n",
" new NoOpAnimationPlayerWithStyles(),\n",
" new NoOpAnimationPlayerWithStyles(),\n",
" ];\n",
" const startingStyles = _makeStyles({});\n",
" const styles = [_makeKeyframe(0, {}), _makeKeyframe(1, {})];\n",
" const player = driver.animate(\n",
" elm, startingStyles, styles, 1000, 1000, null, <AnimationPlayer[]>previousPlayers);\n",
" expect(player.previousStyles).toEqual({});\n",
" });\n"
],
"file_path": "modules/@angular/platform-browser/test/dom/web_animations_driver_spec.ts",
"type": "add",
"edit_start_line_idx": 73
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {TreeNode, emptyTree} from '../util';
export class TreeComponent { data: TreeNode = emptyTree; }
export class AppModule {}
| modules/benchmarks/src/tree/ng2_ftl/tree.ts | 0 | https://github.com/angular/angular/commit/be010a292a2f349b8fc54afff3f0d1e8323b67a2 | [
0.00017759147158358246,
0.0001765662746038288,
0.00017554109217599034,
0.0001765662746038288,
0.0000010251897037960589
] |
{
"id": 4,
"code_window": [
" const details = _formatOptions(player);\n",
" const options = details['options'];\n",
" const keys = Object.keys(options);\n",
" expect(keys.indexOf('easing')).toEqual(-1);\n",
" });\n",
" });\n",
"}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
" it('should only apply the provided easing if present', () => {\n",
" const previousPlayers = [\n",
" new NoOpAnimationPlayerWithStyles(),\n",
" new NoOpAnimationPlayerWithStyles(),\n",
" new NoOpAnimationPlayerWithStyles(),\n",
" ];\n",
" const startingStyles = _makeStyles({});\n",
" const styles = [_makeKeyframe(0, {}), _makeKeyframe(1, {})];\n",
" const player = driver.animate(\n",
" elm, startingStyles, styles, 1000, 1000, null, <AnimationPlayer[]>previousPlayers);\n",
" expect(player.previousStyles).toEqual({});\n",
" });\n"
],
"file_path": "modules/@angular/platform-browser/test/dom/web_animations_driver_spec.ts",
"type": "add",
"edit_start_line_idx": 73
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Injectable} from '@angular/core';
import {__platform_browser_private__} from '@angular/platform-browser';
import {Observable} from 'rxjs/Observable';
import {Observer} from 'rxjs/Observer';
import {ResponseOptions} from '../base_response_options';
import {ContentType, ReadyState, RequestMethod, ResponseContentType, ResponseType} from '../enums';
import {Headers} from '../headers';
import {getResponseURL, isSuccess} from '../http_utils';
import {Connection, ConnectionBackend, XSRFStrategy} from '../interfaces';
import {Request} from '../static_request';
import {Response} from '../static_response';
import {BrowserXhr} from './browser_xhr';
const XSSI_PREFIX = /^\)\]\}',?\n/;
/**
* Creates connections using `XMLHttpRequest`. Given a fully-qualified
* request, an `XHRConnection` will immediately create an `XMLHttpRequest` object and send the
* request.
*
* This class would typically not be created or interacted with directly inside applications, though
* the {@link MockConnection} may be interacted with in tests.
*
* @experimental
*/
export class XHRConnection implements Connection {
request: Request;
/**
* Response {@link EventEmitter} which emits a single {@link Response} value on load event of
* `XMLHttpRequest`.
*/
response: Observable<Response>;
readyState: ReadyState;
constructor(req: Request, browserXHR: BrowserXhr, baseResponseOptions?: ResponseOptions) {
this.request = req;
this.response = new Observable<Response>((responseObserver: Observer<Response>) => {
const _xhr: XMLHttpRequest = browserXHR.build();
_xhr.open(RequestMethod[req.method].toUpperCase(), req.url);
if (req.withCredentials != null) {
_xhr.withCredentials = req.withCredentials;
}
// load event handler
const onLoad = () => {
// normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
let status: number = _xhr.status === 1223 ? 204 : _xhr.status;
let body: any = null;
// HTTP 204 means no content
if (status !== 204) {
// responseText is the old-school way of retrieving response (supported by IE8 & 9)
// response/responseType properties were introduced in ResourceLoader Level2 spec
// (supported by IE10)
body = _xhr.response == null ? _xhr.responseText : _xhr.response;
// Implicitly strip a potential XSSI prefix.
if (typeof body === 'string') {
body = body.replace(XSSI_PREFIX, '');
}
}
// fix status code when it is 0 (0 status is undocumented).
// Occurs when accessing file resources or on Android 4.1 stock browser
// while retrieving files from application cache.
if (status === 0) {
status = body ? 200 : 0;
}
const headers: Headers = Headers.fromResponseHeaderString(_xhr.getAllResponseHeaders());
// IE 9 does not provide the way to get URL of response
const url = getResponseURL(_xhr) || req.url;
const statusText: string = _xhr.statusText || 'OK';
let responseOptions = new ResponseOptions({body, status, headers, statusText, url});
if (baseResponseOptions != null) {
responseOptions = baseResponseOptions.merge(responseOptions);
}
const response = new Response(responseOptions);
response.ok = isSuccess(status);
if (response.ok) {
responseObserver.next(response);
// TODO(gdi2290): defer complete if array buffer until done
responseObserver.complete();
return;
}
responseObserver.error(response);
};
// error event handler
const onError = (err: ErrorEvent) => {
let responseOptions = new ResponseOptions({
body: err,
type: ResponseType.Error,
status: _xhr.status,
statusText: _xhr.statusText,
});
if (baseResponseOptions != null) {
responseOptions = baseResponseOptions.merge(responseOptions);
}
responseObserver.error(new Response(responseOptions));
};
this.setDetectedContentType(req, _xhr);
if (req.headers != null) {
req.headers.forEach((values, name) => _xhr.setRequestHeader(name, values.join(',')));
}
// Select the correct buffer type to store the response
if (req.responseType != null && _xhr.responseType != null) {
switch (req.responseType) {
case ResponseContentType.ArrayBuffer:
_xhr.responseType = 'arraybuffer';
break;
case ResponseContentType.Json:
_xhr.responseType = 'json';
break;
case ResponseContentType.Text:
_xhr.responseType = 'text';
break;
case ResponseContentType.Blob:
_xhr.responseType = 'blob';
break;
default:
throw new Error('The selected responseType is not supported');
}
}
_xhr.addEventListener('load', onLoad);
_xhr.addEventListener('error', onError);
_xhr.send(this.request.getBody());
return () => {
_xhr.removeEventListener('load', onLoad);
_xhr.removeEventListener('error', onError);
_xhr.abort();
};
});
}
setDetectedContentType(req: any /** TODO Request */, _xhr: any /** XMLHttpRequest */) {
// Skip if a custom Content-Type header is provided
if (req.headers != null && req.headers.get('Content-Type') != null) {
return;
}
// Set the detected content type
switch (req.contentType) {
case ContentType.NONE:
break;
case ContentType.JSON:
_xhr.setRequestHeader('content-type', 'application/json');
break;
case ContentType.FORM:
_xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded;charset=UTF-8');
break;
case ContentType.TEXT:
_xhr.setRequestHeader('content-type', 'text/plain');
break;
case ContentType.BLOB:
const blob = req.blob();
if (blob.type) {
_xhr.setRequestHeader('content-type', blob.type);
}
break;
}
}
}
/**
* `XSRFConfiguration` sets up Cross Site Request Forgery (XSRF) protection for the application
* using a cookie. See {@link https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)}
* for more information on XSRF.
*
* Applications can configure custom cookie and header names by binding an instance of this class
* with different `cookieName` and `headerName` values. See the main HTTP documentation for more
* details.
*
* @experimental
*/
export class CookieXSRFStrategy implements XSRFStrategy {
constructor(
private _cookieName: string = 'XSRF-TOKEN', private _headerName: string = 'X-XSRF-TOKEN') {}
configureRequest(req: Request): void {
const xsrfToken = __platform_browser_private__.getDOM().getCookie(this._cookieName);
if (xsrfToken) {
req.headers.set(this._headerName, xsrfToken);
}
}
}
/**
* Creates {@link XHRConnection} instances.
*
* This class would typically not be used by end users, but could be
* overridden if a different backend implementation should be used,
* such as in a node backend.
*
* ### Example
*
* ```
* import {Http, MyNodeBackend, HTTP_PROVIDERS, BaseRequestOptions} from '@angular/http';
* @Component({
* viewProviders: [
* HTTP_PROVIDERS,
* {provide: Http, useFactory: (backend, options) => {
* return new Http(backend, options);
* }, deps: [MyNodeBackend, BaseRequestOptions]}]
* })
* class MyComponent {
* constructor(http:Http) {
* http.request('people.json').subscribe(res => this.people = res.json());
* }
* }
* ```
* @experimental
*/
@Injectable()
export class XHRBackend implements ConnectionBackend {
constructor(
private _browserXHR: BrowserXhr, private _baseResponseOptions: ResponseOptions,
private _xsrfStrategy: XSRFStrategy) {}
createConnection(request: Request): XHRConnection {
this._xsrfStrategy.configureRequest(request);
return new XHRConnection(request, this._browserXHR, this._baseResponseOptions);
}
}
| modules/@angular/http/src/backends/xhr_backend.ts | 0 | https://github.com/angular/angular/commit/be010a292a2f349b8fc54afff3f0d1e8323b67a2 | [
0.00024805593420751393,
0.00017551030032336712,
0.000159866496687755,
0.00017307672533206642,
0.00001566601167724002
] |
{
"id": 5,
"code_window": [
" });\n",
"}\n",
"\n",
"function _formatOptions(player: WebAnimationsPlayer): {[key: string]: any} {\n",
" return {'element': player.element, 'keyframes': player.keyframes, 'options': player.options};\n",
"}"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"class NoOpAnimationPlayerWithStyles extends NoOpAnimationPlayer {\n",
" private _captureStyles() { return {color: 'red'}; }\n",
"}\n",
"\n"
],
"file_path": "modules/@angular/platform-browser/test/dom/web_animations_driver_spec.ts",
"type": "add",
"edit_start_line_idx": 76
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {AnimationPlayer} from '@angular/core';
import {isPresent} from '../facade/lang';
import {AnimationKeyframe, AnimationStyles} from '../private_import_core';
import {AnimationDriver} from './animation_driver';
import {WebAnimationsPlayer} from './web_animations_player';
export class WebAnimationsDriver implements AnimationDriver {
animate(
element: any, startingStyles: AnimationStyles, keyframes: AnimationKeyframe[],
duration: number, delay: number, easing: string,
previousPlayers: AnimationPlayer[] = []): WebAnimationsPlayer {
let formattedSteps: {[key: string]: string | number}[] = [];
let startingStyleLookup: {[key: string]: string | number} = {};
if (isPresent(startingStyles) && startingStyles.styles.length > 0) {
startingStyleLookup = _populateStyles(startingStyles, {});
startingStyleLookup['offset'] = 0;
formattedSteps.push(startingStyleLookup);
}
keyframes.forEach((keyframe: AnimationKeyframe) => {
const data = _populateStyles(keyframe.styles, startingStyleLookup);
data['offset'] = keyframe.offset;
formattedSteps.push(data);
});
// this is a special case when only styles are applied as an
// animation. When this occurs we want to animate from start to
// end with the same values. Removing the offset and having only
// start/end values is suitable enough for the web-animations API
if (formattedSteps.length == 1) {
const start = formattedSteps[0];
start['offset'] = null;
formattedSteps = [start, start];
}
const playerOptions: {[key: string]: string | number} = {
'duration': duration,
'delay': delay,
'fill': 'both' // we use `both` because it allows for styling at 0% to work with `delay`
};
// we check for this to avoid having a null|undefined value be present
// for the easing (which results in an error for certain browsers #9752)
if (easing) {
playerOptions['easing'] = easing;
}
return new WebAnimationsPlayer(
element, formattedSteps, playerOptions, <WebAnimationsPlayer[]>previousPlayers);
}
}
function _populateStyles(styles: AnimationStyles, defaultStyles: {[key: string]: string | number}):
{[key: string]: string | number} {
const data: {[key: string]: string | number} = {};
styles.styles.forEach(
(entry) => { Object.keys(entry).forEach(prop => { data[prop] = entry[prop]; }); });
Object.keys(defaultStyles).forEach(prop => {
if (!isPresent(data[prop])) {
data[prop] = defaultStyles[prop];
}
});
return data;
}
| modules/@angular/platform-browser/src/dom/web_animations_driver.ts | 1 | https://github.com/angular/angular/commit/be010a292a2f349b8fc54afff3f0d1e8323b67a2 | [
0.12785345315933228,
0.02141549624502659,
0.00016812788089737296,
0.0016539336647838354,
0.04105013981461525
] |
{
"id": 5,
"code_window": [
" });\n",
"}\n",
"\n",
"function _formatOptions(player: WebAnimationsPlayer): {[key: string]: any} {\n",
" return {'element': player.element, 'keyframes': player.keyframes, 'options': player.options};\n",
"}"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"class NoOpAnimationPlayerWithStyles extends NoOpAnimationPlayer {\n",
" private _captureStyles() { return {color: 'red'}; }\n",
"}\n",
"\n"
],
"file_path": "modules/@angular/platform-browser/test/dom/web_animations_driver_spec.ts",
"type": "add",
"edit_start_line_idx": 76
} | <!doctype html>
<html>
<title>Web Worker Router Example</title>
<body>
<app></app>
<script src="../../bootstrap.js"></script>
</body>
</html>
| modules/playground/src/web_workers/router/index.html | 0 | https://github.com/angular/angular/commit/be010a292a2f349b8fc54afff3f0d1e8323b67a2 | [
0.00016685949231032282,
0.00016685949231032282,
0.00016685949231032282,
0.00016685949231032282,
0
] |
{
"id": 5,
"code_window": [
" });\n",
"}\n",
"\n",
"function _formatOptions(player: WebAnimationsPlayer): {[key: string]: any} {\n",
" return {'element': player.element, 'keyframes': player.keyframes, 'options': player.options};\n",
"}"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"class NoOpAnimationPlayerWithStyles extends NoOpAnimationPlayer {\n",
" private _captureStyles() { return {color: 'red'}; }\n",
"}\n",
"\n"
],
"file_path": "modules/@angular/platform-browser/test/dom/web_animations_driver_spec.ts",
"type": "add",
"edit_start_line_idx": 76
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/* tslint:disable:no-var-keyword */
'use strict';
var glob = require('glob');
require('zone.js/dist/zone-node.js');
var JasmineRunner = require('jasmine');
var path = require('path');
require('source-map-support').install();
require('zone.js/dist/long-stack-trace-zone.js');
require('zone.js/dist/proxy.js');
require('zone.js/dist/sync-test.js');
require('zone.js/dist/async-test.js');
require('zone.js/dist/fake-async-test.js');
require('reflect-metadata/Reflect');
var jrunner = new JasmineRunner();
(global as any)['jasmine'] = jrunner.jasmine;
require('zone.js/dist/jasmine-patch.js');
var distAll: string = process.cwd() + '/dist/all';
function distAllRequire(moduleId: string) {
return require(path.join(distAll, moduleId));
}
// Tun on full stack traces in errors to help debugging
(<any>Error)['stackTraceLimit'] = Infinity;
jrunner.jasmine.DEFAULT_TIMEOUT_INTERVAL = 100;
// Support passing multiple globs
var globsIndex = process.argv.indexOf('--');
var args: string[];
if (globsIndex < 0) {
args = [process.argv[2]];
} else {
args = process.argv.slice(globsIndex + 1);
}
var specFiles: any =
args.map(function(globstr: string):
string[] {
return glob.sync(globstr, {
cwd: distAll,
ignore: [
// the following code and tests are not compatible with CJS/node environment
'@angular/platform-browser/**',
'@angular/platform-browser-dynamic/**',
'@angular/core/test/zone/**',
'@angular/core/test/fake_async_spec.*',
'@angular/forms/test/**',
'@angular/router/test/route_config/route_config_spec.*',
'@angular/router/test/integration/bootstrap_spec.*',
'@angular/integration_test/symbol_inspector/**',
'@angular/upgrade/**',
'@angular/**/e2e_test/**',
'angular1_router/**',
'payload_tests/**',
]
});
})
// The security spec however works (and must work!) on the server side.
.concat(glob.sync('@angular/platform-browser/test/security/**/*_spec.js', {cwd: distAll}))
.reduce((specFiles: string[], paths: string[]) => specFiles.concat(paths), <string[]>[]);
jasmine.DEFAULT_TIMEOUT_INTERVAL = 100;
jrunner.configureDefaultReporter({showColors: process.argv.indexOf('--no-color') === -1});
jrunner.onComplete(function(passed: boolean) { process.exit(passed ? 0 : 1); });
jrunner.projectBaseDir = path.resolve(__dirname, '../../');
jrunner.specDir = '';
require('./test-cjs-main.js');
distAllRequire('@angular/platform-server/src/parse5_adapter.js').Parse5DomAdapter.makeCurrent();
specFiles.forEach((file: string) => {
const r = distAllRequire(file);
if (r.main) {
r.main();
}
});
jrunner.execute();
| tools/cjs-jasmine/index.ts | 0 | https://github.com/angular/angular/commit/be010a292a2f349b8fc54afff3f0d1e8323b67a2 | [
0.0011047086445614696,
0.0002754417364485562,
0.00016717734979465604,
0.00017192379164043814,
0.00029319775057956576
] |
{
"id": 5,
"code_window": [
" });\n",
"}\n",
"\n",
"function _formatOptions(player: WebAnimationsPlayer): {[key: string]: any} {\n",
" return {'element': player.element, 'keyframes': player.keyframes, 'options': player.options};\n",
"}"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"class NoOpAnimationPlayerWithStyles extends NoOpAnimationPlayer {\n",
" private _captureStyles() { return {color: 'red'}; }\n",
"}\n",
"\n"
],
"file_path": "modules/@angular/platform-browser/test/dom/web_animations_driver_spec.ts",
"type": "add",
"edit_start_line_idx": 76
} | #!/bin/bash
set -e -o pipefail
# Setup environment
cd `dirname $0`
source ../ci-lite/env.sh
# Setup and start Sauce Connect for your TravisCI build
# This script requires your .travis.yml to include the following two private env variables:
# SAUCE_USERNAME
# SAUCE_ACCESS_KEY
# Follow the steps at https://saucelabs.com/opensource/travis to set that up.
#
# Curl and run this script as part of your .travis.yml before_script section:
# before_script:
# - curl https://gist.github.com/santiycr/5139565/raw/sauce_connect_setup.sh | bash
CONNECT_URL="https://saucelabs.com/downloads/sc-${SAUCE_CONNECT_VERSION}-linux.tar.gz"
CONNECT_DIR="/tmp/sauce-connect-$RANDOM"
CONNECT_DOWNLOAD="sc-latest-linux.tar.gz"
CONNECT_LOG="$LOGS_DIR/sauce-connect"
CONNECT_STDOUT="$LOGS_DIR/sauce-connect.stdout"
CONNECT_STDERR="$LOGS_DIR/sauce-connect.stderr"
# Get Connect and start it
mkdir -p $CONNECT_DIR
cd $CONNECT_DIR
curl $CONNECT_URL -o $CONNECT_DOWNLOAD 2> /dev/null 1> /dev/null
mkdir sauce-connect
tar --extract --file=$CONNECT_DOWNLOAD --strip-components=1 --directory=sauce-connect > /dev/null
rm $CONNECT_DOWNLOAD
SAUCE_ACCESS_KEY=`echo $SAUCE_ACCESS_KEY | rev`
ARGS=""
# Set tunnel-id only on Travis, to make local testing easier.
if [ ! -z "$TRAVIS_JOB_NUMBER" ]; then
ARGS="$ARGS --tunnel-identifier $TRAVIS_JOB_NUMBER"
fi
if [ ! -z "$BROWSER_PROVIDER_READY_FILE" ]; then
ARGS="$ARGS --readyfile $BROWSER_PROVIDER_READY_FILE"
fi
echo "Starting Sauce Connect in the background, logging into:"
echo " $CONNECT_LOG"
echo " $CONNECT_STDOUT"
echo " $CONNECT_STDERR"
sauce-connect/bin/sc -u $SAUCE_USERNAME -k $SAUCE_ACCESS_KEY $ARGS \
--logfile $CONNECT_LOG 2> $CONNECT_STDERR 1> $CONNECT_STDOUT &
| scripts/sauce/sauce_connect_setup.sh | 0 | https://github.com/angular/angular/commit/be010a292a2f349b8fc54afff3f0d1e8323b67a2 | [
0.00021958185243420303,
0.0001762740284902975,
0.0001633363135624677,
0.00016883929492905736,
0.00001950919977389276
] |
{
"id": 0,
"code_window": [
"import { SlideDown } from 'app/core/components/Animations/SlideDown';\n",
"import ApiKeysAddedModal from './ApiKeysAddedModal';\n",
"import config from 'app/core/config';\n",
"import appEvents from 'app/core/app_events';\n",
"import EmptyListCTA from 'app/core/components/EmptyListCTA/EmptyListCTA';\n",
"import {\n",
" DeleteButton,\n",
" EventsWithValidation,\n",
" InlineFormLabel,\n",
" LegacyForms,\n",
" ValidationEvents,\n",
" IconButton,\n",
"} from '@grafana/ui';\n",
"const { Input, Switch } = LegacyForms;\n",
"import { NavModel, dateTimeFormat, rangeUtil } from '@grafana/data';\n",
"import { FilterInput } from 'app/core/components/FilterInput/FilterInput';\n",
"import { store } from 'app/store/store';\n",
"import { getTimeZone } from 'app/features/profile/state/selectors';\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { DeleteButton, EventsWithValidation, InlineFormLabel, LegacyForms, ValidationEvents, Icon } from '@grafana/ui';\n"
],
"file_path": "public/app/features/api-keys/ApiKeysPage.tsx",
"type": "replace",
"edit_start_line_idx": 15
} | // Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`Render should render API keys table if there are any keys 1`] = `
<Page
navModel={
Object {
"main": Object {
"text": "Configuration",
},
"node": Object {
"text": "Api Keys",
},
}
}
>
<PageContents
isLoading={true}
/>
</Page>
`;
exports[`Render should render CTA if there are no API keys 1`] = `
<Page
navModel={
Object {
"main": Object {
"text": "Configuration",
},
"node": Object {
"text": "Api Keys",
},
}
}
>
<PageContents
isLoading={false}
>
<EmptyListCTA
buttonIcon="key-skeleton-alt"
buttonLink="#"
buttonTitle=" New API Key"
onClick={[Function]}
proTip="Remember you can provide view-only API access to other applications."
title="You haven't added any API Keys yet."
/>
<Component
in={false}
>
<div
className="cta-form"
>
<IconButton
className="cta-form__close btn btn-transparent"
name="times"
onClick={[Function]}
/>
<h5>
Add API Key
</h5>
<form
className="gf-form-group"
onSubmit={[Function]}
>
<div
className="gf-form-inline"
>
<div
className="gf-form max-width-21"
>
<span
className="gf-form-label"
>
Key name
</span>
<Input
className="gf-form-input"
onChange={[Function]}
placeholder="Name"
type="text"
value=""
/>
</div>
<div
className="gf-form"
>
<span
className="gf-form-label"
>
Role
</span>
<span
className="gf-form-select-wrapper"
>
<select
className="gf-form-input gf-size-auto"
onChange={[Function]}
value="Viewer"
>
<option
key="Viewer"
label="Viewer"
value="Viewer"
>
Viewer
</option>
<option
key="Editor"
label="Editor"
value="Editor"
>
Editor
</option>
<option
key="Admin"
label="Admin"
value="Admin"
>
Admin
</option>
</select>
</span>
</div>
<div
className="gf-form max-width-21"
>
<Component
tooltip="The api key life duration. For example 1d if your key is going to last for one day. All the supported units are: s,m,h,d,w,M,y"
>
Time to live
</Component>
<Input
className="gf-form-input"
onChange={[Function]}
placeholder="1d"
type="text"
validationEvents={
Object {
"onBlur": Array [
Object {
"errorMessage": "Not a valid duration",
"rule": [Function],
},
],
}
}
value=""
/>
</div>
<div
className="gf-form"
>
<button
className="btn gf-form-btn btn-primary"
>
Add
</button>
</div>
</div>
</form>
</div>
</Component>
</PageContents>
</Page>
`;
| public/app/features/api-keys/__snapshots__/ApiKeysPage.test.tsx.snap | 1 | https://github.com/grafana/grafana/commit/5a06ed431cc3bd97759ed514589fbea4ba236777 | [
0.0022466250229626894,
0.0003056710120290518,
0.0001651318889344111,
0.00017514968931209296,
0.0004870544944424182
] |
{
"id": 0,
"code_window": [
"import { SlideDown } from 'app/core/components/Animations/SlideDown';\n",
"import ApiKeysAddedModal from './ApiKeysAddedModal';\n",
"import config from 'app/core/config';\n",
"import appEvents from 'app/core/app_events';\n",
"import EmptyListCTA from 'app/core/components/EmptyListCTA/EmptyListCTA';\n",
"import {\n",
" DeleteButton,\n",
" EventsWithValidation,\n",
" InlineFormLabel,\n",
" LegacyForms,\n",
" ValidationEvents,\n",
" IconButton,\n",
"} from '@grafana/ui';\n",
"const { Input, Switch } = LegacyForms;\n",
"import { NavModel, dateTimeFormat, rangeUtil } from '@grafana/data';\n",
"import { FilterInput } from 'app/core/components/FilterInput/FilterInput';\n",
"import { store } from 'app/store/store';\n",
"import { getTimeZone } from 'app/features/profile/state/selectors';\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { DeleteButton, EventsWithValidation, InlineFormLabel, LegacyForms, ValidationEvents, Icon } from '@grafana/ui';\n"
],
"file_path": "public/app/features/api-keys/ApiKeysPage.tsx",
"type": "replace",
"edit_start_line_idx": 15
} | package migrations
import (
"fmt"
. "github.com/grafana/grafana/pkg/services/sqlstore/migrator"
)
func addDropAllIndicesMigrations(mg *Migrator, versionSuffix string, table Table) {
for _, index := range table.Indices {
migrationId := fmt.Sprintf("drop index %s - %s", index.XName(table.Name), versionSuffix)
mg.AddMigration(migrationId, NewDropIndexMigration(table, index))
}
}
func addTableIndicesMigrations(mg *Migrator, versionSuffix string, table Table) {
for _, index := range table.Indices {
migrationId := fmt.Sprintf("create index %s - %s", index.XName(table.Name), versionSuffix)
mg.AddMigration(migrationId, NewAddIndexMigration(table, index))
}
}
func addTableRenameMigration(mg *Migrator, oldName string, newName string, versionSuffix string) {
migrationId := fmt.Sprintf("Rename table %s to %s - %s", oldName, newName, versionSuffix)
mg.AddMigration(migrationId, NewRenameTableMigration(oldName, newName))
}
func addTableReplaceMigrations(mg *Migrator, from Table, to Table, migrationVersion int64, tableDataMigration map[string]string) {
fromV := version(migrationVersion - 1)
toV := version(migrationVersion)
tmpTableName := to.Name + "_tmp_qwerty"
createTable := fmt.Sprintf("create %v %v", to.Name, toV)
copyTableData := fmt.Sprintf("copy %v %v to %v", to.Name, fromV, toV)
dropTable := fmt.Sprintf("drop %v", tmpTableName)
addDropAllIndicesMigrations(mg, fromV, from)
addTableRenameMigration(mg, from.Name, tmpTableName, fromV)
mg.AddMigration(createTable, NewAddTableMigration(to))
addTableIndicesMigrations(mg, toV, to)
mg.AddMigration(copyTableData, NewCopyTableDataMigration(to.Name, tmpTableName, tableDataMigration))
mg.AddMigration(dropTable, NewDropTableMigration(tmpTableName))
}
func version(v int64) string {
return fmt.Sprintf("v%v", v)
}
| pkg/services/sqlstore/migrations/common.go | 0 | https://github.com/grafana/grafana/commit/5a06ed431cc3bd97759ed514589fbea4ba236777 | [
0.00017612436204217374,
0.00017209994257427752,
0.00016313335800077766,
0.0001750652154441923,
0.000005003682872484205
] |
{
"id": 0,
"code_window": [
"import { SlideDown } from 'app/core/components/Animations/SlideDown';\n",
"import ApiKeysAddedModal from './ApiKeysAddedModal';\n",
"import config from 'app/core/config';\n",
"import appEvents from 'app/core/app_events';\n",
"import EmptyListCTA from 'app/core/components/EmptyListCTA/EmptyListCTA';\n",
"import {\n",
" DeleteButton,\n",
" EventsWithValidation,\n",
" InlineFormLabel,\n",
" LegacyForms,\n",
" ValidationEvents,\n",
" IconButton,\n",
"} from '@grafana/ui';\n",
"const { Input, Switch } = LegacyForms;\n",
"import { NavModel, dateTimeFormat, rangeUtil } from '@grafana/data';\n",
"import { FilterInput } from 'app/core/components/FilterInput/FilterInput';\n",
"import { store } from 'app/store/store';\n",
"import { getTimeZone } from 'app/features/profile/state/selectors';\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { DeleteButton, EventsWithValidation, InlineFormLabel, LegacyForms, ValidationEvents, Icon } from '@grafana/ui';\n"
],
"file_path": "public/app/features/api-keys/ApiKeysPage.tsx",
"type": "replace",
"edit_start_line_idx": 15
} | package influxdb
import (
"encoding/json"
"fmt"
"testing"
"github.com/grafana/grafana/pkg/setting"
. "github.com/smartystreets/goconvey/convey"
)
func TestInfluxdbResponseParser(t *testing.T) {
Convey("Influxdb response parser", t, func() {
Convey("Response parser", func() {
parser := &ResponseParser{}
cfg := setting.NewCfg()
err := cfg.Load(&setting.CommandLineArgs{
HomePath: "../../../",
})
So(err, ShouldBeNil)
response := &Response{
Results: []Result{
{
Series: []Row{
{
Name: "cpu",
Columns: []string{"time", "mean", "sum"},
Tags: map[string]string{"datacenter": "America"},
Values: [][]interface{}{
{json.Number("111"), json.Number("222"), json.Number("333")},
{json.Number("111"), json.Number("222"), json.Number("333")},
{json.Number("111"), json.Number("null"), json.Number("333")},
},
},
},
},
},
}
query := &Query{}
result := parser.Parse(response, query)
Convey("can parse all series", func() {
So(len(result.Series), ShouldEqual, 2)
})
Convey("can parse all points", func() {
So(len(result.Series[0].Points), ShouldEqual, 3)
So(len(result.Series[1].Points), ShouldEqual, 3)
})
Convey("can parse multi row result", func() {
So(result.Series[0].Points[1][0].Float64, ShouldEqual, float64(222))
So(result.Series[1].Points[1][0].Float64, ShouldEqual, float64(333))
})
Convey("can parse null points", func() {
So(result.Series[0].Points[2][0].Valid, ShouldBeFalse)
})
Convey("can format series names", func() {
So(result.Series[0].Name, ShouldEqual, "cpu.mean { datacenter: America }")
So(result.Series[1].Name, ShouldEqual, "cpu.sum { datacenter: America }")
})
})
Convey("Response parser with alias", func() {
parser := &ResponseParser{}
response := &Response{
Results: []Result{
{
Series: []Row{
{
Name: "cpu.upc",
Columns: []string{"time", "mean", "sum"},
Tags: map[string]string{
"datacenter": "America",
"dc.region.name": "Northeast",
},
Values: [][]interface{}{
{json.Number("111"), json.Number("222"), json.Number("333")},
},
},
},
},
},
}
Convey("$ alias", func() {
Convey("simple alias", func() {
query := &Query{Alias: "series alias"}
result := parser.Parse(response, query)
So(result.Series[0].Name, ShouldEqual, "series alias")
})
Convey("measurement alias", func() {
query := &Query{Alias: "alias $m $measurement", Measurement: "10m"}
result := parser.Parse(response, query)
So(result.Series[0].Name, ShouldEqual, "alias 10m 10m")
})
Convey("column alias", func() {
query := &Query{Alias: "alias $col", Measurement: "10m"}
result := parser.Parse(response, query)
So(result.Series[0].Name, ShouldEqual, "alias mean")
So(result.Series[1].Name, ShouldEqual, "alias sum")
})
Convey("tag alias", func() {
query := &Query{Alias: "alias $tag_datacenter"}
result := parser.Parse(response, query)
So(result.Series[0].Name, ShouldEqual, "alias America")
})
Convey("segment alias", func() {
query := &Query{Alias: "alias $1"}
result := parser.Parse(response, query)
So(result.Series[0].Name, ShouldEqual, "alias upc")
})
Convey("segment position out of bound", func() {
query := &Query{Alias: "alias $5"}
result := parser.Parse(response, query)
So(result.Series[0].Name, ShouldEqual, "alias $5")
})
})
Convey("[[]] alias", func() {
Convey("simple alias", func() {
query := &Query{Alias: "series alias"}
result := parser.Parse(response, query)
So(result.Series[0].Name, ShouldEqual, "series alias")
})
Convey("measurement alias", func() {
query := &Query{Alias: "alias [[m]] [[measurement]]", Measurement: "10m"}
result := parser.Parse(response, query)
So(result.Series[0].Name, ShouldEqual, "alias 10m 10m")
})
Convey("column alias", func() {
query := &Query{Alias: "alias [[col]]", Measurement: "10m"}
result := parser.Parse(response, query)
So(result.Series[0].Name, ShouldEqual, "alias mean")
So(result.Series[1].Name, ShouldEqual, "alias sum")
})
Convey("tag alias", func() {
query := &Query{Alias: "alias [[tag_datacenter]]"}
result := parser.Parse(response, query)
So(result.Series[0].Name, ShouldEqual, "alias America")
})
Convey("tag alias with periods", func() {
query := &Query{Alias: "alias [[tag_dc.region.name]]"}
result := parser.Parse(response, query)
So(result.Series[0].Name, ShouldEqual, "alias Northeast")
})
})
})
Convey("Response parser with errors", func() {
parser := &ResponseParser{}
cfg := setting.NewCfg()
err := cfg.Load(&setting.CommandLineArgs{
HomePath: "../../../",
})
So(err, ShouldBeNil)
response := &Response{
Results: []Result{
{
Series: []Row{
{
Name: "cpu",
Columns: []string{"time", "mean", "sum"},
Tags: map[string]string{"datacenter": "America"},
Values: [][]interface{}{
{json.Number("111"), json.Number("222"), json.Number("333")},
{json.Number("111"), json.Number("222"), json.Number("333")},
{json.Number("111"), json.Number("null"), json.Number("333")},
},
},
},
},
{
Err: fmt.Errorf("query-timeout limit exceeded"),
},
},
}
query := &Query{}
result := parser.Parse(response, query)
Convey("can parse all series", func() {
So(len(result.Series), ShouldEqual, 2)
})
Convey("can parse all points", func() {
So(len(result.Series[0].Points), ShouldEqual, 3)
So(len(result.Series[1].Points), ShouldEqual, 3)
})
Convey("can parse errors ", func() {
So(result.Error, ShouldNotBeNil)
So(result.Error.Error(), ShouldEqual, "query-timeout limit exceeded")
})
})
})
}
| pkg/tsdb/influxdb/response_parser_test.go | 0 | https://github.com/grafana/grafana/commit/5a06ed431cc3bd97759ed514589fbea4ba236777 | [
0.00017900680541060865,
0.00017487518198322505,
0.00016510227578692138,
0.00017610707436688244,
0.0000032354832910641562
] |
{
"id": 0,
"code_window": [
"import { SlideDown } from 'app/core/components/Animations/SlideDown';\n",
"import ApiKeysAddedModal from './ApiKeysAddedModal';\n",
"import config from 'app/core/config';\n",
"import appEvents from 'app/core/app_events';\n",
"import EmptyListCTA from 'app/core/components/EmptyListCTA/EmptyListCTA';\n",
"import {\n",
" DeleteButton,\n",
" EventsWithValidation,\n",
" InlineFormLabel,\n",
" LegacyForms,\n",
" ValidationEvents,\n",
" IconButton,\n",
"} from '@grafana/ui';\n",
"const { Input, Switch } = LegacyForms;\n",
"import { NavModel, dateTimeFormat, rangeUtil } from '@grafana/data';\n",
"import { FilterInput } from 'app/core/components/FilterInput/FilterInput';\n",
"import { store } from 'app/store/store';\n",
"import { getTimeZone } from 'app/features/profile/state/selectors';\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { DeleteButton, EventsWithValidation, InlineFormLabel, LegacyForms, ValidationEvents, Icon } from '@grafana/ui';\n"
],
"file_path": "public/app/features/api-keys/ApiKeysPage.tsx",
"type": "replace",
"edit_start_line_idx": 15
} | package dtos
type SignUpForm struct {
Email string `json:"email" binding:"Required"`
}
type SignUpStep2Form struct {
Email string `json:"email"`
Name string `json:"name"`
Username string `json:"username"`
Password string `json:"password"`
Code string `json:"code"`
OrgName string `json:"orgName"`
}
type AdminCreateUserForm struct {
Email string `json:"email"`
Login string `json:"login"`
Name string `json:"name"`
Password string `json:"password" binding:"Required"`
OrgId int64 `json:"orgId"`
}
type AdminUpdateUserForm struct {
Email string `json:"email"`
Login string `json:"login"`
Name string `json:"name"`
}
type AdminUpdateUserPasswordForm struct {
Password string `json:"password" binding:"Required"`
}
type AdminUpdateUserPermissionsForm struct {
IsGrafanaAdmin bool `json:"isGrafanaAdmin"`
}
type AdminUserListItem struct {
Email string `json:"email"`
Name string `json:"name"`
Login string `json:"login"`
IsGrafanaAdmin bool `json:"isGrafanaAdmin"`
}
type SendResetPasswordEmailForm struct {
UserOrEmail string `json:"userOrEmail" binding:"Required"`
}
type ResetUserPasswordForm struct {
Code string `json:"code"`
NewPassword string `json:"newPassword"`
ConfirmPassword string `json:"confirmPassword"`
}
type UserLookupDTO struct {
UserID int64 `json:"userId"`
Login string `json:"login"`
AvatarURL string `json:"avatarUrl"`
}
| pkg/api/dtos/user.go | 0 | https://github.com/grafana/grafana/commit/5a06ed431cc3bd97759ed514589fbea4ba236777 | [
0.00017625809414312243,
0.00016875778965186328,
0.00016468939429614693,
0.00016625990974716842,
0.000004495895154832397
] |
{
"id": 1,
"code_window": [
" renderAddApiKeyForm() {\n",
" const { newApiKey, isAdding } = this.state;\n",
"\n",
" return (\n",
" <SlideDown in={isAdding}>\n",
" <div className=\"cta-form\">\n",
" <IconButton name=\"times\" className=\"cta-form__close btn btn-transparent\" onClick={this.onToggleAdding} />\n",
" <h5>Add API Key</h5>\n",
" <form className=\"gf-form-group\" onSubmit={this.onAddApiKey}>\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
" <div className=\"gf-form-inline cta-form\">\n",
" <button className=\"cta-form__close btn btn-transparent\" onClick={this.onToggleAdding}>\n",
" <Icon name=\"times\" />\n",
" </button>\n"
],
"file_path": "public/app/features/api-keys/ApiKeysPage.tsx",
"type": "replace",
"edit_start_line_idx": 184
} | // Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`Render should render API keys table if there are any keys 1`] = `
<Page
navModel={
Object {
"main": Object {
"text": "Configuration",
},
"node": Object {
"text": "Api Keys",
},
}
}
>
<PageContents
isLoading={true}
/>
</Page>
`;
exports[`Render should render CTA if there are no API keys 1`] = `
<Page
navModel={
Object {
"main": Object {
"text": "Configuration",
},
"node": Object {
"text": "Api Keys",
},
}
}
>
<PageContents
isLoading={false}
>
<EmptyListCTA
buttonIcon="key-skeleton-alt"
buttonLink="#"
buttonTitle=" New API Key"
onClick={[Function]}
proTip="Remember you can provide view-only API access to other applications."
title="You haven't added any API Keys yet."
/>
<Component
in={false}
>
<div
className="cta-form"
>
<IconButton
className="cta-form__close btn btn-transparent"
name="times"
onClick={[Function]}
/>
<h5>
Add API Key
</h5>
<form
className="gf-form-group"
onSubmit={[Function]}
>
<div
className="gf-form-inline"
>
<div
className="gf-form max-width-21"
>
<span
className="gf-form-label"
>
Key name
</span>
<Input
className="gf-form-input"
onChange={[Function]}
placeholder="Name"
type="text"
value=""
/>
</div>
<div
className="gf-form"
>
<span
className="gf-form-label"
>
Role
</span>
<span
className="gf-form-select-wrapper"
>
<select
className="gf-form-input gf-size-auto"
onChange={[Function]}
value="Viewer"
>
<option
key="Viewer"
label="Viewer"
value="Viewer"
>
Viewer
</option>
<option
key="Editor"
label="Editor"
value="Editor"
>
Editor
</option>
<option
key="Admin"
label="Admin"
value="Admin"
>
Admin
</option>
</select>
</span>
</div>
<div
className="gf-form max-width-21"
>
<Component
tooltip="The api key life duration. For example 1d if your key is going to last for one day. All the supported units are: s,m,h,d,w,M,y"
>
Time to live
</Component>
<Input
className="gf-form-input"
onChange={[Function]}
placeholder="1d"
type="text"
validationEvents={
Object {
"onBlur": Array [
Object {
"errorMessage": "Not a valid duration",
"rule": [Function],
},
],
}
}
value=""
/>
</div>
<div
className="gf-form"
>
<button
className="btn gf-form-btn btn-primary"
>
Add
</button>
</div>
</div>
</form>
</div>
</Component>
</PageContents>
</Page>
`;
| public/app/features/api-keys/__snapshots__/ApiKeysPage.test.tsx.snap | 1 | https://github.com/grafana/grafana/commit/5a06ed431cc3bd97759ed514589fbea4ba236777 | [
0.03003581054508686,
0.0025275866501033306,
0.00016427910304628313,
0.00016955197497736663,
0.00727073522284627
] |
{
"id": 1,
"code_window": [
" renderAddApiKeyForm() {\n",
" const { newApiKey, isAdding } = this.state;\n",
"\n",
" return (\n",
" <SlideDown in={isAdding}>\n",
" <div className=\"cta-form\">\n",
" <IconButton name=\"times\" className=\"cta-form__close btn btn-transparent\" onClick={this.onToggleAdding} />\n",
" <h5>Add API Key</h5>\n",
" <form className=\"gf-form-group\" onSubmit={this.onAddApiKey}>\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
" <div className=\"gf-form-inline cta-form\">\n",
" <button className=\"cta-form__close btn btn-transparent\" onClick={this.onToggleAdding}>\n",
" <Icon name=\"times\" />\n",
" </button>\n"
],
"file_path": "public/app/features/api-keys/ApiKeysPage.tsx",
"type": "replace",
"edit_start_line_idx": 184
} | import React from 'react';
import { css, cx } from 'emotion';
import { SeriesColorPicker } from '../ColorPicker/ColorPicker';
import { SeriesIcon, SeriesIconProps } from './SeriesIcon';
interface LegendSeriesIconProps {
disabled: boolean;
color: string;
yAxis: number;
onColorChange: (color: string) => void;
onToggleAxis?: () => void;
}
export const LegendSeriesIcon: React.FunctionComponent<LegendSeriesIconProps> = ({
disabled,
yAxis,
color,
onColorChange,
onToggleAxis,
}) => {
let iconProps: SeriesIconProps = {
color,
};
if (!disabled) {
iconProps = {
...iconProps,
className: 'pointer',
};
}
return disabled ? (
<span
className={cx(
'graph-legend-icon',
disabled &&
css`
cursor: default;
`
)}
>
<SeriesIcon {...iconProps} />
</span>
) : (
<SeriesColorPicker
yaxis={yAxis}
color={color}
onChange={onColorChange}
onToggleAxis={onToggleAxis}
enableNamedColors
>
{({ ref, showColorPicker, hideColorPicker }) => (
<span ref={ref} onClick={showColorPicker} onMouseLeave={hideColorPicker} className="graph-legend-icon">
<SeriesIcon {...iconProps} />
</span>
)}
</SeriesColorPicker>
);
};
LegendSeriesIcon.displayName = 'LegendSeriesIcon';
| packages/grafana-ui/src/components/Legend/LegendSeriesIcon.tsx | 0 | https://github.com/grafana/grafana/commit/5a06ed431cc3bd97759ed514589fbea4ba236777 | [
0.00048204773338511586,
0.0002138991840183735,
0.00016595108900219202,
0.00016961473738774657,
0.00010949573334073648
] |
{
"id": 1,
"code_window": [
" renderAddApiKeyForm() {\n",
" const { newApiKey, isAdding } = this.state;\n",
"\n",
" return (\n",
" <SlideDown in={isAdding}>\n",
" <div className=\"cta-form\">\n",
" <IconButton name=\"times\" className=\"cta-form__close btn btn-transparent\" onClick={this.onToggleAdding} />\n",
" <h5>Add API Key</h5>\n",
" <form className=\"gf-form-group\" onSubmit={this.onAddApiKey}>\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
" <div className=\"gf-form-inline cta-form\">\n",
" <button className=\"cta-form__close btn btn-transparent\" onClick={this.onToggleAdding}>\n",
" <Icon name=\"times\" />\n",
" </button>\n"
],
"file_path": "public/app/features/api-keys/ApiKeysPage.tsx",
"type": "replace",
"edit_start_line_idx": 184
} | package dashboards
import (
"testing"
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/guardian"
. "github.com/smartystreets/goconvey/convey"
)
func TestFolderService(t *testing.T) {
Convey("Folder service tests", t, func() {
service := dashboardServiceImpl{
orgId: 1,
user: &models.SignedInUser{UserId: 1},
}
Convey("Given user has no permissions", func() {
origNewGuardian := guardian.New
guardian.MockDashboardGuardian(&guardian.FakeDashboardGuardian{})
bus.AddHandler("test", func(query *models.GetDashboardQuery) error {
query.Result = models.NewDashboardFolder("Folder")
return nil
})
bus.AddHandler("test", func(cmd *models.ValidateDashboardAlertsCommand) error {
return nil
})
bus.AddHandler("test", func(cmd *models.ValidateDashboardBeforeSaveCommand) error {
cmd.Result = &models.ValidateDashboardBeforeSaveResult{}
return models.ErrDashboardUpdateAccessDenied
})
Convey("When get folder by id should return access denied error", func() {
_, err := service.GetFolderByID(1)
So(err, ShouldNotBeNil)
So(err, ShouldEqual, models.ErrFolderAccessDenied)
})
Convey("When get folder by uid should return access denied error", func() {
_, err := service.GetFolderByUID("uid")
So(err, ShouldNotBeNil)
So(err, ShouldEqual, models.ErrFolderAccessDenied)
})
Convey("When creating folder should return access denied error", func() {
err := service.CreateFolder(&models.CreateFolderCommand{
Title: "Folder",
})
So(err, ShouldNotBeNil)
So(err, ShouldEqual, models.ErrFolderAccessDenied)
})
Convey("When updating folder should return access denied error", func() {
err := service.UpdateFolder("uid", &models.UpdateFolderCommand{
Uid: "uid",
Title: "Folder",
})
So(err, ShouldNotBeNil)
So(err, ShouldEqual, models.ErrFolderAccessDenied)
})
Convey("When deleting folder by uid should return access denied error", func() {
_, err := service.DeleteFolder("uid")
So(err, ShouldNotBeNil)
So(err, ShouldEqual, models.ErrFolderAccessDenied)
})
Reset(func() {
guardian.New = origNewGuardian
})
})
Convey("Given user has permission to save", func() {
origNewGuardian := guardian.New
guardian.MockDashboardGuardian(&guardian.FakeDashboardGuardian{CanSaveValue: true})
dash := models.NewDashboardFolder("Folder")
dash.Id = 1
bus.AddHandler("test", func(query *models.GetDashboardQuery) error {
query.Result = dash
return nil
})
bus.AddHandler("test", func(cmd *models.ValidateDashboardAlertsCommand) error {
return nil
})
bus.AddHandler("test", func(cmd *models.ValidateDashboardBeforeSaveCommand) error {
cmd.Result = &models.ValidateDashboardBeforeSaveResult{}
return nil
})
bus.AddHandler("test", func(cmd *models.UpdateDashboardAlertsCommand) error {
return nil
})
bus.AddHandler("test", func(cmd *models.SaveDashboardCommand) error {
cmd.Result = dash
return nil
})
bus.AddHandler("test", func(cmd *models.DeleteDashboardCommand) error {
return nil
})
provisioningValidated := false
bus.AddHandler("test", func(query *models.GetProvisionedDashboardDataByIdQuery) error {
provisioningValidated = true
query.Result = nil
return nil
})
Convey("When creating folder should not return access denied error", func() {
err := service.CreateFolder(&models.CreateFolderCommand{
Title: "Folder",
})
So(err, ShouldBeNil)
So(provisioningValidated, ShouldBeFalse)
})
Convey("When updating folder should not return access denied error", func() {
err := service.UpdateFolder("uid", &models.UpdateFolderCommand{
Uid: "uid",
Title: "Folder",
})
So(err, ShouldBeNil)
So(provisioningValidated, ShouldBeFalse)
})
Convey("When deleting folder by uid should not return access denied error", func() {
_, err := service.DeleteFolder("uid")
So(err, ShouldBeNil)
})
Reset(func() {
guardian.New = origNewGuardian
})
})
Convey("Given user has permission to view", func() {
origNewGuardian := guardian.New
guardian.MockDashboardGuardian(&guardian.FakeDashboardGuardian{CanViewValue: true})
dashFolder := models.NewDashboardFolder("Folder")
dashFolder.Id = 1
dashFolder.Uid = "uid-abc"
bus.AddHandler("test", func(query *models.GetDashboardQuery) error {
query.Result = dashFolder
return nil
})
Convey("When get folder by id should return folder", func() {
f, _ := service.GetFolderByID(1)
So(f.Id, ShouldEqual, dashFolder.Id)
So(f.Uid, ShouldEqual, dashFolder.Uid)
So(f.Title, ShouldEqual, dashFolder.Title)
})
Convey("When get folder by uid should return folder", func() {
f, _ := service.GetFolderByUID("uid")
So(f.Id, ShouldEqual, dashFolder.Id)
So(f.Uid, ShouldEqual, dashFolder.Uid)
So(f.Title, ShouldEqual, dashFolder.Title)
})
Reset(func() {
guardian.New = origNewGuardian
})
})
Convey("Should map errors correct", func() {
testCases := []struct {
ActualError error
ExpectedError error
}{
{ActualError: models.ErrDashboardTitleEmpty, ExpectedError: models.ErrFolderTitleEmpty},
{ActualError: models.ErrDashboardUpdateAccessDenied, ExpectedError: models.ErrFolderAccessDenied},
{ActualError: models.ErrDashboardWithSameNameInFolderExists, ExpectedError: models.ErrFolderSameNameExists},
{ActualError: models.ErrDashboardWithSameUIDExists, ExpectedError: models.ErrFolderWithSameUIDExists},
{ActualError: models.ErrDashboardVersionMismatch, ExpectedError: models.ErrFolderVersionMismatch},
{ActualError: models.ErrDashboardNotFound, ExpectedError: models.ErrFolderNotFound},
{ActualError: models.ErrDashboardFailedGenerateUniqueUid, ExpectedError: models.ErrFolderFailedGenerateUniqueUid},
{ActualError: models.ErrDashboardInvalidUid, ExpectedError: models.ErrDashboardInvalidUid},
}
for _, tc := range testCases {
actualError := toFolderError(tc.ActualError)
if actualError != tc.ExpectedError {
t.Errorf("For error '%s' expected error '%s', actual '%s'", tc.ActualError, tc.ExpectedError, actualError)
}
}
})
})
}
| pkg/services/dashboards/folder_service_test.go | 0 | https://github.com/grafana/grafana/commit/5a06ed431cc3bd97759ed514589fbea4ba236777 | [
0.00017633070820011199,
0.00017228424258064479,
0.00016271050844807178,
0.00017270093667320907,
0.000002690986775633064
] |
{
"id": 1,
"code_window": [
" renderAddApiKeyForm() {\n",
" const { newApiKey, isAdding } = this.state;\n",
"\n",
" return (\n",
" <SlideDown in={isAdding}>\n",
" <div className=\"cta-form\">\n",
" <IconButton name=\"times\" className=\"cta-form__close btn btn-transparent\" onClick={this.onToggleAdding} />\n",
" <h5>Add API Key</h5>\n",
" <form className=\"gf-form-group\" onSubmit={this.onAddApiKey}>\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
" <div className=\"gf-form-inline cta-form\">\n",
" <button className=\"cta-form__close btn btn-transparent\" onClick={this.onToggleAdding}>\n",
" <Icon name=\"times\" />\n",
" </button>\n"
],
"file_path": "public/app/features/api-keys/ApiKeysPage.tsx",
"type": "replace",
"edit_start_line_idx": 184
} | import React, { useState, useRef, ReactElement } from 'react';
interface LabelProps {
Component: ReactElement;
onClick?: () => void;
}
export const useExpandableLabel = (
initialExpanded: boolean
): [React.ComponentType<LabelProps>, number, boolean, (expanded: boolean) => void] => {
const ref = useRef<HTMLDivElement>(null);
const [expanded, setExpanded] = useState<boolean>(initialExpanded);
const [width, setWidth] = useState(0);
const Label: React.FC<LabelProps> = ({ Component, onClick }) => (
<div
className="gf-form"
ref={ref}
onClick={() => {
setExpanded(true);
if (ref && ref.current) {
setWidth(ref.current.clientWidth * 1.25);
}
if (onClick) {
onClick();
}
}}
>
{Component}
</div>
);
return [Label, width, expanded, setExpanded];
};
| packages/grafana-ui/src/components/Segment/useExpandableLabel.tsx | 0 | https://github.com/grafana/grafana/commit/5a06ed431cc3bd97759ed514589fbea4ba236777 | [
0.0001826765510486439,
0.00017291396216023713,
0.00016805109044071287,
0.0001704641035757959,
0.000005884828624402871
] |
{
"id": 2,
"code_window": [
" <form className=\"gf-form-group\" onSubmit={this.onAddApiKey}>\n",
" <div className=\"gf-form-inline\">\n",
" <div className=\"gf-form max-width-21\">\n",
" <span className=\"gf-form-label\">Key name</span>\n",
" <Input\n"
],
"labels": [
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <h5>Add API Key</h5>\n"
],
"file_path": "public/app/features/api-keys/ApiKeysPage.tsx",
"type": "add",
"edit_start_line_idx": 188
} | // Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`Render should render API keys table if there are any keys 1`] = `
<Page
navModel={
Object {
"main": Object {
"text": "Configuration",
},
"node": Object {
"text": "Api Keys",
},
}
}
>
<PageContents
isLoading={true}
/>
</Page>
`;
exports[`Render should render CTA if there are no API keys 1`] = `
<Page
navModel={
Object {
"main": Object {
"text": "Configuration",
},
"node": Object {
"text": "Api Keys",
},
}
}
>
<PageContents
isLoading={false}
>
<EmptyListCTA
buttonIcon="key-skeleton-alt"
buttonLink="#"
buttonTitle=" New API Key"
onClick={[Function]}
proTip="Remember you can provide view-only API access to other applications."
title="You haven't added any API Keys yet."
/>
<Component
in={false}
>
<div
className="cta-form"
>
<IconButton
className="cta-form__close btn btn-transparent"
name="times"
onClick={[Function]}
/>
<h5>
Add API Key
</h5>
<form
className="gf-form-group"
onSubmit={[Function]}
>
<div
className="gf-form-inline"
>
<div
className="gf-form max-width-21"
>
<span
className="gf-form-label"
>
Key name
</span>
<Input
className="gf-form-input"
onChange={[Function]}
placeholder="Name"
type="text"
value=""
/>
</div>
<div
className="gf-form"
>
<span
className="gf-form-label"
>
Role
</span>
<span
className="gf-form-select-wrapper"
>
<select
className="gf-form-input gf-size-auto"
onChange={[Function]}
value="Viewer"
>
<option
key="Viewer"
label="Viewer"
value="Viewer"
>
Viewer
</option>
<option
key="Editor"
label="Editor"
value="Editor"
>
Editor
</option>
<option
key="Admin"
label="Admin"
value="Admin"
>
Admin
</option>
</select>
</span>
</div>
<div
className="gf-form max-width-21"
>
<Component
tooltip="The api key life duration. For example 1d if your key is going to last for one day. All the supported units are: s,m,h,d,w,M,y"
>
Time to live
</Component>
<Input
className="gf-form-input"
onChange={[Function]}
placeholder="1d"
type="text"
validationEvents={
Object {
"onBlur": Array [
Object {
"errorMessage": "Not a valid duration",
"rule": [Function],
},
],
}
}
value=""
/>
</div>
<div
className="gf-form"
>
<button
className="btn gf-form-btn btn-primary"
>
Add
</button>
</div>
</div>
</form>
</div>
</Component>
</PageContents>
</Page>
`;
| public/app/features/api-keys/__snapshots__/ApiKeysPage.test.tsx.snap | 1 | https://github.com/grafana/grafana/commit/5a06ed431cc3bd97759ed514589fbea4ba236777 | [
0.13421125710010529,
0.009416048415005207,
0.00016353641694877297,
0.00019734282977879047,
0.03136073797941208
] |
{
"id": 2,
"code_window": [
" <form className=\"gf-form-group\" onSubmit={this.onAddApiKey}>\n",
" <div className=\"gf-form-inline\">\n",
" <div className=\"gf-form max-width-21\">\n",
" <span className=\"gf-form-label\">Key name</span>\n",
" <Input\n"
],
"labels": [
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <h5>Add API Key</h5>\n"
],
"file_path": "public/app/features/api-keys/ApiKeysPage.tsx",
"type": "add",
"edit_start_line_idx": 188
} | <?xml version="1.0" encoding="iso-8859-1"?>
<!-- Generator: Adobe Illustrator 19.1.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
width="100px" height="100px" viewBox="0 0 100 100" style="enable-background:new 0 0 100 100;" xml:space="preserve">
<g>
<g>
<path style="fill:#666666;" d="M8.842,11.219h0.1c1.228,0,2.227-0.999,2.227-2.227v-0.1L8.842,11.219z"/>
<path style="fill:#666666;" d="M0.008,2.113l2.054-2.054C0.966,0.139,0.089,1.016,0.008,2.113z"/>
<polygon style="fill:#666666;" points="0,2.998 0,5.533 5.484,0.05 2.948,0.05 "/>
<polygon style="fill:#666666;" points="6.361,0.05 0,6.411 0,8.946 8.896,0.05 "/>
<path style="fill:#666666;" d="M11.169,2.277c0-0.068-0.004-0.134-0.01-0.2l-9.132,9.132c0.066,0.006,0.133,0.01,0.2,0.01h2.325
l6.617-6.617V2.277z"/>
<path style="fill:#666666;" d="M9.654,0.169L0.119,9.704c0.201,0.592,0.643,1.073,1.211,1.324l9.649-9.649
C10.728,0.812,10.247,0.37,9.654,0.169z"/>
<polygon style="fill:#666666;" points="11.169,5.479 5.429,11.219 7.964,11.219 11.169,8.014 "/>
</g>
<path style="fill:#898989;" d="M88.146,11.031H14.866c-1.011,0-1.83-0.82-1.83-1.83v-7.37c0-1.011,0.82-1.831,1.83-1.831h73.281
c1.011,0,1.83,0.82,1.83,1.831v7.37C89.977,10.212,89.157,11.031,88.146,11.031z"/>
<g>
<path style="fill:#666666;" d="M8.842,23.902h0.1c1.228,0,2.227-0.999,2.227-2.227v-0.1L8.842,23.902z"/>
<path style="fill:#666666;" d="M0.008,14.796l2.054-2.054C0.966,12.822,0.089,13.699,0.008,14.796z"/>
<polygon style="fill:#666666;" points="0,15.681 0,18.216 5.484,12.733 2.948,12.733 "/>
<polygon style="fill:#666666;" points="6.361,12.733 0,19.094 0,21.629 8.896,12.733 "/>
<path style="fill:#666666;" d="M11.169,14.96c0-0.068-0.004-0.134-0.01-0.2l-9.132,9.132c0.066,0.006,0.133,0.01,0.2,0.01h2.325
l6.617-6.617V14.96z"/>
<path style="fill:#666666;" d="M9.654,12.852l-9.536,9.536c0.201,0.592,0.643,1.073,1.211,1.324l9.649-9.649
C10.728,13.495,10.247,13.053,9.654,12.852z"/>
<polygon style="fill:#666666;" points="11.169,18.162 5.429,23.902 7.964,23.902 11.169,20.697 "/>
</g>
<path style="fill:#898989;" d="M88.146,23.714H14.866c-1.011,0-1.83-0.82-1.83-1.83v-7.37c0-1.011,0.82-1.83,1.83-1.83h73.281
c1.011,0,1.83,0.82,1.83,1.83v7.37C89.977,22.895,89.157,23.714,88.146,23.714z"/>
<g>
<path style="fill:#666666;" d="M8.842,36.585h0.1c1.228,0,2.227-0.999,2.227-2.227v-0.1L8.842,36.585z"/>
<path style="fill:#666666;" d="M0.008,27.479l2.054-2.054C0.966,25.505,0.089,26.382,0.008,27.479z"/>
<polygon style="fill:#666666;" points="0,28.364 0,30.899 5.484,25.416 2.948,25.416 "/>
<polygon style="fill:#666666;" points="6.361,25.416 0,31.777 0,34.312 8.896,25.416 "/>
<path style="fill:#666666;" d="M11.169,27.643c0-0.068-0.004-0.134-0.01-0.2l-9.132,9.132c0.066,0.006,0.133,0.01,0.2,0.01h2.325
l6.617-6.617V27.643z"/>
<path style="fill:#666666;" d="M9.654,25.535L0.119,35.07c0.201,0.592,0.643,1.073,1.211,1.324l9.649-9.649
C10.728,26.178,10.247,25.736,9.654,25.535z"/>
<polygon style="fill:#666666;" points="11.169,30.845 5.429,36.585 7.964,36.585 11.169,33.38 "/>
</g>
<path style="fill:#898989;" d="M88.146,36.397H14.866c-1.011,0-1.83-0.82-1.83-1.831v-7.37c0-1.011,0.82-1.83,1.83-1.83h73.281
c1.011,0,1.83,0.82,1.83,1.83v7.37C89.977,35.578,89.157,36.397,88.146,36.397z"/>
<g>
<path style="fill:#666666;" d="M8.842,49.268h0.1c1.228,0,2.227-0.999,2.227-2.227v-0.1L8.842,49.268z"/>
<path style="fill:#666666;" d="M0.008,40.162l2.054-2.054C0.966,38.188,0.089,39.065,0.008,40.162z"/>
<polygon style="fill:#666666;" points="0,41.047 0,43.582 5.484,38.099 2.948,38.099 "/>
<polygon style="fill:#666666;" points="6.361,38.099 0,44.46 0,46.995 8.896,38.099 "/>
<path style="fill:#666666;" d="M11.169,40.326c0-0.068-0.004-0.134-0.01-0.2l-9.132,9.132c0.066,0.006,0.133,0.01,0.2,0.01h2.325
l6.617-6.617V40.326z"/>
<path style="fill:#666666;" d="M9.654,38.218l-9.536,9.536c0.201,0.592,0.643,1.073,1.211,1.324l9.649-9.649
C10.728,38.861,10.247,38.419,9.654,38.218z"/>
<polygon style="fill:#666666;" points="11.169,43.528 5.429,49.268 7.964,49.268 11.169,46.063 "/>
</g>
<path style="fill:#898989;" d="M88.146,49.08H14.866c-1.011,0-1.83-0.82-1.83-1.831v-7.37c0-1.011,0.82-1.831,1.83-1.831h73.281
c1.011,0,1.83,0.82,1.83,1.831v7.37C89.977,48.261,89.157,49.08,88.146,49.08z"/>
<g>
<path style="fill:#666666;" d="M8.842,61.951h0.1c1.228,0,2.227-0.999,2.227-2.227v-0.1L8.842,61.951z"/>
<path style="fill:#666666;" d="M0.008,52.845l2.054-2.054C0.966,50.871,0.089,51.748,0.008,52.845z"/>
<polygon style="fill:#666666;" points="0,53.73 0,56.265 5.484,50.782 2.948,50.782 "/>
<polygon style="fill:#666666;" points="6.361,50.782 0,57.143 0,59.678 8.896,50.782 "/>
<path style="fill:#666666;" d="M11.169,53.009c0-0.068-0.004-0.134-0.01-0.2l-9.132,9.132c0.066,0.006,0.133,0.01,0.2,0.01h2.325
l6.617-6.617V53.009z"/>
<path style="fill:#666666;" d="M9.654,50.901l-9.536,9.536c0.201,0.592,0.643,1.073,1.211,1.324l9.649-9.649
C10.728,51.544,10.247,51.102,9.654,50.901z"/>
<polygon style="fill:#666666;" points="11.169,56.211 5.429,61.951 7.964,61.951 11.169,58.746 "/>
</g>
<path style="fill:#898989;" d="M88.146,61.763H14.866c-1.011,0-1.83-0.82-1.83-1.83v-7.37c0-1.011,0.82-1.831,1.83-1.831h73.281
c1.011,0,1.83,0.82,1.83,1.831v7.37C89.977,60.944,89.157,61.763,88.146,61.763z"/>
<g>
<path style="fill:#666666;" d="M8.842,74.634h0.1c1.228,0,2.227-0.999,2.227-2.227v-0.1L8.842,74.634z"/>
<path style="fill:#666666;" d="M0.008,65.528l2.054-2.054C0.966,63.554,0.089,64.431,0.008,65.528z"/>
<polygon style="fill:#666666;" points="0,66.413 0,68.948 5.484,63.465 2.948,63.465 "/>
<polygon style="fill:#666666;" points="6.361,63.465 0,69.826 0,72.361 8.896,63.465 "/>
<path style="fill:#666666;" d="M11.169,65.692c0-0.068-0.004-0.134-0.01-0.2l-9.132,9.132c0.066,0.006,0.133,0.01,0.2,0.01h2.325
l6.617-6.617V65.692z"/>
<path style="fill:#666666;" d="M9.654,63.584l-9.536,9.536c0.201,0.592,0.643,1.073,1.211,1.324l9.649-9.649
C10.728,64.227,10.247,63.785,9.654,63.584z"/>
<polygon style="fill:#666666;" points="11.169,68.894 5.429,74.634 7.964,74.634 11.169,71.429 "/>
</g>
<path style="fill:#898989;" d="M88.146,74.446H14.866c-1.011,0-1.83-0.82-1.83-1.83v-7.37c0-1.011,0.82-1.831,1.83-1.831h73.281
c1.011,0,1.83,0.82,1.83,1.831v7.37C89.977,73.627,89.157,74.446,88.146,74.446z"/>
<g>
<path style="fill:#666666;" d="M8.842,87.317h0.1c1.228,0,2.227-0.999,2.227-2.227v-0.1L8.842,87.317z"/>
<path style="fill:#666666;" d="M0.008,78.211l2.054-2.054C0.966,76.237,0.089,77.114,0.008,78.211z"/>
<polygon style="fill:#666666;" points="0,79.096 0,81.631 5.484,76.148 2.948,76.148 "/>
<polygon style="fill:#666666;" points="6.361,76.148 0,82.509 0,85.044 8.896,76.148 "/>
<path style="fill:#666666;" d="M11.169,78.375c0-0.068-0.004-0.134-0.01-0.2l-9.132,9.132c0.066,0.006,0.133,0.01,0.2,0.01h2.325
l6.617-6.617V78.375z"/>
<path style="fill:#666666;" d="M9.654,76.267l-9.536,9.536c0.201,0.592,0.643,1.073,1.211,1.324l9.649-9.649
C10.728,76.91,10.247,76.468,9.654,76.267z"/>
<polygon style="fill:#666666;" points="11.169,81.577 5.429,87.317 7.964,87.317 11.169,84.112 "/>
</g>
<path style="fill:#898989;" d="M88.146,87.129H14.866c-1.011,0-1.83-0.82-1.83-1.83v-7.37c0-1.011,0.82-1.831,1.83-1.831h73.281
c1.011,0,1.83,0.82,1.83,1.831v7.37C89.977,86.31,89.157,87.129,88.146,87.129z"/>
<g>
<path style="fill:#666666;" d="M8.842,100h0.1c1.228,0,2.227-0.999,2.227-2.227v-0.1L8.842,100z"/>
<path style="fill:#666666;" d="M0.008,90.894l2.054-2.054C0.966,88.92,0.089,89.797,0.008,90.894z"/>
<polygon style="fill:#666666;" points="0,91.779 0,94.314 5.484,88.831 2.948,88.831 "/>
<polygon style="fill:#666666;" points="6.361,88.831 0,95.192 0,97.727 8.896,88.831 "/>
<path style="fill:#666666;" d="M11.169,91.058c0-0.068-0.004-0.134-0.01-0.2L2.027,99.99c0.066,0.006,0.133,0.01,0.2,0.01h2.325
l6.617-6.617V91.058z"/>
<path style="fill:#666666;" d="M9.654,88.95l-9.536,9.536c0.201,0.592,0.643,1.073,1.211,1.324l9.649-9.649
C10.728,89.593,10.247,89.151,9.654,88.95z"/>
<polygon style="fill:#666666;" points="11.169,94.26 5.429,100 7.964,100 11.169,96.795 "/>
</g>
<path style="fill:#898989;" d="M88.146,99.812H14.866c-1.011,0-1.83-0.82-1.83-1.83v-7.37c0-1.011,0.82-1.83,1.83-1.83h73.281
c1.011,0,1.83,0.82,1.83,1.83v7.37C89.977,98.993,89.157,99.812,88.146,99.812z"/>
<circle style="fill:#F7941E;" cx="96.125" cy="5.637" r="3.875"/>
<circle style="fill:#898989;" cx="96.125" cy="18.37" r="3.875"/>
<circle style="fill:#898989;" cx="96.125" cy="31.104" r="3.875"/>
<circle style="fill:#F7941E;" cx="96.125" cy="43.837" r="3.875"/>
<circle style="fill:#F7941E;" cx="96.125" cy="56.57" r="3.875"/>
<circle style="fill:#898989;" cx="96.125" cy="69.304" r="3.875"/>
<circle style="fill:#F7941E;" cx="96.125" cy="82.037" r="3.875"/>
<circle style="fill:#898989;" cx="96.125" cy="94.77" r="3.875"/>
</g>
</svg>
| public/app/plugins/panel/gettingstarted/img/icn-dashlist-panel.svg | 0 | https://github.com/grafana/grafana/commit/5a06ed431cc3bd97759ed514589fbea4ba236777 | [
0.00021315747289918363,
0.00017409845895599574,
0.0001639570400584489,
0.000166426514624618,
0.000014664490663562901
] |
{
"id": 2,
"code_window": [
" <form className=\"gf-form-group\" onSubmit={this.onAddApiKey}>\n",
" <div className=\"gf-form-inline\">\n",
" <div className=\"gf-form max-width-21\">\n",
" <span className=\"gf-form-label\">Key name</span>\n",
" <Input\n"
],
"labels": [
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <h5>Add API Key</h5>\n"
],
"file_path": "public/app/features/api-keys/ApiKeysPage.tsx",
"type": "add",
"edit_start_line_idx": 188
} | import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import sourceMaps from 'rollup-plugin-sourcemaps';
import { terser } from 'rollup-plugin-terser';
const pkg = require('./package.json');
const libraryName = pkg.name;
const buildCjsPackage = ({ env }) => {
return {
input: `compiled/index.js`,
output: [
{
file: `dist/index.${env}.js`,
name: libraryName,
format: 'cjs',
sourcemap: true,
exports: 'named',
globals: {},
},
],
external: ['lodash', '@grafana/ui', '@grafana/data'], // Use Lodash from grafana
plugins: [
commonjs({
include: /node_modules/,
namedExports: {
'../../node_modules/lodash/lodash.js': [
'flatten',
'find',
'upperFirst',
'debounce',
'isNil',
'isNumber',
'flattenDeep',
'map',
'chunk',
'sortBy',
'uniqueId',
'zip',
],
},
}),
resolve(),
sourceMaps(),
env === 'production' && terser(),
],
};
};
export default [buildCjsPackage({ env: 'development' }), buildCjsPackage({ env: 'production' })];
| packages/grafana-runtime/rollup.config.ts | 0 | https://github.com/grafana/grafana/commit/5a06ed431cc3bd97759ed514589fbea4ba236777 | [
0.00017387093976140022,
0.0001709487842163071,
0.00016845620120875537,
0.00017095825751312077,
0.000002125898845406482
] |
{
"id": 2,
"code_window": [
" <form className=\"gf-form-group\" onSubmit={this.onAddApiKey}>\n",
" <div className=\"gf-form-inline\">\n",
" <div className=\"gf-form max-width-21\">\n",
" <span className=\"gf-form-label\">Key name</span>\n",
" <Input\n"
],
"labels": [
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <h5>Add API Key</h5>\n"
],
"file_path": "public/app/features/api-keys/ApiKeysPage.tsx",
"type": "add",
"edit_start_line_idx": 188
} | package datasources
import (
"github.com/grafana/grafana/pkg/infra/log"
)
var (
plog = log.New("datasources")
)
| pkg/services/datasources/log.go | 0 | https://github.com/grafana/grafana/commit/5a06ed431cc3bd97759ed514589fbea4ba236777 | [
0.00017179384303744882,
0.00017179384303744882,
0.00017179384303744882,
0.00017179384303744882,
0
] |
{
"id": 3,
"code_window": [
" <Component\n",
" in={false}\n",
" >\n",
" <div\n",
" className=\"cta-form\"\n",
" >\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" className=\"gf-form-inline cta-form\"\n"
],
"file_path": "public/app/features/api-keys/__snapshots__/ApiKeysPage.test.tsx.snap",
"type": "replace",
"edit_start_line_idx": 49
} | // Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`Render should render API keys table if there are any keys 1`] = `
<Page
navModel={
Object {
"main": Object {
"text": "Configuration",
},
"node": Object {
"text": "Api Keys",
},
}
}
>
<PageContents
isLoading={true}
/>
</Page>
`;
exports[`Render should render CTA if there are no API keys 1`] = `
<Page
navModel={
Object {
"main": Object {
"text": "Configuration",
},
"node": Object {
"text": "Api Keys",
},
}
}
>
<PageContents
isLoading={false}
>
<EmptyListCTA
buttonIcon="key-skeleton-alt"
buttonLink="#"
buttonTitle=" New API Key"
onClick={[Function]}
proTip="Remember you can provide view-only API access to other applications."
title="You haven't added any API Keys yet."
/>
<Component
in={false}
>
<div
className="cta-form"
>
<IconButton
className="cta-form__close btn btn-transparent"
name="times"
onClick={[Function]}
/>
<h5>
Add API Key
</h5>
<form
className="gf-form-group"
onSubmit={[Function]}
>
<div
className="gf-form-inline"
>
<div
className="gf-form max-width-21"
>
<span
className="gf-form-label"
>
Key name
</span>
<Input
className="gf-form-input"
onChange={[Function]}
placeholder="Name"
type="text"
value=""
/>
</div>
<div
className="gf-form"
>
<span
className="gf-form-label"
>
Role
</span>
<span
className="gf-form-select-wrapper"
>
<select
className="gf-form-input gf-size-auto"
onChange={[Function]}
value="Viewer"
>
<option
key="Viewer"
label="Viewer"
value="Viewer"
>
Viewer
</option>
<option
key="Editor"
label="Editor"
value="Editor"
>
Editor
</option>
<option
key="Admin"
label="Admin"
value="Admin"
>
Admin
</option>
</select>
</span>
</div>
<div
className="gf-form max-width-21"
>
<Component
tooltip="The api key life duration. For example 1d if your key is going to last for one day. All the supported units are: s,m,h,d,w,M,y"
>
Time to live
</Component>
<Input
className="gf-form-input"
onChange={[Function]}
placeholder="1d"
type="text"
validationEvents={
Object {
"onBlur": Array [
Object {
"errorMessage": "Not a valid duration",
"rule": [Function],
},
],
}
}
value=""
/>
</div>
<div
className="gf-form"
>
<button
className="btn gf-form-btn btn-primary"
>
Add
</button>
</div>
</div>
</form>
</div>
</Component>
</PageContents>
</Page>
`;
| public/app/features/api-keys/__snapshots__/ApiKeysPage.test.tsx.snap | 1 | https://github.com/grafana/grafana/commit/5a06ed431cc3bd97759ed514589fbea4ba236777 | [
0.7685397267341614,
0.04586271569132805,
0.00016478080942761153,
0.00017671800742391497,
0.1806773841381073
] |
{
"id": 3,
"code_window": [
" <Component\n",
" in={false}\n",
" >\n",
" <div\n",
" className=\"cta-form\"\n",
" >\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" className=\"gf-form-inline cta-form\"\n"
],
"file_path": "public/app/features/api-keys/__snapshots__/ApiKeysPage.test.tsx.snap",
"type": "replace",
"edit_start_line_idx": 49
} | #!/bin/bash
# When not limiting the open file descriptors limit, the memory consumption of
# slapd is absurdly high. See https://github.com/docker/docker/issues/8231
ulimit -n 8192
set -e
chown -R openldap:openldap /var/lib/ldap/
if [[ ! -d /etc/ldap/slapd.d ]]; then
if [[ -z "$SLAPD_PASSWORD" ]]; then
echo -n >&2 "Error: Container not configured and SLAPD_PASSWORD not set. "
echo >&2 "Did you forget to add -e SLAPD_PASSWORD=... ?"
exit 1
fi
if [[ -z "$SLAPD_DOMAIN" ]]; then
echo -n >&2 "Error: Container not configured and SLAPD_DOMAIN not set. "
echo >&2 "Did you forget to add -e SLAPD_DOMAIN=... ?"
exit 1
fi
SLAPD_ORGANIZATION="${SLAPD_ORGANIZATION:-${SLAPD_DOMAIN}}"
cp -a /etc/ldap.dist/* /etc/ldap
cat <<-EOF | debconf-set-selections
slapd slapd/no_configuration boolean false
slapd slapd/password1 password $SLAPD_PASSWORD
slapd slapd/password2 password $SLAPD_PASSWORD
slapd shared/organization string $SLAPD_ORGANIZATION
slapd slapd/domain string $SLAPD_DOMAIN
slapd slapd/backend select HDB
slapd slapd/allow_ldap_v2 boolean false
slapd slapd/purge_database boolean false
slapd slapd/move_old_database boolean true
EOF
dpkg-reconfigure -f noninteractive slapd >/dev/null 2>&1
dc_string=""
IFS="."; declare -a dc_parts=($SLAPD_DOMAIN)
for dc_part in "${dc_parts[@]}"; do
dc_string="$dc_string,dc=$dc_part"
done
base_string="BASE ${dc_string:1}"
sed -i "s/^#BASE.*/${base_string}/g" /etc/ldap/ldap.conf
if [[ -n "$SLAPD_CONFIG_PASSWORD" ]]; then
password_hash=`slappasswd -s "${SLAPD_CONFIG_PASSWORD}"`
sed_safe_password_hash=${password_hash//\//\\\/}
slapcat -n0 -F /etc/ldap/slapd.d -l /tmp/config.ldif
sed -i "s/\(olcRootDN: cn=admin,cn=config\)/\1\nolcRootPW: ${sed_safe_password_hash}/g" /tmp/config.ldif
rm -rf /etc/ldap/slapd.d/*
slapadd -n0 -F /etc/ldap/slapd.d -l /tmp/config.ldif >/dev/null 2>&1
fi
if [[ -n "$SLAPD_ADDITIONAL_SCHEMAS" ]]; then
IFS=","; declare -a schemas=($SLAPD_ADDITIONAL_SCHEMAS); unset IFS
for schema in "${schemas[@]}"; do
slapadd -n0 -F /etc/ldap/slapd.d -l "/etc/ldap/schema/${schema}.ldif" >/dev/null 2>&1
done
fi
if [[ -n "$SLAPD_ADDITIONAL_MODULES" ]]; then
IFS=","; declare -a modules=($SLAPD_ADDITIONAL_MODULES); unset IFS
for module in "${modules[@]}"; do
echo "Adding module ${module}"
slapadd -n0 -F /etc/ldap/slapd.d -l "/etc/ldap/modules/${module}.ldif" >/dev/null 2>&1
done
fi
# This needs to run in background
# Will prepopulate entries after ldap daemon has started
./prepopulate.sh &
chown -R openldap:openldap /etc/ldap/slapd.d/ /var/lib/ldap/ /var/run/slapd/
else
slapd_configs_in_env=`env | grep 'SLAPD_'`
if [ -n "${slapd_configs_in_env:+x}" ]; then
echo "Info: Container already configured, therefore ignoring SLAPD_xxx environment variables"
fi
fi
exec "$@"
| devenv/docker/blocks/multiple-openldap/entrypoint.sh | 0 | https://github.com/grafana/grafana/commit/5a06ed431cc3bd97759ed514589fbea4ba236777 | [
0.000171013773069717,
0.00016862049233168364,
0.00016629228775855154,
0.0001688345946604386,
0.0000013857825251761824
] |
{
"id": 3,
"code_window": [
" <Component\n",
" in={false}\n",
" >\n",
" <div\n",
" className=\"cta-form\"\n",
" >\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" className=\"gf-form-inline cta-form\"\n"
],
"file_path": "public/app/features/api-keys/__snapshots__/ApiKeysPage.test.tsx.snap",
"type": "replace",
"edit_start_line_idx": 49
} | // List Icons
// -------------------------
.#{$fa-css-prefix}-ul {
padding-left: 0;
margin-left: $fa-li-width;
list-style-type: none;
> li {
position: relative;
}
}
.#{$fa-css-prefix}-li {
position: absolute;
left: -$fa-li-width;
width: $fa-li-width;
top: (2em / 14);
text-align: center;
&.#{$fa-css-prefix}-lg {
left: -$fa-li-width + (4em / 14);
}
}
| public/sass/base/font-awesome/_list.scss | 0 | https://github.com/grafana/grafana/commit/5a06ed431cc3bd97759ed514589fbea4ba236777 | [
0.00017617727280594409,
0.00017272704280912876,
0.00017083204875234514,
0.00017117185052484274,
0.000002443611492708442
] |
{
"id": 3,
"code_window": [
" <Component\n",
" in={false}\n",
" >\n",
" <div\n",
" className=\"cta-form\"\n",
" >\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" className=\"gf-form-inline cta-form\"\n"
],
"file_path": "public/app/features/api-keys/__snapshots__/ApiKeysPage.test.tsx.snap",
"type": "replace",
"edit_start_line_idx": 49
} | +++
# -----------------------------------------------------------------------
# Do not edit this file. It is automatically generated by API Documenter.
# -----------------------------------------------------------------------
title = "GrafanaBootConfig"
keywords = ["grafana","documentation","sdk","@grafana/runtime"]
type = "docs"
+++
## GrafanaBootConfig class
<b>Signature</b>
```typescript
export declare class GrafanaBootConfig implements GrafanaConfig
```
<b>Import</b>
```typescript
import { GrafanaBootConfig } from '@grafana/runtime';
```
<b>Constructors</b>
| Constructor | Modifiers | Description |
| --- | --- | --- |
| [constructor(options)](#constructor-options) | | Constructs a new instance of the <code>GrafanaBootConfig</code> class |
<b>Properties</b>
| Property | Modifiers | Type | Description |
| --- | --- | --- | --- |
| [alertingEnabled](#alertingenabled-property) | | <code>boolean</code> | |
| [alertingErrorOrTimeout](#alertingerrorortimeout-property) | | <code>string</code> | |
| [alertingMinInterval](#alertingmininterval-property) | | <code>number</code> | |
| [alertingNoDataOrNullValues](#alertingnodataornullvalues-property) | | <code>string</code> | |
| [allowOrgCreate](#alloworgcreate-property) | | <code>boolean</code> | |
| [appSubUrl](#appsuburl-property) | | <code>string</code> | |
| [appUrl](#appurl-property) | | <code>string</code> | |
| [authProxyEnabled](#authproxyenabled-property) | | <code>boolean</code> | |
| [autoAssignOrg](#autoassignorg-property) | | <code>boolean</code> | |
| [bootData](#bootdata-property) | | <code>any</code> | |
| [buildInfo](#buildinfo-property) | | <code>BuildInfo</code> | |
| [datasources](#datasources-property) | | <code>{</code><br/><code> [str: string]: DataSourceInstanceSettings;</code><br/><code> }</code> | |
| [defaultDatasource](#defaultdatasource-property) | | <code>string</code> | |
| [disableLoginForm](#disableloginform-property) | | <code>boolean</code> | |
| [disableSanitizeHtml](#disablesanitizehtml-property) | | <code>boolean</code> | |
| [disableUserSignUp](#disableusersignup-property) | | <code>boolean</code> | |
| [editorsCanAdmin](#editorscanadmin-property) | | <code>boolean</code> | |
| [exploreEnabled](#exploreenabled-property) | | <code>boolean</code> | |
| [externalUserMngInfo](#externalusermnginfo-property) | | <code>string</code> | |
| [externalUserMngLinkName](#externalusermnglinkname-property) | | <code>string</code> | |
| [externalUserMngLinkUrl](#externalusermnglinkurl-property) | | <code>string</code> | |
| [featureToggles](#featuretoggles-property) | | <code>FeatureToggles</code> | |
| [ldapEnabled](#ldapenabled-property) | | <code>boolean</code> | |
| [licenseInfo](#licenseinfo-property) | | <code>LicenseInfo</code> | |
| [loginError](#loginerror-property) | | <code>any</code> | |
| [loginHint](#loginhint-property) | | <code>any</code> | |
| [minRefreshInterval](#minrefreshinterval-property) | | <code>string</code> | |
| [navTree](#navtree-property) | | <code>any</code> | |
| [newPanelTitle](#newpaneltitle-property) | | <code>string</code> | |
| [oauth](#oauth-property) | | <code>any</code> | |
| [panels](#panels-property) | | <code>{</code><br/><code> [key: string]: PanelPluginMeta;</code><br/><code> }</code> | |
| [passwordHint](#passwordhint-property) | | <code>any</code> | |
| [pluginsToPreload](#pluginstopreload-property) | | <code>string[]</code> | |
| [rendererAvailable](#rendereravailable-property) | | <code>boolean</code> | |
| [samlEnabled](#samlenabled-property) | | <code>boolean</code> | |
| [theme](#theme-property) | | <code>GrafanaTheme</code> | |
| [verifyEmailEnabled](#verifyemailenabled-property) | | <code>boolean</code> | |
| [viewersCanEdit](#viewerscanedit-property) | | <code>boolean</code> | |
| [windowTitlePrefix](#windowtitleprefix-property) | | <code>string</code> | |
### constructor(options)
Constructs a new instance of the `GrafanaBootConfig` class
<b>Signature</b>
```typescript
constructor(options: GrafanaBootConfig);
```
<b>Parameters</b>
| Parameter | Type | Description |
| --- | --- | --- |
| options | <code>GrafanaBootConfig</code> | |
### alertingEnabled property
<b>Signature</b>
```typescript
alertingEnabled: boolean;
```
### alertingErrorOrTimeout property
<b>Signature</b>
```typescript
alertingErrorOrTimeout: string;
```
### alertingMinInterval property
<b>Signature</b>
```typescript
alertingMinInterval: number;
```
### alertingNoDataOrNullValues property
<b>Signature</b>
```typescript
alertingNoDataOrNullValues: string;
```
### allowOrgCreate property
<b>Signature</b>
```typescript
allowOrgCreate: boolean;
```
### appSubUrl property
<b>Signature</b>
```typescript
appSubUrl: string;
```
### appUrl property
<b>Signature</b>
```typescript
appUrl: string;
```
### authProxyEnabled property
<b>Signature</b>
```typescript
authProxyEnabled: boolean;
```
### autoAssignOrg property
<b>Signature</b>
```typescript
autoAssignOrg: boolean;
```
### bootData property
<b>Signature</b>
```typescript
bootData: any;
```
### buildInfo property
<b>Signature</b>
```typescript
buildInfo: BuildInfo;
```
### datasources property
<b>Signature</b>
```typescript
datasources: {
[str: string]: DataSourceInstanceSettings;
};
```
### defaultDatasource property
<b>Signature</b>
```typescript
defaultDatasource: string;
```
### disableLoginForm property
<b>Signature</b>
```typescript
disableLoginForm: boolean;
```
### disableSanitizeHtml property
<b>Signature</b>
```typescript
disableSanitizeHtml: boolean;
```
### disableUserSignUp property
<b>Signature</b>
```typescript
disableUserSignUp: boolean;
```
### editorsCanAdmin property
<b>Signature</b>
```typescript
editorsCanAdmin: boolean;
```
### exploreEnabled property
<b>Signature</b>
```typescript
exploreEnabled: boolean;
```
### externalUserMngInfo property
<b>Signature</b>
```typescript
externalUserMngInfo: string;
```
### externalUserMngLinkName property
<b>Signature</b>
```typescript
externalUserMngLinkName: string;
```
### externalUserMngLinkUrl property
<b>Signature</b>
```typescript
externalUserMngLinkUrl: string;
```
### featureToggles property
<b>Signature</b>
```typescript
featureToggles: FeatureToggles;
```
### ldapEnabled property
<b>Signature</b>
```typescript
ldapEnabled: boolean;
```
### licenseInfo property
<b>Signature</b>
```typescript
licenseInfo: LicenseInfo;
```
### loginError property
<b>Signature</b>
```typescript
loginError: any;
```
### loginHint property
<b>Signature</b>
```typescript
loginHint: any;
```
### minRefreshInterval property
<b>Signature</b>
```typescript
minRefreshInterval: string;
```
### navTree property
<b>Signature</b>
```typescript
navTree: any;
```
### newPanelTitle property
<b>Signature</b>
```typescript
newPanelTitle: string;
```
### oauth property
<b>Signature</b>
```typescript
oauth: any;
```
### panels property
<b>Signature</b>
```typescript
panels: {
[key: string]: PanelPluginMeta;
};
```
### passwordHint property
<b>Signature</b>
```typescript
passwordHint: any;
```
### pluginsToPreload property
<b>Signature</b>
```typescript
pluginsToPreload: string[];
```
### rendererAvailable property
<b>Signature</b>
```typescript
rendererAvailable: boolean;
```
### samlEnabled property
<b>Signature</b>
```typescript
samlEnabled: boolean;
```
### theme property
<b>Signature</b>
```typescript
theme: GrafanaTheme;
```
### verifyEmailEnabled property
<b>Signature</b>
```typescript
verifyEmailEnabled: boolean;
```
### viewersCanEdit property
<b>Signature</b>
```typescript
viewersCanEdit: boolean;
```
### windowTitlePrefix property
<b>Signature</b>
```typescript
windowTitlePrefix: string;
```
| docs/sources/packages_api/runtime/grafanabootconfig.md | 0 | https://github.com/grafana/grafana/commit/5a06ed431cc3bd97759ed514589fbea4ba236777 | [
0.01119913812726736,
0.00044372669071890414,
0.0001636555971344933,
0.00016848654195200652,
0.0017007046844810247
] |
{
"id": 4,
"code_window": [
" >\n",
" <IconButton\n",
" className=\"cta-form__close btn btn-transparent\"\n"
],
"labels": [
"keep",
"replace",
"keep"
],
"after_edit": [
" <button\n"
],
"file_path": "public/app/features/api-keys/__snapshots__/ApiKeysPage.test.tsx.snap",
"type": "replace",
"edit_start_line_idx": 51
} | // Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`Render should render API keys table if there are any keys 1`] = `
<Page
navModel={
Object {
"main": Object {
"text": "Configuration",
},
"node": Object {
"text": "Api Keys",
},
}
}
>
<PageContents
isLoading={true}
/>
</Page>
`;
exports[`Render should render CTA if there are no API keys 1`] = `
<Page
navModel={
Object {
"main": Object {
"text": "Configuration",
},
"node": Object {
"text": "Api Keys",
},
}
}
>
<PageContents
isLoading={false}
>
<EmptyListCTA
buttonIcon="key-skeleton-alt"
buttonLink="#"
buttonTitle=" New API Key"
onClick={[Function]}
proTip="Remember you can provide view-only API access to other applications."
title="You haven't added any API Keys yet."
/>
<Component
in={false}
>
<div
className="cta-form"
>
<IconButton
className="cta-form__close btn btn-transparent"
name="times"
onClick={[Function]}
/>
<h5>
Add API Key
</h5>
<form
className="gf-form-group"
onSubmit={[Function]}
>
<div
className="gf-form-inline"
>
<div
className="gf-form max-width-21"
>
<span
className="gf-form-label"
>
Key name
</span>
<Input
className="gf-form-input"
onChange={[Function]}
placeholder="Name"
type="text"
value=""
/>
</div>
<div
className="gf-form"
>
<span
className="gf-form-label"
>
Role
</span>
<span
className="gf-form-select-wrapper"
>
<select
className="gf-form-input gf-size-auto"
onChange={[Function]}
value="Viewer"
>
<option
key="Viewer"
label="Viewer"
value="Viewer"
>
Viewer
</option>
<option
key="Editor"
label="Editor"
value="Editor"
>
Editor
</option>
<option
key="Admin"
label="Admin"
value="Admin"
>
Admin
</option>
</select>
</span>
</div>
<div
className="gf-form max-width-21"
>
<Component
tooltip="The api key life duration. For example 1d if your key is going to last for one day. All the supported units are: s,m,h,d,w,M,y"
>
Time to live
</Component>
<Input
className="gf-form-input"
onChange={[Function]}
placeholder="1d"
type="text"
validationEvents={
Object {
"onBlur": Array [
Object {
"errorMessage": "Not a valid duration",
"rule": [Function],
},
],
}
}
value=""
/>
</div>
<div
className="gf-form"
>
<button
className="btn gf-form-btn btn-primary"
>
Add
</button>
</div>
</div>
</form>
</div>
</Component>
</PageContents>
</Page>
`;
| public/app/features/api-keys/__snapshots__/ApiKeysPage.test.tsx.snap | 1 | https://github.com/grafana/grafana/commit/5a06ed431cc3bd97759ed514589fbea4ba236777 | [
0.30434364080429077,
0.01824035681784153,
0.00016588544531259686,
0.00016724751912988722,
0.07152891904115677
] |
{
"id": 4,
"code_window": [
" >\n",
" <IconButton\n",
" className=\"cta-form__close btn btn-transparent\"\n"
],
"labels": [
"keep",
"replace",
"keep"
],
"after_edit": [
" <button\n"
],
"file_path": "public/app/features/api-keys/__snapshots__/ApiKeysPage.test.tsx.snap",
"type": "replace",
"edit_start_line_idx": 51
} | export { componentTpl } from './component.tsx.template';
export { storyTpl } from './story.tsx.template';
export { docsTpl } from './docs.mdx.template';
export { testTpl } from './component.test.tsx.template';
| packages/grafana-toolkit/src/cli/templates/index.ts | 0 | https://github.com/grafana/grafana/commit/5a06ed431cc3bd97759ed514589fbea4ba236777 | [
0.00017076186486519873,
0.00017076186486519873,
0.00017076186486519873,
0.00017076186486519873,
0
] |
{
"id": 4,
"code_window": [
" >\n",
" <IconButton\n",
" className=\"cta-form__close btn btn-transparent\"\n"
],
"labels": [
"keep",
"replace",
"keep"
],
"after_edit": [
" <button\n"
],
"file_path": "public/app/features/api-keys/__snapshots__/ApiKeysPage.test.tsx.snap",
"type": "replace",
"edit_start_line_idx": 51
} | package api
import (
"errors"
"fmt"
"github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/infra/metrics"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/util"
)
func AdminCreateUser(c *models.ReqContext, form dtos.AdminCreateUserForm) Response {
cmd := models.CreateUserCommand{
Login: form.Login,
Email: form.Email,
Password: form.Password,
Name: form.Name,
OrgId: form.OrgId,
}
if len(cmd.Login) == 0 {
cmd.Login = cmd.Email
if len(cmd.Login) == 0 {
return Error(400, "Validation error, need specify either username or email", nil)
}
}
if len(cmd.Password) < 4 {
return Error(400, "Password is missing or too short", nil)
}
if err := bus.Dispatch(&cmd); err != nil {
if errors.Is(err, models.ErrOrgNotFound) {
return Error(400, err.Error(), nil)
}
if errors.Is(err, models.ErrUserAlreadyExists) {
return Error(412, fmt.Sprintf("User with email '%s' or username '%s' already exists", form.Email, form.Login), err)
}
return Error(500, "failed to create user", err)
}
metrics.MApiAdminUserCreate.Inc()
user := cmd.Result
result := models.UserIdDTO{
Message: "User created",
Id: user.Id,
}
return JSON(200, result)
}
func AdminUpdateUserPassword(c *models.ReqContext, form dtos.AdminUpdateUserPasswordForm) Response {
userID := c.ParamsInt64(":id")
if len(form.Password) < 4 {
return Error(400, "New password too short", nil)
}
userQuery := models.GetUserByIdQuery{Id: userID}
if err := bus.Dispatch(&userQuery); err != nil {
return Error(500, "Could not read user from database", err)
}
passwordHashed, err := util.EncodePassword(form.Password, userQuery.Result.Salt)
if err != nil {
return Error(500, "Could not encode password", err)
}
cmd := models.ChangeUserPasswordCommand{
UserId: userID,
NewPassword: passwordHashed,
}
if err := bus.Dispatch(&cmd); err != nil {
return Error(500, "Failed to update user password", err)
}
return Success("User password updated")
}
// PUT /api/admin/users/:id/permissions
func AdminUpdateUserPermissions(c *models.ReqContext, form dtos.AdminUpdateUserPermissionsForm) Response {
userID := c.ParamsInt64(":id")
cmd := models.UpdateUserPermissionsCommand{
UserId: userID,
IsGrafanaAdmin: form.IsGrafanaAdmin,
}
if err := bus.Dispatch(&cmd); err != nil {
if err == models.ErrLastGrafanaAdmin {
return Error(400, models.ErrLastGrafanaAdmin.Error(), nil)
}
return Error(500, "Failed to update user permissions", err)
}
return Success("User permissions updated")
}
func AdminDeleteUser(c *models.ReqContext) Response {
userID := c.ParamsInt64(":id")
cmd := models.DeleteUserCommand{UserId: userID}
if err := bus.Dispatch(&cmd); err != nil {
if err == models.ErrUserNotFound {
return Error(404, models.ErrUserNotFound.Error(), nil)
}
return Error(500, "Failed to delete user", err)
}
return Success("User deleted")
}
// POST /api/admin/users/:id/disable
func (server *HTTPServer) AdminDisableUser(c *models.ReqContext) Response {
userID := c.ParamsInt64(":id")
// External users shouldn't be disabled from API
authInfoQuery := &models.GetAuthInfoQuery{UserId: userID}
if err := bus.Dispatch(authInfoQuery); err != models.ErrUserNotFound {
return Error(500, "Could not disable external user", nil)
}
disableCmd := models.DisableUserCommand{UserId: userID, IsDisabled: true}
if err := bus.Dispatch(&disableCmd); err != nil {
if err == models.ErrUserNotFound {
return Error(404, models.ErrUserNotFound.Error(), nil)
}
return Error(500, "Failed to disable user", err)
}
err := server.AuthTokenService.RevokeAllUserTokens(c.Req.Context(), userID)
if err != nil {
return Error(500, "Failed to disable user", err)
}
return Success("User disabled")
}
// POST /api/admin/users/:id/enable
func AdminEnableUser(c *models.ReqContext) Response {
userID := c.ParamsInt64(":id")
// External users shouldn't be disabled from API
authInfoQuery := &models.GetAuthInfoQuery{UserId: userID}
if err := bus.Dispatch(authInfoQuery); err != models.ErrUserNotFound {
return Error(500, "Could not enable external user", nil)
}
disableCmd := models.DisableUserCommand{UserId: userID, IsDisabled: false}
if err := bus.Dispatch(&disableCmd); err != nil {
if err == models.ErrUserNotFound {
return Error(404, models.ErrUserNotFound.Error(), nil)
}
return Error(500, "Failed to enable user", err)
}
return Success("User enabled")
}
// POST /api/admin/users/:id/logout
func (server *HTTPServer) AdminLogoutUser(c *models.ReqContext) Response {
userID := c.ParamsInt64(":id")
if c.UserId == userID {
return Error(400, "You cannot logout yourself", nil)
}
return server.logoutUserFromAllDevicesInternal(c.Req.Context(), userID)
}
// GET /api/admin/users/:id/auth-tokens
func (server *HTTPServer) AdminGetUserAuthTokens(c *models.ReqContext) Response {
userID := c.ParamsInt64(":id")
return server.getUserAuthTokensInternal(c, userID)
}
// POST /api/admin/users/:id/revoke-auth-token
func (server *HTTPServer) AdminRevokeUserAuthToken(c *models.ReqContext, cmd models.RevokeAuthTokenCmd) Response {
userID := c.ParamsInt64(":id")
return server.revokeUserAuthTokenInternal(c, userID, cmd)
}
| pkg/api/admin_users.go | 0 | https://github.com/grafana/grafana/commit/5a06ed431cc3bd97759ed514589fbea4ba236777 | [
0.00018585466023068875,
0.00017040966486092657,
0.00016373051039408892,
0.00017004847177304327,
0.000004630470812116982
] |
{
"id": 4,
"code_window": [
" >\n",
" <IconButton\n",
" className=\"cta-form__close btn btn-transparent\"\n"
],
"labels": [
"keep",
"replace",
"keep"
],
"after_edit": [
" <button\n"
],
"file_path": "public/app/features/api-keys/__snapshots__/ApiKeysPage.test.tsx.snap",
"type": "replace",
"edit_start_line_idx": 51
} | <div ng-controller="JsonEditorCtrl">
<div class="tabbed-view-header">
<h2 class="tabbed-view-title">
JSON
</h2>
<button class="tabbed-view-close-btn" ng-click="dismiss()">
<icon name="'times'"></icon>
</button>
</div>
<div class="tabbed-view-body">
<div class="gf-form">
<code-editor content="json" data-mode="json" data-max-lines="20"></code-editor>
</div>
<div class="gf-form-button-row">
<button type="button" class="btn btn-primary" ng-show="canUpdate" ng-click="update(); dismiss();">Update</button>
<button class="btn btn-secondary" ng-if="canCopy" clipboard-button="getContentForClipboard()">
Copy to Clipboard
</button>
</div>
</div>
</div>
| public/app/partials/edit_json.html | 0 | https://github.com/grafana/grafana/commit/5a06ed431cc3bd97759ed514589fbea4ba236777 | [
0.0005891009932383895,
0.00045178551226854324,
0.00028781782020814717,
0.00047843772335909307,
0.0001244337618118152
] |
{
"id": 5,
"code_window": [
" className=\"cta-form__close btn btn-transparent\"\n",
" name=\"times\"\n",
" onClick={[Function]}\n"
],
"labels": [
"keep",
"replace",
"keep"
],
"after_edit": [],
"file_path": "public/app/features/api-keys/__snapshots__/ApiKeysPage.test.tsx.snap",
"type": "replace",
"edit_start_line_idx": 53
} | import React, { PureComponent } from 'react';
import ReactDOMServer from 'react-dom/server';
import { connect } from 'react-redux';
import { hot } from 'react-hot-loader';
// Utils
import { ApiKey, CoreEvents, NewApiKey, OrgRole } from 'app/types';
import { getNavModel } from 'app/core/selectors/navModel';
import { getApiKeys, getApiKeysCount } from './state/selectors';
import { addApiKey, deleteApiKey, loadApiKeys } from './state/actions';
import Page from 'app/core/components/Page/Page';
import { SlideDown } from 'app/core/components/Animations/SlideDown';
import ApiKeysAddedModal from './ApiKeysAddedModal';
import config from 'app/core/config';
import appEvents from 'app/core/app_events';
import EmptyListCTA from 'app/core/components/EmptyListCTA/EmptyListCTA';
import {
DeleteButton,
EventsWithValidation,
InlineFormLabel,
LegacyForms,
ValidationEvents,
IconButton,
} from '@grafana/ui';
const { Input, Switch } = LegacyForms;
import { NavModel, dateTimeFormat, rangeUtil } from '@grafana/data';
import { FilterInput } from 'app/core/components/FilterInput/FilterInput';
import { store } from 'app/store/store';
import { getTimeZone } from 'app/features/profile/state/selectors';
import { setSearchQuery } from './state/reducers';
const timeRangeValidationEvents: ValidationEvents = {
[EventsWithValidation.onBlur]: [
{
rule: value => {
if (!value) {
return true;
}
try {
rangeUtil.intervalToSeconds(value);
return true;
} catch {
return false;
}
},
errorMessage: 'Not a valid duration',
},
],
};
export interface Props {
navModel: NavModel;
apiKeys: ApiKey[];
searchQuery: string;
hasFetched: boolean;
loadApiKeys: typeof loadApiKeys;
deleteApiKey: typeof deleteApiKey;
setSearchQuery: typeof setSearchQuery;
addApiKey: typeof addApiKey;
apiKeysCount: number;
includeExpired: boolean;
}
export interface State {
isAdding: boolean;
newApiKey: NewApiKey;
}
enum ApiKeyStateProps {
Name = 'name',
Role = 'role',
SecondsToLive = 'secondsToLive',
}
const initialApiKeyState = {
name: '',
role: OrgRole.Viewer,
secondsToLive: '',
};
const tooltipText =
'The api key life duration. For example 1d if your key is going to last for one day. All the supported units are: s,m,h,d,w,M,y';
export class ApiKeysPage extends PureComponent<Props, any> {
constructor(props: Props) {
super(props);
this.state = { isAdding: false, newApiKey: initialApiKeyState, includeExpired: false };
}
componentDidMount() {
this.fetchApiKeys();
}
async fetchApiKeys() {
await this.props.loadApiKeys(this.state.includeExpired);
}
onDeleteApiKey(key: ApiKey) {
this.props.deleteApiKey(key.id, this.props.includeExpired);
}
onSearchQueryChange = (value: string) => {
this.props.setSearchQuery(value);
};
onIncludeExpiredChange = (value: boolean) => {
this.setState({ hasFetched: false, includeExpired: value }, this.fetchApiKeys);
};
onToggleAdding = () => {
this.setState({ isAdding: !this.state.isAdding });
};
onAddApiKey = async (evt: any) => {
evt.preventDefault();
const openModal = (apiKey: string) => {
const rootPath = window.location.origin + config.appSubUrl;
const modalTemplate = ReactDOMServer.renderToString(<ApiKeysAddedModal apiKey={apiKey} rootPath={rootPath} />);
appEvents.emit(CoreEvents.showModal, {
templateHtml: modalTemplate,
});
};
// make sure that secondsToLive is number or null
const secondsToLive = this.state.newApiKey['secondsToLive'];
this.state.newApiKey['secondsToLive'] = secondsToLive ? rangeUtil.intervalToSeconds(secondsToLive) : null;
this.props.addApiKey(this.state.newApiKey, openModal, this.props.includeExpired);
this.setState((prevState: State) => {
return {
...prevState,
newApiKey: initialApiKeyState,
isAdding: false,
};
});
};
onApiKeyStateUpdate = (evt: any, prop: string) => {
const value = evt.currentTarget.value;
this.setState((prevState: State) => {
const newApiKey: any = {
...prevState.newApiKey,
};
newApiKey[prop] = value;
return {
...prevState,
newApiKey: newApiKey,
};
});
};
renderEmptyList() {
const { isAdding } = this.state;
return (
<>
{!isAdding && (
<EmptyListCTA
title="You haven't added any API Keys yet."
buttonIcon="key-skeleton-alt"
buttonLink="#"
onClick={this.onToggleAdding}
buttonTitle=" New API Key"
proTip="Remember you can provide view-only API access to other applications."
/>
)}
{this.renderAddApiKeyForm()}
</>
);
}
formatDate(date: any, format?: string) {
if (!date) {
return 'No expiration date';
}
const timeZone = getTimeZone(store.getState().user);
return dateTimeFormat(date, { format, timeZone });
}
renderAddApiKeyForm() {
const { newApiKey, isAdding } = this.state;
return (
<SlideDown in={isAdding}>
<div className="cta-form">
<IconButton name="times" className="cta-form__close btn btn-transparent" onClick={this.onToggleAdding} />
<h5>Add API Key</h5>
<form className="gf-form-group" onSubmit={this.onAddApiKey}>
<div className="gf-form-inline">
<div className="gf-form max-width-21">
<span className="gf-form-label">Key name</span>
<Input
type="text"
className="gf-form-input"
value={newApiKey.name}
placeholder="Name"
onChange={evt => this.onApiKeyStateUpdate(evt, ApiKeyStateProps.Name)}
/>
</div>
<div className="gf-form">
<span className="gf-form-label">Role</span>
<span className="gf-form-select-wrapper">
<select
className="gf-form-input gf-size-auto"
value={newApiKey.role}
onChange={evt => this.onApiKeyStateUpdate(evt, ApiKeyStateProps.Role)}
>
{Object.keys(OrgRole).map(role => {
return (
<option key={role} label={role} value={role}>
{role}
</option>
);
})}
</select>
</span>
</div>
<div className="gf-form max-width-21">
<InlineFormLabel tooltip={tooltipText}>Time to live</InlineFormLabel>
<Input
type="text"
className="gf-form-input"
placeholder="1d"
validationEvents={timeRangeValidationEvents}
value={newApiKey.secondsToLive}
onChange={evt => this.onApiKeyStateUpdate(evt, ApiKeyStateProps.SecondsToLive)}
/>
</div>
<div className="gf-form">
<button className="btn gf-form-btn btn-primary">Add</button>
</div>
</div>
</form>
</div>
</SlideDown>
);
}
renderApiKeyList() {
const { isAdding } = this.state;
const { apiKeys, searchQuery, includeExpired } = this.props;
return (
<>
<div className="page-action-bar">
<div className="gf-form gf-form--grow">
<FilterInput
labelClassName="gf-form--has-input-icon gf-form--grow"
inputClassName="gf-form-input"
placeholder="Search keys"
value={searchQuery}
onChange={this.onSearchQueryChange}
/>
</div>
<div className="page-action-bar__spacer" />
<button className="btn btn-primary pull-right" onClick={this.onToggleAdding} disabled={isAdding}>
Add API key
</button>
</div>
{this.renderAddApiKeyForm()}
<h3 className="page-heading">Existing Keys</h3>
<Switch
label="Show expired"
checked={includeExpired}
onChange={event => {
// @ts-ignore
this.onIncludeExpiredChange(event.target.checked);
}}
/>
<table className="filter-table">
<thead>
<tr>
<th>Name</th>
<th>Role</th>
<th>Expires</th>
<th style={{ width: '34px' }} />
</tr>
</thead>
{apiKeys.length > 0 ? (
<tbody>
{apiKeys.map(key => {
return (
<tr key={key.id}>
<td>{key.name}</td>
<td>{key.role}</td>
<td>{this.formatDate(key.expiration)}</td>
<td>
<DeleteButton size="sm" onConfirm={() => this.onDeleteApiKey(key)} />
</td>
</tr>
);
})}
</tbody>
) : null}
</table>
</>
);
}
render() {
const { hasFetched, navModel, apiKeysCount } = this.props;
return (
<Page navModel={navModel}>
<Page.Contents isLoading={!hasFetched}>
{hasFetched && (apiKeysCount > 0 ? this.renderApiKeyList() : this.renderEmptyList())}
</Page.Contents>
</Page>
);
}
}
function mapStateToProps(state: any) {
return {
navModel: getNavModel(state.navIndex, 'apikeys'),
apiKeys: getApiKeys(state.apiKeys),
searchQuery: state.apiKeys.searchQuery,
includeExpired: state.includeExpired,
apiKeysCount: getApiKeysCount(state.apiKeys),
hasFetched: state.apiKeys.hasFetched,
};
}
const mapDispatchToProps = {
loadApiKeys,
deleteApiKey,
setSearchQuery,
addApiKey,
};
export default hot(module)(connect(mapStateToProps, mapDispatchToProps)(ApiKeysPage));
| public/app/features/api-keys/ApiKeysPage.tsx | 1 | https://github.com/grafana/grafana/commit/5a06ed431cc3bd97759ed514589fbea4ba236777 | [
0.015621275641024113,
0.0006435303948819637,
0.00016403678455390036,
0.00016950519056990743,
0.00260835699737072
] |
{
"id": 5,
"code_window": [
" className=\"cta-form__close btn btn-transparent\"\n",
" name=\"times\"\n",
" onClick={[Function]}\n"
],
"labels": [
"keep",
"replace",
"keep"
],
"after_edit": [],
"file_path": "public/app/features/api-keys/__snapshots__/ApiKeysPage.test.tsx.snap",
"type": "replace",
"edit_start_line_idx": 53
} | <?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 20.1.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
width="64px" height="64px" viewBox="0 0 64 64" style="enable-background:new 0 0 64 64;" xml:space="preserve">
<style type="text/css">
.st0{fill:#E3E3E3;}
.st1{fill:url(#SVGID_1_);}
.st2{fill:url(#SVGID_2_);}
.st3{fill:url(#SVGID_3_);}
.st4{fill:url(#SVGID_4_);}
.st5{fill:url(#SVGID_5_);}
.st6{fill:url(#SVGID_6_);}
</style>
<g>
<g>
<path class="st0" d="M32,59.4c3.3,0,6-2.7,6-6H26C26,56.7,28.7,59.4,32,59.4z"/>
</g>
</g>
<g>
<path class="st0" d="M47.7,43.8v-7.6c0-9.4-4.9-17.2-11.6-19.6c0-2.3-1.8-4.1-4.1-4.1c-2.3,0-4.1,1.8-4.1,4.1
c-6.7,2.3-11.6,10.2-11.6,19.6v7.6c-1.8,0-3.3,1.5-3.3,3.3c0,1.8,1.5,3.3,3.3,3.3v0h0h31.4h0v0c1.8,0,3.3-1.5,3.3-3.3
C51,45.3,49.6,43.9,47.7,43.8z"/>
</g>
<g>
<linearGradient id="SVGID_1_" gradientUnits="userSpaceOnUse" x1="52.0976" y1="33.7801" x2="52.0976" y2="-1.9525">
<stop offset="0" style="stop-color:#FFF33B"/>
<stop offset="5.948725e-02" style="stop-color:#FFE029"/>
<stop offset="0.1303" style="stop-color:#FFD218"/>
<stop offset="0.2032" style="stop-color:#FEC90F"/>
<stop offset="0.2809" style="stop-color:#FDC70C"/>
<stop offset="0.6685" style="stop-color:#F3903F"/>
<stop offset="0.8876" style="stop-color:#ED683C"/>
<stop offset="1" style="stop-color:#E93E3A"/>
</linearGradient>
<path class="st1" d="M56.4,24.4c-0.7,0-1.3-0.4-1.5-1c-1.8-4.3-4.6-8.2-8.1-11.3c-0.7-0.6-0.8-1.7-0.2-2.4c0.6-0.7,1.7-0.8,2.4-0.2
c3.9,3.4,7.1,7.8,9,12.6c0.4,0.9-0.1,1.8-0.9,2.2C56.8,24.4,56.6,24.4,56.4,24.4z"/>
</g>
<g>
<linearGradient id="SVGID_2_" gradientUnits="userSpaceOnUse" x1="46.9877" y1="33.7801" x2="46.9877" y2="-1.9525">
<stop offset="0" style="stop-color:#FFF33B"/>
<stop offset="5.948725e-02" style="stop-color:#FFE029"/>
<stop offset="0.1303" style="stop-color:#FFD218"/>
<stop offset="0.2032" style="stop-color:#FEC90F"/>
<stop offset="0.2809" style="stop-color:#FDC70C"/>
<stop offset="0.6685" style="stop-color:#F3903F"/>
<stop offset="0.8876" style="stop-color:#ED683C"/>
<stop offset="1" style="stop-color:#E93E3A"/>
</linearGradient>
<path class="st2" d="M50.3,26.9c-0.7,0-1.3-0.4-1.5-1c-1.4-3.3-3.5-6.3-6.2-8.6c-0.7-0.6-0.8-1.7-0.2-2.4c0.6-0.7,1.7-0.8,2.4-0.2
c3.1,2.7,5.5,6.1,7.1,9.9c0.4,0.9-0.1,1.8-0.9,2.2C50.7,26.8,50.5,26.9,50.3,26.9z"/>
</g>
<g>
<linearGradient id="SVGID_3_" gradientUnits="userSpaceOnUse" x1="57.4685" y1="33.7801" x2="57.4685" y2="-1.9525">
<stop offset="0" style="stop-color:#FFF33B"/>
<stop offset="5.948725e-02" style="stop-color:#FFE029"/>
<stop offset="0.1303" style="stop-color:#FFD218"/>
<stop offset="0.2032" style="stop-color:#FEC90F"/>
<stop offset="0.2809" style="stop-color:#FDC70C"/>
<stop offset="0.6685" style="stop-color:#F3903F"/>
<stop offset="0.8876" style="stop-color:#ED683C"/>
<stop offset="1" style="stop-color:#E93E3A"/>
</linearGradient>
<path class="st3" d="M62.3,21.4c-0.7,0-1.3-0.4-1.5-1c-2-4.9-5.2-9.4-9.3-12.9c-0.7-0.6-0.8-1.7-0.2-2.4C52,4.5,53,4.4,53.7,5
c4.4,3.8,7.9,8.7,10.2,14.1c0.4,0.9-0.1,1.8-0.9,2.2C62.8,21.4,62.5,21.4,62.3,21.4z"/>
</g>
<g>
<linearGradient id="SVGID_4_" gradientUnits="userSpaceOnUse" x1="11.902" y1="33.7801" x2="11.902" y2="-1.9525">
<stop offset="0" style="stop-color:#FFF33B"/>
<stop offset="5.948725e-02" style="stop-color:#FFE029"/>
<stop offset="0.1303" style="stop-color:#FFD218"/>
<stop offset="0.2032" style="stop-color:#FEC90F"/>
<stop offset="0.2809" style="stop-color:#FDC70C"/>
<stop offset="0.6685" style="stop-color:#F3903F"/>
<stop offset="0.8876" style="stop-color:#ED683C"/>
<stop offset="1" style="stop-color:#E93E3A"/>
</linearGradient>
<path class="st4" d="M7.6,24.4c-0.2,0-0.4,0-0.6-0.1c-0.9-0.4-1.3-1.3-0.9-2.2c2-4.8,5.1-9.2,9-12.6c0.7-0.6,1.8-0.5,2.4,0.2
c0.6,0.7,0.5,1.8-0.2,2.4c-3.5,3.1-6.4,7-8.1,11.3C8.9,24,8.3,24.4,7.6,24.4z"/>
</g>
<g>
<linearGradient id="SVGID_5_" gradientUnits="userSpaceOnUse" x1="17.0123" y1="33.7801" x2="17.0123" y2="-1.9525">
<stop offset="0" style="stop-color:#FFF33B"/>
<stop offset="5.948725e-02" style="stop-color:#FFE029"/>
<stop offset="0.1303" style="stop-color:#FFD218"/>
<stop offset="0.2032" style="stop-color:#FEC90F"/>
<stop offset="0.2809" style="stop-color:#FDC70C"/>
<stop offset="0.6685" style="stop-color:#F3903F"/>
<stop offset="0.8876" style="stop-color:#ED683C"/>
<stop offset="1" style="stop-color:#E93E3A"/>
</linearGradient>
<path class="st5" d="M13.7,26.9c-0.2,0-0.4,0-0.6-0.1c-0.9-0.4-1.3-1.3-0.9-2.2c1.5-3.8,4-7.2,7.1-9.9c0.7-0.6,1.8-0.5,2.4,0.2
c0.6,0.7,0.5,1.8-0.2,2.4c-2.7,2.3-4.8,5.3-6.2,8.6C15,26.5,14.4,26.9,13.7,26.9z"/>
</g>
<g>
<linearGradient id="SVGID_6_" gradientUnits="userSpaceOnUse" x1="6.5315" y1="33.7801" x2="6.5315" y2="-1.9525">
<stop offset="0" style="stop-color:#FFF33B"/>
<stop offset="5.948725e-02" style="stop-color:#FFE029"/>
<stop offset="0.1303" style="stop-color:#FFD218"/>
<stop offset="0.2032" style="stop-color:#FEC90F"/>
<stop offset="0.2809" style="stop-color:#FDC70C"/>
<stop offset="0.6685" style="stop-color:#F3903F"/>
<stop offset="0.8876" style="stop-color:#ED683C"/>
<stop offset="1" style="stop-color:#E93E3A"/>
</linearGradient>
<path class="st6" d="M1.7,21.4c-0.2,0-0.4,0-0.6-0.1C0.2,21-0.2,20,0.1,19.1C2.3,13.7,5.9,8.8,10.3,5C11,4.4,12,4.5,12.7,5.2
c0.6,0.7,0.5,1.8-0.2,2.4c-4,3.5-7.2,8-9.3,12.9C3,21,2.3,21.4,1.7,21.4z"/>
</g>
</svg>
| public/img/icons_dark_theme/icon_alert_alt.svg | 0 | https://github.com/grafana/grafana/commit/5a06ed431cc3bd97759ed514589fbea4ba236777 | [
0.0001743393950164318,
0.0001712915109237656,
0.0001662691356614232,
0.0001721721637295559,
0.000002302074108229135
] |
{
"id": 5,
"code_window": [
" className=\"cta-form__close btn btn-transparent\"\n",
" name=\"times\"\n",
" onClick={[Function]}\n"
],
"labels": [
"keep",
"replace",
"keep"
],
"after_edit": [],
"file_path": "public/app/features/api-keys/__snapshots__/ApiKeysPage.test.tsx.snap",
"type": "replace",
"edit_start_line_idx": 53
} | package notifications
import (
"io/ioutil"
"testing"
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/setting"
. "github.com/smartystreets/goconvey/convey"
)
func TestEmailIntegrationTest(t *testing.T) {
SkipConvey("Given the notifications service", t, func() {
setting.StaticRootPath = "../../../public/"
setting.BuildVersion = "4.0.0"
ns := &NotificationService{}
ns.Bus = bus.New()
ns.Cfg = setting.NewCfg()
ns.Cfg.Smtp.Enabled = true
ns.Cfg.Smtp.TemplatesPattern = "emails/*.html"
ns.Cfg.Smtp.FromAddress = "[email protected]"
ns.Cfg.Smtp.FromName = "Grafana Admin"
err := ns.Init()
So(err, ShouldBeNil)
Convey("When sending reset email password", func() {
cmd := &models.SendEmailCommand{
Data: map[string]interface{}{
"Title": "[CRITICAL] Imaginary timeseries alert",
"State": "Firing",
"Name": "Imaginary timeseries alert",
"Severity": "ok",
"SeverityColor": "#D63232",
"Message": "Alert message that will support markdown in some distant future.",
"RuleUrl": "http://localhost:3000/dashboard/db/graphite-dashboard",
"ImageLink": "http://localhost:3000/render/dashboard-solo/db/graphite-dashboard?panelId=1&from=1471008499616&to=1471012099617&width=1000&height=500",
"AlertPageUrl": "http://localhost:3000/alerting",
"EmbeddedImage": "test.png",
"EvalMatches": []map[string]string{
{
"Metric": "desktop",
"Value": "40",
},
{
"Metric": "mobile",
"Value": "20",
},
},
},
To: []string{"[email protected]"},
Template: "alert_notification.html",
}
err := ns.sendEmailCommandHandler(cmd)
So(err, ShouldBeNil)
sentMsg := <-ns.mailQueue
So(sentMsg.From, ShouldEqual, "Grafana Admin <[email protected]>")
So(sentMsg.To[0], ShouldEqual, "[email protected]")
err = ioutil.WriteFile("../../../tmp/test_email.html", []byte(sentMsg.Body), 0777)
So(err, ShouldBeNil)
})
})
}
| pkg/services/notifications/send_email_integration_test.go | 0 | https://github.com/grafana/grafana/commit/5a06ed431cc3bd97759ed514589fbea4ba236777 | [
0.00017215443949680775,
0.00016939034685492516,
0.00016228703316301107,
0.0001709849020699039,
0.0000032040375117503572
] |
{
"id": 5,
"code_window": [
" className=\"cta-form__close btn btn-transparent\"\n",
" name=\"times\"\n",
" onClick={[Function]}\n"
],
"labels": [
"keep",
"replace",
"keep"
],
"after_edit": [],
"file_path": "public/app/features/api-keys/__snapshots__/ApiKeysPage.test.tsx.snap",
"type": "replace",
"edit_start_line_idx": 53
} | import { PanelModel } from 'app/features/dashboard/state';
export class ThresholdMapper {
static alertToGraphThresholds(panel: PanelModel) {
if (!panel.alert) {
return false; // no update when no alerts
}
for (let i = 0; i < panel.alert.conditions.length; i++) {
const condition = panel.alert.conditions[i];
if (condition.type !== 'query') {
continue;
}
const evaluator = condition.evaluator;
const thresholds: any[] = (panel.thresholds = []);
switch (evaluator.type) {
case 'gt': {
const value = evaluator.params[0];
thresholds.push({ value: value, op: 'gt' });
break;
}
case 'lt': {
const value = evaluator.params[0];
thresholds.push({ value: value, op: 'lt' });
break;
}
case 'outside_range': {
const value1 = evaluator.params[0];
const value2 = evaluator.params[1];
if (value1 > value2) {
thresholds.push({ value: value1, op: 'gt' });
thresholds.push({ value: value2, op: 'lt' });
} else {
thresholds.push({ value: value1, op: 'lt' });
thresholds.push({ value: value2, op: 'gt' });
}
break;
}
case 'within_range': {
const value1 = evaluator.params[0];
const value2 = evaluator.params[1];
if (value1 > value2) {
thresholds.push({ value: value1, op: 'lt' });
thresholds.push({ value: value2, op: 'gt' });
} else {
thresholds.push({ value: value1, op: 'gt' });
thresholds.push({ value: value2, op: 'lt' });
}
break;
}
}
break;
}
for (const t of panel.thresholds) {
t.fill = panel.options.alertThreshold;
t.line = panel.options.alertThreshold;
t.colorMode = 'critical';
}
const updated = true;
return updated;
}
}
| public/app/features/alerting/state/ThresholdMapper.ts | 0 | https://github.com/grafana/grafana/commit/5a06ed431cc3bd97759ed514589fbea4ba236777 | [
0.00017704350466374308,
0.0001715852558845654,
0.0001672299695201218,
0.00017083562852349132,
0.0000029181078389228787
] |
{
"id": 6,
"code_window": [
" onClick={[Function]}\n",
" />\n",
" <h5>\n",
" Add API Key\n",
" </h5>\n",
" <form\n",
" className=\"gf-form-group\"\n",
" onSubmit={[Function]}\n",
" >\n"
],
"labels": [
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" >\n",
" <Icon\n",
" name=\"times\"\n",
" />\n",
" </button>\n"
],
"file_path": "public/app/features/api-keys/__snapshots__/ApiKeysPage.test.tsx.snap",
"type": "replace",
"edit_start_line_idx": 55
} | // Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`Render should render API keys table if there are any keys 1`] = `
<Page
navModel={
Object {
"main": Object {
"text": "Configuration",
},
"node": Object {
"text": "Api Keys",
},
}
}
>
<PageContents
isLoading={true}
/>
</Page>
`;
exports[`Render should render CTA if there are no API keys 1`] = `
<Page
navModel={
Object {
"main": Object {
"text": "Configuration",
},
"node": Object {
"text": "Api Keys",
},
}
}
>
<PageContents
isLoading={false}
>
<EmptyListCTA
buttonIcon="key-skeleton-alt"
buttonLink="#"
buttonTitle=" New API Key"
onClick={[Function]}
proTip="Remember you can provide view-only API access to other applications."
title="You haven't added any API Keys yet."
/>
<Component
in={false}
>
<div
className="cta-form"
>
<IconButton
className="cta-form__close btn btn-transparent"
name="times"
onClick={[Function]}
/>
<h5>
Add API Key
</h5>
<form
className="gf-form-group"
onSubmit={[Function]}
>
<div
className="gf-form-inline"
>
<div
className="gf-form max-width-21"
>
<span
className="gf-form-label"
>
Key name
</span>
<Input
className="gf-form-input"
onChange={[Function]}
placeholder="Name"
type="text"
value=""
/>
</div>
<div
className="gf-form"
>
<span
className="gf-form-label"
>
Role
</span>
<span
className="gf-form-select-wrapper"
>
<select
className="gf-form-input gf-size-auto"
onChange={[Function]}
value="Viewer"
>
<option
key="Viewer"
label="Viewer"
value="Viewer"
>
Viewer
</option>
<option
key="Editor"
label="Editor"
value="Editor"
>
Editor
</option>
<option
key="Admin"
label="Admin"
value="Admin"
>
Admin
</option>
</select>
</span>
</div>
<div
className="gf-form max-width-21"
>
<Component
tooltip="The api key life duration. For example 1d if your key is going to last for one day. All the supported units are: s,m,h,d,w,M,y"
>
Time to live
</Component>
<Input
className="gf-form-input"
onChange={[Function]}
placeholder="1d"
type="text"
validationEvents={
Object {
"onBlur": Array [
Object {
"errorMessage": "Not a valid duration",
"rule": [Function],
},
],
}
}
value=""
/>
</div>
<div
className="gf-form"
>
<button
className="btn gf-form-btn btn-primary"
>
Add
</button>
</div>
</div>
</form>
</div>
</Component>
</PageContents>
</Page>
`;
| public/app/features/api-keys/__snapshots__/ApiKeysPage.test.tsx.snap | 1 | https://github.com/grafana/grafana/commit/5a06ed431cc3bd97759ed514589fbea4ba236777 | [
0.9404770135879517,
0.05659200996160507,
0.00016752697410993278,
0.000221692695049569,
0.22098518908023834
] |
{
"id": 6,
"code_window": [
" onClick={[Function]}\n",
" />\n",
" <h5>\n",
" Add API Key\n",
" </h5>\n",
" <form\n",
" className=\"gf-form-group\"\n",
" onSubmit={[Function]}\n",
" >\n"
],
"labels": [
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" >\n",
" <Icon\n",
" name=\"times\"\n",
" />\n",
" </button>\n"
],
"file_path": "public/app/features/api-keys/__snapshots__/ApiKeysPage.test.tsx.snap",
"type": "replace",
"edit_start_line_idx": 55
} | import { locale, scaledUnits, simpleCountUnit, toFixedUnit, ValueFormatCategory, stringFormater } from './valueFormats';
import {
dateTimeAsIso,
dateTimeAsIsoNoDateIfToday,
dateTimeAsUS,
dateTimeAsUSNoDateIfToday,
getDateTimeAsLocalFormat,
dateTimeFromNow,
toClockMilliseconds,
toClockSeconds,
toDays,
toDurationInDaysHoursMinutesSeconds,
toDurationInHoursMinutesSeconds,
toDurationInMilliseconds,
toDurationInSeconds,
toHours,
toMicroSeconds,
toMilliSeconds,
toMinutes,
toNanoSeconds,
toSeconds,
toTimeTicks,
} from './dateTimeFormatters';
import { toHex, sci, toHex0x, toPercent, toPercentUnit } from './arithmeticFormatters';
import { binaryPrefix, currency, SIPrefix } from './symbolFormatters';
export const getCategories = (): ValueFormatCategory[] => [
{
name: 'Misc',
formats: [
{ name: 'none', id: 'none', fn: toFixedUnit('') },
{ name: 'String', id: 'string', fn: stringFormater },
{
name: 'short',
id: 'short',
fn: scaledUnits(1000, ['', ' K', ' Mil', ' Bil', ' Tri', ' Quadr', ' Quint', ' Sext', ' Sept']),
},
{ name: 'Percent (0-100)', id: 'percent', fn: toPercent },
{ name: 'Percent (0.0-1.0)', id: 'percentunit', fn: toPercentUnit },
{ name: 'Humidity (%H)', id: 'humidity', fn: toFixedUnit('%H') },
{ name: 'Decibel', id: 'dB', fn: toFixedUnit('dB') },
{ name: 'Hexadecimal (0x)', id: 'hex0x', fn: toHex0x },
{ name: 'Hexadecimal', id: 'hex', fn: toHex },
{ name: 'Scientific notation', id: 'sci', fn: sci },
{ name: 'Locale format', id: 'locale', fn: locale },
{ name: 'Pixels', id: 'pixel', fn: toFixedUnit('px') },
],
},
{
name: 'Acceleration',
formats: [
{ name: 'Meters/sec²', id: 'accMS2', fn: toFixedUnit('m/sec²') },
{ name: 'Feet/sec²', id: 'accFS2', fn: toFixedUnit('f/sec²') },
{ name: 'G unit', id: 'accG', fn: toFixedUnit('g') },
],
},
{
name: 'Angle',
formats: [
{ name: 'Degrees (°)', id: 'degree', fn: toFixedUnit('°') },
{ name: 'Radians', id: 'radian', fn: toFixedUnit('rad') },
{ name: 'Gradian', id: 'grad', fn: toFixedUnit('grad') },
{ name: 'Arc Minutes', id: 'arcmin', fn: toFixedUnit('arcmin') },
{ name: 'Arc Seconds', id: 'arcsec', fn: toFixedUnit('arcsec') },
],
},
{
name: 'Area',
formats: [
{ name: 'Square Meters (m²)', id: 'areaM2', fn: toFixedUnit('m²') },
{ name: 'Square Feet (ft²)', id: 'areaF2', fn: toFixedUnit('ft²') },
{ name: 'Square Miles (mi²)', id: 'areaMI2', fn: toFixedUnit('mi²') },
],
},
{
name: 'Computation',
formats: [
{ name: 'FLOP/s', id: 'flops', fn: SIPrefix('FLOP/s') },
{ name: 'MFLOP/s', id: 'mflops', fn: SIPrefix('FLOP/s', 2) },
{ name: 'GFLOP/s', id: 'gflops', fn: SIPrefix('FLOP/s', 3) },
{ name: 'TFLOP/s', id: 'tflops', fn: SIPrefix('FLOP/s', 4) },
{ name: 'PFLOP/s', id: 'pflops', fn: SIPrefix('FLOP/s', 5) },
{ name: 'EFLOP/s', id: 'eflops', fn: SIPrefix('FLOP/s', 6) },
{ name: 'ZFLOP/s', id: 'zflops', fn: SIPrefix('FLOP/s', 7) },
{ name: 'YFLOP/s', id: 'yflops', fn: SIPrefix('FLOP/s', 8) },
],
},
{
name: 'Concentration',
formats: [
{ name: 'parts-per-million (ppm)', id: 'ppm', fn: toFixedUnit('ppm') },
{ name: 'parts-per-billion (ppb)', id: 'conppb', fn: toFixedUnit('ppb') },
{ name: 'nanogram per cubic meter (ng/m³)', id: 'conngm3', fn: toFixedUnit('ng/m³') },
{ name: 'nanogram per normal cubic meter (ng/Nm³)', id: 'conngNm3', fn: toFixedUnit('ng/Nm³') },
{ name: 'microgram per cubic meter (μg/m³)', id: 'conμgm3', fn: toFixedUnit('μg/m³') },
{ name: 'microgram per normal cubic meter (μg/Nm³)', id: 'conμgNm3', fn: toFixedUnit('μg/Nm³') },
{ name: 'milligram per cubic meter (mg/m³)', id: 'conmgm3', fn: toFixedUnit('mg/m³') },
{ name: 'milligram per normal cubic meter (mg/Nm³)', id: 'conmgNm3', fn: toFixedUnit('mg/Nm³') },
{ name: 'gram per cubic meter (g/m³)', id: 'congm3', fn: toFixedUnit('g/m³') },
{ name: 'gram per normal cubic meter (g/Nm³)', id: 'congNm3', fn: toFixedUnit('g/Nm³') },
{ name: 'milligrams per decilitre (mg/dL)', id: 'conmgdL', fn: toFixedUnit('mg/dL') },
{ name: 'millimoles per litre (mmol/L)', id: 'conmmolL', fn: toFixedUnit('mmol/L') },
],
},
{
name: 'Currency',
formats: [
{ name: 'Dollars ($)', id: 'currencyUSD', fn: currency('$') },
{ name: 'Pounds (£)', id: 'currencyGBP', fn: currency('£') },
{ name: 'Euro (€)', id: 'currencyEUR', fn: currency('€') },
{ name: 'Yen (¥)', id: 'currencyJPY', fn: currency('¥') },
{ name: 'Rubles (₽)', id: 'currencyRUB', fn: currency('₽') },
{ name: 'Hryvnias (₴)', id: 'currencyUAH', fn: currency('₴') },
{ name: 'Real (R$)', id: 'currencyBRL', fn: currency('R$') },
{ name: 'Danish Krone (kr)', id: 'currencyDKK', fn: currency('kr', true) },
{ name: 'Icelandic Króna (kr)', id: 'currencyISK', fn: currency('kr', true) },
{ name: 'Norwegian Krone (kr)', id: 'currencyNOK', fn: currency('kr', true) },
{ name: 'Swedish Krona (kr)', id: 'currencySEK', fn: currency('kr', true) },
{ name: 'Czech koruna (czk)', id: 'currencyCZK', fn: currency('czk') },
{ name: 'Swiss franc (CHF)', id: 'currencyCHF', fn: currency('CHF') },
{ name: 'Polish Złoty (PLN)', id: 'currencyPLN', fn: currency('PLN') },
{ name: 'Bitcoin (฿)', id: 'currencyBTC', fn: currency('฿') },
{ name: 'Milli Bitcoin (฿)', id: 'currencymBTC', fn: currency('mBTC') },
{ name: 'Micro Bitcoin (฿)', id: 'currencyμBTC', fn: currency('μBTC') },
{ name: 'South African Rand (R)', id: 'currencyZAR', fn: currency('R') },
{ name: 'Indian Rupee (₹)', id: 'currencyINR', fn: currency('₹') },
{ name: 'South Korean Won (₩)', id: 'currencyKRW', fn: currency('₩') },
],
},
{
name: 'Data',
formats: [
{ name: 'bytes(IEC)', id: 'bytes', fn: binaryPrefix('B') },
{ name: 'bytes(SI)', id: 'decbytes', fn: SIPrefix('B') },
{ name: 'bits(IEC)', id: 'bits', fn: binaryPrefix('b') },
{ name: 'bits(SI)', id: 'decbits', fn: SIPrefix('b') },
{ name: 'kibibytes', id: 'kbytes', fn: binaryPrefix('B', 1) },
{ name: 'kilobytes', id: 'deckbytes', fn: SIPrefix('B', 1) },
{ name: 'mebibytes', id: 'mbytes', fn: binaryPrefix('B', 2) },
{ name: 'megabytes', id: 'decmbytes', fn: SIPrefix('B', 2) },
{ name: 'gibibytes', id: 'gbytes', fn: binaryPrefix('B', 3) },
{ name: 'gigabytes', id: 'decgbytes', fn: SIPrefix('B', 3) },
{ name: 'tebibytes', id: 'tbytes', fn: binaryPrefix('B', 4) },
{ name: 'terabytes', id: 'dectbytes', fn: SIPrefix('B', 4) },
{ name: 'pebibytes', id: 'pbytes', fn: binaryPrefix('B', 5) },
{ name: 'petabytes', id: 'decpbytes', fn: SIPrefix('B', 5) },
],
},
{
name: 'Data rate',
formats: [
{ name: 'packets/sec', id: 'pps', fn: SIPrefix('p/s') },
{ name: 'bytes/sec(IEC)', id: 'Bps', fn: binaryPrefix('B/s') },
{ name: 'bytes/sec(SI)', id: 'decBps', fn: SIPrefix('B/s') },
{ name: 'bits/sec(IEC)', id: 'bps', fn: binaryPrefix('b/s') },
{ name: 'bits/sec(SI)', id: 'decbps', fn: SIPrefix('b/s') },
{ name: 'kibibytes/sec', id: 'KiBs', fn: binaryPrefix('B/s', 1) },
{ name: 'kibibits/sec', id: 'Kibits', fn: binaryPrefix('b/s', 1) },
{ name: 'kilobytes/sec', id: 'KBs', fn: SIPrefix('B/s', 1) },
{ name: 'kilobits/sec', id: 'Kbits', fn: SIPrefix('b/s', 1) },
{ name: 'mibibytes/sec', id: 'MiBs', fn: binaryPrefix('B/s', 2) },
{ name: 'mibibits/sec', id: 'Mibits', fn: binaryPrefix('b/s', 2) },
{ name: 'megabytes/sec', id: 'MBs', fn: SIPrefix('B/s', 2) },
{ name: 'megabits/sec', id: 'Mbits', fn: SIPrefix('b/s', 2) },
{ name: 'gibibytes/sec', id: 'GiBs', fn: binaryPrefix('B/s', 3) },
{ name: 'gibibits/sec', id: 'Gibits', fn: binaryPrefix('b/s', 3) },
{ name: 'gigabytes/sec', id: 'GBs', fn: SIPrefix('B/s', 3) },
{ name: 'gigabits/sec', id: 'Gbits', fn: SIPrefix('b/s', 3) },
{ name: 'tebibytes/sec', id: 'TiBs', fn: binaryPrefix('B/s', 4) },
{ name: 'tebibits/sec', id: 'Tibits', fn: binaryPrefix('b/s', 4) },
{ name: 'terabytes/sec', id: 'TBs', fn: SIPrefix('B/s', 4) },
{ name: 'terabits/sec', id: 'Tbits', fn: SIPrefix('b/s', 4) },
{ name: 'petibytes/sec', id: 'PiBs', fn: binaryPrefix('B/s', 5) },
{ name: 'petibits/sec', id: 'Pibits', fn: binaryPrefix('b/s', 5) },
{ name: 'petabytes/sec', id: 'PBs', fn: SIPrefix('B/s', 5) },
{ name: 'petabits/sec', id: 'Pbits', fn: SIPrefix('b/s', 5) },
],
},
{
name: 'Date & time',
formats: [
{ name: 'Datetime ISO', id: 'dateTimeAsIso', fn: dateTimeAsIso },
{ name: 'Datetime ISO (No date if today)', id: 'dateTimeAsIsoNoDateIfToday', fn: dateTimeAsIsoNoDateIfToday },
{ name: 'Datetime US', id: 'dateTimeAsUS', fn: dateTimeAsUS },
{ name: 'Datetime US (No date if today)', id: 'dateTimeAsUSNoDateIfToday', fn: dateTimeAsUSNoDateIfToday },
{ name: 'Datetime local', id: 'dateTimeAsLocal', fn: getDateTimeAsLocalFormat() },
{ name: 'From Now', id: 'dateTimeFromNow', fn: dateTimeFromNow },
],
},
{
name: 'Energy',
formats: [
{ name: 'Watt (W)', id: 'watt', fn: SIPrefix('W') },
{ name: 'Kilowatt (kW)', id: 'kwatt', fn: SIPrefix('W', 1) },
{ name: 'Megawatt (MW)', id: 'megwatt', fn: SIPrefix('W', 2) },
{ name: 'Gigawatt (GW)', id: 'gwatt', fn: SIPrefix('W', 3) },
{ name: 'Milliwatt (mW)', id: 'mwatt', fn: SIPrefix('W', -1) },
{ name: 'Watt per square meter (W/m²)', id: 'Wm2', fn: toFixedUnit('W/m²') },
{ name: 'Volt-ampere (VA)', id: 'voltamp', fn: SIPrefix('VA') },
{ name: 'Kilovolt-ampere (kVA)', id: 'kvoltamp', fn: SIPrefix('VA', 1) },
{ name: 'Volt-ampere reactive (var)', id: 'voltampreact', fn: SIPrefix('var') },
{ name: 'Kilovolt-ampere reactive (kvar)', id: 'kvoltampreact', fn: SIPrefix('var', 1) },
{ name: 'Watt-hour (Wh)', id: 'watth', fn: SIPrefix('Wh') },
{ name: 'Watt-hour per Kilogram (Wh/kg)', id: 'watthperkg', fn: SIPrefix('Wh/kg') },
{ name: 'Kilowatt-hour (kWh)', id: 'kwatth', fn: SIPrefix('Wh', 1) },
{ name: 'Kilowatt-min (kWm)', id: 'kwattm', fn: SIPrefix('W-Min', 1) },
{ name: 'Ampere-hour (Ah)', id: 'amph', fn: SIPrefix('Ah') },
{ name: 'Kiloampere-hour (kAh)', id: 'kamph', fn: SIPrefix('Ah', 1) },
{ name: 'Milliampere-hour (mAh)', id: 'mamph', fn: SIPrefix('Ah', -1) },
{ name: 'Joule (J)', id: 'joule', fn: SIPrefix('J') },
{ name: 'Electron volt (eV)', id: 'ev', fn: SIPrefix('eV') },
{ name: 'Ampere (A)', id: 'amp', fn: SIPrefix('A') },
{ name: 'Kiloampere (kA)', id: 'kamp', fn: SIPrefix('A', 1) },
{ name: 'Milliampere (mA)', id: 'mamp', fn: SIPrefix('A', -1) },
{ name: 'Volt (V)', id: 'volt', fn: SIPrefix('V') },
{ name: 'Kilovolt (kV)', id: 'kvolt', fn: SIPrefix('V', 1) },
{ name: 'Millivolt (mV)', id: 'mvolt', fn: SIPrefix('V', -1) },
{ name: 'Decibel-milliwatt (dBm)', id: 'dBm', fn: SIPrefix('dBm') },
{ name: 'Ohm (Ω)', id: 'ohm', fn: SIPrefix('Ω') },
{ name: 'Kiloohm (kΩ)', id: 'kohm', fn: SIPrefix('Ω', 1) },
{ name: 'Megaohm (MΩ)', id: 'Mohm', fn: SIPrefix('Ω', 2) },
{ name: 'Farad (F)', id: 'farad', fn: SIPrefix('F') },
{ name: 'Microfarad (µF)', id: 'µfarad', fn: SIPrefix('F', -2) },
{ name: 'Nanofarad (nF)', id: 'nfarad', fn: SIPrefix('F', -3) },
{ name: 'Picofarad (pF)', id: 'pfarad', fn: SIPrefix('F', -4) },
{ name: 'Femtofarad (fF)', id: 'ffarad', fn: SIPrefix('F', -5) },
{ name: 'Henry (H)', id: 'henry', fn: SIPrefix('H') },
{ name: 'Millihenry (mH)', id: 'mhenry', fn: SIPrefix('H', -1) },
{ name: 'Microhenry (µH)', id: 'µhenry', fn: SIPrefix('H', -2) },
{ name: 'Lumens (Lm)', id: 'lumens', fn: SIPrefix('Lm') },
],
},
{
name: 'Flow',
formats: [
{ name: 'Gallons/min (gpm)', id: 'flowgpm', fn: toFixedUnit('gpm') },
{ name: 'Cubic meters/sec (cms)', id: 'flowcms', fn: toFixedUnit('cms') },
{ name: 'Cubic feet/sec (cfs)', id: 'flowcfs', fn: toFixedUnit('cfs') },
{ name: 'Cubic feet/min (cfm)', id: 'flowcfm', fn: toFixedUnit('cfm') },
{ name: 'Litre/hour', id: 'litreh', fn: toFixedUnit('L/h') },
{ name: 'Litre/min (L/min)', id: 'flowlpm', fn: toFixedUnit('L/min') },
{ name: 'milliLitre/min (mL/min)', id: 'flowmlpm', fn: toFixedUnit('mL/min') },
{ name: 'Lux (lx)', id: 'lux', fn: toFixedUnit('lux') },
],
},
{
name: 'Force',
formats: [
{ name: 'Newton-meters (Nm)', id: 'forceNm', fn: SIPrefix('Nm') },
{ name: 'Kilonewton-meters (kNm)', id: 'forcekNm', fn: SIPrefix('Nm', 1) },
{ name: 'Newtons (N)', id: 'forceN', fn: SIPrefix('N') },
{ name: 'Kilonewtons (kN)', id: 'forcekN', fn: SIPrefix('N', 1) },
],
},
{
name: 'Hash rate',
formats: [
{ name: 'hashes/sec', id: 'Hs', fn: SIPrefix('H/s') },
{ name: 'kilohashes/sec', id: 'KHs', fn: SIPrefix('H/s', 1) },
{ name: 'megahashes/sec', id: 'MHs', fn: SIPrefix('H/s', 2) },
{ name: 'gigahashes/sec', id: 'GHs', fn: SIPrefix('H/s', 3) },
{ name: 'terahashes/sec', id: 'THs', fn: SIPrefix('H/s', 4) },
{ name: 'petahashes/sec', id: 'PHs', fn: SIPrefix('H/s', 5) },
{ name: 'exahashes/sec', id: 'EHs', fn: SIPrefix('H/s', 6) },
],
},
{
name: 'Mass',
formats: [
{ name: 'milligram (mg)', id: 'massmg', fn: SIPrefix('g', -1) },
{ name: 'gram (g)', id: 'massg', fn: SIPrefix('g') },
{ name: 'kilogram (kg)', id: 'masskg', fn: SIPrefix('g', 1) },
{ name: 'metric ton (t)', id: 'masst', fn: toFixedUnit('t') },
],
},
{
name: 'Length',
formats: [
{ name: 'millimeter (mm)', id: 'lengthmm', fn: SIPrefix('m', -1) },
{ name: 'feet (ft)', id: 'lengthft', fn: toFixedUnit('ft') },
{ name: 'meter (m)', id: 'lengthm', fn: SIPrefix('m') },
{ name: 'kilometer (km)', id: 'lengthkm', fn: SIPrefix('m', 1) },
{ name: 'mile (mi)', id: 'lengthmi', fn: toFixedUnit('mi') },
],
},
{
name: 'Pressure',
formats: [
{ name: 'Millibars', id: 'pressurembar', fn: SIPrefix('bar', -1) },
{ name: 'Bars', id: 'pressurebar', fn: SIPrefix('bar') },
{ name: 'Kilobars', id: 'pressurekbar', fn: SIPrefix('bar', 1) },
{ name: 'Pascals', id: 'pressurepa', fn: SIPrefix('Pa') },
{ name: 'Hectopascals', id: 'pressurehpa', fn: toFixedUnit('hPa') },
{ name: 'Kilopascals', id: 'pressurekpa', fn: toFixedUnit('kPa') },
{ name: 'Inches of mercury', id: 'pressurehg', fn: toFixedUnit('"Hg') },
{ name: 'PSI', id: 'pressurepsi', fn: scaledUnits(1000, ['psi', 'ksi', 'Mpsi']) },
],
},
{
name: 'Radiation',
formats: [
{ name: 'Becquerel (Bq)', id: 'radbq', fn: SIPrefix('Bq') },
{ name: 'curie (Ci)', id: 'radci', fn: SIPrefix('Ci') },
{ name: 'Gray (Gy)', id: 'radgy', fn: SIPrefix('Gy') },
{ name: 'rad', id: 'radrad', fn: SIPrefix('rad') },
{ name: 'Sievert (Sv)', id: 'radsv', fn: SIPrefix('Sv') },
{ name: 'milliSievert (mSv)', id: 'radmsv', fn: SIPrefix('Sv', -1) },
{ name: 'microSievert (µSv)', id: 'radusv', fn: SIPrefix('Sv', -2) },
{ name: 'rem', id: 'radrem', fn: SIPrefix('rem') },
{ name: 'Exposure (C/kg)', id: 'radexpckg', fn: SIPrefix('C/kg') },
{ name: 'roentgen (R)', id: 'radr', fn: SIPrefix('R') },
{ name: 'Sievert/hour (Sv/h)', id: 'radsvh', fn: SIPrefix('Sv/h') },
{ name: 'milliSievert/hour (mSv/h)', id: 'radmsvh', fn: SIPrefix('Sv/h', -1) },
{ name: 'microSievert/hour (µSv/h)', id: 'radusvh', fn: SIPrefix('Sv/h', -2) },
],
},
{
name: 'Rotational Speed',
formats: [
{ name: 'Revolutions per minute (rpm)', id: 'rotrpm', fn: toFixedUnit('rpm') },
{ name: 'Hertz (Hz)', id: 'rothz', fn: SIPrefix('Hz') },
{ name: 'Radians per second (rad/s)', id: 'rotrads', fn: toFixedUnit('rad/s') },
{ name: 'Degrees per second (°/s)', id: 'rotdegs', fn: toFixedUnit('°/s') },
],
},
{
name: 'Temperature',
formats: [
{ name: 'Celsius (°C)', id: 'celsius', fn: toFixedUnit('°C') },
{ name: 'Fahrenheit (°F)', id: 'fahrenheit', fn: toFixedUnit('°F') },
{ name: 'Kelvin (K)', id: 'kelvin', fn: toFixedUnit('K') },
],
},
{
name: 'Time',
formats: [
{ name: 'Hertz (1/s)', id: 'hertz', fn: SIPrefix('Hz') },
{ name: 'nanoseconds (ns)', id: 'ns', fn: toNanoSeconds },
{ name: 'microseconds (µs)', id: 'µs', fn: toMicroSeconds },
{ name: 'milliseconds (ms)', id: 'ms', fn: toMilliSeconds },
{ name: 'seconds (s)', id: 's', fn: toSeconds },
{ name: 'minutes (m)', id: 'm', fn: toMinutes },
{ name: 'hours (h)', id: 'h', fn: toHours },
{ name: 'days (d)', id: 'd', fn: toDays },
{ name: 'duration (ms)', id: 'dtdurationms', fn: toDurationInMilliseconds },
{ name: 'duration (s)', id: 'dtdurations', fn: toDurationInSeconds },
{ name: 'duration (hh:mm:ss)', id: 'dthms', fn: toDurationInHoursMinutesSeconds },
{ name: 'duration (d hh:mm:ss)', id: 'dtdhms', fn: toDurationInDaysHoursMinutesSeconds },
{ name: 'Timeticks (s/100)', id: 'timeticks', fn: toTimeTicks },
{ name: 'clock (ms)', id: 'clockms', fn: toClockMilliseconds },
{ name: 'clock (s)', id: 'clocks', fn: toClockSeconds },
],
},
{
name: 'Throughput',
formats: [
{ name: 'counts/sec (cps)', id: 'cps', fn: simpleCountUnit('cps') },
{ name: 'ops/sec (ops)', id: 'ops', fn: simpleCountUnit('ops') },
{ name: 'requests/sec (rps)', id: 'reqps', fn: simpleCountUnit('reqps') },
{ name: 'reads/sec (rps)', id: 'rps', fn: simpleCountUnit('rps') },
{ name: 'writes/sec (wps)', id: 'wps', fn: simpleCountUnit('wps') },
{ name: 'I/O ops/sec (iops)', id: 'iops', fn: simpleCountUnit('iops') },
{ name: 'counts/min (cpm)', id: 'cpm', fn: simpleCountUnit('cpm') },
{ name: 'ops/min (opm)', id: 'opm', fn: simpleCountUnit('opm') },
{ name: 'reads/min (rpm)', id: 'rpm', fn: simpleCountUnit('rpm') },
{ name: 'writes/min (wpm)', id: 'wpm', fn: simpleCountUnit('wpm') },
],
},
{
name: 'Velocity',
formats: [
{ name: 'meters/second (m/s)', id: 'velocityms', fn: toFixedUnit('m/s') },
{ name: 'kilometers/hour (km/h)', id: 'velocitykmh', fn: toFixedUnit('km/h') },
{ name: 'miles/hour (mph)', id: 'velocitymph', fn: toFixedUnit('mph') },
{ name: 'knot (kn)', id: 'velocityknot', fn: toFixedUnit('kn') },
],
},
{
name: 'Volume',
formats: [
{ name: 'millilitre (mL)', id: 'mlitre', fn: SIPrefix('L', -1) },
{ name: 'litre (L)', id: 'litre', fn: SIPrefix('L') },
{ name: 'cubic meter', id: 'm3', fn: toFixedUnit('m³') },
{ name: 'Normal cubic meter', id: 'Nm3', fn: toFixedUnit('Nm³') },
{ name: 'cubic decimeter', id: 'dm3', fn: toFixedUnit('dm³') },
{ name: 'gallons', id: 'gallons', fn: toFixedUnit('gal') },
],
},
];
| packages/grafana-data/src/valueFormats/categories.ts | 0 | https://github.com/grafana/grafana/commit/5a06ed431cc3bd97759ed514589fbea4ba236777 | [
0.00018053766689263284,
0.00017500738613307476,
0.00016991532174870372,
0.00017491736798547208,
0.000002178859858759097
] |
{
"id": 6,
"code_window": [
" onClick={[Function]}\n",
" />\n",
" <h5>\n",
" Add API Key\n",
" </h5>\n",
" <form\n",
" className=\"gf-form-group\"\n",
" onSubmit={[Function]}\n",
" >\n"
],
"labels": [
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" >\n",
" <Icon\n",
" name=\"times\"\n",
" />\n",
" </button>\n"
],
"file_path": "public/app/features/api-keys/__snapshots__/ApiKeysPage.test.tsx.snap",
"type": "replace",
"edit_start_line_idx": 55
} | import cloneDeep from 'lodash/cloneDeep';
import { ConstantVariableModel } from '../types';
import { dispatch } from '../../../store/store';
import { setOptionAsCurrent, setOptionFromUrl } from '../state/actions';
import { VariableAdapter } from '../adapters';
import { constantVariableReducer, initialConstantVariableModelState } from './reducer';
import { OptionsPicker } from '../pickers';
import { ConstantVariableEditor } from './ConstantVariableEditor';
import { updateConstantVariableOptions } from './actions';
import { toVariableIdentifier } from '../state/types';
export const createConstantVariableAdapter = (): VariableAdapter<ConstantVariableModel> => {
return {
id: 'constant',
description: 'Define a hidden constant variable, useful for metric prefixes in dashboards you want to share',
name: 'Constant',
initialState: initialConstantVariableModelState,
reducer: constantVariableReducer,
picker: OptionsPicker,
editor: ConstantVariableEditor,
dependsOn: () => {
return false;
},
setValue: async (variable, option, emitChanges = false) => {
await dispatch(setOptionAsCurrent(toVariableIdentifier(variable), option, emitChanges));
},
setValueFromUrl: async (variable, urlValue) => {
await dispatch(setOptionFromUrl(toVariableIdentifier(variable), urlValue));
},
updateOptions: async variable => {
await dispatch(updateConstantVariableOptions(toVariableIdentifier(variable)));
},
getSaveModel: variable => {
const { index, id, initLock, global, ...rest } = cloneDeep(variable);
return rest;
},
getValueForUrl: variable => {
return variable.current.value;
},
};
};
| public/app/features/variables/constant/adapter.ts | 0 | https://github.com/grafana/grafana/commit/5a06ed431cc3bd97759ed514589fbea4ba236777 | [
0.00017507186566945165,
0.00017299610772170126,
0.00016928446711972356,
0.00017323679639957845,
0.0000020067643617949216
] |
{
"id": 6,
"code_window": [
" onClick={[Function]}\n",
" />\n",
" <h5>\n",
" Add API Key\n",
" </h5>\n",
" <form\n",
" className=\"gf-form-group\"\n",
" onSubmit={[Function]}\n",
" >\n"
],
"labels": [
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" >\n",
" <Icon\n",
" name=\"times\"\n",
" />\n",
" </button>\n"
],
"file_path": "public/app/features/api-keys/__snapshots__/ApiKeysPage.test.tsx.snap",
"type": "replace",
"edit_start_line_idx": 55
} | import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import sourceMaps from 'rollup-plugin-sourcemaps';
import { terser } from 'rollup-plugin-terser';
const pkg = require('./package.json');
const libraryName = pkg.name;
const buildCjsPackage = ({ env }) => {
return {
input: `compiled/index.js`,
output: [
{
file: `dist/index.${env}.js`,
name: libraryName,
format: 'cjs',
sourcemap: true,
exports: 'named',
globals: {},
},
],
external: ['lodash', '@grafana/ui', '@grafana/data'], // Use Lodash from grafana
plugins: [
commonjs({
include: /node_modules/,
namedExports: {
'../../node_modules/lodash/lodash.js': [
'flatten',
'find',
'upperFirst',
'debounce',
'isNil',
'isNumber',
'flattenDeep',
'map',
'chunk',
'sortBy',
'uniqueId',
'zip',
],
},
}),
resolve(),
sourceMaps(),
env === 'production' && terser(),
],
};
};
export default [buildCjsPackage({ env: 'development' }), buildCjsPackage({ env: 'production' })];
| packages/grafana-runtime/rollup.config.ts | 0 | https://github.com/grafana/grafana/commit/5a06ed431cc3bd97759ed514589fbea4ba236777 | [
0.0001777936122380197,
0.00017424406541977078,
0.00017167955229524523,
0.00017349483096040785,
0.000002276434315717779
] |
{
"id": 7,
"code_window": [
" className=\"gf-form-group\"\n",
" onSubmit={[Function]}\n",
" >\n",
" <div\n",
" className=\"gf-form-inline\"\n",
" >\n",
" <div\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <h5>\n",
" Add API Key\n",
" </h5>\n"
],
"file_path": "public/app/features/api-keys/__snapshots__/ApiKeysPage.test.tsx.snap",
"type": "add",
"edit_start_line_idx": 63
} | // Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`Render should render API keys table if there are any keys 1`] = `
<Page
navModel={
Object {
"main": Object {
"text": "Configuration",
},
"node": Object {
"text": "Api Keys",
},
}
}
>
<PageContents
isLoading={true}
/>
</Page>
`;
exports[`Render should render CTA if there are no API keys 1`] = `
<Page
navModel={
Object {
"main": Object {
"text": "Configuration",
},
"node": Object {
"text": "Api Keys",
},
}
}
>
<PageContents
isLoading={false}
>
<EmptyListCTA
buttonIcon="key-skeleton-alt"
buttonLink="#"
buttonTitle=" New API Key"
onClick={[Function]}
proTip="Remember you can provide view-only API access to other applications."
title="You haven't added any API Keys yet."
/>
<Component
in={false}
>
<div
className="cta-form"
>
<IconButton
className="cta-form__close btn btn-transparent"
name="times"
onClick={[Function]}
/>
<h5>
Add API Key
</h5>
<form
className="gf-form-group"
onSubmit={[Function]}
>
<div
className="gf-form-inline"
>
<div
className="gf-form max-width-21"
>
<span
className="gf-form-label"
>
Key name
</span>
<Input
className="gf-form-input"
onChange={[Function]}
placeholder="Name"
type="text"
value=""
/>
</div>
<div
className="gf-form"
>
<span
className="gf-form-label"
>
Role
</span>
<span
className="gf-form-select-wrapper"
>
<select
className="gf-form-input gf-size-auto"
onChange={[Function]}
value="Viewer"
>
<option
key="Viewer"
label="Viewer"
value="Viewer"
>
Viewer
</option>
<option
key="Editor"
label="Editor"
value="Editor"
>
Editor
</option>
<option
key="Admin"
label="Admin"
value="Admin"
>
Admin
</option>
</select>
</span>
</div>
<div
className="gf-form max-width-21"
>
<Component
tooltip="The api key life duration. For example 1d if your key is going to last for one day. All the supported units are: s,m,h,d,w,M,y"
>
Time to live
</Component>
<Input
className="gf-form-input"
onChange={[Function]}
placeholder="1d"
type="text"
validationEvents={
Object {
"onBlur": Array [
Object {
"errorMessage": "Not a valid duration",
"rule": [Function],
},
],
}
}
value=""
/>
</div>
<div
className="gf-form"
>
<button
className="btn gf-form-btn btn-primary"
>
Add
</button>
</div>
</div>
</form>
</div>
</Component>
</PageContents>
</Page>
`;
| public/app/features/api-keys/__snapshots__/ApiKeysPage.test.tsx.snap | 1 | https://github.com/grafana/grafana/commit/5a06ed431cc3bd97759ed514589fbea4ba236777 | [
0.9738966226577759,
0.057887692004442215,
0.00016678297834005207,
0.0002637686557136476,
0.22900338470935822
] |
{
"id": 7,
"code_window": [
" className=\"gf-form-group\"\n",
" onSubmit={[Function]}\n",
" >\n",
" <div\n",
" className=\"gf-form-inline\"\n",
" >\n",
" <div\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <h5>\n",
" Add API Key\n",
" </h5>\n"
],
"file_path": "public/app/features/api-keys/__snapshots__/ApiKeysPage.test.tsx.snap",
"type": "add",
"edit_start_line_idx": 63
} | import React, { PureComponent } from 'react';
import { dateTimeFormat } from '@grafana/data';
import { SyncInfo, UserDTO } from 'app/types';
import { Button, LinkButton } from '@grafana/ui';
interface Props {
ldapSyncInfo: SyncInfo;
user: UserDTO;
onUserSync: () => void;
}
interface State {}
const format = 'dddd YYYY-MM-DD HH:mm zz';
const debugLDAPMappingBaseURL = '/admin/ldap';
export class UserLdapSyncInfo extends PureComponent<Props, State> {
onUserSync = () => {
this.props.onUserSync();
};
render() {
const { ldapSyncInfo, user } = this.props;
const prevSyncSuccessful = ldapSyncInfo && ldapSyncInfo.prevSync;
const nextSyncSuccessful = ldapSyncInfo && ldapSyncInfo.nextSync;
const nextSyncTime = nextSyncSuccessful ? dateTimeFormat(ldapSyncInfo.nextSync, { format }) : '';
const prevSyncTime = prevSyncSuccessful ? dateTimeFormat(ldapSyncInfo.prevSync!.started, { format }) : '';
const debugLDAPMappingURL = `${debugLDAPMappingBaseURL}?user=${user && user.login}`;
return (
<>
<h3 className="page-heading">LDAP Synchronisation</h3>
<div className="gf-form-group">
<div className="gf-form">
<table className="filter-table form-inline">
<tbody>
<tr>
<td>External sync</td>
<td>User synced via LDAP – some changes must be done in LDAP or mappings.</td>
<td>
<span className="label label-tag">LDAP</span>
</td>
</tr>
<tr>
{ldapSyncInfo.enabled ? (
<>
<td>Next scheduled synchronisation</td>
<td colSpan={2}>{nextSyncTime}</td>
</>
) : (
<>
<td>Next scheduled synchronisation</td>
<td colSpan={2}>Not enabled</td>
</>
)}
</tr>
<tr>
{prevSyncSuccessful ? (
<>
<td>Last synchronisation</td>
<td>{prevSyncTime}</td>
<td>Successful</td>
</>
) : (
<td colSpan={3}>Last synchronisation</td>
)}
</tr>
</tbody>
</table>
</div>
<div className="gf-form-button-row">
<Button variant="secondary" onClick={this.onUserSync}>
Sync user
</Button>
<LinkButton variant="secondary" href={debugLDAPMappingURL}>
Debug LDAP Mapping
</LinkButton>
</div>
</div>
</>
);
}
}
| public/app/features/admin/UserLdapSyncInfo.tsx | 0 | https://github.com/grafana/grafana/commit/5a06ed431cc3bd97759ed514589fbea4ba236777 | [
0.001619952730834484,
0.000335166318109259,
0.00016610401507932693,
0.00017053600458893925,
0.0004544305265881121
] |
{
"id": 7,
"code_window": [
" className=\"gf-form-group\"\n",
" onSubmit={[Function]}\n",
" >\n",
" <div\n",
" className=\"gf-form-inline\"\n",
" >\n",
" <div\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <h5>\n",
" Add API Key\n",
" </h5>\n"
],
"file_path": "public/app/features/api-keys/__snapshots__/ApiKeysPage.test.tsx.snap",
"type": "add",
"edit_start_line_idx": 63
} | # # config file version
apiVersion: 1
# # list of datasources that should be deleted from the database
#deleteDatasources:
# - name: Graphite
# orgId: 1
# # list of datasources to insert/update depending
# # on what's available in the database
#datasources:
# # <string, required> name of the datasource. Required
# - name: Graphite
# # <string, required> datasource type. Required
# type: graphite
# # <string, required> access mode. direct or proxy. Required
# access: proxy
# # <int> org id. will default to orgId 1 if not specified
# orgId: 1
# # <string> url
# url: http://localhost:8080
# # <string> database password, if used
# password:
# # <string> database user, if used
# user:
# # <string> database name, if used
# database:
# # <bool> enable/disable basic auth
# basicAuth:
# # <string> basic auth username
# basicAuthUser:
# # <string> basic auth password
# basicAuthPassword:
# # <bool> enable/disable with credentials headers
# withCredentials:
# # <bool> mark as default datasource. Max one per org
# isDefault:
# # <map> fields that will be converted to json and stored in json_data
# jsonData:
# graphiteVersion: "1.1"
# tlsAuth: true
# tlsAuthWithCACert: true
# httpHeaderName1: "Authorization"
# # <string> json object of data that will be encrypted.
# secureJsonData:
# tlsCACert: "..."
# tlsClientCert: "..."
# tlsClientKey: "..."
# # <openshift\kubernetes token example>
# httpHeaderValue1: "Bearer xf5yhfkpsnmgo"
# version: 1
# # <bool> allow users to edit datasources from the UI.
# editable: false
| conf/provisioning/datasources/sample.yaml | 0 | https://github.com/grafana/grafana/commit/5a06ed431cc3bd97759ed514589fbea4ba236777 | [
0.0001711147342575714,
0.00016748793132137507,
0.0001638142130104825,
0.00016742697334848344,
0.000002438977844576584
] |
{
"id": 7,
"code_window": [
" className=\"gf-form-group\"\n",
" onSubmit={[Function]}\n",
" >\n",
" <div\n",
" className=\"gf-form-inline\"\n",
" >\n",
" <div\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <h5>\n",
" Add API Key\n",
" </h5>\n"
],
"file_path": "public/app/features/api-keys/__snapshots__/ApiKeysPage.test.tsx.snap",
"type": "add",
"edit_start_line_idx": 63
} | package gtime
import (
"fmt"
"regexp"
"strconv"
"time"
)
var dateUnitPattern = regexp.MustCompile(`^(\d+)([dwMy])$`)
// ParseInterval parses an interval with support for all units that Grafana uses.
func ParseInterval(interval string) (time.Duration, error) {
result := dateUnitPattern.FindSubmatch([]byte(interval))
if len(result) != 3 {
return time.ParseDuration(interval)
}
num, _ := strconv.Atoi(string(result[1]))
period := string(result[2])
now := time.Now()
switch period {
case "d":
return now.Sub(now.AddDate(0, 0, -num)), nil
case "w":
return now.Sub(now.AddDate(0, 0, -num*7)), nil
case "M":
return now.Sub(now.AddDate(0, -num, 0)), nil
case "y":
return now.Sub(now.AddDate(-num, 0, 0)), nil
}
return 0, fmt.Errorf("ParseInterval: invalid duration %q", interval)
}
| pkg/components/gtime/gtime.go | 0 | https://github.com/grafana/grafana/commit/5a06ed431cc3bd97759ed514589fbea4ba236777 | [
0.00019079407502431422,
0.00017666679923422635,
0.00016755284741520882,
0.00017416014452464879,
0.000008701358638063539
] |
{
"id": 0,
"code_window": [
" font-family: inherit;\n",
"}\n",
"\n",
".searchbar-clear-icon {\n",
" margin: 0;\n",
" padding: 0;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" display: none;\n",
"\n"
],
"file_path": "ionic/components/searchbar/searchbar.scss",
"type": "add",
"edit_start_line_idx": 40
} | @import "../../globals.core";
// Search Bar
// --------------------------------------------------
ion-searchbar {
position: relative;
display: flex;
align-items: center;
width: 100%;
}
.searchbar-icon {
// Don't let them tap on the icon
pointer-events: none;
}
.searchbar-input-container {
position: relative;
display: block;
flex-shrink: 1;
width: 100%;
}
.searchbar-input {
@include appearance(none);
display: block;
width: 100%;
border: 0;
font-family: inherit;
}
.searchbar-clear-icon {
margin: 0;
padding: 0;
min-height: 0;
}
| ionic/components/searchbar/searchbar.scss | 1 | https://github.com/ionic-team/ionic-framework/commit/ecf93023f3a41e8922508dfcc17aeace77bc1aa8 | [
0.986732542514801,
0.19787408411502838,
0.00022968160919845104,
0.000687341031152755,
0.39442938566207886
] |
{
"id": 0,
"code_window": [
" font-family: inherit;\n",
"}\n",
"\n",
".searchbar-clear-icon {\n",
" margin: 0;\n",
" padding: 0;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" display: none;\n",
"\n"
],
"file_path": "ionic/components/searchbar/searchbar.scss",
"type": "add",
"edit_start_line_idx": 40
} |
<ion-toolbar>
<ion-title>Inset Focus</ion-title>
<ion-buttons end>
<button (click)="reload()">
Reload
</button>
</ion-buttons>
</ion-toolbar>
<ion-content>
<p>Paragraph text with a <a href="#">link</a>.</p>
<ion-list>
<ion-item>
<ion-label>Text 1:</ion-label>
<ion-input></ion-input>
</ion-item>
<ion-item>
Item with button right
<button item-right>Button 1</button>
</ion-item>
<ion-item>
<ion-label id="my-label1">Text 2:</ion-label>
<ion-input value="value"></ion-input>
</ion-item>
<button ion-item>
Button Item
</button>
<ion-item>
<ion-label>Text 3:</ion-label>
<ion-input></ion-input>
<button clear item-right>
<ion-icon name="power"></ion-icon>
</button>
</ion-item>
<ion-item>
<ion-label>Comments:</ion-label>
<ion-textarea>Comment value</ion-textarea>
</ion-item>
<ion-item>
<ion-icon name="globe" item-left></ion-icon>
<ion-label>Website:</ion-label>
<ion-input value="http://ionic.io/" type="url"></ion-input>
</ion-item>
<ion-item>
<ion-icon name="mail" item-left></ion-icon>
<ion-label>Email:</ion-label>
<ion-input value="[email protected]" type="email"></ion-input>
</ion-item>
<ion-item>
<ion-icon name="create" item-left></ion-icon>
<ion-label>Feedback:</ion-label>
<ion-textarea placeholder="Placeholder Text"></ion-textarea>
</ion-item>
<ion-item>
<ion-label>Toggle</ion-label>
<ion-toggle></ion-toggle>
</ion-item>
<ion-item>
<ion-label>More Info:</ion-label>
<ion-input placeholder="Placeholder Text"></ion-input>
<ion-icon name="flag" item-right></ion-icon>
</ion-item>
<ion-item>
<ion-label>Checkbox</ion-label>
<ion-checkbox></ion-checkbox>
</ion-item>
<ion-item>
<ion-label>Score:</ion-label>
<ion-input value="10" type="number"></ion-input>
<button outline item-right>Update</button>
</ion-item>
<ion-item>
<ion-label>First Name:</ion-label>
<ion-input value="Lightning"></ion-input>
</ion-item>
<ion-item>
<ion-label>Last Name:</ion-label>
<ion-input value="McQueen"></ion-input>
</ion-item>
<ion-item>
<ion-label>Message:</ion-label>
<ion-textarea value="KA-CHOW!"></ion-textarea>
</ion-item>
<ion-item>
Item
</ion-item>
<ion-item>
Item
</ion-item>
</ion-list>
<ion-list radio-group>
<ion-list-header>
Radios
</ion-list-header>
<ion-item>
<ion-label>Radio 1</ion-label>
<ion-radio value="1"></ion-radio>
</ion-item>
<ion-item>
<ion-label>Radio 2</ion-label>
<ion-radio value="2"></ion-radio>
</ion-item>
</ion-list>
</ion-content>
| ionic/components/input/test/input-focus/main.html | 0 | https://github.com/ionic-team/ionic-framework/commit/ecf93023f3a41e8922508dfcc17aeace77bc1aa8 | [
0.00018635491142049432,
0.00016969100397545844,
0.000164842713274993,
0.00016676225641276687,
0.000006592432328034192
] |
{
"id": 0,
"code_window": [
" font-family: inherit;\n",
"}\n",
"\n",
".searchbar-clear-icon {\n",
" margin: 0;\n",
" padding: 0;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" display: none;\n",
"\n"
],
"file_path": "ionic/components/searchbar/searchbar.scss",
"type": "add",
"edit_start_line_idx": 40
} | {
"name": "ionic-angular",
"version": "<%= ionicVersion %>",
"description": "An advanced HTML5 mobile app framework built on Angular2",
"license": "MIT",
"keywords": ["ionic", "framework", "mobile", "app", "hybrid", "webapp", "cordova"],
"repository": {
"type": "git",
"url": "https://github.com/driftyco/ionic.git#2.0`"
},
"dependencies": {
"colors": "^1.1.2",
"inquirer": "0.11.0",
"lodash": "3.10.1",
"mkdirp-no-bin": "0.5.1",
"q": "1.4.1"
},
"peerDependencies": {
"angular2": "^<%= angularVersion %>"
}
}
| scripts/npm/package.json | 0 | https://github.com/ionic-team/ionic-framework/commit/ecf93023f3a41e8922508dfcc17aeace77bc1aa8 | [
0.00017863066750578582,
0.00017146130267065018,
0.000164619050337933,
0.00017113414651248604,
0.000005724893981096102
] |
{
"id": 0,
"code_window": [
" font-family: inherit;\n",
"}\n",
"\n",
".searchbar-clear-icon {\n",
" margin: 0;\n",
" padding: 0;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" display: none;\n",
"\n"
],
"file_path": "ionic/components/searchbar/searchbar.scss",
"type": "add",
"edit_start_line_idx": 40
} |
export * from './config/bootstrap';
export * from './config/config';
export * from './config/directives';
export * from './decorators/app';
export * from './decorators/page';
export * from './components';
export * from './platform/platform';
export * from './platform/storage';
export * from './util/click-block';
export * from './util/events';
export * from './util/keyboard';
export * from './util/form';
export * from './animations/animation';
export * from './transitions/transition';
export * from './translation/translate';
export * from './translation/translate_pipe';
// these modules don't export anything
import './config/modes';
import './platform/registry';
import './animations/builtins';
import './transitions/transition-ios';
import './transitions/transition-md';
import './transitions/transition-wp';
| ionic/index.ts | 0 | https://github.com/ionic-team/ionic-framework/commit/ecf93023f3a41e8922508dfcc17aeace77bc1aa8 | [
0.0001745591580402106,
0.00017285303329117596,
0.0001711436198092997,
0.000172854692209512,
0.0000013557435067923507
] |
{
"id": 1,
"code_window": [
"\n",
" min-height: 0;\n",
"}\n"
],
"labels": [
"keep",
"keep",
"add"
],
"after_edit": [
"\n",
".searchbar-has-value.searchbar-focused .searchbar-clear-icon {\n",
" display: block;\n",
"}"
],
"file_path": "ionic/components/searchbar/searchbar.scss",
"type": "add",
"edit_start_line_idx": 45
} | import {ElementRef, Component, Directive, Host, HostBinding, HostListener, ViewChild, Input, Output, EventEmitter, Optional} from 'angular2/core';
import {NgIf, NgClass, NgControl, FORM_DIRECTIVES} from 'angular2/common';
import {Ion} from '../ion';
import {Config} from '../../config/config';
import {Icon} from '../icon/icon';
import {Button} from '../button/button';
import {isPresent, debounce} from '../../util/util';
/**
* @private
*/
@Directive({
selector: '.searchbar-input',
})
export class SearchbarInput {
@HostListener('input', ['$event'])
/**
* @private
* Don't send the input's input event
*/
private stopInput(ev) {
ev.preventDefault();
ev.stopPropagation();
}
constructor(private _elementRef: ElementRef) {}
}
/**
* @name Searchbar
* @module ionic
* @description
* Manages the display of a Searchbar which can be used to search or filter items.
*
* @usage
* ```html
* <ion-searchbar
* [(ngModel)]="myInput"
* [hideCancelButton]="shouldHideCancel"
* (input)="onInput($event)"
* (cancel)="onCancel($event)">
* </ion-searchbar>
* ```
*
* @demo /docs/v2/demos/searchbar/
* @see {@link /docs/v2/components#searchbar Searchbar Component Docs}
*/
@Component({
selector: 'ion-searchbar',
host: {
'[class.searchbar-has-value]': 'value',
'[class.searchbar-hide-cancel]': 'hideCancelButton'
},
template:
'<div class="searchbar-input-container">' +
'<button (click)="cancelSearchbar()" (mousedown)="cancelSearchbar()" [hidden]="hideCancelButton" clear dark class="searchbar-md-cancel">' +
'<ion-icon name="arrow-back"></ion-icon>' +
'</button>' +
'<div class="searchbar-search-icon"></div>' +
'<input [value]="value" (input)="inputChanged($event)" (blur)="inputBlurred()" (focus)="inputFocused()" class="searchbar-input" type="search" [attr.placeholder]="placeholder" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false">' +
'<button clear *ngIf="value" class="searchbar-clear-icon" (click)="clearInput()" (mousedown)="clearInput()"></button>' +
'</div>' +
'<button clear (click)="cancelSearchbar()" (mousedown)="cancelSearchbar()" [hidden]="hideCancelButton" class="searchbar-ios-cancel">{{cancelButtonText}}</button>',
directives: [FORM_DIRECTIVES, NgIf, NgClass, Icon, Button, SearchbarInput]
})
export class Searchbar extends Ion {
private _tmr: any;
/**
* @private
*/
@ViewChild(SearchbarInput) searchbarInput;
/**
* @input {string} Sets the cancel button text to the value passed in
*/
@Input() cancelButtonText: string;
/**
* @input {boolean} Hides the cancel button
*/
@Input() hideCancelButton: any;
/**
* @input {number} How long, in milliseconds, to wait to trigger the `input` event after each keystroke. Default `250`.
*/
@Input() debounce: number = 250;
/**
* @input {string} Sets input placeholder to the value passed in
*/
@Input() placeholder: string;
/**
* @input {any} Expression to evaluate when the Searchbar input has changed including cleared
*/
@Input() ngModel: any;
/**
* @output {event} When the Searchbar input has changed including cleared
*/
@Output() input: EventEmitter<Searchbar> = new EventEmitter();
/**
* @output {event} When the Searchbar input has blurred
*/
@Output() blur: EventEmitter<Searchbar> = new EventEmitter();
/**
* @output {event} When the Searchbar input has focused
*/
@Output() focus: EventEmitter<Searchbar> = new EventEmitter();
/**
* @output {event} When the cancel button is clicked
*/
@Output() cancel: EventEmitter<Searchbar> = new EventEmitter();
/**
* @output {event} When the clear input button is clicked
*/
@Output() clear: EventEmitter<Searchbar> = new EventEmitter();
/**
* @private
*/
value: string = '';
/**
* @private
*/
blurInput: boolean = true;
/**
* @private
*/
inputElement: any;
/**
* @private
*/
searchIconElement: any;
/**
* @private
*/
mode: string;
/**
* @private
*/
@HostBinding('class.searchbar-focused') isFocused;
/**
* @private
*/
@HostBinding('class.searchbar-left-aligned') shouldLeftAlign;
constructor(
private _elementRef: ElementRef,
private _config: Config,
@Optional() ngControl: NgControl
) {
super(_elementRef);
// If the user passed a ngControl we need to set the valueAccessor
if (ngControl) {
ngControl.valueAccessor = this;
}
}
/**
* @private
* On Initialization check for attributes
*/
ngOnInit() {
this.mode = this._config.get('mode');
let hideCancelButton = this.hideCancelButton;
if (typeof hideCancelButton === 'string') {
this.hideCancelButton = (hideCancelButton === '' || hideCancelButton === 'true');
}
this.cancelButtonText = this.cancelButtonText || 'Cancel';
this.placeholder = this.placeholder || 'Search';
if (this.ngModel) this.value = this.ngModel;
this.onChange(this.value);
this.shouldLeftAlign = this.value && this.value.trim() !== '';
// Using querySelector instead of searchbarInput because at this point it doesn't exist
this.inputElement = this._elementRef.nativeElement.querySelector('.searchbar-input');
this.searchIconElement = this._elementRef.nativeElement.querySelector('.searchbar-search-icon');
this.setElementLeft();
}
/**
* @private
* After View Initialization check the value
*/
ngAfterViewInit() {
// If the user passes an undefined variable to ngModel this will warn
// and set the value to an empty string
if (!isPresent(this.value)) {
console.warn('Searchbar was passed an undefined value in ngModel. Please make sure the variable is defined.');
this.value = '';
this.onChange(this.value);
}
}
/**
* @private
* Determines whether or not to add style to the element
* to center it properly (ios only)
*/
setElementLeft() {
if (this.mode !== 'ios') return;
if (this.shouldLeftAlign) {
this.inputElement.removeAttribute('style');
this.searchIconElement.removeAttribute('style');
} else {
this.addElementLeft();
}
}
/**
* @private
* Calculates the amount of padding/margin left for the elements
* in order to center them based on the placeholder width
*/
addElementLeft() {
// Create a dummy span to get the placeholder width
let tempSpan = document.createElement('span');
tempSpan.innerHTML = this.placeholder;
document.body.appendChild(tempSpan);
// Get the width of the span then remove it
let textWidth = tempSpan.offsetWidth;
tempSpan.remove();
// Set the input padding left
let inputLeft = 'calc(50% - ' + (textWidth / 2) + 'px)';
this.inputElement.style.paddingLeft = inputLeft;
// Set the icon margin left
let iconLeft = 'calc(50% - ' + ((textWidth / 2) + 30) + 'px)';
this.searchIconElement.style.marginLeft = iconLeft;
}
/**
* @private
* Update the Searchbar input value when the input changes
*/
inputChanged(ev) {
let value = ev.target.value;
clearTimeout(this._tmr);
this._tmr = setTimeout(() => {
this.value = value;
this.onChange(value);
this.input.emit(this);
}, Math.round(this.debounce));
}
/**
* @private
* Sets the Searchbar to focused and aligned left on input focus.
*/
inputFocused() {
this.focus.emit(this);
this.isFocused = true;
this.shouldLeftAlign = true;
this.setElementLeft();
}
/**
* @private
* Sets the Searchbar to not focused and checks if it should align left
* based on whether there is a value in the searchbar or not.
*/
inputBlurred() {
// blurInput determines if it should blur
// if we are clearing the input we still want to stay focused in the input
if (this.blurInput === false) {
this.searchbarInput._elementRef.nativeElement.focus();
this.blurInput = true;
return;
}
this.blur.emit(this);
this.isFocused = false;
this.shouldLeftAlign = this.value && this.value.trim() !== '';
this.setElementLeft();
}
/**
* @private
* Clears the input field and triggers the control change.
*/
clearInput() {
this.clear.emit(this);
this.value = '';
this.onChange(this.value);
this.input.emit(this);
this.blurInput = false;
}
/**
* @private
* Clears the input field and tells the input to blur since
* the clearInput function doesn't want the input to blur
* then calls the custom cancel function if the user passed one in.
*/
cancelSearchbar() {
this.cancel.emit(this);
this.clearInput();
this.blurInput = true;
}
/**
* @private
* Write a new value to the element.
*/
writeValue(value: any) {
this.value = value;
}
/**
* @private
*/
onChange = (_: any) => {};
/**
* @private
*/
onTouched = () => {};
/**
* @private
* Set the function to be called when the control receives a change event.
*/
registerOnChange(fn: (_: any) => {}): void {
this.onChange = fn;
}
/**
* @private
* Set the function to be called when the control receives a touch event.
*/
registerOnTouched(fn: () => {}): void {
this.onTouched = fn;
}
}
| ionic/components/searchbar/searchbar.ts | 1 | https://github.com/ionic-team/ionic-framework/commit/ecf93023f3a41e8922508dfcc17aeace77bc1aa8 | [
0.000246326788328588,
0.00017803900118451566,
0.00016767624765634537,
0.00017160296556539834,
0.000016865118595887907
] |
{
"id": 1,
"code_window": [
"\n",
" min-height: 0;\n",
"}\n"
],
"labels": [
"keep",
"keep",
"add"
],
"after_edit": [
"\n",
".searchbar-has-value.searchbar-focused .searchbar-clear-icon {\n",
" display: block;\n",
"}"
],
"file_path": "ionic/components/searchbar/searchbar.scss",
"type": "add",
"edit_start_line_idx": 45
} | import {Component, Directive, Host, ElementRef, Optional, forwardRef, Inject, ContentChildren, ContentChild, QueryList} from 'angular2/core';
import {Ion} from '../ion';
import {MenuToggle} from '../menu/menu-toggle';
import {Navbar} from '../navbar/navbar';
import {Button} from '../button/button';
/**
* @private
*/
export class ToolbarBase extends Ion {
itemRefs = [];
titleRef = null;
titleCmp: any;
constructor(elementRef: ElementRef) {
super(elementRef);
}
/**
* @private
*/
setTitleCmp(titleCmp) {
this.titleCmp = titleCmp;
}
/**
* @private
* Returns the toolbar title text if it exists or an empty string
*/
getTitleText() {
return (this.titleCmp && this.titleCmp.getTitleText()) || '';
}
/**
* @private
*/
getTitleRef() {
return this.titleCmp && this.titleCmp.elementRef;
}
/**
* @private
* A toolbar items include the left and right side `ion-buttons`,
* and every `menu-toggle`. It does not include the `ion-title`.
* @returns {TODO} Array of this toolbar's item ElementRefs.
*/
getItemRefs() {
return this.itemRefs;
}
/**
* @private
*/
addItemRef(itemElementRef) {
this.itemRefs.push(itemElementRef);
}
}
/**
* @name Toolbar
* @description
* The toolbar is generic bar that sits above or below content.
* Unlike an `Navbar`, `Toolbar` can be used for a subheader as well.
* Since it's based on flexbox, you can place the toolbar where you
* need it and flexbox will handle everything else. Toolbars will automatically
* assume they should be placed before an `ion-content`, so to specify that you want it
* below, you can add the property `position="bottom"`. This will change the flex order
* property.
*
* @usage
* ```html
* <ion-toolbar>
* <ion-title>My Toolbar Title</ion-title>
* </ion-toolbar>
*
* <ion-toolbar>
* <ion-title>I'm a subheader</ion-title>
* </ion-toolbar>
*
* <ion-content></ion-content>
*
* <ion-toolbar position="bottom">
* <ion-title>I'm a subfooter</ion-title>
* </ion-toolbar>
*
* <ion-toolbar position="bottom">
* <ion-title>I'm a footer</ion-title>
* </ion-toolbar>
*
* ```
*
* @property {any} [position] - set position of the toolbar, `top` or `bottom`.
* Default `top`.
* @demo /docs/v2/demos/toolbar/
* @see {@link ../../navbar/Navbar/ Navbar API Docs}
*/
@Component({
selector: 'ion-toolbar',
template:
'<div class="toolbar-background"></div>' +
'<ng-content select="[menuToggle],ion-buttons[left]"></ng-content>' +
'<ng-content select="ion-buttons[start]"></ng-content>' +
'<ng-content select="ion-buttons[end],ion-buttons[right]"></ng-content>' +
'<div class="toolbar-content">' +
'<ng-content></ng-content>' +
'</div>',
host: {
'class': 'toolbar'
}
})
export class Toolbar extends ToolbarBase {
constructor(elementRef: ElementRef) {
super(elementRef);
}
}
/**
* @name Title
* @description
* `ion-title` is a component that sets the title of the `Toolbar` or `Navbar`
* @usage
* ```html
* <ion-navbar *navbar>
* <ion-title>Tab 1</ion-title>
* </ion-navbar>
*
*<!-- or if you wanted to create a subheader title-->
* <ion-navbar *navbar>
* <ion-title>Tab 1</ion-title>
* </ion-navbar>
* <ion-toolbar>
* <ion-title>SubHeader</ion-title>
* </ion-toolbar>
* ```
* @demo /docs/v2/demos/title/
*/
@Component({
selector: 'ion-title',
template:
'<div class="toolbar-title">' +
'<ng-content></ng-content>' +
'</div>'
})
export class ToolbarTitle extends Ion {
constructor(
elementRef: ElementRef,
@Optional() toolbar: Toolbar,
@Optional() @Inject(forwardRef(() => Navbar)) navbar: Navbar
) {
super(elementRef);
toolbar && toolbar.setTitleCmp(this);
navbar && navbar.setTitleCmp(this);
}
/**
* @private
*/
getTitleText() {
return this.getNativeElement().textContent;
}
}
/**
* @private
*/
@Directive({
selector: 'ion-buttons,[menuToggle],ion-nav-items'
})
export class ToolbarItem {
inToolbar: boolean;
constructor(
elementRef: ElementRef,
@Optional() toolbar: Toolbar,
@Optional() @Inject(forwardRef(() => Navbar)) navbar: Navbar
) {
toolbar && toolbar.addItemRef(elementRef);
navbar && navbar.addItemRef(elementRef);
this.inToolbar = !!(toolbar || navbar);
// Deprecation warning
if (elementRef.nativeElement.tagName === 'ION-NAV-ITEMS') {
if (elementRef.nativeElement.hasAttribute('primary')) {
console.warn('<ion-nav-items primary> has been renamed to <ion-buttons start>, please update your HTML');
elementRef.nativeElement.setAttribute('start', '');
} else if (elementRef.nativeElement.hasAttribute('secondary')) {
console.warn('<ion-nav-items secondary> has been renamed to <ion-buttons end>, please update your HTML');
elementRef.nativeElement.setAttribute('end', '');
} else {
console.warn('<ion-nav-items> has been renamed to <ion-buttons>, please update your HTML');
}
}
}
@ContentChildren(Button)
set _buttons(buttons) {
if (this.inToolbar) {
Button.setRoles(buttons, 'bar-button');
}
}
}
| ionic/components/toolbar/toolbar.ts | 0 | https://github.com/ionic-team/ionic-framework/commit/ecf93023f3a41e8922508dfcc17aeace77bc1aa8 | [
0.0005992343067191541,
0.00019288723706267774,
0.00016528420383110642,
0.0001705144823063165,
0.00008897313819034025
] |
{
"id": 1,
"code_window": [
"\n",
" min-height: 0;\n",
"}\n"
],
"labels": [
"keep",
"keep",
"add"
],
"after_edit": [
"\n",
".searchbar-has-value.searchbar-focused .searchbar-clear-icon {\n",
" display: block;\n",
"}"
],
"file_path": "ionic/components/searchbar/searchbar.scss",
"type": "add",
"edit_start_line_idx": 45
} |
<ion-toolbar>
<ion-title>Buttons Icons</ion-title>
</ion-toolbar>
<ion-content padding>
<div>
<button>
<ion-icon name="home"></ion-icon>
Left Icon
</button>
<a button>
<ion-icon name="home"></ion-icon>
Left Icon
</a>
</div>
<div>
<button>
Right Icon
<ion-icon name="star"></ion-icon>
</button>
<a button>
Right Icon
<ion-icon name="star"></ion-icon>
</a>
</div>
<div>
<button>
<ion-icon name="flag"></ion-icon>
</button>
<a button>
<ion-icon name="flag"></ion-icon>
</a>
</div>
<div>
<button large>
<ion-icon name="help-circle"></ion-icon>
Left, Large
</button>
<a button large>
<ion-icon name="help-circle"></ion-icon>
Left, Large
</a>
</div>
<div>
<button large>
Right, Large
<ion-icon name="settings"></ion-icon>
</button>
<a button large>
Right, Large
<ion-icon name="settings"></ion-icon>
</a>
</div>
<div>
<button large>
<ion-icon name="heart"></ion-icon>
</button>
<a button large>
<ion-icon name="heart"></ion-icon>
</a>
</div>
<div>
<button small>
<ion-icon name="checkmark"></ion-icon>
Left, Small
</button>
<a button small>
<ion-icon name="checkmark"></ion-icon>
Left, Small
</a>
</div>
<div>
<button small>
Right, Small
<ion-icon name="arrow-forward"></ion-icon>
</button>
<a button small>
Right, Small
<ion-icon name="arrow-forward"></ion-icon>
</a>
</div>
<div>
<button small>
<ion-icon name="search"></ion-icon>
</button>
<a button small>
<ion-icon name="search"></ion-icon>
</a>
</div>
</ion-content>
| ionic/components/button/test/icons/main.html | 0 | https://github.com/ionic-team/ionic-framework/commit/ecf93023f3a41e8922508dfcc17aeace77bc1aa8 | [
0.0002505457669030875,
0.0001911139697767794,
0.00016981149383354932,
0.00017419536015950143,
0.00002767647492873948
] |
{
"id": 1,
"code_window": [
"\n",
" min-height: 0;\n",
"}\n"
],
"labels": [
"keep",
"keep",
"add"
],
"after_edit": [
"\n",
".searchbar-has-value.searchbar-focused .searchbar-clear-icon {\n",
" display: block;\n",
"}"
],
"file_path": "ionic/components/searchbar/searchbar.scss",
"type": "add",
"edit_start_line_idx": 45
} | @import "../../globals.ios";
@import "./input";
// iOS Input
// --------------------------------------------------
$text-input-ios-background-color: $list-ios-background-color !default;
$text-input-ios-margin-top: $item-ios-padding-top !default;
$text-input-ios-margin-right: ($item-ios-padding-right / 2) !default;
$text-input-ios-margin-bottom: $item-ios-padding-bottom !default;
$text-input-ios-margin-left: 0 !default;
$text-input-ios-input-clear-icon-width: 30px !default;
$text-input-ios-input-clear-icon-color: rgba(0, 0, 0, .5) !default;
$text-input-ios-input-clear-icon-svg: "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 512 512'><path fill='" + $text-input-ios-input-clear-icon-color + "' d='M403.1,108.9c-81.2-81.2-212.9-81.2-294.2,0s-81.2,212.9,0,294.2c81.2,81.2,212.9,81.2,294.2,0S484.3,190.1,403.1,108.9z M352,340.2L340.2,352l-84.4-84.2l-84,83.8L160,339.8l84-83.8l-84-83.8l11.8-11.8l84,83.8l84.4-84.2l11.8,11.8L267.6,256L352,340.2z'/></svg>" !default;
$text-input-ios-input-clear-icon-size: 18px !default;
// iOS Default Input
// --------------------------------------------------
.text-input {
margin: $text-input-ios-margin-top $text-input-ios-margin-right $text-input-ios-margin-bottom $text-input-ios-margin-left;
padding: 0;
width: calc(100% - #{$text-input-ios-margin-right} - #{$text-input-ios-margin-left});
}
// iOS Inset Input
// --------------------------------------------------
.inset-input {
margin: ($item-ios-padding-top / 2) $item-ios-padding-right ($item-ios-padding-bottom / 2) 0;
padding: ($item-ios-padding-top / 2) ($item-ios-padding-right / 2) ($item-ios-padding-bottom / 2) ($item-ios-padding-left / 2);
}
// iOS Stacked & Floating Inputs
// --------------------------------------------------
.item-label-stacked .text-input,
.item-label-floating .text-input {
margin-top: 8px;
margin-bottom: 8px;
margin-left: 0;
width: calc(100% - #{$text-input-ios-margin-right});
}
.item-label-stacked ion-select,
.item-label-floating ion-select {
padding-top: 8px;
padding-bottom: 8px;
padding-left: 0;
}
.item-label-floating .text-input.cloned-input,
.item-label-stacked .text-input.cloned-input {
top: 30px;
}
// iOS Clear Input Icon
// --------------------------------------------------
ion-input[clearInput] {
position: relative;
.text-input {
padding-right: $text-input-ios-input-clear-icon-width;
}
}
.text-input-clear-icon {
@include svg-background-image($text-input-ios-input-clear-icon-svg);
right: ($item-ios-padding-right / 2);
bottom: 0;
width: $text-input-ios-input-clear-icon-width;
background-size: $text-input-ios-input-clear-icon-size;
}
| ionic/components/input/input.ios.scss | 0 | https://github.com/ionic-team/ionic-framework/commit/ecf93023f3a41e8922508dfcc17aeace77bc1aa8 | [
0.010979313403367996,
0.0015131219988688827,
0.0001681116846157238,
0.0003414885140955448,
0.0033483884762972593
] |
{
"id": 2,
"code_window": [
" '</button>' +\n",
" '<div class=\"searchbar-search-icon\"></div>' +\n",
" '<input [value]=\"value\" (input)=\"inputChanged($event)\" (blur)=\"inputBlurred()\" (focus)=\"inputFocused()\" class=\"searchbar-input\" type=\"search\" [attr.placeholder]=\"placeholder\" autocomplete=\"off\" autocorrect=\"off\" autocapitalize=\"off\" spellcheck=\"false\">' +\n",
" '<button clear *ngIf=\"value\" class=\"searchbar-clear-icon\" (click)=\"clearInput()\" (mousedown)=\"clearInput()\"></button>' +\n",
" '</div>' +\n",
" '<button clear (click)=\"cancelSearchbar()\" (mousedown)=\"cancelSearchbar()\" [hidden]=\"hideCancelButton\" class=\"searchbar-ios-cancel\">{{cancelButtonText}}</button>',\n",
" directives: [FORM_DIRECTIVES, NgIf, NgClass, Icon, Button, SearchbarInput]\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" '<button clear class=\"searchbar-clear-icon\" (click)=\"clearInput()\" (mousedown)=\"clearInput()\"></button>' +\n"
],
"file_path": "ionic/components/searchbar/searchbar.ts",
"type": "replace",
"edit_start_line_idx": 63
} | @import "../../globals.core";
// Search Bar
// --------------------------------------------------
ion-searchbar {
position: relative;
display: flex;
align-items: center;
width: 100%;
}
.searchbar-icon {
// Don't let them tap on the icon
pointer-events: none;
}
.searchbar-input-container {
position: relative;
display: block;
flex-shrink: 1;
width: 100%;
}
.searchbar-input {
@include appearance(none);
display: block;
width: 100%;
border: 0;
font-family: inherit;
}
.searchbar-clear-icon {
margin: 0;
padding: 0;
min-height: 0;
}
| ionic/components/searchbar/searchbar.scss | 1 | https://github.com/ionic-team/ionic-framework/commit/ecf93023f3a41e8922508dfcc17aeace77bc1aa8 | [
0.0022188089787960052,
0.000636048149317503,
0.00016495624731760472,
0.00017661575111560524,
0.0007990230806171894
] |
{
"id": 2,
"code_window": [
" '</button>' +\n",
" '<div class=\"searchbar-search-icon\"></div>' +\n",
" '<input [value]=\"value\" (input)=\"inputChanged($event)\" (blur)=\"inputBlurred()\" (focus)=\"inputFocused()\" class=\"searchbar-input\" type=\"search\" [attr.placeholder]=\"placeholder\" autocomplete=\"off\" autocorrect=\"off\" autocapitalize=\"off\" spellcheck=\"false\">' +\n",
" '<button clear *ngIf=\"value\" class=\"searchbar-clear-icon\" (click)=\"clearInput()\" (mousedown)=\"clearInput()\"></button>' +\n",
" '</div>' +\n",
" '<button clear (click)=\"cancelSearchbar()\" (mousedown)=\"cancelSearchbar()\" [hidden]=\"hideCancelButton\" class=\"searchbar-ios-cancel\">{{cancelButtonText}}</button>',\n",
" directives: [FORM_DIRECTIVES, NgIf, NgClass, Icon, Button, SearchbarInput]\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" '<button clear class=\"searchbar-clear-icon\" (click)=\"clearInput()\" (mousedown)=\"clearInput()\"></button>' +\n"
],
"file_path": "ionic/components/searchbar/searchbar.ts",
"type": "replace",
"edit_start_line_idx": 63
} | import {ViewController} from '../nav/view-controller';
import {Animation} from '../../animations/animation';
import {Transition, TransitionOptions} from '../../transitions/transition';
/**
* @name Modal
* @description
* A Modal is a content pane that goes over the user's current page.
* Usually it is used for making a choice or editing an item. A modal uses the
* `NavController` to
* {@link /docs/v2/api/components/nav/NavController/#present present}
* itself in the root nav stack. It is added to the stack similar to how
* {@link /docs/v2/api/components/nav/NavController/#push NavController.push}
* works.
*
* When a modal (or any other overlay such as an alert or actionsheet) is
* "presented" to a nav controller, the overlay is added to the app's root nav.
* After the modal has been presented, from within the component instance The
* modal can later be closed or "dismissed" by using the ViewController's
* `dismiss` method. Additionally, you can dismiss any overlay by using `pop`
* on the root nav controller.
*
* Data can be passed to a new modal through `Modal.create()` as the second
* argument. The data can gen be accessed from the opened page by injecting
* `NavParams`. Note that the page, which opened as a modal, has no special
* "modal" logic within it, but uses `NavParams` no differently than a
* standard page.
*
* @usage
* ```ts
* import {Page, Modal, NavController, NavParams} from 'ionic-angular';
*
* @Page(...)
* class HomePage {
*
* constructor(nav: NavController) {
* this.nav = nav;
* }
*
* presentProfileModal() {
* let profileModal = Modal.create(Profile, { userId: 8675309 });
* this.nav.present(profileModal);
* }
*
* }
*
* @Page(...)
* class Profile {
*
* constructor(params: NavParams) {
* console.log('UserId', params.get('userId'));
* }
*
* }
* ```
*
* A modal can also emit data, which is useful when it is used to add or edit
* data. For example, a profile page could slide up in a modal, and on submit,
* the submit button could pass the updated profile data, then dismiss the
* modal.
*
* ```ts
* import {Page, Modal, NavController, ViewController} from 'ionic-angular';
*
* @Page(...)
* class HomePage {
*
* constructor(nav: NavController) {
* this.nav = nav;
* }
*
* presentContactModal() {
* let contactModal = Modal.create(ContactUs);
* this.nav.present(contactModal);
* }
*
* presentProfileModal() {
* let profileModal = Modal.create(Profile, { userId: 8675309 });
* profileModal.onDismiss(data => {
* console.log(data);
* });
* this.nav.present(profileModal);
* }
*
* }
*
* @Page(...)
* class Profile {
*
* constructor(viewCtrl: ViewController) {
* this.viewCtrl = viewCtrl;
* }
*
* dismiss() {
* let data = { 'foo': 'bar' };
* this.viewCtrl.dismiss(data);
* }
*
* }
* ```
* @demo /docs/v2/demos/modal/
* @see {@link /docs/v2/components#modals Modal Component Docs}
*/
export class Modal extends ViewController {
constructor(componentType, data = {}) {
super(componentType, data);
this.viewType = 'modal';
this.isOverlay = true;
}
/**
* @private
*/
getTransitionName(direction) {
let key = (direction === 'back' ? 'modalLeave' : 'modalEnter');
return this._nav && this._nav.config.get(key);
}
/**
* @param {any} componentType Modal
* @param {object} data Modal options
*/
static create(componentType, data = {}) {
return new Modal(componentType, data);
}
}
/**
* Animations for modals
*/
class ModalSlideIn extends Transition {
constructor(enteringView: ViewController, leavingView: ViewController, opts: TransitionOptions) {
super(opts);
this
.element(enteringView.pageRef())
.easing('cubic-bezier(0.36,0.66,0.04,1)')
.duration(400)
.fromTo('translateY', '100%', '0%')
.before.addClass('show-page');
if (enteringView.hasNavbar()) {
// entering page has a navbar
let enteringNavBar = new Animation(enteringView.navbarRef());
enteringNavBar.before.addClass('show-navbar');
this.add(enteringNavBar);
}
}
}
Transition.register('modal-slide-in', ModalSlideIn);
class ModalSlideOut extends Transition {
constructor(enteringView: ViewController, leavingView: ViewController, opts: TransitionOptions) {
super(opts);
this
.element(leavingView.pageRef())
.easing('ease-out')
.duration(250)
.fromTo('translateY', '0%', '100%');
}
}
Transition.register('modal-slide-out', ModalSlideOut);
class ModalMDSlideIn extends Transition {
constructor(enteringView: ViewController, leavingView: ViewController, opts: TransitionOptions) {
super(opts);
this
.element(enteringView.pageRef())
.easing('cubic-bezier(0.36,0.66,0.04,1)')
.duration(280)
.fromTo('translateY', '40px', '0px')
.fadeIn()
.before.addClass('show-page');
if (enteringView.hasNavbar()) {
// entering page has a navbar
let enteringNavBar = new Animation(enteringView.navbarRef());
enteringNavBar.before.addClass('show-navbar');
this.add(enteringNavBar);
}
}
}
Transition.register('modal-md-slide-in', ModalMDSlideIn);
class ModalMDSlideOut extends Transition {
constructor(enteringView: ViewController, leavingView: ViewController, opts: TransitionOptions) {
super(opts);
this
.element(leavingView.pageRef())
.duration(200)
.easing('cubic-bezier(0.47,0,0.745,0.715)')
.fromTo('translateY', '0px', '40px')
.fadeOut();
}
}
Transition.register('modal-md-slide-out', ModalMDSlideOut);
| ionic/components/modal/modal.ts | 0 | https://github.com/ionic-team/ionic-framework/commit/ecf93023f3a41e8922508dfcc17aeace77bc1aa8 | [
0.0001710224023554474,
0.00016716694517526776,
0.0001596506335772574,
0.00016712714568711817,
0.000003075295808230294
] |
{
"id": 2,
"code_window": [
" '</button>' +\n",
" '<div class=\"searchbar-search-icon\"></div>' +\n",
" '<input [value]=\"value\" (input)=\"inputChanged($event)\" (blur)=\"inputBlurred()\" (focus)=\"inputFocused()\" class=\"searchbar-input\" type=\"search\" [attr.placeholder]=\"placeholder\" autocomplete=\"off\" autocorrect=\"off\" autocapitalize=\"off\" spellcheck=\"false\">' +\n",
" '<button clear *ngIf=\"value\" class=\"searchbar-clear-icon\" (click)=\"clearInput()\" (mousedown)=\"clearInput()\"></button>' +\n",
" '</div>' +\n",
" '<button clear (click)=\"cancelSearchbar()\" (mousedown)=\"cancelSearchbar()\" [hidden]=\"hideCancelButton\" class=\"searchbar-ios-cancel\">{{cancelButtonText}}</button>',\n",
" directives: [FORM_DIRECTIVES, NgIf, NgClass, Icon, Button, SearchbarInput]\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" '<button clear class=\"searchbar-clear-icon\" (click)=\"clearInput()\" (mousedown)=\"clearInput()\"></button>' +\n"
],
"file_path": "ionic/components/searchbar/searchbar.ts",
"type": "replace",
"edit_start_line_idx": 63
} | import {FORM_DIRECTIVES, FormBuilder, Validators, Control, ControlGroup} from 'angular2/common';
import {App, IonicApp} from 'ionic-angular';
@App({
templateUrl: 'main.html',
providers: [FormBuilder],
directives: [FORM_DIRECTIVES]
})
class MyApp {
relationship: string = 'enemies';
modelStyle: string = 'B';
appType: string = 'free';
icons: string = 'camera';
myForm;
constructor(fb: FormBuilder) {
this.myForm = fb.group({
mapStyle: ['hybrid', Validators.required]
});
}
onSegmentChanged(segmentButton) {
console.log("Segment changed to", segmentButton.value);
}
onSegmentSelected(segmentButton) {
console.log("Segment selected", segmentButton.value);
}
doSubmit(event) {
console.log('Submitting form', this.myForm.value);
event.preventDefault();
}
}
| ionic/components/segment/test/basic/index.ts | 0 | https://github.com/ionic-team/ionic-framework/commit/ecf93023f3a41e8922508dfcc17aeace77bc1aa8 | [
0.004202375654131174,
0.0011877681827172637,
0.0001652618229854852,
0.00019171752501279116,
0.0017405988182872534
] |
{
"id": 2,
"code_window": [
" '</button>' +\n",
" '<div class=\"searchbar-search-icon\"></div>' +\n",
" '<input [value]=\"value\" (input)=\"inputChanged($event)\" (blur)=\"inputBlurred()\" (focus)=\"inputFocused()\" class=\"searchbar-input\" type=\"search\" [attr.placeholder]=\"placeholder\" autocomplete=\"off\" autocorrect=\"off\" autocapitalize=\"off\" spellcheck=\"false\">' +\n",
" '<button clear *ngIf=\"value\" class=\"searchbar-clear-icon\" (click)=\"clearInput()\" (mousedown)=\"clearInput()\"></button>' +\n",
" '</div>' +\n",
" '<button clear (click)=\"cancelSearchbar()\" (mousedown)=\"cancelSearchbar()\" [hidden]=\"hideCancelButton\" class=\"searchbar-ios-cancel\">{{cancelButtonText}}</button>',\n",
" directives: [FORM_DIRECTIVES, NgIf, NgClass, Icon, Button, SearchbarInput]\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" '<button clear class=\"searchbar-clear-icon\" (click)=\"clearInput()\" (mousedown)=\"clearInput()\"></button>' +\n"
],
"file_path": "ionic/components/searchbar/searchbar.ts",
"type": "replace",
"edit_start_line_idx": 63
} | @import "../../globals.core";
// Toolbar
// --------------------------------------------------
.toolbar {
position: relative;
z-index: $z-index-toolbar;
display: flex;
overflow: hidden;
flex: 0;
flex-direction: row;
align-items: center;
justify-content: space-between;
order: $flex-order-toolbar-top;
width: 100%;
}
.toolbar-background {
position: absolute;
top: 0;
left: 0;
z-index: $z-index-toolbar-background;
width: 100%;
height: 100%;
border: 0;
transform: translateZ(0);
pointer-events: none;
}
.toolbar[position=bottom] {
order: $flex-order-toolbar-bottom;
}
ion-title {
display: flex;
flex: 1;
align-items: center;
transform: translateZ(0);
}
.toolbar-title {
display: block;
overflow: hidden;
width: 100%;
text-overflow: ellipsis;
white-space: nowrap;
}
ion-buttons {
display: block;
margin: 0 .2rem;
transform: translateZ(0);
pointer-events: none;
}
ion-buttons button,
ion-buttons a,
ion-buttons input,
ion-buttons textarea,
ion-buttons div {
pointer-events: auto;
}
// Transparent Toolbar
// --------------------------------------------------
.toolbar[transparent] .toolbar-background {
border-color: transparent;
background: transparent;
}
// TODO this is a temp hack to fix segment overlapping ion-nav-item
ion-buttons,
.bar-button-menutoggle {
z-index: 99;
transform: translateZ(0);
}
// Navbar
// --------------------------------------------------
ion-navbar.toolbar {
display: flex;
opacity: 0;
transform: translateZ(0);
&.show-navbar {
opacity: 1;
}
}
| ionic/components/toolbar/toolbar.scss | 0 | https://github.com/ionic-team/ionic-framework/commit/ecf93023f3a41e8922508dfcc17aeace77bc1aa8 | [
0.00016757793491706252,
0.00016480391786899418,
0.00016146541747730225,
0.00016453540592920035,
0.0000021365144675655756
] |
{
"id": 0,
"code_window": [
" onChange = (e: any) => {\n",
" setAlias(e.target.value);\n",
" propagateOnChange(e.target.value);\n",
" };\n",
"\n",
" return <Input type=\"text\" value={alias} onChange={onChange} />;\n",
"};"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" return <Input type=\"text\" value={alias} onChange={onChange} aria-label=\"Optional alias\" />;\n"
],
"file_path": "public/app/plugins/datasource/cloudwatch/components/Alias.tsx",
"type": "replace",
"edit_start_line_idx": 19
} | import React from 'react';
import { EditorField, EditorFieldGroup, EditorRow, EditorRows } from '@grafana/experimental';
import { Select, Switch } from '@grafana/ui';
import { Dimensions } from '..';
import { CloudWatchDatasource } from '../../datasource';
import { useDimensionKeys, useMetrics, useNamespaces } from '../../hooks';
import { CloudWatchMetricsQuery } from '../../types';
import { appendTemplateVariables, toOption } from '../../utils/utils';
export type Props = {
query: CloudWatchMetricsQuery;
datasource: CloudWatchDatasource;
disableExpressions?: boolean;
onChange: (value: CloudWatchMetricsQuery) => void;
onRunQuery: () => void;
};
export function MetricStatEditor({
query,
datasource,
disableExpressions = false,
onChange,
onRunQuery,
}: React.PropsWithChildren<Props>) {
const { region, namespace, metricName, dimensions } = query;
const namespaces = useNamespaces(datasource);
const metrics = useMetrics(datasource, region, namespace);
const dimensionKeys = useDimensionKeys(datasource, region, namespace, metricName, dimensions ?? {});
const onQueryChange = (query: CloudWatchMetricsQuery) => {
onChange(query);
onRunQuery();
};
return (
<EditorRows>
<EditorRow>
<EditorFieldGroup>
<EditorField label="Namespace" width={26}>
<Select
value={query.namespace}
allowCustomValue
options={namespaces}
onChange={({ value: namespace }) => {
if (namespace) {
onQueryChange({ ...query, namespace });
}
}}
/>
</EditorField>
<EditorField label="Metric name" width={16}>
<Select
value={query.metricName}
allowCustomValue
options={metrics}
onChange={({ value: metricName }) => {
if (metricName) {
onQueryChange({ ...query, metricName });
}
}}
/>
</EditorField>
<EditorField label="Statistic" width={16}>
<Select
inputId={`${query.refId}-metric-stat-editor-select-statistic`}
allowCustomValue
value={toOption(query.statistic ?? datasource.standardStatistics[0])}
options={appendTemplateVariables(
datasource,
datasource.standardStatistics.filter((s) => s !== query.statistic).map(toOption)
)}
onChange={({ value: statistic }) => {
if (
!statistic ||
(!datasource.standardStatistics.includes(statistic) &&
!/^p\d{2}(?:\.\d{1,2})?$/.test(statistic) &&
!statistic.startsWith('$'))
) {
return;
}
onQueryChange({ ...query, statistic });
}}
/>
</EditorField>
</EditorFieldGroup>
</EditorRow>
<EditorRow>
<EditorField label="Dimensions">
<Dimensions
query={query}
onChange={(dimensions) => onQueryChange({ ...query, dimensions })}
dimensionKeys={dimensionKeys}
disableExpressions={disableExpressions}
datasource={datasource}
/>
</EditorField>
</EditorRow>
{!disableExpressions && (
<EditorRow>
<EditorField
label="Match exact"
optional={true}
tooltip="Only show metrics that exactly match all defined dimension names."
>
<Switch
id={`${query.refId}-cloudwatch-match-exact`}
value={!!query.matchExact}
onChange={(e) => {
onQueryChange({
...query,
matchExact: e.currentTarget.checked,
});
}}
/>
</EditorField>
</EditorRow>
)}
</EditorRows>
);
}
| public/app/plugins/datasource/cloudwatch/components/MetricStatEditor/MetricStatEditor.tsx | 1 | https://github.com/grafana/grafana/commit/ba58b34219739aada59dd8853d4cb9cf640eae8f | [
0.9701635241508484,
0.1802220344543457,
0.00016415303980465978,
0.0044151428155601025,
0.3369520902633667
] |
{
"id": 0,
"code_window": [
" onChange = (e: any) => {\n",
" setAlias(e.target.value);\n",
" propagateOnChange(e.target.value);\n",
" };\n",
"\n",
" return <Input type=\"text\" value={alias} onChange={onChange} />;\n",
"};"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" return <Input type=\"text\" value={alias} onChange={onChange} aria-label=\"Optional alias\" />;\n"
],
"file_path": "public/app/plugins/datasource/cloudwatch/components/Alias.tsx",
"type": "replace",
"edit_start_line_idx": 19
} | import React from 'react';
import { TimePickerTitle } from './TimePickerTitle';
import { Button } from '../../Button';
import { selectors } from '@grafana/e2e-selectors';
import { TimePickerCalendarProps } from './TimePickerCalendar';
import { useStyles2 } from '../../../themes';
import { GrafanaTheme2 } from '@grafana/data';
import { css } from '@emotion/css';
export function Header({ onClose }: TimePickerCalendarProps) {
const styles = useStyles2(getHeaderStyles);
return (
<div className={styles.container}>
<TimePickerTitle>Select a time range</TimePickerTitle>
<Button
aria-label={selectors.components.TimePicker.calendar.closeButton}
icon="times"
variant="secondary"
onClick={onClose}
/>
</div>
);
}
Header.displayName = 'Header';
const getHeaderStyles = (theme: GrafanaTheme2) => {
return {
container: css`
background-color: ${theme.colors.background.primary};
display: flex;
align-items: center;
justify-content: space-between;
padding: 7px;
`,
};
};
| packages/grafana-ui/src/components/DateTimePickers/TimeRangePicker/CalendarHeader.tsx | 0 | https://github.com/grafana/grafana/commit/ba58b34219739aada59dd8853d4cb9cf640eae8f | [
0.0001860088959801942,
0.00017422102973796427,
0.00016499115736223757,
0.00017294204735662788,
0.000007710609679634217
] |
{
"id": 0,
"code_window": [
" onChange = (e: any) => {\n",
" setAlias(e.target.value);\n",
" propagateOnChange(e.target.value);\n",
" };\n",
"\n",
" return <Input type=\"text\" value={alias} onChange={onChange} />;\n",
"};"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" return <Input type=\"text\" value={alias} onChange={onChange} aria-label=\"Optional alias\" />;\n"
],
"file_path": "public/app/plugins/datasource/cloudwatch/components/Alias.tsx",
"type": "replace",
"edit_start_line_idx": 19
} | import datetime
import time
from django.utils.timezone import get_current_timezone
from django.core.urlresolvers import get_script_prefix
from django.http import HttpResponse
from django.shortcuts import render_to_response, get_object_or_404
from pytz import timezone
from graphite.util import json
from graphite.events import models
from graphite.render.attime import parseATTime
def to_timestamp(dt):
return time.mktime(dt.timetuple())
class EventEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime.datetime):
return to_timestamp(obj)
return json.JSONEncoder.default(self, obj)
def view_events(request):
if request.method == "GET":
context = { 'events' : fetch(request),
'slash' : get_script_prefix()
}
return render_to_response("events.html", context)
else:
return post_event(request)
def detail(request, event_id):
e = get_object_or_404(models.Event, pk=event_id)
context = { 'event' : e,
'slash' : get_script_prefix()
}
return render_to_response("event.html", context)
def post_event(request):
if request.method == 'POST':
event = json.loads(request.body)
assert isinstance(event, dict)
values = {}
values["what"] = event["what"]
values["tags"] = event.get("tags", None)
values["when"] = datetime.datetime.fromtimestamp(
event.get("when", time.time()))
if "data" in event:
values["data"] = event["data"]
e = models.Event(**values)
e.save()
return HttpResponse(status=200)
else:
return HttpResponse(status=405)
def get_data(request):
if 'jsonp' in request.REQUEST:
response = HttpResponse(
"%s(%s)" % (request.REQUEST.get('jsonp'),
json.dumps(fetch(request), cls=EventEncoder)),
mimetype='text/javascript')
else:
response = HttpResponse(
json.dumps(fetch(request), cls=EventEncoder),
mimetype="application/json")
return response
def fetch(request):
#XXX we need to move to USE_TZ=True to get rid of naive-time conversions
def make_naive(dt):
if 'tz' in request.GET:
tz = timezone(request.GET['tz'])
else:
tz = get_current_timezone()
local_dt = dt.astimezone(tz)
if hasattr(local_dt, 'normalize'):
local_dt = local_dt.normalize()
return local_dt.replace(tzinfo=None)
if request.GET.get("from", None) is not None:
time_from = make_naive(parseATTime(request.GET["from"]))
else:
time_from = datetime.datetime.fromtimestamp(0)
if request.GET.get("until", None) is not None:
time_until = make_naive(parseATTime(request.GET["until"]))
else:
time_until = datetime.datetime.now()
tags = request.GET.get("tags", None)
if tags is not None:
tags = request.GET.get("tags").split(" ")
return [x.as_dict() for x in
models.Event.find_events(time_from, time_until, tags=tags)]
| devenv/docker/blocks/graphite09/files/events_views.py | 0 | https://github.com/grafana/grafana/commit/ba58b34219739aada59dd8853d4cb9cf640eae8f | [
0.0006623855442740023,
0.00021970164380036294,
0.0001663622388150543,
0.0001730890217004344,
0.000140347023261711
] |
{
"id": 0,
"code_window": [
" onChange = (e: any) => {\n",
" setAlias(e.target.value);\n",
" propagateOnChange(e.target.value);\n",
" };\n",
"\n",
" return <Input type=\"text\" value={alias} onChange={onChange} />;\n",
"};"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" return <Input type=\"text\" value={alias} onChange={onChange} aria-label=\"Optional alias\" />;\n"
],
"file_path": "public/app/plugins/datasource/cloudwatch/components/Alias.tsx",
"type": "replace",
"edit_start_line_idx": 19
} | import React from 'react';
import { DataSourceSettings } from '@grafana/data';
import { DataSourceHttpSettings } from './DataSourceHttpSettings';
import { UseState } from '../../utils/storybook/UseState';
import mdx from './DataSourceHttpSettings.mdx';
const settingsMock: DataSourceSettings<any, any> = {
id: 4,
orgId: 1,
uid: 'x',
name: 'gdev-influxdb',
type: 'influxdb',
typeName: 'Influxdb',
typeLogoUrl: '',
access: 'direct',
url: 'http://localhost:8086',
password: '',
user: 'grafana',
database: 'site',
basicAuth: false,
basicAuthUser: '',
basicAuthPassword: '',
withCredentials: false,
isDefault: false,
jsonData: {
timeInterval: '15s',
httpMode: 'GET',
keepCookies: ['cookie1', 'cookie2'],
serverName: '',
},
secureJsonData: {
password: true,
},
secureJsonFields: {},
readOnly: true,
};
export default {
title: 'Data Source/DataSourceHttpSettings',
component: DataSourceHttpSettings,
parameters: {
docs: {
page: mdx,
},
},
};
export const basic = () => {
return (
<UseState initialState={settingsMock} logState>
{(dataSourceSettings, updateDataSourceSettings) => {
return (
<DataSourceHttpSettings
defaultUrl="http://localhost:9999"
dataSourceConfig={dataSourceSettings}
onChange={updateDataSourceSettings}
showAccessOptions={true}
/>
);
}}
</UseState>
);
};
| packages/grafana-ui/src/components/DataSourceSettings/DataSourceHttpSettings.story.tsx | 0 | https://github.com/grafana/grafana/commit/ba58b34219739aada59dd8853d4cb9cf640eae8f | [
0.006105280015617609,
0.0010248890612274408,
0.00017118066898547113,
0.00017438080976717174,
0.0020740898326039314
] |
{
"id": 1,
"code_window": [
" <LegacyForms.FormField\n",
" label=\"Region\"\n",
" labelWidth={4}\n",
" inputEl={\n",
" <Select\n",
" menuShouldPortal\n",
" options={regions}\n",
" value={selectedRegion}\n",
" onChange={(v) => this.setSelectedRegion(v)}\n",
" width={18}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" aria-label=\"Region\"\n"
],
"file_path": "public/app/plugins/datasource/cloudwatch/components/LogsQueryField.tsx",
"type": "add",
"edit_start_line_idx": 333
} | import React from 'react';
import { EditorField, EditorFieldGroup, EditorRow, EditorRows } from '@grafana/experimental';
import { Select, Switch } from '@grafana/ui';
import { Dimensions } from '..';
import { CloudWatchDatasource } from '../../datasource';
import { useDimensionKeys, useMetrics, useNamespaces } from '../../hooks';
import { CloudWatchMetricsQuery } from '../../types';
import { appendTemplateVariables, toOption } from '../../utils/utils';
export type Props = {
query: CloudWatchMetricsQuery;
datasource: CloudWatchDatasource;
disableExpressions?: boolean;
onChange: (value: CloudWatchMetricsQuery) => void;
onRunQuery: () => void;
};
export function MetricStatEditor({
query,
datasource,
disableExpressions = false,
onChange,
onRunQuery,
}: React.PropsWithChildren<Props>) {
const { region, namespace, metricName, dimensions } = query;
const namespaces = useNamespaces(datasource);
const metrics = useMetrics(datasource, region, namespace);
const dimensionKeys = useDimensionKeys(datasource, region, namespace, metricName, dimensions ?? {});
const onQueryChange = (query: CloudWatchMetricsQuery) => {
onChange(query);
onRunQuery();
};
return (
<EditorRows>
<EditorRow>
<EditorFieldGroup>
<EditorField label="Namespace" width={26}>
<Select
value={query.namespace}
allowCustomValue
options={namespaces}
onChange={({ value: namespace }) => {
if (namespace) {
onQueryChange({ ...query, namespace });
}
}}
/>
</EditorField>
<EditorField label="Metric name" width={16}>
<Select
value={query.metricName}
allowCustomValue
options={metrics}
onChange={({ value: metricName }) => {
if (metricName) {
onQueryChange({ ...query, metricName });
}
}}
/>
</EditorField>
<EditorField label="Statistic" width={16}>
<Select
inputId={`${query.refId}-metric-stat-editor-select-statistic`}
allowCustomValue
value={toOption(query.statistic ?? datasource.standardStatistics[0])}
options={appendTemplateVariables(
datasource,
datasource.standardStatistics.filter((s) => s !== query.statistic).map(toOption)
)}
onChange={({ value: statistic }) => {
if (
!statistic ||
(!datasource.standardStatistics.includes(statistic) &&
!/^p\d{2}(?:\.\d{1,2})?$/.test(statistic) &&
!statistic.startsWith('$'))
) {
return;
}
onQueryChange({ ...query, statistic });
}}
/>
</EditorField>
</EditorFieldGroup>
</EditorRow>
<EditorRow>
<EditorField label="Dimensions">
<Dimensions
query={query}
onChange={(dimensions) => onQueryChange({ ...query, dimensions })}
dimensionKeys={dimensionKeys}
disableExpressions={disableExpressions}
datasource={datasource}
/>
</EditorField>
</EditorRow>
{!disableExpressions && (
<EditorRow>
<EditorField
label="Match exact"
optional={true}
tooltip="Only show metrics that exactly match all defined dimension names."
>
<Switch
id={`${query.refId}-cloudwatch-match-exact`}
value={!!query.matchExact}
onChange={(e) => {
onQueryChange({
...query,
matchExact: e.currentTarget.checked,
});
}}
/>
</EditorField>
</EditorRow>
)}
</EditorRows>
);
}
| public/app/plugins/datasource/cloudwatch/components/MetricStatEditor/MetricStatEditor.tsx | 1 | https://github.com/grafana/grafana/commit/ba58b34219739aada59dd8853d4cb9cf640eae8f | [
0.00017748009122442454,
0.000167484613484703,
0.00016323821910191327,
0.00016582122771069407,
0.000004054641067341436
] |
{
"id": 1,
"code_window": [
" <LegacyForms.FormField\n",
" label=\"Region\"\n",
" labelWidth={4}\n",
" inputEl={\n",
" <Select\n",
" menuShouldPortal\n",
" options={regions}\n",
" value={selectedRegion}\n",
" onChange={(v) => this.setSelectedRegion(v)}\n",
" width={18}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" aria-label=\"Region\"\n"
],
"file_path": "public/app/plugins/datasource/cloudwatch/components/LogsQueryField.tsx",
"type": "add",
"edit_start_line_idx": 333
} | import $ from 'jquery';
// @ts-ignore
import baron from 'baron';
import coreModule from 'app/angular/core_module';
const scrollBarHTML = `
<div class="baron__track">
<div class="baron__bar"></div>
</div>
`;
const scrollRootClass = 'baron baron__root';
const scrollerClass = 'baron__scroller';
export function geminiScrollbar() {
return {
restrict: 'A',
link: (scope: any, elem: any, attrs: any) => {
let scrollRoot = elem.parent();
const scroller = elem;
if (attrs.grafanaScrollbar && attrs.grafanaScrollbar === 'scrollonroot') {
scrollRoot = scroller;
}
scrollRoot.addClass(scrollRootClass);
$(scrollBarHTML).appendTo(scrollRoot);
elem.addClass(scrollerClass);
const scrollParams = {
root: scrollRoot[0],
scroller: scroller[0],
bar: '.baron__bar',
barOnCls: '_scrollbar',
scrollingCls: '_scrolling',
track: '.baron__track',
direction: 'v',
};
const scrollbar = baron(scrollParams);
scope.$on('$destroy', () => {
scrollbar.dispose();
});
},
};
}
coreModule.directive('grafanaScrollbar', geminiScrollbar);
| public/app/angular/components/scroll.ts | 0 | https://github.com/grafana/grafana/commit/ba58b34219739aada59dd8853d4cb9cf640eae8f | [
0.0001765541237546131,
0.00017384761304128915,
0.00017210454097948968,
0.00017341048805974424,
0.0000014677327726531075
] |
{
"id": 1,
"code_window": [
" <LegacyForms.FormField\n",
" label=\"Region\"\n",
" labelWidth={4}\n",
" inputEl={\n",
" <Select\n",
" menuShouldPortal\n",
" options={regions}\n",
" value={selectedRegion}\n",
" onChange={(v) => this.setSelectedRegion(v)}\n",
" width={18}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" aria-label=\"Region\"\n"
],
"file_path": "public/app/plugins/datasource/cloudwatch/components/LogsQueryField.tsx",
"type": "add",
"edit_start_line_idx": 333
} | import { QueryRunner } from '@grafana/data';
let factory: QueryRunnerFactory | undefined;
/**
* @internal
*/
export type QueryRunnerFactory = () => QueryRunner;
/**
* Used to bootstrap the {@link createQueryRunner} during application start.
*
* @internal
*/
export const setQueryRunnerFactory = (instance: QueryRunnerFactory): void => {
if (factory) {
throw new Error('Runner should only be set when Grafana is starting.');
}
factory = instance;
};
/**
* Used to create QueryRunner instances from outside the core Grafana application.
* This is helpful to be able to create a QueryRunner to execute queries in e.g. an app plugin.
*
* @internal
*/
export const createQueryRunner = (): QueryRunner => {
if (!factory) {
throw new Error('`createQueryRunner` can only be used after Grafana instance has started.');
}
return factory();
};
| packages/grafana-runtime/src/services/QueryRunner.ts | 0 | https://github.com/grafana/grafana/commit/ba58b34219739aada59dd8853d4cb9cf640eae8f | [
0.00016874444554559886,
0.00016700637934263796,
0.0001643337745917961,
0.0001674736267887056,
0.0000016567447573834215
] |
{
"id": 1,
"code_window": [
" <LegacyForms.FormField\n",
" label=\"Region\"\n",
" labelWidth={4}\n",
" inputEl={\n",
" <Select\n",
" menuShouldPortal\n",
" options={regions}\n",
" value={selectedRegion}\n",
" onChange={(v) => this.setSelectedRegion(v)}\n",
" width={18}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" aria-label=\"Region\"\n"
],
"file_path": "public/app/plugins/datasource/cloudwatch/components/LogsQueryField.tsx",
"type": "add",
"edit_start_line_idx": 333
} | import { Observable, Subscription } from 'rxjs';
import { expectObservable, forceObservableCompletion } from './utils';
import { matcherHint, printReceived } from 'jest-matcher-utils';
function tryExpectations(received: any[], expectations: (received: any[]) => void): jest.CustomMatcherResult {
try {
expectations(received);
return {
pass: true,
message: () => `${matcherHint('.not.toEmitValues')}
Expected observable to complete with
${printReceived(received)}
`,
};
} catch (err) {
return {
pass: false,
message: () => 'failed ' + err,
};
}
}
/**
* Collect all the values emitted by the observables (also errors) and pass them to the expectations functions after
* the observable ended (or emitted error). If Observable does not complete within OBSERVABLE_TEST_TIMEOUT_IN_MS the
* test fails.
*/
export function toEmitValuesWith(
received: Observable<any>,
expectations: (actual: any[]) => void
): Promise<jest.CustomMatcherResult> {
const failsChecks = expectObservable(received);
if (failsChecks) {
return Promise.resolve(failsChecks);
}
return new Promise((resolve) => {
const receivedValues: any[] = [];
const subscription = new Subscription();
subscription.add(
received.subscribe({
next: (value) => {
receivedValues.push(value);
},
error: (err) => {
receivedValues.push(err);
subscription.unsubscribe();
resolve(tryExpectations(receivedValues, expectations));
},
complete: () => {
subscription.unsubscribe();
resolve(tryExpectations(receivedValues, expectations));
},
})
);
forceObservableCompletion(subscription, resolve);
});
}
| public/test/matchers/toEmitValuesWith.ts | 0 | https://github.com/grafana/grafana/commit/ba58b34219739aada59dd8853d4cb9cf640eae8f | [
0.00017471968021709472,
0.00017240144370589405,
0.00016764171596150845,
0.00017322407802566886,
0.0000023947347926878138
] |
{
"id": 2,
"code_window": [
" label=\"Log Groups\"\n",
" labelWidth={6}\n",
" className=\"flex-grow-1\"\n",
" inputEl={\n",
" <MultiSelect\n",
" menuShouldPortal\n",
" allowCustomValue={allowCustomValue}\n",
" options={unionBy(availableLogGroups, selectedLogGroups, 'value')}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" aria-label=\"Log Groups\"\n"
],
"file_path": "public/app/plugins/datasource/cloudwatch/components/LogsQueryField.tsx",
"type": "add",
"edit_start_line_idx": 350
} | // Libraries
import React, { ReactNode } from 'react';
import { intersectionBy, debounce, unionBy } from 'lodash';
import {
BracesPlugin,
LegacyForms,
MultiSelect,
QueryField,
Select,
SlatePrism,
TypeaheadInput,
TypeaheadOutput,
} from '@grafana/ui';
// Utils & Services
// dom also includes Element polyfills
import { Editor, Node, Plugin } from 'slate';
import syntax from '../syntax';
// Types
import { AbsoluteTimeRange, QueryEditorProps, SelectableValue } from '@grafana/data';
import { CloudWatchJsonData, CloudWatchLogsQuery, CloudWatchQuery } from '../types';
import { CloudWatchDatasource } from '../datasource';
import { LanguageMap, languages as prismLanguages } from 'prismjs';
import { CloudWatchLanguageProvider } from '../language_provider';
import { css } from '@emotion/css';
import { ExploreId } from 'app/types';
import { dispatch } from 'app/store/store';
import { notifyApp } from 'app/core/actions';
import { createErrorNotification } from 'app/core/copy/appNotification';
import { InputActionMeta } from '@grafana/ui/src/components/Select/types';
import { getStatsGroups } from '../utils/query/getStatsGroups';
export interface CloudWatchLogsQueryFieldProps
extends QueryEditorProps<CloudWatchDatasource, CloudWatchQuery, CloudWatchJsonData> {
absoluteRange: AbsoluteTimeRange;
onLabelsRefresh?: () => void;
ExtraFieldElement?: ReactNode;
exploreId: ExploreId;
allowCustomValue?: boolean;
}
const containerClass = css`
flex-grow: 1;
min-height: 35px;
`;
const rowGap = css`
gap: 3px;
`;
interface State {
selectedLogGroups: Array<SelectableValue<string>>;
availableLogGroups: Array<SelectableValue<string>>;
loadingLogGroups: boolean;
regions: Array<SelectableValue<string>>;
selectedRegion: SelectableValue<string>;
invalidLogGroups: boolean;
hint:
| {
message: string;
fix: {
label: string;
action: () => void;
};
}
| undefined;
}
export class CloudWatchLogsQueryField extends React.PureComponent<CloudWatchLogsQueryFieldProps, State> {
state: State = {
selectedLogGroups:
(this.props.query as CloudWatchLogsQuery).logGroupNames?.map((logGroup) => ({
value: logGroup,
label: logGroup,
})) ?? [],
availableLogGroups: [],
regions: [],
invalidLogGroups: false,
selectedRegion: (this.props.query as CloudWatchLogsQuery).region
? {
label: (this.props.query as CloudWatchLogsQuery).region,
value: (this.props.query as CloudWatchLogsQuery).region,
text: (this.props.query as CloudWatchLogsQuery).region,
}
: { label: 'default', value: 'default', text: 'default' },
loadingLogGroups: false,
hint: undefined,
};
plugins: Plugin[];
constructor(props: CloudWatchLogsQueryFieldProps, context: React.Context<any>) {
super(props, context);
this.plugins = [
BracesPlugin(),
SlatePrism(
{
onlyIn: (node: Node) => node.object === 'block' && node.type === 'code_block',
getSyntax: (node: Node) => 'cloudwatch',
},
{ ...(prismLanguages as LanguageMap), cloudwatch: syntax }
),
];
}
fetchLogGroupOptions = async (region: string, logGroupNamePrefix?: string) => {
try {
const logGroups: string[] = await this.props.datasource.describeLogGroups({
refId: this.props.query.refId,
region,
logGroupNamePrefix,
});
return logGroups.map((logGroup) => ({
value: logGroup,
label: logGroup,
}));
} catch (err) {
let errMessage = 'unknown error';
if (typeof err !== 'string') {
try {
errMessage = JSON.stringify(err);
} catch (e) {}
} else {
errMessage = err;
}
dispatch(notifyApp(createErrorNotification(errMessage)));
return [];
}
};
onLogGroupSearch = (searchTerm: string, region: string, actionMeta: InputActionMeta) => {
if (actionMeta.action !== 'input-change') {
return Promise.resolve();
}
// No need to fetch matching log groups if the search term isn't valid
// This is also useful for preventing searches when a user is typing out a log group with template vars
// See https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_LogGroup.html for the source of the pattern below
const logGroupNamePattern = /^[\.\-_/#A-Za-z0-9]+$/;
if (!logGroupNamePattern.test(searchTerm)) {
return Promise.resolve();
}
this.setState({
loadingLogGroups: true,
});
return this.fetchLogGroupOptions(region, searchTerm)
.then((matchingLogGroups) => {
this.setState((state) => ({
availableLogGroups: unionBy(state.availableLogGroups, matchingLogGroups, 'value'),
}));
})
.finally(() => {
this.setState({
loadingLogGroups: false,
});
});
};
onLogGroupSearchDebounced = debounce(this.onLogGroupSearch, 300);
componentDidMount = () => {
const { datasource, query, onChange } = this.props;
this.setState({
loadingLogGroups: true,
});
query.region &&
this.fetchLogGroupOptions(query.region).then((logGroups) => {
this.setState((state) => {
const selectedLogGroups = state.selectedLogGroups;
if (onChange) {
const nextQuery = {
...query,
logGroupNames: selectedLogGroups.map((group) => group.value!),
};
onChange(nextQuery);
}
return {
loadingLogGroups: false,
availableLogGroups: logGroups,
selectedLogGroups,
};
});
});
datasource.getRegions().then((regions) => {
this.setState({
regions,
});
});
};
onChangeQuery = (value: string) => {
// Send text change to parent
const { query, onChange } = this.props;
const { selectedLogGroups, selectedRegion } = this.state;
if (onChange) {
const nextQuery = {
...query,
expression: value,
logGroupNames: selectedLogGroups?.map((logGroupName) => logGroupName.value!) ?? [],
region: selectedRegion.value ?? 'default',
statsGroups: getStatsGroups(value),
};
onChange(nextQuery);
}
};
setSelectedLogGroups = (selectedLogGroups: Array<SelectableValue<string>>) => {
this.setState({
selectedLogGroups,
});
const { onChange, query } = this.props;
onChange?.({
...(query as CloudWatchLogsQuery),
logGroupNames: selectedLogGroups.map((logGroupName) => logGroupName.value!) ?? [],
});
};
setCustomLogGroups = (v: string) => {
const customLogGroup: SelectableValue<string> = { value: v, label: v };
const selectedLogGroups = [...this.state.selectedLogGroups, customLogGroup];
this.setSelectedLogGroups(selectedLogGroups);
};
setSelectedRegion = async (v: SelectableValue<string>) => {
this.setState({
selectedRegion: v,
loadingLogGroups: true,
});
const logGroups = await this.fetchLogGroupOptions(v.value!);
this.setState((state) => {
const selectedLogGroups = intersectionBy(state.selectedLogGroups, logGroups, 'value');
const { onChange, query } = this.props;
if (onChange) {
const nextQuery = {
...query,
region: v.value ?? 'default',
logGroupNames: selectedLogGroups.map((group) => group.value!),
};
onChange(nextQuery);
}
return {
availableLogGroups: logGroups,
selectedLogGroups: selectedLogGroups,
loadingLogGroups: false,
};
});
};
onTypeahead = async (typeahead: TypeaheadInput): Promise<TypeaheadOutput> => {
const { datasource, query } = this.props;
const { selectedLogGroups } = this.state;
if (!datasource.languageProvider) {
return { suggestions: [] };
}
const cloudwatchLanguageProvider = datasource.languageProvider as CloudWatchLanguageProvider;
const { history, absoluteRange } = this.props;
const { prefix, text, value, wrapperClasses, labelKey, editor } = typeahead;
return await cloudwatchLanguageProvider.provideCompletionItems(
{ text, value, prefix, wrapperClasses, labelKey, editor },
{
history,
absoluteRange,
logGroupNames: selectedLogGroups.map((logGroup) => logGroup.value!),
region: query.region,
}
);
};
onQueryFieldClick = (_event: Event, _editor: Editor, next: () => any) => {
const { selectedLogGroups, loadingLogGroups } = this.state;
const queryFieldDisabled = loadingLogGroups || selectedLogGroups.length === 0;
if (queryFieldDisabled) {
this.setState({
invalidLogGroups: true,
});
}
next();
};
onOpenLogGroupMenu = () => {
this.setState({
invalidLogGroups: false,
});
};
render() {
const { ExtraFieldElement, data, query, datasource, allowCustomValue } = this.props;
const {
selectedLogGroups,
availableLogGroups,
regions,
selectedRegion,
loadingLogGroups,
hint,
invalidLogGroups,
} = this.state;
const showError = data && data.error && data.error.refId === query.refId;
const cleanText = datasource.languageProvider ? datasource.languageProvider.cleanText : undefined;
const MAX_LOG_GROUPS = 20;
return (
<>
<div className={`gf-form gf-form--grow flex-grow-1 ${rowGap}`}>
<LegacyForms.FormField
label="Region"
labelWidth={4}
inputEl={
<Select
menuShouldPortal
options={regions}
value={selectedRegion}
onChange={(v) => this.setSelectedRegion(v)}
width={18}
placeholder="Choose Region"
maxMenuHeight={500}
/>
}
/>
<LegacyForms.FormField
label="Log Groups"
labelWidth={6}
className="flex-grow-1"
inputEl={
<MultiSelect
menuShouldPortal
allowCustomValue={allowCustomValue}
options={unionBy(availableLogGroups, selectedLogGroups, 'value')}
value={selectedLogGroups}
onChange={(v) => {
this.setSelectedLogGroups(v);
}}
onCreateOption={(v) => {
this.setCustomLogGroups(v);
}}
className={containerClass}
closeMenuOnSelect={false}
isClearable={true}
invalid={invalidLogGroups}
isOptionDisabled={() => selectedLogGroups.length >= MAX_LOG_GROUPS}
placeholder="Choose Log Groups"
maxVisibleValues={4}
noOptionsMessage="No log groups available"
isLoading={loadingLogGroups}
onOpenMenu={this.onOpenLogGroupMenu}
onInputChange={(value, actionMeta) => {
this.onLogGroupSearchDebounced(value, selectedRegion.value ?? 'default', actionMeta);
}}
/>
}
/>
</div>
<div className="gf-form-inline gf-form-inline--nowrap flex-grow-1">
<div className="gf-form gf-form--grow flex-shrink-1">
<QueryField
additionalPlugins={this.plugins}
query={query.expression ?? ''}
onChange={this.onChangeQuery}
onBlur={this.props.onBlur}
onClick={this.onQueryFieldClick}
onRunQuery={this.props.onRunQuery}
onTypeahead={this.onTypeahead}
cleanText={cleanText}
placeholder="Enter a CloudWatch Logs Insights query (run with Shift+Enter)"
portalOrigin="cloudwatch"
disabled={loadingLogGroups || selectedLogGroups.length === 0}
/>
</div>
{ExtraFieldElement}
</div>
{hint && (
<div className="query-row-break">
<div className="text-warning">
{hint.message}
<a className="text-link muted" onClick={hint.fix.action}>
{hint.fix.label}
</a>
</div>
</div>
)}
{showError ? (
<div className="query-row-break">
<div className="prom-query-field-info text-error">{data?.error?.message}</div>
</div>
) : null}
</>
);
}
}
| public/app/plugins/datasource/cloudwatch/components/LogsQueryField.tsx | 1 | https://github.com/grafana/grafana/commit/ba58b34219739aada59dd8853d4cb9cf640eae8f | [
0.6202494502067566,
0.024088064208626747,
0.0001646374148549512,
0.0019966894760727882,
0.09932207316160202
] |
{
"id": 2,
"code_window": [
" label=\"Log Groups\"\n",
" labelWidth={6}\n",
" className=\"flex-grow-1\"\n",
" inputEl={\n",
" <MultiSelect\n",
" menuShouldPortal\n",
" allowCustomValue={allowCustomValue}\n",
" options={unionBy(availableLogGroups, selectedLogGroups, 'value')}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" aria-label=\"Log Groups\"\n"
],
"file_path": "public/app/plugins/datasource/cloudwatch/components/LogsQueryField.tsx",
"type": "add",
"edit_start_line_idx": 350
} | {
"extends": ["@grafana/eslint-config"],
"root": true,
"plugins": ["no-only-tests", "@emotion", "lodash"],
"rules": {
"no-only-tests/no-only-tests": "error",
"react/prop-types": "off",
"@emotion/jsx-import": "error",
"lodash/import-scope": [2, "member"]
},
"overrides": [
{
"files": ["packages/grafana-ui/src/components/uPlot/**/*.{ts,tsx}"],
"rules": {
"react-hooks/rules-of-hooks": "off",
"react-hooks/exhaustive-deps": "off"
}
},
{
"files": ["packages/grafana-ui/src/components/ThemeDemos/**/*.{ts,tsx}"],
"rules": {
"@emotion/jsx-import": "off",
"react/jsx-uses-react": "off",
"react/react-in-jsx-scope": "off"
}
}
]
}
| .eslintrc | 0 | https://github.com/grafana/grafana/commit/ba58b34219739aada59dd8853d4cb9cf640eae8f | [
0.00017468436271883547,
0.0001735836995067075,
0.0001722432643873617,
0.00017382351506967098,
0.0000010108968808708596
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.