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": 2,
"code_window": [
" input: {\n",
" font: 'inherit',\n",
" padding: '6px 0',\n",
" border: 0,\n",
" display: 'block',\n",
" verticalAlign: 'middle',\n",
" whiteSpace: 'normal',\n",
" background: 'none',\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" boxSizing: 'content-box',\n"
],
"file_path": "src/Input/Input.js",
"type": "add",
"edit_start_line_idx": 56
} | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let Mouse = (props) => (
<SvgIcon {...props}>
<path d="M13 1.07V9h7c0-4.08-3.05-7.44-7-7.93zM4 15c0 4.42 3.58 8 8 8s8-3.58 8-8v-4H4v4zm7-13.93C7.05 1.56 4 4.92 4 9h7V1.07z"/>
</SvgIcon>
);
Mouse = pure(Mouse);
Mouse.muiName = 'SvgIcon';
export default Mouse;
| packages/material-ui-icons/src/Mouse.js | 0 | https://github.com/mui/material-ui/commit/2611239179c1457b8e5fd9513d2d32b67b8e90f2 | [
0.00017237996507901698,
0.00017051715985871851,
0.00016865436919033527,
0.00017051715985871851,
0.0000018627979443408549
] |
{
"id": 2,
"code_window": [
" input: {\n",
" font: 'inherit',\n",
" padding: '6px 0',\n",
" border: 0,\n",
" display: 'block',\n",
" verticalAlign: 'middle',\n",
" whiteSpace: 'normal',\n",
" background: 'none',\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" boxSizing: 'content-box',\n"
],
"file_path": "src/Input/Input.js",
"type": "add",
"edit_start_line_idx": 56
} | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let PhoneMissed = (props) => (
<SvgIcon {...props}>
<path d="M6.5 5.5L12 11l7-7-1-1-6 6-4.5-4.5H11V3H5v6h1.5V5.5zm17.21 11.17C20.66 13.78 16.54 12 12 12 7.46 12 3.34 13.78.29 16.67c-.18.18-.29.43-.29.71s.11.53.29.71l2.48 2.48c.18.18.43.29.71.29.27 0 .52-.11.7-.28.79-.74 1.69-1.36 2.66-1.85.33-.16.56-.5.56-.9v-3.1c1.45-.48 3-.73 4.6-.73 1.6 0 3.15.25 4.6.72v3.1c0 .39.23.74.56.9.98.49 1.87 1.12 2.67 1.85.18.18.43.28.7.28.28 0 .53-.11.71-.29l2.48-2.48c.18-.18.29-.43.29-.71s-.12-.52-.3-.7z"/>
</SvgIcon>
);
PhoneMissed = pure(PhoneMissed);
PhoneMissed.muiName = 'SvgIcon';
export default PhoneMissed;
| packages/material-ui-icons/src/PhoneMissed.js | 0 | https://github.com/mui/material-ui/commit/2611239179c1457b8e5fd9513d2d32b67b8e90f2 | [
0.00016800912271719426,
0.0001678886474110186,
0.0001677681866567582,
0.0001678886474110186,
1.2046803021803498e-7
] |
{
"id": 3,
"code_window": [
" appearance: 'none',\n",
" },\n",
" },\n",
" singleline: {\n",
" appearance: 'textfield', // Improve type search style.\n",
" },\n",
" multiline: {\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" height: '1em',\n"
],
"file_path": "src/Input/Input.js",
"type": "add",
"edit_start_line_idx": 71
} | // @flow weak
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { createStyleSheet } from 'jss-theme-reactor';
import withStyles from '../styles/withStyles';
import Textarea from './Textarea';
function isDirty(obj) {
return obj && obj.value && obj.value.length > 0;
}
export const styleSheet = createStyleSheet('MuiInput', theme => ({
wrapper: {
// Mimics the default input display property used by browsers for an input.
display: 'inline-block',
position: 'relative',
fontFamily: theme.typography.fontFamily,
},
formControl: {
marginTop: 10,
marginBottom: 10,
},
inkbar: {
'&:after': {
backgroundColor: theme.palette.primary[500],
left: 0,
bottom: -2,
// Doing the other way around crash on IE11 "''" https://github.com/cssinjs/jss/issues/242
content: '""',
height: 2,
position: 'absolute',
right: 0,
transform: 'scaleX(0)',
transition: theme.transitions.create('transform', {
duration: theme.transitions.duration.shorter,
easing: theme.transitions.easing.easeOut,
}),
},
'&$focused:after': {
transform: 'scaleX(1)',
},
},
focused: {},
error: {
'&:after': {
backgroundColor: theme.palette.error[500],
transform: 'scaleX(1)', // error is always underlined in red
},
},
input: {
font: 'inherit',
padding: '6px 0',
border: 0,
display: 'block',
verticalAlign: 'middle',
whiteSpace: 'normal',
background: 'none',
margin: 0, // Reset for Safari
color: theme.palette.text.primary,
width: '100%',
'&:focus': {
outline: 0,
},
'&::-webkit-search-decoration': {
// Remove the padding when type=search.
appearance: 'none',
},
},
singleline: {
appearance: 'textfield', // Improve type search style.
},
multiline: {
resize: 'none',
padding: 0,
},
multilineWrapper: {
padding: '6px 0',
},
disabled: {
color: theme.palette.text.disabled,
},
underline: {
borderBottom: `1px solid ${theme.palette.text.divider}`,
'&$disabled': {
borderBottomStyle: 'dotted',
},
},
}));
class Input extends Component {
static defaultProps = {
disabled: false,
type: 'text',
disableUnderline: false,
multiline: false,
};
state = {
focused: false,
};
componentWillMount() {
if (this.isControlled()) {
this.checkDirty(this.props);
}
}
componentDidMount() {
if (!this.isControlled()) {
this.checkDirty(this.input);
}
}
componentWillUpdate(nextProps) {
if (this.isControlled()) {
this.checkDirty(nextProps);
}
}
// Holds the input reference
input = null;
handleFocus = event => {
this.setState({ focused: true });
if (this.props.onFocus) {
this.props.onFocus(event);
}
};
handleBlur = event => {
this.setState({ focused: false });
if (this.props.onBlur) {
this.props.onBlur(event);
}
};
handleChange = event => {
if (!this.isControlled()) {
this.checkDirty(this.input);
}
if (this.props.onChange) {
this.props.onChange(event);
}
};
handleRefInput = node => {
this.input = node;
if (this.props.inputRef) {
this.props.inputRef(node);
}
};
handleRefTextarea = node => {
this.input = node;
if (this.props.inputRef) {
this.props.inputRef(node);
}
};
isControlled() {
return typeof this.props.value === 'string';
}
checkDirty(obj) {
const { muiFormControl } = this.context;
if (isDirty(obj)) {
if (muiFormControl && muiFormControl.onDirty) {
muiFormControl.onDirty();
}
if (this.props.onDirty) {
this.props.onDirty();
}
return;
}
if (muiFormControl && muiFormControl.onClean) {
muiFormControl.onClean();
}
if (this.props.onClean) {
this.props.onClean();
}
}
render() {
const {
classes,
className: classNameProp,
component,
defaultValue,
disabled,
disableUnderline,
error: errorProp,
id,
inputClassName: inputClassNameProp,
inputProps: inputPropsProp,
inputRef, // eslint-disable-line no-unused-vars
multiline,
onBlur, // eslint-disable-line no-unused-vars
onFocus, // eslint-disable-line no-unused-vars
onChange, // eslint-disable-line no-unused-vars
onKeyDown,
onKeyUp,
placeholder,
name,
rows,
rowsMax,
type,
value,
...other
} = this.props;
const { muiFormControl } = this.context;
let error = errorProp;
if (typeof error === 'undefined' && muiFormControl) {
error = muiFormControl.error;
}
const wrapperClassName = classNames(
classes.wrapper,
{
[classes.disabled]: disabled,
[classes.error]: error,
[classes.focused]: this.state.focused,
[classes.formControl]: muiFormControl,
[classes.inkbar]: !disableUnderline,
[classes.multilineWrapper]: multiline,
[classes.underline]: !disableUnderline,
},
classNameProp,
);
const inputClassName = classNames(
classes.input,
{
[classes.disabled]: disabled,
[classes.singleline]: !multiline,
[classes.multiline]: multiline,
},
inputClassNameProp,
);
const required = muiFormControl && muiFormControl.required === true;
let InputComponent = 'input';
let inputProps = {
ref: this.handleRefInput,
...inputPropsProp,
};
if (component) {
inputProps = {
rowsMax,
...inputProps,
};
InputComponent = component;
} else if (multiline) {
if (rows && !rowsMax) {
inputProps = {
...inputProps,
};
InputComponent = 'textarea';
} else {
inputProps = {
rowsMax,
textareaRef: this.handleRefTextarea,
...inputProps,
ref: null,
};
InputComponent = Textarea;
}
}
return (
<div className={wrapperClassName} {...other}>
<InputComponent
className={inputClassName}
onBlur={this.handleBlur}
onFocus={this.handleFocus}
onChange={this.handleChange}
onKeyUp={onKeyUp}
onKeyDown={onKeyDown}
disabled={disabled}
aria-required={required ? true : undefined}
value={value}
id={id}
name={name}
defaultValue={defaultValue}
placeholder={placeholder}
type={type}
rows={rows}
{...inputProps}
/>
</div>
);
}
}
Input.propTypes = {
/**
* Useful to extend the style applied to components.
*/
classes: PropTypes.object.isRequired,
/**
* The CSS class name of the wrapper element.
*/
className: PropTypes.string,
/**
* The component used for the root node.
* Either a string to use a DOM element or a component.
* It's an `input` by default.
*/
component: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),
/**
* The default value of the `Input` element.
*/
defaultValue: PropTypes.string,
/**
* If `true`, the input will be disabled.
*/
disabled: PropTypes.bool,
/**
* If `true`, the input will not have an underline.
*/
disableUnderline: PropTypes.bool,
/**
* If `true`, the input will indicate an error.
*/
error: PropTypes.bool,
/*
* @ignore
*/
id: PropTypes.string,
/**
* The CSS class name of the input element.
*/
inputClassName: PropTypes.string,
/**
* Properties applied to the `input` element.
*/
inputProps: PropTypes.object,
/**
* Use that property to pass a ref callback to the native input component.
*/
inputRef: PropTypes.func,
/**
* If `true`, a textarea element will be rendered.
*/
multiline: PropTypes.bool,
/**
* @ignore
*/
name: PropTypes.string,
/**
* @ignore
*/
onBlur: PropTypes.func,
/**
* @ignore
*/
onChange: PropTypes.func,
/**
* @ignore
*/
onClean: PropTypes.func,
/**
* @ignore
*/
onDirty: PropTypes.func,
/**
* @ignore
*/
onFocus: PropTypes.func,
/**
* @ignore
*/
onKeyDown: PropTypes.func,
/**
* @ignore
*/
onKeyUp: PropTypes.func,
/**
* @ignore
*/
placeholder: PropTypes.string,
/**
* Number of rows to display when multiline option is set to true.
*/
rows: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
/**
* Maxium number of rows to display when multiline option is set to true.
*/
rowsMax: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
/**
* Type of the input element. It should be a valid HTML5 input type.
*/
type: PropTypes.string,
/**
* The input value, required for a controlled component.
*/
value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
};
Input.contextTypes = {
muiFormControl: PropTypes.object,
};
export default withStyles(styleSheet)(Input);
| src/Input/Input.js | 1 | https://github.com/mui/material-ui/commit/2611239179c1457b8e5fd9513d2d32b67b8e90f2 | [
0.9948890805244446,
0.09469256550073624,
0.00016473871073685586,
0.00017029792070388794,
0.2901063859462738
] |
{
"id": 3,
"code_window": [
" appearance: 'none',\n",
" },\n",
" },\n",
" singleline: {\n",
" appearance: 'textfield', // Improve type search style.\n",
" },\n",
" multiline: {\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" height: '1em',\n"
],
"file_path": "src/Input/Input.js",
"type": "add",
"edit_start_line_idx": 71
} | // @flow weak
import React from 'react';
import BottomNavigation, { BottomNavigationButton } from 'material-ui/BottomNavigation';
import Icon from 'material-ui/Icon';
export default function LabelBottomNavigation() {
return (
<BottomNavigation index={0} showLabel={false}>
<BottomNavigationButton label="Recents" icon={<Icon>restore</Icon>} />
<BottomNavigationButton label="Favorites" icon={<Icon>favorite</Icon>} />
</BottomNavigation>
);
}
| test/regressions/tests/BottomNavigation/LabelBottomNavigation.js | 0 | https://github.com/mui/material-ui/commit/2611239179c1457b8e5fd9513d2d32b67b8e90f2 | [
0.00016998079081531614,
0.00016844208585098386,
0.0001669033954385668,
0.00016844208585098386,
0.0000015386976883746684
] |
{
"id": 3,
"code_window": [
" appearance: 'none',\n",
" },\n",
" },\n",
" singleline: {\n",
" appearance: 'textfield', // Improve type search style.\n",
" },\n",
" multiline: {\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" height: '1em',\n"
],
"file_path": "src/Input/Input.js",
"type": "add",
"edit_start_line_idx": 71
} | ---
components: Card, CardActions, CardContent, CardHeader, CardMedia, Collapse
---
# Cards
A [card](https://material.google.com/components/cards.html) is a sheet of material that serves as an entry point to more detailed information.
Cards display content composed of different elements whose size or supported actions vary.
Cards are a convenient means of displaying content composed of different elements. They’re also well-suited for showcasing elements whose size or supported actions vary, like photos with captions of variable length.
## Simple Card
Although cards can support multiple actions, UI controls, and an overflow menu, use restraint and remember that cards are entry points to more complex and detailed information.
{{demo='pages/component-demos/cards/SimpleCard.js'}}
## Media
Example of a card using an image to reinforce the content.
{{demo='pages/component-demos/cards/SimpleMediaCard.js'}}
## UI Controls
Supplemental actions within the card are explicitly called out using icons, text, and UI controls, typically placed at the bottom of the card.
Here's an example of a media control card.
{{demo='pages/component-demos/cards/NowPlayingCard.js'}}
## Complex Interaction
On desktop, card content can expand and scroll internally.
{{demo='pages/component-demos/cards/RecipeReviewCard.js'}}
| docs/src/pages/component-demos/cards/cards.md | 0 | https://github.com/mui/material-ui/commit/2611239179c1457b8e5fd9513d2d32b67b8e90f2 | [
0.00016749583301134408,
0.00016650487668812275,
0.00016502341895829886,
0.00016675013466738164,
9.080772542802151e-7
] |
{
"id": 3,
"code_window": [
" appearance: 'none',\n",
" },\n",
" },\n",
" singleline: {\n",
" appearance: 'textfield', // Improve type search style.\n",
" },\n",
" multiline: {\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" height: '1em',\n"
],
"file_path": "src/Input/Input.js",
"type": "add",
"edit_start_line_idx": 71
} | ## Roadmap
The roadmap is a living document, and it is likely that priorities will change, but the list below should give some indication of our plans for the next major release, and for the future.
### 0.15.0
#### Breaking Changes
- Remove deprecated usage of JSON to generate children across the components.
- [[#3108](https://github.com/callemall/material-ui/pull/3108)] Remove deprecated components, methods & props.
- [[#2957](https://github.com/callemall/material-ui/issues/2957)] Standardize callback signatures.
- [[#2980](https://github.com/callemall/material-ui/issues/2980)] [[#1839](https://github.com/callemall/material-ui/issues/1839)] Standardise Datepicker for ISO 8601.
#### Deprecations
- [[#2880](https://github.com/callemall/material-ui/issues/2880)] Deprecate valueLink.
- [[#1793](https://github.com/callemall/material-ui/issues/1793)][[#2679](https://github.com/callemall/material-ui/issues/2679)] PascalCase component names and reorganise directory structure. Deprecate old names.
- [[#2697](https://github.com/callemall/material-ui/issues/2697)] Rename LeftNav and deprecate old name.
#### Core
- [[#2903](https://github.com/callemall/material-ui/issues/2903)] Enforce eslint rules.
- [[#2493](https://github.com/callemall/material-ui/pull/2493)] Use higher order components across the library to abstract themes passed down from context.
- [[#2627](https://github.com/callemall/material-ui/issues/2627)] Improve overall theme handling.
- [[#2573](https://github.com/callemall/material-ui/issues/2573)] Remove the usage of isMounted().
- [[#2437](https://github.com/callemall/material-ui/issues/2437)] Remove mixins.
#### Major features
- [[#1321](https://github.com/callemall/material-ui/pull/1321#issuecomment-174108805)] Composable AppBar component.
- [[#3132](https://github.com/callemall/material-ui/pull/3132)] New Stepper component.
- [[#2861](https://github.com/callemall/material-ui/pull/2861)] Scrollable Tabs.
- [[#2979](https://github.com/callemall/material-ui/pull/2979)] New Subheader component.
#### Documentation
- [[#1986](https://github.com/callemall/material-ui/issues/1986)]Documentation versioning.
- Add example on how to use [react-list](https://github.com/orgsync/react-list) for lists, menu items and table.
- [[#2635](https://github.com/callemall/material-ui/pull/2635)] Document the new theme calculation, and it's usage.
- [[#3191](https://github.com/callemall/material-ui/issues/3191)] Improve component property documentation.
### Future
#### Deprecations
- Deprecate & eventually remove all imperative methods.
#### Core
- Make extensive use of `popover` and `render-to-layer`.
- [[#458](https://github.com/callemall/material-ui/issues/458)] Migrate components to [ES6 Classes](https://github.com/callemall/material-ui/tree/es6-classes).
- [[#2784](https://github.com/callemall/material-ui/issues/2784)] Stateless components.
- Improve performance with `shouldComponentUpdate` and removed inefficient computations.
- Standardize API naming and available `prop` convention across the library.
- Better accessibility support.
- Better keyboard navigation support.
#### Features
- [[#2416](https://github.com/callemall/material-ui/issues/2416)] TextField as a composable component for various field types.
- Responsive components to better support MD spec for mobile component sizes, and in preparation for react-native support.
- [[#2863](https://github.com/callemall/material-ui/issues/2863)] Add missing components, and missing features from current ones.
- [[#2251](https://github.com/callemall/material-ui/issues/2251)] Full featured Table.
- Full Featured Tabs (close, [disable](https://github.com/callemall/material-ui/issues/1613), move, sizing, [scrolling](https://github.com/callemall/material-ui/pull/2861)).
- Full support for react-native
- [[#1673](https://github.com/callemall/material-ui/issues/1673)] I18n for the doc-site.
| ROADMAP.md | 0 | https://github.com/mui/material-ui/commit/2611239179c1457b8e5fd9513d2d32b67b8e90f2 | [
0.0004121581732761115,
0.00020144577138125896,
0.00016486678214278072,
0.00016598004731349647,
0.00008604235335951671
] |
{
"id": 0,
"code_window": [
" changed_by_name: changedByName,\n",
" changed_by_url: changedByUrl,\n",
" },\n",
" },\n",
" }: any) => <a href={changedByUrl}>{changedByName}</a>,\n",
" Header: t('Creator'),\n",
" accessor: 'changed_by_fk',\n",
" },\n",
" {\n",
" Cell: ({\n",
" row: {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" Header: t('Modified By'),\n",
" accessor: 'changed_by.first_name',\n"
],
"file_path": "superset-frontend/src/views/chartList/ChartList.tsx",
"type": "replace",
"edit_start_line_idx": 148
} | # 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 json
import logging
from typing import Any, Dict
import simplejson
from flask import g, make_response, redirect, request, Response, url_for
from flask_appbuilder.api import expose, protect, rison, safe
from flask_appbuilder.models.sqla.interface import SQLAInterface
from flask_babel import gettext as _, ngettext
from marshmallow import ValidationError
from werkzeug.wrappers import Response as WerkzeugResponse
from werkzeug.wsgi import FileWrapper
from superset import is_feature_enabled, thumbnail_cache
from superset.charts.commands.bulk_delete import BulkDeleteChartCommand
from superset.charts.commands.create import CreateChartCommand
from superset.charts.commands.delete import DeleteChartCommand
from superset.charts.commands.exceptions import (
ChartBulkDeleteFailedError,
ChartCreateFailedError,
ChartDeleteFailedError,
ChartForbiddenError,
ChartInvalidError,
ChartNotFoundError,
ChartUpdateFailedError,
)
from superset.charts.commands.update import UpdateChartCommand
from superset.charts.dao import ChartDAO
from superset.charts.filters import ChartFilter, ChartNameOrDescriptionFilter
from superset.charts.schemas import (
CHART_SCHEMAS,
ChartDataQueryContextSchema,
ChartPostSchema,
ChartPutSchema,
get_delete_ids_schema,
openapi_spec_methods_override,
screenshot_query_schema,
thumbnail_query_schema,
)
from superset.constants import RouteMethod
from superset.exceptions import SupersetSecurityException
from superset.extensions import event_logger
from superset.models.slice import Slice
from superset.tasks.thumbnails import cache_chart_thumbnail
from superset.utils.core import ChartDataResultFormat, json_int_dttm_ser
from superset.utils.screenshots import ChartScreenshot
from superset.utils.urls import get_url_path
from superset.views.base_api import (
BaseSupersetModelRestApi,
RelatedFieldFilter,
statsd_metrics,
)
from superset.views.core import CsvResponse, generate_download_headers
from superset.views.filters import FilterRelatedOwners
logger = logging.getLogger(__name__)
class ChartRestApi(BaseSupersetModelRestApi):
datamodel = SQLAInterface(Slice)
resource_name = "chart"
allow_browser_login = True
include_route_methods = RouteMethod.REST_MODEL_VIEW_CRUD_SET | {
RouteMethod.EXPORT,
RouteMethod.RELATED,
"bulk_delete", # not using RouteMethod since locally defined
"data",
"viz_types",
"datasources",
}
class_permission_name = "SliceModelView"
show_columns = [
"slice_name",
"description",
"owners.id",
"owners.username",
"owners.first_name",
"owners.last_name",
"dashboards.id",
"dashboards.dashboard_title",
"viz_type",
"params",
"cache_timeout",
]
show_select_columns = show_columns + ["table.id"]
list_columns = [
"id",
"slice_name",
"url",
"description",
"changed_by_fk",
"created_by_fk",
"changed_by_name",
"changed_by_url",
"changed_by.first_name",
"changed_by.last_name",
"changed_on_utc",
"changed_on_delta_humanized",
"datasource_id",
"datasource_type",
"datasource_name_text",
"datasource_url",
"table.default_endpoint",
"table.table_name",
"viz_type",
"params",
"cache_timeout",
]
list_select_columns = list_columns + ["changed_on"]
order_columns = [
"slice_name",
"viz_type",
"datasource_name",
"changed_by_fk",
"changed_on_delta_humanized",
]
search_columns = (
"slice_name",
"description",
"viz_type",
"datasource_name",
"datasource_id",
"datasource_type",
"owners",
)
base_order = ("changed_on", "desc")
base_filters = [["id", ChartFilter, lambda: []]]
search_filters = {"slice_name": [ChartNameOrDescriptionFilter]}
# Will just affect _info endpoint
edit_columns = ["slice_name"]
add_columns = edit_columns
add_model_schema = ChartPostSchema()
edit_model_schema = ChartPutSchema()
openapi_spec_tag = "Charts"
""" Override the name set for this collection of endpoints """
openapi_spec_component_schemas = CHART_SCHEMAS
apispec_parameter_schemas = {
"screenshot_query_schema": screenshot_query_schema,
"get_delete_ids_schema": get_delete_ids_schema,
}
""" Add extra schemas to the OpenAPI components schema section """
openapi_spec_methods = openapi_spec_methods_override
""" Overrides GET methods OpenApi descriptions """
order_rel_fields = {
"slices": ("slice_name", "asc"),
"owners": ("first_name", "asc"),
}
related_field_filters = {
"owners": RelatedFieldFilter("first_name", FilterRelatedOwners)
}
allowed_rel_fields = {"owners"}
def __init__(self) -> None:
if is_feature_enabled("THUMBNAILS"):
self.include_route_methods = self.include_route_methods | {
"thumbnail",
"screenshot",
"cache_screenshot",
}
super().__init__()
@expose("/", methods=["POST"])
@protect()
@safe
@statsd_metrics
def post(self) -> Response:
"""Creates a new Chart
---
post:
description: >-
Create a new Chart.
requestBody:
description: Chart schema
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/{{self.__class__.__name__}}.post'
responses:
201:
description: Chart added
content:
application/json:
schema:
type: object
properties:
id:
type: number
result:
$ref: '#/components/schemas/{{self.__class__.__name__}}.post'
400:
$ref: '#/components/responses/400'
401:
$ref: '#/components/responses/401'
422:
$ref: '#/components/responses/422'
500:
$ref: '#/components/responses/500'
"""
if not request.is_json:
return self.response_400(message="Request is not JSON")
try:
item = self.add_model_schema.load(request.json)
# This validates custom Schema with custom validations
except ValidationError as error:
return self.response_400(message=error.messages)
try:
new_model = CreateChartCommand(g.user, item).run()
return self.response(201, id=new_model.id, result=item)
except ChartInvalidError as ex:
return self.response_422(message=ex.normalized_messages())
except ChartCreateFailedError as ex:
logger.error(
"Error creating model %s: %s", self.__class__.__name__, str(ex)
)
return self.response_422(message=str(ex))
@expose("/<pk>", methods=["PUT"])
@protect()
@safe
@statsd_metrics
def put( # pylint: disable=too-many-return-statements, arguments-differ
self, pk: int
) -> Response:
"""Changes a Chart
---
put:
description: >-
Changes a Chart.
parameters:
- in: path
schema:
type: integer
name: pk
requestBody:
description: Chart schema
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/{{self.__class__.__name__}}.put'
responses:
200:
description: Chart changed
content:
application/json:
schema:
type: object
properties:
id:
type: number
result:
$ref: '#/components/schemas/{{self.__class__.__name__}}.put'
400:
$ref: '#/components/responses/400'
401:
$ref: '#/components/responses/401'
403:
$ref: '#/components/responses/403'
404:
$ref: '#/components/responses/404'
422:
$ref: '#/components/responses/422'
500:
$ref: '#/components/responses/500'
"""
if not request.is_json:
return self.response_400(message="Request is not JSON")
try:
item = self.edit_model_schema.load(request.json)
# This validates custom Schema with custom validations
except ValidationError as error:
return self.response_400(message=error.messages)
try:
changed_model = UpdateChartCommand(g.user, pk, item).run()
return self.response(200, id=changed_model.id, result=item)
except ChartNotFoundError:
return self.response_404()
except ChartForbiddenError:
return self.response_403()
except ChartInvalidError as ex:
return self.response_422(message=ex.normalized_messages())
except ChartUpdateFailedError as ex:
logger.error(
"Error updating model %s: %s", self.__class__.__name__, str(ex)
)
return self.response_422(message=str(ex))
@expose("/<pk>", methods=["DELETE"])
@protect()
@safe
@statsd_metrics
def delete(self, pk: int) -> Response: # pylint: disable=arguments-differ
"""Deletes a Chart
---
delete:
description: >-
Deletes a Chart.
parameters:
- in: path
schema:
type: integer
name: pk
responses:
200:
description: Chart delete
content:
application/json:
schema:
type: object
properties:
message:
type: string
401:
$ref: '#/components/responses/401'
403:
$ref: '#/components/responses/403'
404:
$ref: '#/components/responses/404'
422:
$ref: '#/components/responses/422'
500:
$ref: '#/components/responses/500'
"""
try:
DeleteChartCommand(g.user, pk).run()
return self.response(200, message="OK")
except ChartNotFoundError:
return self.response_404()
except ChartForbiddenError:
return self.response_403()
except ChartDeleteFailedError as ex:
logger.error(
"Error deleting model %s: %s", self.__class__.__name__, str(ex)
)
return self.response_422(message=str(ex))
@expose("/", methods=["DELETE"])
@protect()
@safe
@statsd_metrics
@rison(get_delete_ids_schema)
def bulk_delete(
self, **kwargs: Any
) -> Response: # pylint: disable=arguments-differ
"""Delete bulk Charts
---
delete:
description: >-
Deletes multiple Charts in a bulk operation.
parameters:
- in: query
name: q
content:
application/json:
schema:
$ref: '#/components/schemas/get_delete_ids_schema'
responses:
200:
description: Charts bulk delete
content:
application/json:
schema:
type: object
properties:
message:
type: string
401:
$ref: '#/components/responses/401'
403:
$ref: '#/components/responses/403'
404:
$ref: '#/components/responses/404'
422:
$ref: '#/components/responses/422'
500:
$ref: '#/components/responses/500'
"""
item_ids = kwargs["rison"]
try:
BulkDeleteChartCommand(g.user, item_ids).run()
return self.response(
200,
message=ngettext(
"Deleted %(num)d chart", "Deleted %(num)d charts", num=len(item_ids)
),
)
except ChartNotFoundError:
return self.response_404()
except ChartForbiddenError:
return self.response_403()
except ChartBulkDeleteFailedError as ex:
return self.response_422(message=str(ex))
@expose("/data", methods=["POST"])
@event_logger.log_this
@protect()
@safe
@statsd_metrics
def data(self) -> Response: # pylint: disable=too-many-return-statements
"""
Takes a query context constructed in the client and returns payload
data response for the given query.
---
post:
description: >-
Takes a query context constructed in the client and returns payload data
response for the given query.
requestBody:
description: >-
A query context consists of a datasource from which to fetch data
and one or many query objects.
required: true
content:
application/json:
schema:
$ref: "#/components/schemas/ChartDataQueryContextSchema"
responses:
200:
description: Query result
content:
application/json:
schema:
$ref: "#/components/schemas/ChartDataResponseSchema"
400:
$ref: '#/components/responses/400'
500:
$ref: '#/components/responses/500'
"""
if request.is_json:
json_body = request.json
elif request.form.get("form_data"):
# CSV export submits regular form data
json_body = json.loads(request.form["form_data"])
else:
return self.response_400(message="Request is not JSON")
try:
query_context = ChartDataQueryContextSchema().load(json_body)
except KeyError:
return self.response_400(message="Request is incorrect")
except ValidationError as error:
return self.response_400(
message=_("Request is incorrect: %(error)s", error=error.messages)
)
try:
query_context.raise_for_access()
except SupersetSecurityException:
return self.response_401()
payload = query_context.get_payload()
for query in payload:
if query.get("error"):
return self.response_400(message=f"Error: {query['error']}")
result_format = query_context.result_format
if result_format == ChartDataResultFormat.CSV:
# return the first result
result = payload[0]["data"]
return CsvResponse(
result,
status=200,
headers=generate_download_headers("csv"),
mimetype="application/csv",
)
if result_format == ChartDataResultFormat.JSON:
response_data = simplejson.dumps(
{"result": payload}, default=json_int_dttm_ser, ignore_nan=True
)
resp = make_response(response_data, 200)
resp.headers["Content-Type"] = "application/json; charset=utf-8"
return resp
return self.response_400(message=f"Unsupported result_format: {result_format}")
@expose("/<pk>/cache_screenshot/", methods=["GET"])
@protect()
@rison(screenshot_query_schema)
@safe
@statsd_metrics
def cache_screenshot(self, pk: int, **kwargs: Dict[str, bool]) -> WerkzeugResponse:
"""
---
get:
description: Compute and cache a screenshot.
parameters:
- in: path
schema:
type: integer
name: pk
- in: query
name: q
content:
application/json:
schema:
$ref: '#/components/schemas/screenshot_query_schema'
responses:
200:
description: Chart async result
content:
application/json:
schema:
$ref: "#/components/schemas/ChartCacheScreenshotResponseSchema"
302:
description: Redirects to the current digest
400:
$ref: '#/components/responses/400'
401:
$ref: '#/components/responses/401'
404:
$ref: '#/components/responses/404'
500:
$ref: '#/components/responses/500'
"""
rison_dict = kwargs["rison"]
window_size = rison_dict.get("window_size") or (800, 600)
# Don't shrink the image if thumb_size is not specified
thumb_size = rison_dict.get("thumb_size") or window_size
chart = self.datamodel.get(pk, self._base_filters)
if not chart:
return self.response_404()
chart_url = get_url_path("Superset.slice", slice_id=chart.id, standalone="true")
screenshot_obj = ChartScreenshot(chart_url, chart.digest)
cache_key = screenshot_obj.cache_key(window_size, thumb_size)
image_url = get_url_path(
"ChartRestApi.screenshot", pk=chart.id, digest=cache_key
)
def trigger_celery() -> WerkzeugResponse:
logger.info("Triggering screenshot ASYNC")
kwargs = {
"url": chart_url,
"digest": chart.digest,
"force": True,
"window_size": window_size,
"thumb_size": thumb_size,
}
cache_chart_thumbnail.delay(**kwargs)
return self.response(
202, cache_key=cache_key, chart_url=chart_url, image_url=image_url,
)
return trigger_celery()
@expose("/<pk>/screenshot/<digest>/", methods=["GET"])
@protect()
@rison(screenshot_query_schema)
@safe
@statsd_metrics
def screenshot(self, pk: int, digest: str) -> WerkzeugResponse:
"""Get Chart screenshot
---
get:
description: Get a computed screenshot from cache.
parameters:
- in: path
schema:
type: integer
name: pk
- in: path
schema:
type: string
name: digest
responses:
200:
description: Chart thumbnail image
content:
image/*:
schema:
type: string
format: binary
302:
description: Redirects to the current digest
400:
$ref: '#/components/responses/400'
401:
$ref: '#/components/responses/401'
404:
$ref: '#/components/responses/404'
500:
$ref: '#/components/responses/500'
"""
chart = self.datamodel.get(pk, self._base_filters)
# Making sure the chart still exists
if not chart:
return self.response_404()
# TODO make sure the user has access to the chart
# fetch the chart screenshot using the current user and cache if set
img = ChartScreenshot.get_from_cache_key(thumbnail_cache, digest)
if img:
return Response(
FileWrapper(img), mimetype="image/png", direct_passthrough=True
)
# TODO: return an empty image
return self.response_404()
@expose("/<pk>/thumbnail/<digest>/", methods=["GET"])
@protect()
@rison(thumbnail_query_schema)
@safe
@statsd_metrics
def thumbnail(
self, pk: int, digest: str, **kwargs: Dict[str, bool]
) -> WerkzeugResponse:
"""Get Chart thumbnail
---
get:
description: Compute or get already computed chart thumbnail from cache.
parameters:
- in: path
schema:
type: integer
name: pk
- in: path
schema:
type: string
name: digest
responses:
200:
description: Chart thumbnail image
/content:
image/*:
schema:
type: string
format: binary
302:
description: Redirects to the current digest
400:
$ref: '#/components/responses/400'
401:
$ref: '#/components/responses/401'
404:
$ref: '#/components/responses/404'
500:
$ref: '#/components/responses/500'
"""
chart = self.datamodel.get(pk, self._base_filters)
if not chart:
return self.response_404()
url = get_url_path("Superset.slice", slice_id=chart.id, standalone="true")
if kwargs["rison"].get("force", False):
logger.info(
"Triggering thumbnail compute (chart id: %s) ASYNC", str(chart.id)
)
cache_chart_thumbnail.delay(url, chart.digest, force=True)
return self.response(202, message="OK Async")
# fetch the chart screenshot using the current user and cache if set
screenshot = ChartScreenshot(url, chart.digest).get_from_cache(
cache=thumbnail_cache
)
# If not screenshot then send request to compute thumb to celery
if not screenshot:
logger.info(
"Triggering thumbnail compute (chart id: %s) ASYNC", str(chart.id)
)
cache_chart_thumbnail.delay(url, chart.digest, force=True)
return self.response(202, message="OK Async")
# If digests
if chart.digest != digest:
return redirect(
url_for(
f"{self.__class__.__name__}.thumbnail", pk=pk, digest=chart.digest
)
)
return Response(
FileWrapper(screenshot), mimetype="image/png", direct_passthrough=True
)
@expose("/datasources", methods=["GET"])
@protect()
@safe
def datasources(self) -> Response:
"""Get available datasources
---
get:
description: Get available datasources.
responses:
200:
description: Query result
content:
application/json:
schema:
$ref: "#/components/schemas/ChartGetDatasourceResponseSchema"
400:
$ref: '#/components/responses/400'
401:
$ref: '#/components/responses/401'
404:
$ref: '#/components/responses/404'
422:
$ref: '#/components/responses/422'
500:
$ref: '#/components/responses/500'
"""
datasources = ChartDAO.fetch_all_datasources()
if not datasources:
return self.response(200, count=0, result=[])
result = [
{
"label": str(ds),
"value": {"datasource_id": ds.id, "datasource_type": ds.type},
}
for ds in datasources
]
return self.response(200, count=len(result), result=result)
| superset/charts/api.py | 1 | https://github.com/apache/superset/commit/2b061fc64b88831574878b6bd470d700a1527dec | [
0.0003260699741076678,
0.00017228606157004833,
0.00016364747716579586,
0.00017016558558680117,
0.000018211518181487918
] |
{
"id": 0,
"code_window": [
" changed_by_name: changedByName,\n",
" changed_by_url: changedByUrl,\n",
" },\n",
" },\n",
" }: any) => <a href={changedByUrl}>{changedByName}</a>,\n",
" Header: t('Creator'),\n",
" accessor: 'changed_by_fk',\n",
" },\n",
" {\n",
" Cell: ({\n",
" row: {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" Header: t('Modified By'),\n",
" accessor: 'changed_by.first_name',\n"
],
"file_path": "superset-frontend/src/views/chartList/ChartList.tsx",
"type": "replace",
"edit_start_line_idx": 148
} | /**
* 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 { mount } from 'enzyme';
import CssEditor from 'src/dashboard/components/CssEditor';
describe('CssEditor', () => {
const mockedProps = {
triggerNode: <i className="fa fa-edit" />,
};
it('is valid', () => {
expect(React.isValidElement(<CssEditor {...mockedProps} />)).toBe(true);
});
it('renders the trigger node', () => {
const wrapper = mount(<CssEditor {...mockedProps} />);
expect(wrapper.find('.fa-edit')).toHaveLength(1);
});
});
| superset-frontend/spec/javascripts/dashboard/components/CssEditor_spec.jsx | 0 | https://github.com/apache/superset/commit/2b061fc64b88831574878b6bd470d700a1527dec | [
0.00017562010907568038,
0.0001743584289215505,
0.00017232935351785272,
0.00017474210471846163,
0.0000012259407640158315
] |
{
"id": 0,
"code_window": [
" changed_by_name: changedByName,\n",
" changed_by_url: changedByUrl,\n",
" },\n",
" },\n",
" }: any) => <a href={changedByUrl}>{changedByName}</a>,\n",
" Header: t('Creator'),\n",
" accessor: 'changed_by_fk',\n",
" },\n",
" {\n",
" Cell: ({\n",
" row: {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" Header: t('Modified By'),\n",
" accessor: 'changed_by.first_name',\n"
],
"file_path": "superset-frontend/src/views/chartList/ChartList.tsx",
"type": "replace",
"edit_start_line_idx": 148
} | /**
* 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 { getChartControlPanelRegistry } from '@superset-ui/chart';
import { applyDefaultFormData } from 'src/explore/store';
describe('store', () => {
beforeAll(() => {
getChartControlPanelRegistry().registerValue('test-chart', {
controlPanelSections: [
{
label: 'Test section',
expanded: true,
controlSetRows: [['row_limit']],
},
],
});
});
afterAll(() => {
getChartControlPanelRegistry().remove('test-chart');
});
describe('applyDefaultFormData', () => {
window.featureFlags = {
SCOPED_FILTER: false,
};
it('applies default to formData if the key is missing', () => {
const inputFormData = {
datasource: '11_table',
viz_type: 'test-chart',
};
let outputFormData = applyDefaultFormData(inputFormData);
expect(outputFormData.row_limit).toEqual(10000);
const inputWithRowLimit = {
...inputFormData,
row_limit: 888,
};
outputFormData = applyDefaultFormData(inputWithRowLimit);
expect(outputFormData.row_limit).toEqual(888);
});
it('keeps null if key is defined with null', () => {
const inputFormData = {
datasource: '11_table',
viz_type: 'test-chart',
row_limit: null,
};
const outputFormData = applyDefaultFormData(inputFormData);
expect(outputFormData.row_limit).toBe(null);
});
it('removes out of scope, or deprecated keys', () => {
const staleQueryFields = { staleKey: 'staleValue' };
const inputFormData = {
datasource: '11_table',
viz_type: 'table',
queryFields: staleQueryFields,
this_should_no_be_here: true,
};
const outputFormData = applyDefaultFormData(inputFormData);
expect(outputFormData.this_should_no_be_here).toBe(undefined);
expect(outputFormData.queryFields).not.toBe(staleQueryFields);
});
});
});
| superset-frontend/spec/javascripts/explore/store_spec.jsx | 0 | https://github.com/apache/superset/commit/2b061fc64b88831574878b6bd470d700a1527dec | [
0.00017622682207729667,
0.00017169069906231016,
0.00016704588779248297,
0.00017098343232646585,
0.0000026646007427189033
] |
{
"id": 0,
"code_window": [
" changed_by_name: changedByName,\n",
" changed_by_url: changedByUrl,\n",
" },\n",
" },\n",
" }: any) => <a href={changedByUrl}>{changedByName}</a>,\n",
" Header: t('Creator'),\n",
" accessor: 'changed_by_fk',\n",
" },\n",
" {\n",
" Cell: ({\n",
" row: {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" Header: t('Modified By'),\n",
" accessor: 'changed_by.first_name',\n"
],
"file_path": "superset-frontend/src/views/chartList/ChartList.tsx",
"type": "replace",
"edit_start_line_idx": 148
} | /**
* 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 { NEW_COMPONENTS_SOURCE_ID } from './constants';
import findParentId from './findParentId';
import getDetailedComponentWidth from './getDetailedComponentWidth';
import newComponentFactory from './newComponentFactory';
export default function getComponentWidthFromDrop({
dropResult,
layout: components,
}) {
const { source, destination, dragging } = dropResult;
const isNewComponent = source.id === NEW_COMPONENTS_SOURCE_ID;
const component = isNewComponent
? newComponentFactory(dragging.type)
: components[dragging.id] || {};
// moving a component within the same container shouldn't change its width
if (source.id === destination.id) {
return component.meta.width;
}
const draggingWidth = getDetailedComponentWidth({
component,
components,
});
const destinationWidth = getDetailedComponentWidth({
id: destination.id,
components,
});
let destinationCapacity =
destinationWidth.width - destinationWidth.occupiedWidth;
if (isNaN(destinationCapacity)) {
const grandparentWidth = getDetailedComponentWidth({
id: findParentId({
childId: destination.id,
layout: components,
}),
components,
});
destinationCapacity =
grandparentWidth.width - grandparentWidth.occupiedWidth;
}
if (isNaN(destinationCapacity) || isNaN(draggingWidth.width)) {
return draggingWidth.width;
} else if (destinationCapacity >= draggingWidth.width) {
return draggingWidth.width;
} else if (destinationCapacity >= draggingWidth.minimumWidth) {
return destinationCapacity;
}
return -1;
}
| superset-frontend/src/dashboard/util/getComponentWidthFromDrop.js | 0 | https://github.com/apache/superset/commit/2b061fc64b88831574878b6bd470d700a1527dec | [
0.00017510427278466523,
0.0001706958282738924,
0.00016716810932848603,
0.00017007786664180458,
0.00000265812514044228
] |
{
"id": 1,
"code_window": [
" changed_by_name: changedByName,\n",
" changed_by_url: changedByUrl,\n",
" },\n",
" },\n",
" }: any) => <a href={changedByUrl}>{changedByName}</a>,\n",
" Header: t('Creator'),\n",
" accessor: 'changed_by_fk',\n",
" },\n",
" {\n",
" Cell: ({\n",
" row: {\n",
" original: { published },\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" Header: t('Modified By'),\n",
" accessor: 'changed_by.first_name',\n"
],
"file_path": "superset-frontend/src/views/dashboardList/DashboardList.tsx",
"type": "replace",
"edit_start_line_idx": 163
} | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import json
import logging
from typing import Any, Dict
import simplejson
from flask import g, make_response, redirect, request, Response, url_for
from flask_appbuilder.api import expose, protect, rison, safe
from flask_appbuilder.models.sqla.interface import SQLAInterface
from flask_babel import gettext as _, ngettext
from marshmallow import ValidationError
from werkzeug.wrappers import Response as WerkzeugResponse
from werkzeug.wsgi import FileWrapper
from superset import is_feature_enabled, thumbnail_cache
from superset.charts.commands.bulk_delete import BulkDeleteChartCommand
from superset.charts.commands.create import CreateChartCommand
from superset.charts.commands.delete import DeleteChartCommand
from superset.charts.commands.exceptions import (
ChartBulkDeleteFailedError,
ChartCreateFailedError,
ChartDeleteFailedError,
ChartForbiddenError,
ChartInvalidError,
ChartNotFoundError,
ChartUpdateFailedError,
)
from superset.charts.commands.update import UpdateChartCommand
from superset.charts.dao import ChartDAO
from superset.charts.filters import ChartFilter, ChartNameOrDescriptionFilter
from superset.charts.schemas import (
CHART_SCHEMAS,
ChartDataQueryContextSchema,
ChartPostSchema,
ChartPutSchema,
get_delete_ids_schema,
openapi_spec_methods_override,
screenshot_query_schema,
thumbnail_query_schema,
)
from superset.constants import RouteMethod
from superset.exceptions import SupersetSecurityException
from superset.extensions import event_logger
from superset.models.slice import Slice
from superset.tasks.thumbnails import cache_chart_thumbnail
from superset.utils.core import ChartDataResultFormat, json_int_dttm_ser
from superset.utils.screenshots import ChartScreenshot
from superset.utils.urls import get_url_path
from superset.views.base_api import (
BaseSupersetModelRestApi,
RelatedFieldFilter,
statsd_metrics,
)
from superset.views.core import CsvResponse, generate_download_headers
from superset.views.filters import FilterRelatedOwners
logger = logging.getLogger(__name__)
class ChartRestApi(BaseSupersetModelRestApi):
datamodel = SQLAInterface(Slice)
resource_name = "chart"
allow_browser_login = True
include_route_methods = RouteMethod.REST_MODEL_VIEW_CRUD_SET | {
RouteMethod.EXPORT,
RouteMethod.RELATED,
"bulk_delete", # not using RouteMethod since locally defined
"data",
"viz_types",
"datasources",
}
class_permission_name = "SliceModelView"
show_columns = [
"slice_name",
"description",
"owners.id",
"owners.username",
"owners.first_name",
"owners.last_name",
"dashboards.id",
"dashboards.dashboard_title",
"viz_type",
"params",
"cache_timeout",
]
show_select_columns = show_columns + ["table.id"]
list_columns = [
"id",
"slice_name",
"url",
"description",
"changed_by_fk",
"created_by_fk",
"changed_by_name",
"changed_by_url",
"changed_by.first_name",
"changed_by.last_name",
"changed_on_utc",
"changed_on_delta_humanized",
"datasource_id",
"datasource_type",
"datasource_name_text",
"datasource_url",
"table.default_endpoint",
"table.table_name",
"viz_type",
"params",
"cache_timeout",
]
list_select_columns = list_columns + ["changed_on"]
order_columns = [
"slice_name",
"viz_type",
"datasource_name",
"changed_by_fk",
"changed_on_delta_humanized",
]
search_columns = (
"slice_name",
"description",
"viz_type",
"datasource_name",
"datasource_id",
"datasource_type",
"owners",
)
base_order = ("changed_on", "desc")
base_filters = [["id", ChartFilter, lambda: []]]
search_filters = {"slice_name": [ChartNameOrDescriptionFilter]}
# Will just affect _info endpoint
edit_columns = ["slice_name"]
add_columns = edit_columns
add_model_schema = ChartPostSchema()
edit_model_schema = ChartPutSchema()
openapi_spec_tag = "Charts"
""" Override the name set for this collection of endpoints """
openapi_spec_component_schemas = CHART_SCHEMAS
apispec_parameter_schemas = {
"screenshot_query_schema": screenshot_query_schema,
"get_delete_ids_schema": get_delete_ids_schema,
}
""" Add extra schemas to the OpenAPI components schema section """
openapi_spec_methods = openapi_spec_methods_override
""" Overrides GET methods OpenApi descriptions """
order_rel_fields = {
"slices": ("slice_name", "asc"),
"owners": ("first_name", "asc"),
}
related_field_filters = {
"owners": RelatedFieldFilter("first_name", FilterRelatedOwners)
}
allowed_rel_fields = {"owners"}
def __init__(self) -> None:
if is_feature_enabled("THUMBNAILS"):
self.include_route_methods = self.include_route_methods | {
"thumbnail",
"screenshot",
"cache_screenshot",
}
super().__init__()
@expose("/", methods=["POST"])
@protect()
@safe
@statsd_metrics
def post(self) -> Response:
"""Creates a new Chart
---
post:
description: >-
Create a new Chart.
requestBody:
description: Chart schema
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/{{self.__class__.__name__}}.post'
responses:
201:
description: Chart added
content:
application/json:
schema:
type: object
properties:
id:
type: number
result:
$ref: '#/components/schemas/{{self.__class__.__name__}}.post'
400:
$ref: '#/components/responses/400'
401:
$ref: '#/components/responses/401'
422:
$ref: '#/components/responses/422'
500:
$ref: '#/components/responses/500'
"""
if not request.is_json:
return self.response_400(message="Request is not JSON")
try:
item = self.add_model_schema.load(request.json)
# This validates custom Schema with custom validations
except ValidationError as error:
return self.response_400(message=error.messages)
try:
new_model = CreateChartCommand(g.user, item).run()
return self.response(201, id=new_model.id, result=item)
except ChartInvalidError as ex:
return self.response_422(message=ex.normalized_messages())
except ChartCreateFailedError as ex:
logger.error(
"Error creating model %s: %s", self.__class__.__name__, str(ex)
)
return self.response_422(message=str(ex))
@expose("/<pk>", methods=["PUT"])
@protect()
@safe
@statsd_metrics
def put( # pylint: disable=too-many-return-statements, arguments-differ
self, pk: int
) -> Response:
"""Changes a Chart
---
put:
description: >-
Changes a Chart.
parameters:
- in: path
schema:
type: integer
name: pk
requestBody:
description: Chart schema
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/{{self.__class__.__name__}}.put'
responses:
200:
description: Chart changed
content:
application/json:
schema:
type: object
properties:
id:
type: number
result:
$ref: '#/components/schemas/{{self.__class__.__name__}}.put'
400:
$ref: '#/components/responses/400'
401:
$ref: '#/components/responses/401'
403:
$ref: '#/components/responses/403'
404:
$ref: '#/components/responses/404'
422:
$ref: '#/components/responses/422'
500:
$ref: '#/components/responses/500'
"""
if not request.is_json:
return self.response_400(message="Request is not JSON")
try:
item = self.edit_model_schema.load(request.json)
# This validates custom Schema with custom validations
except ValidationError as error:
return self.response_400(message=error.messages)
try:
changed_model = UpdateChartCommand(g.user, pk, item).run()
return self.response(200, id=changed_model.id, result=item)
except ChartNotFoundError:
return self.response_404()
except ChartForbiddenError:
return self.response_403()
except ChartInvalidError as ex:
return self.response_422(message=ex.normalized_messages())
except ChartUpdateFailedError as ex:
logger.error(
"Error updating model %s: %s", self.__class__.__name__, str(ex)
)
return self.response_422(message=str(ex))
@expose("/<pk>", methods=["DELETE"])
@protect()
@safe
@statsd_metrics
def delete(self, pk: int) -> Response: # pylint: disable=arguments-differ
"""Deletes a Chart
---
delete:
description: >-
Deletes a Chart.
parameters:
- in: path
schema:
type: integer
name: pk
responses:
200:
description: Chart delete
content:
application/json:
schema:
type: object
properties:
message:
type: string
401:
$ref: '#/components/responses/401'
403:
$ref: '#/components/responses/403'
404:
$ref: '#/components/responses/404'
422:
$ref: '#/components/responses/422'
500:
$ref: '#/components/responses/500'
"""
try:
DeleteChartCommand(g.user, pk).run()
return self.response(200, message="OK")
except ChartNotFoundError:
return self.response_404()
except ChartForbiddenError:
return self.response_403()
except ChartDeleteFailedError as ex:
logger.error(
"Error deleting model %s: %s", self.__class__.__name__, str(ex)
)
return self.response_422(message=str(ex))
@expose("/", methods=["DELETE"])
@protect()
@safe
@statsd_metrics
@rison(get_delete_ids_schema)
def bulk_delete(
self, **kwargs: Any
) -> Response: # pylint: disable=arguments-differ
"""Delete bulk Charts
---
delete:
description: >-
Deletes multiple Charts in a bulk operation.
parameters:
- in: query
name: q
content:
application/json:
schema:
$ref: '#/components/schemas/get_delete_ids_schema'
responses:
200:
description: Charts bulk delete
content:
application/json:
schema:
type: object
properties:
message:
type: string
401:
$ref: '#/components/responses/401'
403:
$ref: '#/components/responses/403'
404:
$ref: '#/components/responses/404'
422:
$ref: '#/components/responses/422'
500:
$ref: '#/components/responses/500'
"""
item_ids = kwargs["rison"]
try:
BulkDeleteChartCommand(g.user, item_ids).run()
return self.response(
200,
message=ngettext(
"Deleted %(num)d chart", "Deleted %(num)d charts", num=len(item_ids)
),
)
except ChartNotFoundError:
return self.response_404()
except ChartForbiddenError:
return self.response_403()
except ChartBulkDeleteFailedError as ex:
return self.response_422(message=str(ex))
@expose("/data", methods=["POST"])
@event_logger.log_this
@protect()
@safe
@statsd_metrics
def data(self) -> Response: # pylint: disable=too-many-return-statements
"""
Takes a query context constructed in the client and returns payload
data response for the given query.
---
post:
description: >-
Takes a query context constructed in the client and returns payload data
response for the given query.
requestBody:
description: >-
A query context consists of a datasource from which to fetch data
and one or many query objects.
required: true
content:
application/json:
schema:
$ref: "#/components/schemas/ChartDataQueryContextSchema"
responses:
200:
description: Query result
content:
application/json:
schema:
$ref: "#/components/schemas/ChartDataResponseSchema"
400:
$ref: '#/components/responses/400'
500:
$ref: '#/components/responses/500'
"""
if request.is_json:
json_body = request.json
elif request.form.get("form_data"):
# CSV export submits regular form data
json_body = json.loads(request.form["form_data"])
else:
return self.response_400(message="Request is not JSON")
try:
query_context = ChartDataQueryContextSchema().load(json_body)
except KeyError:
return self.response_400(message="Request is incorrect")
except ValidationError as error:
return self.response_400(
message=_("Request is incorrect: %(error)s", error=error.messages)
)
try:
query_context.raise_for_access()
except SupersetSecurityException:
return self.response_401()
payload = query_context.get_payload()
for query in payload:
if query.get("error"):
return self.response_400(message=f"Error: {query['error']}")
result_format = query_context.result_format
if result_format == ChartDataResultFormat.CSV:
# return the first result
result = payload[0]["data"]
return CsvResponse(
result,
status=200,
headers=generate_download_headers("csv"),
mimetype="application/csv",
)
if result_format == ChartDataResultFormat.JSON:
response_data = simplejson.dumps(
{"result": payload}, default=json_int_dttm_ser, ignore_nan=True
)
resp = make_response(response_data, 200)
resp.headers["Content-Type"] = "application/json; charset=utf-8"
return resp
return self.response_400(message=f"Unsupported result_format: {result_format}")
@expose("/<pk>/cache_screenshot/", methods=["GET"])
@protect()
@rison(screenshot_query_schema)
@safe
@statsd_metrics
def cache_screenshot(self, pk: int, **kwargs: Dict[str, bool]) -> WerkzeugResponse:
"""
---
get:
description: Compute and cache a screenshot.
parameters:
- in: path
schema:
type: integer
name: pk
- in: query
name: q
content:
application/json:
schema:
$ref: '#/components/schemas/screenshot_query_schema'
responses:
200:
description: Chart async result
content:
application/json:
schema:
$ref: "#/components/schemas/ChartCacheScreenshotResponseSchema"
302:
description: Redirects to the current digest
400:
$ref: '#/components/responses/400'
401:
$ref: '#/components/responses/401'
404:
$ref: '#/components/responses/404'
500:
$ref: '#/components/responses/500'
"""
rison_dict = kwargs["rison"]
window_size = rison_dict.get("window_size") or (800, 600)
# Don't shrink the image if thumb_size is not specified
thumb_size = rison_dict.get("thumb_size") or window_size
chart = self.datamodel.get(pk, self._base_filters)
if not chart:
return self.response_404()
chart_url = get_url_path("Superset.slice", slice_id=chart.id, standalone="true")
screenshot_obj = ChartScreenshot(chart_url, chart.digest)
cache_key = screenshot_obj.cache_key(window_size, thumb_size)
image_url = get_url_path(
"ChartRestApi.screenshot", pk=chart.id, digest=cache_key
)
def trigger_celery() -> WerkzeugResponse:
logger.info("Triggering screenshot ASYNC")
kwargs = {
"url": chart_url,
"digest": chart.digest,
"force": True,
"window_size": window_size,
"thumb_size": thumb_size,
}
cache_chart_thumbnail.delay(**kwargs)
return self.response(
202, cache_key=cache_key, chart_url=chart_url, image_url=image_url,
)
return trigger_celery()
@expose("/<pk>/screenshot/<digest>/", methods=["GET"])
@protect()
@rison(screenshot_query_schema)
@safe
@statsd_metrics
def screenshot(self, pk: int, digest: str) -> WerkzeugResponse:
"""Get Chart screenshot
---
get:
description: Get a computed screenshot from cache.
parameters:
- in: path
schema:
type: integer
name: pk
- in: path
schema:
type: string
name: digest
responses:
200:
description: Chart thumbnail image
content:
image/*:
schema:
type: string
format: binary
302:
description: Redirects to the current digest
400:
$ref: '#/components/responses/400'
401:
$ref: '#/components/responses/401'
404:
$ref: '#/components/responses/404'
500:
$ref: '#/components/responses/500'
"""
chart = self.datamodel.get(pk, self._base_filters)
# Making sure the chart still exists
if not chart:
return self.response_404()
# TODO make sure the user has access to the chart
# fetch the chart screenshot using the current user and cache if set
img = ChartScreenshot.get_from_cache_key(thumbnail_cache, digest)
if img:
return Response(
FileWrapper(img), mimetype="image/png", direct_passthrough=True
)
# TODO: return an empty image
return self.response_404()
@expose("/<pk>/thumbnail/<digest>/", methods=["GET"])
@protect()
@rison(thumbnail_query_schema)
@safe
@statsd_metrics
def thumbnail(
self, pk: int, digest: str, **kwargs: Dict[str, bool]
) -> WerkzeugResponse:
"""Get Chart thumbnail
---
get:
description: Compute or get already computed chart thumbnail from cache.
parameters:
- in: path
schema:
type: integer
name: pk
- in: path
schema:
type: string
name: digest
responses:
200:
description: Chart thumbnail image
/content:
image/*:
schema:
type: string
format: binary
302:
description: Redirects to the current digest
400:
$ref: '#/components/responses/400'
401:
$ref: '#/components/responses/401'
404:
$ref: '#/components/responses/404'
500:
$ref: '#/components/responses/500'
"""
chart = self.datamodel.get(pk, self._base_filters)
if not chart:
return self.response_404()
url = get_url_path("Superset.slice", slice_id=chart.id, standalone="true")
if kwargs["rison"].get("force", False):
logger.info(
"Triggering thumbnail compute (chart id: %s) ASYNC", str(chart.id)
)
cache_chart_thumbnail.delay(url, chart.digest, force=True)
return self.response(202, message="OK Async")
# fetch the chart screenshot using the current user and cache if set
screenshot = ChartScreenshot(url, chart.digest).get_from_cache(
cache=thumbnail_cache
)
# If not screenshot then send request to compute thumb to celery
if not screenshot:
logger.info(
"Triggering thumbnail compute (chart id: %s) ASYNC", str(chart.id)
)
cache_chart_thumbnail.delay(url, chart.digest, force=True)
return self.response(202, message="OK Async")
# If digests
if chart.digest != digest:
return redirect(
url_for(
f"{self.__class__.__name__}.thumbnail", pk=pk, digest=chart.digest
)
)
return Response(
FileWrapper(screenshot), mimetype="image/png", direct_passthrough=True
)
@expose("/datasources", methods=["GET"])
@protect()
@safe
def datasources(self) -> Response:
"""Get available datasources
---
get:
description: Get available datasources.
responses:
200:
description: Query result
content:
application/json:
schema:
$ref: "#/components/schemas/ChartGetDatasourceResponseSchema"
400:
$ref: '#/components/responses/400'
401:
$ref: '#/components/responses/401'
404:
$ref: '#/components/responses/404'
422:
$ref: '#/components/responses/422'
500:
$ref: '#/components/responses/500'
"""
datasources = ChartDAO.fetch_all_datasources()
if not datasources:
return self.response(200, count=0, result=[])
result = [
{
"label": str(ds),
"value": {"datasource_id": ds.id, "datasource_type": ds.type},
}
for ds in datasources
]
return self.response(200, count=len(result), result=result)
| superset/charts/api.py | 1 | https://github.com/apache/superset/commit/2b061fc64b88831574878b6bd470d700a1527dec | [
0.0009297374053858221,
0.00018544579506851733,
0.00016511109424754977,
0.00017152345390059054,
0.00009094026609091088
] |
{
"id": 1,
"code_window": [
" changed_by_name: changedByName,\n",
" changed_by_url: changedByUrl,\n",
" },\n",
" },\n",
" }: any) => <a href={changedByUrl}>{changedByName}</a>,\n",
" Header: t('Creator'),\n",
" accessor: 'changed_by_fk',\n",
" },\n",
" {\n",
" Cell: ({\n",
" row: {\n",
" original: { published },\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" Header: t('Modified By'),\n",
" accessor: 'changed_by.first_name',\n"
],
"file_path": "superset-frontend/src/views/dashboardList/DashboardList.tsx",
"type": "replace",
"edit_start_line_idx": 163
} | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import logging
import re
import textwrap
import time
from collections import defaultdict, deque
from contextlib import closing
from datetime import datetime
from distutils.version import StrictVersion
from typing import Any, cast, Dict, List, Optional, Tuple, TYPE_CHECKING
from urllib import parse
import pandas as pd
import simplejson as json
from sqlalchemy import Column, literal_column
from sqlalchemy.engine.base import Engine
from sqlalchemy.engine.reflection import Inspector
from sqlalchemy.engine.result import RowProxy
from sqlalchemy.engine.url import URL
from sqlalchemy.orm import Session
from sqlalchemy.sql.expression import ColumnClause, Select
from superset import app, cache, is_feature_enabled, security_manager
from superset.db_engine_specs.base import BaseEngineSpec
from superset.exceptions import SupersetTemplateException
from superset.models.sql_lab import Query
from superset.models.sql_types.presto_sql_types import type_map as presto_type_map
from superset.sql_parse import ParsedQuery
from superset.utils import core as utils
if TYPE_CHECKING:
# prevent circular imports
from superset.models.core import Database # pylint: disable=unused-import
QueryStatus = utils.QueryStatus
config = app.config
logger = logging.getLogger(__name__)
# See here: https://github.com/dropbox/PyHive/blob/8eb0aeab8ca300f3024655419b93dad926c1a351/pyhive/presto.py#L93 # pylint: disable=line-too-long
DEFAULT_PYHIVE_POLL_INTERVAL = 1
def get_children(column: Dict[str, str]) -> List[Dict[str, str]]:
"""
Get the children of a complex Presto type (row or array).
For arrays, we return a single list with the base type:
>>> get_children(dict(name="a", type="ARRAY(BIGINT)"))
[{"name": "a", "type": "BIGINT"}]
For rows, we return a list of the columns:
>>> get_children(dict(name="a", type="ROW(BIGINT,FOO VARCHAR)"))
[{'name': 'a._col0', 'type': 'BIGINT'}, {'name': 'a.foo', 'type': 'VARCHAR'}]
:param column: dictionary representing a Presto column
:return: list of dictionaries representing children columns
"""
pattern = re.compile(r"(?P<type>\w+)\((?P<children>.*)\)")
match = pattern.match(column["type"])
if not match:
raise Exception(f"Unable to parse column type {column['type']}")
group = match.groupdict()
type_ = group["type"].upper()
children_type = group["children"]
if type_ == "ARRAY":
return [{"name": column["name"], "type": children_type}]
if type_ == "ROW":
nameless_columns = 0
columns = []
for child in utils.split(children_type, ","):
parts = list(utils.split(child.strip(), " "))
if len(parts) == 2:
name, type_ = parts
name = name.strip('"')
else:
name = f"_col{nameless_columns}"
type_ = parts[0]
nameless_columns += 1
columns.append({"name": f"{column['name']}.{name.lower()}", "type": type_})
return columns
raise Exception(f"Unknown type {type_}!")
class PrestoEngineSpec(BaseEngineSpec):
engine = "presto"
_time_grain_expressions = {
None: "{col}",
"PT1S": "date_trunc('second', CAST({col} AS TIMESTAMP))",
"PT1M": "date_trunc('minute', CAST({col} AS TIMESTAMP))",
"PT1H": "date_trunc('hour', CAST({col} AS TIMESTAMP))",
"P1D": "date_trunc('day', CAST({col} AS TIMESTAMP))",
"P1W": "date_trunc('week', CAST({col} AS TIMESTAMP))",
"P1M": "date_trunc('month', CAST({col} AS TIMESTAMP))",
"P0.25Y": "date_trunc('quarter', CAST({col} AS TIMESTAMP))",
"P1Y": "date_trunc('year', CAST({col} AS TIMESTAMP))",
"P1W/1970-01-03T00:00:00Z": "date_add('day', 5, date_trunc('week', "
"date_add('day', 1, CAST({col} AS TIMESTAMP))))",
"1969-12-28T00:00:00Z/P1W": "date_add('day', -1, date_trunc('week', "
"date_add('day', 1, CAST({col} AS TIMESTAMP))))",
}
@classmethod
def get_allow_cost_estimate(cls, version: Optional[str] = None) -> bool:
return version is not None and StrictVersion(version) >= StrictVersion("0.319")
@classmethod
def get_table_names(
cls, database: "Database", inspector: Inspector, schema: Optional[str]
) -> List[str]:
tables = super().get_table_names(database, inspector, schema)
if not is_feature_enabled("PRESTO_SPLIT_VIEWS_FROM_TABLES"):
return tables
views = set(cls.get_view_names(database, inspector, schema))
actual_tables = set(tables) - views
return list(actual_tables)
@classmethod
def get_view_names(
cls, database: "Database", inspector: Inspector, schema: Optional[str]
) -> List[str]:
"""Returns an empty list
get_table_names() function returns all table names and view names,
and get_view_names() is not implemented in sqlalchemy_presto.py
https://github.com/dropbox/PyHive/blob/e25fc8440a0686bbb7a5db5de7cb1a77bdb4167a/pyhive/sqlalchemy_presto.py
"""
if not is_feature_enabled("PRESTO_SPLIT_VIEWS_FROM_TABLES"):
return []
if schema:
sql = (
"SELECT table_name FROM information_schema.views "
"WHERE table_schema=%(schema)s"
)
params = {"schema": schema}
else:
sql = "SELECT table_name FROM information_schema.views"
params = {}
engine = cls.get_engine(database, schema=schema)
with closing(engine.raw_connection()) as conn:
with closing(conn.cursor()) as cursor:
cursor.execute(sql, params)
results = cursor.fetchall()
return [row[0] for row in results]
@classmethod
def _create_column_info(cls, name: str, data_type: str) -> Dict[str, Any]:
"""
Create column info object
:param name: column name
:param data_type: column data type
:return: column info object
"""
return {"name": name, "type": f"{data_type}"}
@classmethod
def _get_full_name(cls, names: List[Tuple[str, str]]) -> str:
"""
Get the full column name
:param names: list of all individual column names
:return: full column name
"""
return ".".join(column[0] for column in names if column[0])
@classmethod
def _has_nested_data_types(cls, component_type: str) -> bool:
"""
Check if string contains a data type. We determine if there is a data type by
whitespace or multiple data types by commas
:param component_type: data type
:return: boolean
"""
comma_regex = r",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)"
white_space_regex = r"\s(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)"
return (
re.search(comma_regex, component_type) is not None
or re.search(white_space_regex, component_type) is not None
)
@classmethod
def _split_data_type(cls, data_type: str, delimiter: str) -> List[str]:
"""
Split data type based on given delimiter. Do not split the string if the
delimiter is enclosed in quotes
:param data_type: data type
:param delimiter: string separator (i.e. open parenthesis, closed parenthesis,
comma, whitespace)
:return: list of strings after breaking it by the delimiter
"""
return re.split(
r"{}(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)".format(delimiter), data_type
)
@classmethod
def _parse_structural_column( # pylint: disable=too-many-locals,too-many-branches
cls,
parent_column_name: str,
parent_data_type: str,
result: List[Dict[str, Any]],
) -> None:
"""
Parse a row or array column
:param result: list tracking the results
"""
formatted_parent_column_name = parent_column_name
# Quote the column name if there is a space
if " " in parent_column_name:
formatted_parent_column_name = f'"{parent_column_name}"'
full_data_type = f"{formatted_parent_column_name} {parent_data_type}"
original_result_len = len(result)
# split on open parenthesis ( to get the structural
# data type and its component types
data_types = cls._split_data_type(full_data_type, r"\(")
stack: List[Tuple[str, str]] = []
for data_type in data_types:
# split on closed parenthesis ) to track which component
# types belong to what structural data type
inner_types = cls._split_data_type(data_type, r"\)")
for inner_type in inner_types:
# We have finished parsing multiple structural data types
if not inner_type and stack:
stack.pop()
elif cls._has_nested_data_types(inner_type):
# split on comma , to get individual data types
single_fields = cls._split_data_type(inner_type, ",")
for single_field in single_fields:
single_field = single_field.strip()
# If component type starts with a comma, the first single field
# will be an empty string. Disregard this empty string.
if not single_field:
continue
# split on whitespace to get field name and data type
field_info = cls._split_data_type(single_field, r"\s")
# check if there is a structural data type within
# overall structural data type
if field_info[1] == "array" or field_info[1] == "row":
stack.append((field_info[0], field_info[1]))
full_parent_path = cls._get_full_name(stack)
result.append(
cls._create_column_info(
full_parent_path, presto_type_map[field_info[1]]()
)
)
else: # otherwise this field is a basic data type
full_parent_path = cls._get_full_name(stack)
column_name = "{}.{}".format(
full_parent_path, field_info[0]
)
result.append(
cls._create_column_info(
column_name, presto_type_map[field_info[1]]()
)
)
# If the component type ends with a structural data type, do not pop
# the stack. We have run across a structural data type within the
# overall structural data type. Otherwise, we have completely parsed
# through the entire structural data type and can move on.
if not (inner_type.endswith("array") or inner_type.endswith("row")):
stack.pop()
# We have an array of row objects (i.e. array(row(...)))
elif inner_type in ("array", "row"):
# Push a dummy object to represent the structural data type
stack.append(("", inner_type))
# We have an array of a basic data types(i.e. array(varchar)).
elif stack:
# Because it is an array of a basic data type. We have finished
# parsing the structural data type and can move on.
stack.pop()
# Unquote the column name if necessary
if formatted_parent_column_name != parent_column_name:
for index in range(original_result_len, len(result)):
result[index]["name"] = result[index]["name"].replace(
formatted_parent_column_name, parent_column_name
)
@classmethod
def _show_columns(
cls, inspector: Inspector, table_name: str, schema: Optional[str]
) -> List[RowProxy]:
"""
Show presto column names
:param inspector: object that performs database schema inspection
:param table_name: table name
:param schema: schema name
:return: list of column objects
"""
quote = inspector.engine.dialect.identifier_preparer.quote_identifier
full_table = quote(table_name)
if schema:
full_table = "{}.{}".format(quote(schema), full_table)
columns = inspector.bind.execute("SHOW COLUMNS FROM {}".format(full_table))
return columns
@classmethod
def get_columns(
cls, inspector: Inspector, table_name: str, schema: Optional[str]
) -> List[Dict[str, Any]]:
"""
Get columns from a Presto data source. This includes handling row and
array data types
:param inspector: object that performs database schema inspection
:param table_name: table name
:param schema: schema name
:return: a list of results that contain column info
(i.e. column name and data type)
"""
columns = cls._show_columns(inspector, table_name, schema)
result: List[Dict[str, Any]] = []
for column in columns:
try:
# parse column if it is a row or array
if is_feature_enabled("PRESTO_EXPAND_DATA") and (
"array" in column.Type or "row" in column.Type
):
structural_column_index = len(result)
cls._parse_structural_column(column.Column, column.Type, result)
result[structural_column_index]["nullable"] = getattr(
column, "Null", True
)
result[structural_column_index]["default"] = None
continue
# otherwise column is a basic data type
column_type = presto_type_map[column.Type]()
except KeyError:
logger.info(
"Did not recognize type {} of column {}".format( # pylint: disable=logging-format-interpolation
column.Type, column.Column
)
)
column_type = "OTHER"
column_info = cls._create_column_info(column.Column, column_type)
column_info["nullable"] = getattr(column, "Null", True)
column_info["default"] = None
result.append(column_info)
return result
@classmethod
def _is_column_name_quoted(cls, column_name: str) -> bool:
"""
Check if column name is in quotes
:param column_name: column name
:return: boolean
"""
return column_name.startswith('"') and column_name.endswith('"')
@classmethod
def _get_fields(cls, cols: List[Dict[str, Any]]) -> List[ColumnClause]:
"""
Format column clauses where names are in quotes and labels are specified
:param cols: columns
:return: column clauses
"""
column_clauses = []
# Column names are separated by periods. This regex will find periods in a
# string if they are not enclosed in quotes because if a period is enclosed in
# quotes, then that period is part of a column name.
dot_pattern = r"""\. # split on period
(?= # look ahead
(?: # create non-capture group
[^\"]*\"[^\"]*\" # two quotes
)*[^\"]*$) # end regex"""
dot_regex = re.compile(dot_pattern, re.VERBOSE)
for col in cols:
# get individual column names
col_names = re.split(dot_regex, col["name"])
# quote each column name if it is not already quoted
for index, col_name in enumerate(col_names):
if not cls._is_column_name_quoted(col_name):
col_names[index] = '"{}"'.format(col_name)
quoted_col_name = ".".join(
col_name if cls._is_column_name_quoted(col_name) else f'"{col_name}"'
for col_name in col_names
)
# create column clause in the format "name"."name" AS "name.name"
column_clause = literal_column(quoted_col_name).label(col["name"])
column_clauses.append(column_clause)
return column_clauses
@classmethod
def select_star( # pylint: disable=too-many-arguments
cls,
database: "Database",
table_name: str,
engine: Engine,
schema: Optional[str] = None,
limit: int = 100,
show_cols: bool = False,
indent: bool = True,
latest_partition: bool = True,
cols: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Include selecting properties of row objects. We cannot easily break arrays into
rows, so render the whole array in its own row and skip columns that correspond
to an array's contents.
"""
cols = cols or []
presto_cols = cols
if is_feature_enabled("PRESTO_EXPAND_DATA") and show_cols:
dot_regex = r"\.(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)"
presto_cols = [
col for col in presto_cols if not re.search(dot_regex, col["name"])
]
return super().select_star(
database,
table_name,
engine,
schema,
limit,
show_cols,
indent,
latest_partition,
presto_cols,
)
@classmethod
def estimate_statement_cost( # pylint: disable=too-many-locals
cls, statement: str, database: "Database", cursor: Any, user_name: str
) -> Dict[str, Any]:
"""
Run a SQL query that estimates the cost of a given statement.
:param statement: A single SQL statement
:param database: Database instance
:param cursor: Cursor instance
:param username: Effective username
:return: JSON response from Presto
"""
parsed_query = ParsedQuery(statement)
sql = parsed_query.stripped()
sql_query_mutator = config["SQL_QUERY_MUTATOR"]
if sql_query_mutator:
sql = sql_query_mutator(sql, user_name, security_manager, database)
sql = f"EXPLAIN (TYPE IO, FORMAT JSON) {sql}"
cursor.execute(sql)
# the output from Presto is a single column and a single row containing
# JSON:
#
# {
# ...
# "estimate" : {
# "outputRowCount" : 8.73265878E8,
# "outputSizeInBytes" : 3.41425774958E11,
# "cpuCost" : 3.41425774958E11,
# "maxMemory" : 0.0,
# "networkCost" : 3.41425774958E11
# }
# }
result = json.loads(cursor.fetchone()[0])
return result
@classmethod
def query_cost_formatter(
cls, raw_cost: List[Dict[str, Any]]
) -> List[Dict[str, str]]:
"""
Format cost estimate.
:param raw_cost: JSON estimate from Presto
:return: Human readable cost estimate
"""
def humanize(value: Any, suffix: str) -> str:
try:
value = int(value)
except ValueError:
return str(value)
prefixes = ["K", "M", "G", "T", "P", "E", "Z", "Y"]
prefix = ""
to_next_prefix = 1000
while value > to_next_prefix and prefixes:
prefix = prefixes.pop(0)
value //= to_next_prefix
return f"{value} {prefix}{suffix}"
cost = []
columns = [
("outputRowCount", "Output count", " rows"),
("outputSizeInBytes", "Output size", "B"),
("cpuCost", "CPU cost", ""),
("maxMemory", "Max memory", "B"),
("networkCost", "Network cost", ""),
]
for row in raw_cost:
estimate: Dict[str, float] = row.get("estimate", {})
statement_cost = {}
for key, label, suffix in columns:
if key in estimate:
statement_cost[label] = humanize(estimate[key], suffix).strip()
cost.append(statement_cost)
return cost
@classmethod
def adjust_database_uri(
cls, uri: URL, selected_schema: Optional[str] = None
) -> None:
database = uri.database
if selected_schema and database:
selected_schema = parse.quote(selected_schema, safe="")
if "/" in database:
database = database.split("/")[0] + "/" + selected_schema
else:
database += "/" + selected_schema
uri.database = database
@classmethod
def convert_dttm(cls, target_type: str, dttm: datetime) -> Optional[str]:
tt = target_type.upper()
if tt == utils.TemporalType.DATE:
return f"""from_iso8601_date('{dttm.date().isoformat()}')"""
if tt == utils.TemporalType.TIMESTAMP:
return f"""from_iso8601_timestamp('{dttm.isoformat(timespec="microseconds")}')""" # pylint: disable=line-too-long
return None
@classmethod
def epoch_to_dttm(cls) -> str:
return "from_unixtime({col})"
@classmethod
def get_all_datasource_names(
cls, database: "Database", datasource_type: str
) -> List[utils.DatasourceName]:
datasource_df = database.get_df(
"SELECT table_schema, table_name FROM INFORMATION_SCHEMA.{}S "
"ORDER BY concat(table_schema, '.', table_name)".format(
datasource_type.upper()
),
None,
)
datasource_names: List[utils.DatasourceName] = []
for _unused, row in datasource_df.iterrows():
datasource_names.append(
utils.DatasourceName(
schema=row["table_schema"], table=row["table_name"]
)
)
return datasource_names
@classmethod
def expand_data( # pylint: disable=too-many-locals
cls, columns: List[Dict[Any, Any]], data: List[Dict[Any, Any]]
) -> Tuple[List[Dict[Any, Any]], List[Dict[Any, Any]], List[Dict[Any, Any]]]:
"""
We do not immediately display rows and arrays clearly in the data grid. This
method separates out nested fields and data values to help clearly display
structural columns.
Example: ColumnA is a row(nested_obj varchar) and ColumnB is an array(int)
Original data set = [
{'ColumnA': ['a1'], 'ColumnB': [1, 2]},
{'ColumnA': ['a2'], 'ColumnB': [3, 4]},
]
Expanded data set = [
{'ColumnA': ['a1'], 'ColumnA.nested_obj': 'a1', 'ColumnB': 1},
{'ColumnA': '', 'ColumnA.nested_obj': '', 'ColumnB': 2},
{'ColumnA': ['a2'], 'ColumnA.nested_obj': 'a2', 'ColumnB': 3},
{'ColumnA': '', 'ColumnA.nested_obj': '', 'ColumnB': 4},
]
:param columns: columns selected in the query
:param data: original data set
:return: list of all columns(selected columns and their nested fields),
expanded data set, listed of nested fields
"""
if not is_feature_enabled("PRESTO_EXPAND_DATA"):
return columns, data, []
# process each column, unnesting ARRAY types and
# expanding ROW types into new columns
to_process = deque((column, 0) for column in columns)
all_columns: List[Dict[str, Any]] = []
expanded_columns = []
current_array_level = None
while to_process:
column, level = to_process.popleft()
if column["name"] not in [column["name"] for column in all_columns]:
all_columns.append(column)
# When unnesting arrays we need to keep track of how many extra rows
# were added, for each original row. This is necessary when we expand
# multiple arrays, so that the arrays after the first reuse the rows
# added by the first. every time we change a level in the nested arrays
# we reinitialize this.
if level != current_array_level:
unnested_rows: Dict[int, int] = defaultdict(int)
current_array_level = level
name = column["name"]
if column["type"].startswith("ARRAY("):
# keep processing array children; we append to the right so that
# multiple nested arrays are processed breadth-first
to_process.append((get_children(column)[0], level + 1))
# unnest array objects data into new rows
i = 0
while i < len(data):
row = data[i]
values = row.get(name)
if values:
# how many extra rows we need to unnest the data?
extra_rows = len(values) - 1
# how many rows were already added for this row?
current_unnested_rows = unnested_rows[i]
# add any necessary rows
missing = extra_rows - current_unnested_rows
for _ in range(missing):
data.insert(i + current_unnested_rows + 1, {})
unnested_rows[i] += 1
# unnest array into rows
for j, value in enumerate(values):
data[i + j][name] = value
# skip newly unnested rows
i += unnested_rows[i]
i += 1
if column["type"].startswith("ROW("):
# expand columns; we append them to the left so they are added
# immediately after the parent
expanded = get_children(column)
to_process.extendleft((column, level) for column in expanded)
expanded_columns.extend(expanded)
# expand row objects into new columns
for row in data:
for value, col in zip(row.get(name) or [], expanded):
row[col["name"]] = value
data = [
{k["name"]: row.get(k["name"], "") for k in all_columns} for row in data
]
return all_columns, data, expanded_columns
@classmethod
def extra_table_metadata(
cls, database: "Database", table_name: str, schema_name: str
) -> Dict[str, Any]:
metadata = {}
indexes = database.get_indexes(table_name, schema_name)
if indexes:
cols = indexes[0].get("column_names", [])
full_table_name = table_name
if schema_name and "." not in table_name:
full_table_name = "{}.{}".format(schema_name, table_name)
pql = cls._partition_query(full_table_name, database)
col_names, latest_parts = cls.latest_partition(
table_name, schema_name, database, show_first=True
)
if not latest_parts:
latest_parts = tuple([None] * len(col_names)) # type: ignore
metadata["partitions"] = {
"cols": cols,
"latest": dict(zip(col_names, latest_parts)), # type: ignore
"partitionQuery": pql,
}
# flake8 is not matching `Optional[str]` to `Any` for some reason...
metadata["view"] = cast(
Any, cls.get_create_view(database, schema_name, table_name)
)
return metadata
@classmethod
def get_create_view(
cls, database: "Database", schema: str, table: str
) -> Optional[str]:
"""
Return a CREATE VIEW statement, or `None` if not a view.
:param database: Database instance
:param schema: Schema name
:param table: Table (view) name
"""
from pyhive.exc import DatabaseError
engine = cls.get_engine(database, schema)
with closing(engine.raw_connection()) as conn:
with closing(conn.cursor()) as cursor:
sql = f"SHOW CREATE VIEW {schema}.{table}"
try:
cls.execute(cursor, sql)
polled = cursor.poll()
while polled:
time.sleep(0.2)
polled = cursor.poll()
except DatabaseError: # not a VIEW
return None
rows = cls.fetch_data(cursor, 1)
return rows[0][0]
@classmethod
def handle_cursor(cls, cursor: Any, query: Query, session: Session) -> None:
"""Updates progress information"""
query_id = query.id
poll_interval = query.database.connect_args.get(
"poll_interval", DEFAULT_PYHIVE_POLL_INTERVAL
)
logger.info("Query %i: Polling the cursor for progress", query_id)
polled = cursor.poll()
# poll returns dict -- JSON status information or ``None``
# if the query is done
# https://github.com/dropbox/PyHive/blob/
# b34bdbf51378b3979eaf5eca9e956f06ddc36ca0/pyhive/presto.py#L178
while polled:
# Update the object and wait for the kill signal.
stats = polled.get("stats", {})
query = session.query(type(query)).filter_by(id=query_id).one()
if query.status in [QueryStatus.STOPPED, QueryStatus.TIMED_OUT]:
cursor.cancel()
break
if stats:
state = stats.get("state")
# if already finished, then stop polling
if state == "FINISHED":
break
completed_splits = float(stats.get("completedSplits"))
total_splits = float(stats.get("totalSplits"))
if total_splits and completed_splits:
progress = 100 * (completed_splits / total_splits)
logger.info(
"Query {} progress: {} / {} " # pylint: disable=logging-format-interpolation
"splits".format(query_id, completed_splits, total_splits)
)
if progress > query.progress:
query.progress = progress
session.commit()
time.sleep(poll_interval)
logger.info("Query %i: Polling the cursor for progress", query_id)
polled = cursor.poll()
@classmethod
def _extract_error_message(cls, ex: Exception) -> Optional[str]:
if (
hasattr(ex, "orig")
and type(ex.orig).__name__ == "DatabaseError" # type: ignore
and isinstance(ex.orig[0], dict) # type: ignore
):
error_dict = ex.orig[0] # type: ignore
return "{} at {}: {}".format(
error_dict.get("errorName"),
error_dict.get("errorLocation"),
error_dict.get("message"),
)
if type(ex).__name__ == "DatabaseError" and hasattr(ex, "args") and ex.args:
error_dict = ex.args[0]
return error_dict.get("message")
return utils.error_msg_from_exception(ex)
@classmethod
def _partition_query( # pylint: disable=too-many-arguments,too-many-locals
cls,
table_name: str,
database: "Database",
limit: int = 0,
order_by: Optional[List[Tuple[str, bool]]] = None,
filters: Optional[Dict[Any, Any]] = None,
) -> str:
"""Returns a partition query
:param table_name: the name of the table to get partitions from
:type table_name: str
:param limit: the number of partitions to be returned
:type limit: int
:param order_by: a list of tuples of field name and a boolean
that determines if that field should be sorted in descending
order
:type order_by: list of (str, bool) tuples
:param filters: dict of field name and filter value combinations
"""
limit_clause = "LIMIT {}".format(limit) if limit else ""
order_by_clause = ""
if order_by:
l = []
for field, desc in order_by:
l.append(field + " DESC" if desc else "")
order_by_clause = "ORDER BY " + ", ".join(l)
where_clause = ""
if filters:
l = []
for field, value in filters.items():
l.append(f"{field} = '{value}'")
where_clause = "WHERE " + " AND ".join(l)
presto_version = database.get_extra().get("version")
# Partition select syntax changed in v0.199, so check here.
# Default to the new syntax if version is unset.
partition_select_clause = (
f'SELECT * FROM "{table_name}$partitions"'
if not presto_version
or StrictVersion(presto_version) >= StrictVersion("0.199")
else f"SHOW PARTITIONS FROM {table_name}"
)
sql = textwrap.dedent(
f"""\
{partition_select_clause}
{where_clause}
{order_by_clause}
{limit_clause}
"""
)
return sql
@classmethod
def where_latest_partition( # pylint: disable=too-many-arguments
cls,
table_name: str,
schema: Optional[str],
database: "Database",
query: Select,
columns: Optional[List[Dict[str, str]]] = None,
) -> Optional[Select]:
try:
col_names, values = cls.latest_partition(
table_name, schema, database, show_first=True
)
except Exception: # pylint: disable=broad-except
# table is not partitioned
return None
if values is None:
return None
column_names = {column.get("name") for column in columns or []}
for col_name, value in zip(col_names, values):
if col_name in column_names:
query = query.where(Column(col_name) == value)
return query
@classmethod
def _latest_partition_from_df(cls, df: pd.DataFrame) -> Optional[List[str]]:
if not df.empty:
return df.to_records(index=False)[0].item()
return None
@classmethod
def latest_partition(
cls,
table_name: str,
schema: Optional[str],
database: "Database",
show_first: bool = False,
) -> Tuple[List[str], Optional[List[str]]]:
"""Returns col name and the latest (max) partition value for a table
:param table_name: the name of the table
:param schema: schema / database / namespace
:param database: database query will be run against
:type database: models.Database
:param show_first: displays the value for the first partitioning key
if there are many partitioning keys
:type show_first: bool
>>> latest_partition('foo_table')
(['ds'], ('2018-01-01',))
"""
indexes = database.get_indexes(table_name, schema)
if not indexes:
raise SupersetTemplateException(
f"Error getting partition for {schema}.{table_name}. "
"Verify that this table has a partition."
)
if len(indexes[0]["column_names"]) < 1:
raise SupersetTemplateException(
"The table should have one partitioned field"
)
if not show_first and len(indexes[0]["column_names"]) > 1:
raise SupersetTemplateException(
"The table should have a single partitioned field "
"to use this function. You may want to use "
"`presto.latest_sub_partition`"
)
column_names = indexes[0]["column_names"]
part_fields = [(column_name, True) for column_name in column_names]
sql = cls._partition_query(table_name, database, 1, part_fields)
df = database.get_df(sql, schema)
return column_names, cls._latest_partition_from_df(df)
@classmethod
def latest_sub_partition(
cls, table_name: str, schema: Optional[str], database: "Database", **kwargs: Any
) -> Any:
"""Returns the latest (max) partition value for a table
A filtering criteria should be passed for all fields that are
partitioned except for the field to be returned. For example,
if a table is partitioned by (``ds``, ``event_type`` and
``event_category``) and you want the latest ``ds``, you'll want
to provide a filter as keyword arguments for both
``event_type`` and ``event_category`` as in
``latest_sub_partition('my_table',
event_category='page', event_type='click')``
:param table_name: the name of the table, can be just the table
name or a fully qualified table name as ``schema_name.table_name``
:type table_name: str
:param schema: schema / database / namespace
:type schema: str
:param database: database query will be run against
:type database: models.Database
:param kwargs: keyword arguments define the filtering criteria
on the partition list. There can be many of these.
:type kwargs: str
>>> latest_sub_partition('sub_partition_table', event_type='click')
'2018-01-01'
"""
indexes = database.get_indexes(table_name, schema)
part_fields = indexes[0]["column_names"]
for k in kwargs.keys(): # pylint: disable=consider-iterating-dictionary
if k not in k in part_fields: # pylint: disable=comparison-with-itself
msg = "Field [{k}] is not part of the portioning key"
raise SupersetTemplateException(msg)
if len(kwargs.keys()) != len(part_fields) - 1:
msg = (
"A filter needs to be specified for {} out of the " "{} fields."
).format(len(part_fields) - 1, len(part_fields))
raise SupersetTemplateException(msg)
for field in part_fields:
if field not in kwargs.keys():
field_to_return = field
sql = cls._partition_query(
table_name, database, 1, [(field_to_return, True)], kwargs
)
df = database.get_df(sql, schema)
if df.empty:
return ""
return df.to_dict()[field_to_return][0]
@classmethod
@cache.memoize()
def get_function_names(cls, database: "Database") -> List[str]:
"""
Get a list of function names that are able to be called on the database.
Used for SQL Lab autocomplete.
:param database: The database to get functions for
:return: A list of function names useable in the database
"""
return database.get_df("SHOW FUNCTIONS")["Function"].tolist()
| superset/db_engine_specs/presto.py | 0 | https://github.com/apache/superset/commit/2b061fc64b88831574878b6bd470d700a1527dec | [
0.0014484539860859513,
0.0001845681545091793,
0.00016027720994316041,
0.00016789164510555565,
0.00012891876394860446
] |
{
"id": 1,
"code_window": [
" changed_by_name: changedByName,\n",
" changed_by_url: changedByUrl,\n",
" },\n",
" },\n",
" }: any) => <a href={changedByUrl}>{changedByName}</a>,\n",
" Header: t('Creator'),\n",
" accessor: 'changed_by_fk',\n",
" },\n",
" {\n",
" Cell: ({\n",
" row: {\n",
" original: { published },\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" Header: t('Modified By'),\n",
" accessor: 'changed_by.first_name',\n"
],
"file_path": "superset-frontend/src/views/dashboardList/DashboardList.tsx",
"type": "replace",
"edit_start_line_idx": 163
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import React from 'react';
import PropTypes from 'prop-types';
import { t } from '@superset-ui/translation';
import { isEmpty } from 'lodash';
const propTypes = {
label: PropTypes.string.isRequired,
values: PropTypes.array.isRequired,
clickIconHandler: PropTypes.func,
};
const defaultProps = {
clickIconHandler: undefined,
};
export default function FilterIndicatorTooltip({
label,
values,
clickIconHandler,
}) {
const displayValue = isEmpty(values) ? t('Not filtered') : values.join(', ');
return (
<div className="tooltip-item">
<div className="filter-content">
<label htmlFor={`filter-tooltip-${label}`}>{label}:</label>
<span> {displayValue}</span>
</div>
{clickIconHandler && (
<i
className="fa fa-pencil filter-edit"
onClick={clickIconHandler}
role="button"
tabIndex="0"
/>
)}
</div>
);
}
FilterIndicatorTooltip.propTypes = propTypes;
FilterIndicatorTooltip.defaultProps = defaultProps;
| superset-frontend/src/dashboard/components/FilterIndicatorTooltip.jsx | 0 | https://github.com/apache/superset/commit/2b061fc64b88831574878b6bd470d700a1527dec | [
0.00017504801508039236,
0.00017111354100052267,
0.00016808972577564418,
0.00017016971833072603,
0.000002518636847526068
] |
{
"id": 1,
"code_window": [
" changed_by_name: changedByName,\n",
" changed_by_url: changedByUrl,\n",
" },\n",
" },\n",
" }: any) => <a href={changedByUrl}>{changedByName}</a>,\n",
" Header: t('Creator'),\n",
" accessor: 'changed_by_fk',\n",
" },\n",
" {\n",
" Cell: ({\n",
" row: {\n",
" original: { published },\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" Header: t('Modified By'),\n",
" accessor: 'changed_by.first_name',\n"
],
"file_path": "superset-frontend/src/views/dashboardList/DashboardList.tsx",
"type": "replace",
"edit_start_line_idx": 163
} | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import logging
from typing import Optional
from colorama import Fore, Style
logger = logging.getLogger(__name__)
class BaseStatsLogger:
"""Base class for logging realtime events"""
def __init__(self, prefix: str = "superset") -> None:
self.prefix = prefix
def key(self, key: str) -> str:
if self.prefix:
return self.prefix + key
return key
def incr(self, key: str) -> None:
"""Increment a counter"""
raise NotImplementedError()
def decr(self, key: str) -> None:
"""Decrement a counter"""
raise NotImplementedError()
def timing(self, key: str, value: float) -> None:
raise NotImplementedError()
def gauge(self, key: str) -> None:
"""Setup a gauge"""
raise NotImplementedError()
class DummyStatsLogger(BaseStatsLogger):
def incr(self, key: str) -> None:
logger.debug(Fore.CYAN + "[stats_logger] (incr) " + key + Style.RESET_ALL)
def decr(self, key: str) -> None:
logger.debug((Fore.CYAN + "[stats_logger] (decr) " + key + Style.RESET_ALL))
def timing(self, key: str, value: float) -> None:
logger.debug(
(Fore.CYAN + f"[stats_logger] (timing) {key} | {value} " + Style.RESET_ALL)
)
def gauge(self, key: str) -> None:
logger.debug(
(Fore.CYAN + "[stats_logger] (gauge) " + f"{key}" + Style.RESET_ALL)
)
try:
from statsd import StatsClient
class StatsdStatsLogger(BaseStatsLogger):
def __init__( # pylint: disable=super-init-not-called
self,
host: str = "localhost",
port: int = 8125,
prefix: str = "superset",
statsd_client: Optional[StatsClient] = None,
) -> None:
"""
Initializes from either params or a supplied, pre-constructed statsd client.
If statsd_client argument is given, all other arguments are ignored and the
supplied client will be used to emit metrics.
"""
if statsd_client:
self.client = statsd_client
else:
self.client = StatsClient(host=host, port=port, prefix=prefix)
def incr(self, key: str) -> None:
self.client.incr(key)
def decr(self, key: str) -> None:
self.client.decr(key)
def timing(self, key: str, value: float) -> None:
self.client.timing(key, value)
def gauge(self, key: str) -> None:
# pylint: disable=no-value-for-parameter
self.client.gauge(key)
except Exception: # pylint: disable=broad-except
pass
| superset/stats_logger.py | 0 | https://github.com/apache/superset/commit/2b061fc64b88831574878b6bd470d700a1527dec | [
0.0021466990001499653,
0.0003534240531735122,
0.0001656064996495843,
0.00017408060375601053,
0.0005671107210218906
] |
{
"id": 2,
"code_window": [
" };\n",
" };\n",
" }) => <a href={url}>{dashboardTitle}</a>,\n",
" },\n",
" {\n",
" accessor: 'changed_by_fk',\n",
" Header: 'Creator',\n",
" Cell: ({\n",
" row: {\n",
" original: { changed_by_name: changedByName, changedByUrl },\n",
" },\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" accessor: 'changed_by.first_name',\n",
" Header: 'Modified By',\n"
],
"file_path": "superset-frontend/src/welcome/DashboardTable.tsx",
"type": "replace",
"edit_start_line_idx": 79
} | /**
* 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 { t } from '@superset-ui/translation';
import { SupersetClient } from '@superset-ui/connection';
import { debounce } from 'lodash';
import ListView from 'src/components/ListView/ListView';
import withToasts from 'src/messageToasts/enhancers/withToasts';
import { Dashboard } from 'src/types/bootstrapTypes';
import { FetchDataConfig } from 'src/components/ListView/types';
const PAGE_SIZE = 25;
interface DashboardTableProps {
addDangerToast: (message: string) => void;
search?: string;
}
interface DashboardTableState {
dashboards: Dashboard[];
dashboard_count: number;
loading: boolean;
}
class DashboardTable extends React.PureComponent<
DashboardTableProps,
DashboardTableState
> {
state = {
dashboards: [],
dashboard_count: 0,
loading: false,
};
componentDidUpdate(prevProps: DashboardTableProps) {
if (prevProps.search !== this.props.search) {
this.fetchDataDebounced({
pageSize: PAGE_SIZE,
pageIndex: 0,
sortBy: this.initialSort,
filters: [],
});
}
}
columns = [
{
accessor: 'dashboard_title',
Header: 'Dashboard',
Cell: ({
row: {
original: { url, dashboard_title: dashboardTitle },
},
}: {
row: {
original: {
url: string;
dashboard_title: string;
};
};
}) => <a href={url}>{dashboardTitle}</a>,
},
{
accessor: 'changed_by_fk',
Header: 'Creator',
Cell: ({
row: {
original: { changed_by_name: changedByName, changedByUrl },
},
}: {
row: {
original: {
changed_by_name: string;
changedByUrl: string;
};
};
}) => <a href={changedByUrl}>{changedByName}</a>,
},
{
accessor: 'changed_on_delta_humanized',
Header: 'Modified',
Cell: ({
row: {
original: { changed_on_delta_humanized: changedOn },
},
}: {
row: {
original: {
changed_on_delta_humanized: string;
};
};
}) => <span className="no-wrap">{changedOn}</span>,
},
];
initialSort = [{ id: 'changed_on_delta_humanized', desc: true }];
fetchData = ({ pageIndex, pageSize, sortBy, filters }: FetchDataConfig) => {
this.setState({ loading: true });
const filterExps = Object.keys(filters)
.map(fk => ({
col: fk,
opr: filters[fk].filterId,
value: filters[fk].filterValue,
}))
.concat(
this.props.search
? [
{
col: 'dashboard_title',
opr: 'ct',
value: this.props.search,
},
]
: [],
);
const queryParams = JSON.stringify({
order_column: sortBy[0].id,
order_direction: sortBy[0].desc ? 'desc' : 'asc',
page: pageIndex,
page_size: pageSize,
...(filterExps.length ? { filters: filterExps } : {}),
});
return SupersetClient.get({
endpoint: `/api/v1/dashboard/?q=${queryParams}`,
})
.then(({ json }) => {
this.setState({ dashboards: json.result, dashboard_count: json.count });
})
.catch(response => {
if (response.status === 401) {
this.props.addDangerToast(
t(
"You don't have the necessary permissions to load dashboards. Please contact your administrator.",
),
);
} else {
this.props.addDangerToast(
t('An error occurred while fetching Dashboards'),
);
}
})
.finally(() => this.setState({ loading: false }));
};
fetchDataDebounced = debounce(this.fetchData, 200);
render() {
return (
<ListView
columns={this.columns}
data={this.state.dashboards}
count={this.state.dashboard_count}
pageSize={PAGE_SIZE}
fetchData={this.fetchData}
loading={this.state.loading}
initialSort={this.initialSort}
/>
);
}
}
export default withToasts(DashboardTable);
| superset-frontend/src/welcome/DashboardTable.tsx | 1 | https://github.com/apache/superset/commit/2b061fc64b88831574878b6bd470d700a1527dec | [
0.8737698197364807,
0.06574743986129761,
0.00017050252063199878,
0.0003140131593681872,
0.2042594701051712
] |
{
"id": 2,
"code_window": [
" };\n",
" };\n",
" }) => <a href={url}>{dashboardTitle}</a>,\n",
" },\n",
" {\n",
" accessor: 'changed_by_fk',\n",
" Header: 'Creator',\n",
" Cell: ({\n",
" row: {\n",
" original: { changed_by_name: changedByName, changedByUrl },\n",
" },\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" accessor: 'changed_by.first_name',\n",
" Header: 'Modified By',\n"
],
"file_path": "superset-frontend/src/welcome/DashboardTable.tsx",
"type": "replace",
"edit_start_line_idx": 79
} | #
# 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.
#
# requires github-changes, run
# `npm install -g github-changes`
# requires $GITHUB_TOKEN to be set
# usage: ./github-changes 0.20.0 0.20.1
# will overwrites the local CHANGELOG.md, somehow you need to merge it in
github-changes -o apache -r incubator-superset --token $GITHUB_TOKEN --between-tags $1...$2
| scripts/gen_changelog.sh | 0 | https://github.com/apache/superset/commit/2b061fc64b88831574878b6bd470d700a1527dec | [
0.00017716594447847456,
0.00017421440861653537,
0.00017055422358680516,
0.00017492304323241115,
0.0000027453404527477687
] |
{
"id": 2,
"code_window": [
" };\n",
" };\n",
" }) => <a href={url}>{dashboardTitle}</a>,\n",
" },\n",
" {\n",
" accessor: 'changed_by_fk',\n",
" Header: 'Creator',\n",
" Cell: ({\n",
" row: {\n",
" original: { changed_by_name: changedByName, changedByUrl },\n",
" },\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" accessor: 'changed_by.first_name',\n",
" Header: 'Modified By',\n"
],
"file_path": "superset-frontend/src/welcome/DashboardTable.tsx",
"type": "replace",
"edit_start_line_idx": 79
} | /**
* 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 getDashboardUrl from 'src/dashboard/util/getDashboardUrl';
import { DASHBOARD_FILTER_SCOPE_GLOBAL } from 'src/dashboard/reducers/dashboardFilters';
describe('getChartIdsFromLayout', () => {
it('should encode filters', () => {
const filters = {
'35_key': {
values: ['value'],
scope: DASHBOARD_FILTER_SCOPE_GLOBAL,
},
};
const url = getDashboardUrl('path', filters);
expect(url).toBe(
'path?preselect_filters=%7B%2235%22%3A%7B%22key%22%3A%5B%22value%22%5D%7D%7D',
);
});
});
| superset-frontend/spec/javascripts/dashboard/util/getDashboardUrl_spec.js | 0 | https://github.com/apache/superset/commit/2b061fc64b88831574878b6bd470d700a1527dec | [
0.0001984190457733348,
0.0001777392317308113,
0.00016419720486737788,
0.00017417033086530864,
0.00001265516402781941
] |
{
"id": 2,
"code_window": [
" };\n",
" };\n",
" }) => <a href={url}>{dashboardTitle}</a>,\n",
" },\n",
" {\n",
" accessor: 'changed_by_fk',\n",
" Header: 'Creator',\n",
" Cell: ({\n",
" row: {\n",
" original: { changed_by_name: changedByName, changedByUrl },\n",
" },\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" accessor: 'changed_by.first_name',\n",
" Header: 'Modified By',\n"
],
"file_path": "superset-frontend/src/welcome/DashboardTable.tsx",
"type": "replace",
"edit_start_line_idx": 79
} | # 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 logging
from typing import Any
import yaml
from flask import g, request, Response
from flask_appbuilder.api import expose, protect, rison, safe
from flask_appbuilder.models.sqla.interface import SQLAInterface
from marshmallow import ValidationError
from superset.connectors.sqla.models import SqlaTable
from superset.constants import RouteMethod
from superset.datasets.commands.create import CreateDatasetCommand
from superset.datasets.commands.delete import DeleteDatasetCommand
from superset.datasets.commands.exceptions import (
DatasetCreateFailedError,
DatasetDeleteFailedError,
DatasetForbiddenError,
DatasetInvalidError,
DatasetNotFoundError,
DatasetRefreshFailedError,
DatasetUpdateFailedError,
)
from superset.datasets.commands.refresh import RefreshDatasetCommand
from superset.datasets.commands.update import UpdateDatasetCommand
from superset.datasets.dao import DatasetDAO
from superset.datasets.schemas import (
DatasetPostSchema,
DatasetPutSchema,
DatasetRelatedObjectsResponse,
get_export_ids_schema,
)
from superset.views.base import DatasourceFilter, generate_download_headers
from superset.views.base_api import (
BaseSupersetModelRestApi,
RelatedFieldFilter,
statsd_metrics,
)
from superset.views.database.filters import DatabaseFilter
from superset.views.filters import FilterRelatedOwners
logger = logging.getLogger(__name__)
class DatasetRestApi(BaseSupersetModelRestApi):
datamodel = SQLAInterface(SqlaTable)
base_filters = [["id", DatasourceFilter, lambda: []]]
resource_name = "dataset"
allow_browser_login = True
class_permission_name = "TableModelView"
include_route_methods = RouteMethod.REST_MODEL_VIEW_CRUD_SET | {
RouteMethod.EXPORT,
RouteMethod.RELATED,
"refresh",
"related_objects",
}
list_columns = [
"id",
"database_id",
"database_name",
"changed_by_fk",
"changed_by_name",
"changed_by_url",
"changed_by.username",
"changed_on",
"default_endpoint",
"explore_url",
"kind",
"owners.id",
"owners.username",
"owners.first_name",
"owners.last_name",
"schema",
"sql",
"table_name",
]
show_columns = [
"database.database_name",
"database.id",
"table_name",
"sql",
"filter_select_enabled",
"fetch_values_predicate",
"schema",
"description",
"main_dttm_col",
"offset",
"default_endpoint",
"cache_timeout",
"is_sqllab_view",
"template_params",
"owners.id",
"owners.username",
"owners.first_name",
"owners.last_name",
"columns",
"metrics",
]
add_model_schema = DatasetPostSchema()
edit_model_schema = DatasetPutSchema()
add_columns = ["database", "schema", "table_name", "owners"]
edit_columns = [
"table_name",
"sql",
"filter_select_enabled",
"fetch_values_predicate",
"schema",
"description",
"main_dttm_col",
"offset",
"default_endpoint",
"cache_timeout",
"is_sqllab_view",
"template_params",
"owners",
"columns",
"metrics",
]
openapi_spec_tag = "Datasets"
related_field_filters = {
"owners": RelatedFieldFilter("first_name", FilterRelatedOwners),
"database": "database_name",
}
filter_rel_fields = {"database": [["id", DatabaseFilter, lambda: []]]}
allowed_rel_fields = {"database", "owners"}
openapi_spec_component_schemas = (DatasetRelatedObjectsResponse,)
@expose("/", methods=["POST"])
@protect()
@safe
@statsd_metrics
def post(self) -> Response:
"""Creates a new Dataset
---
post:
description: >-
Create a new Dataset
requestBody:
description: Dataset schema
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/{{self.__class__.__name__}}.post'
responses:
201:
description: Dataset added
content:
application/json:
schema:
type: object
properties:
id:
type: number
result:
$ref: '#/components/schemas/{{self.__class__.__name__}}.post'
400:
$ref: '#/components/responses/400'
401:
$ref: '#/components/responses/401'
422:
$ref: '#/components/responses/422'
500:
$ref: '#/components/responses/500'
"""
if not request.is_json:
return self.response_400(message="Request is not JSON")
try:
item = self.add_model_schema.load(request.json)
# This validates custom Schema with custom validations
except ValidationError as error:
return self.response_400(message=error.messages)
try:
new_model = CreateDatasetCommand(g.user, item).run()
return self.response(201, id=new_model.id, result=item)
except DatasetInvalidError as ex:
return self.response_422(message=ex.normalized_messages())
except DatasetCreateFailedError as ex:
logger.error(
"Error creating model %s: %s", self.__class__.__name__, str(ex)
)
return self.response_422(message=str(ex))
@expose("/<pk>", methods=["PUT"])
@protect()
@safe
@statsd_metrics
def put( # pylint: disable=too-many-return-statements, arguments-differ
self, pk: int
) -> Response:
"""Changes a Dataset
---
put:
description: >-
Changes a Dataset
parameters:
- in: path
schema:
type: integer
name: pk
requestBody:
description: Dataset schema
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/{{self.__class__.__name__}}.put'
responses:
200:
description: Dataset changed
content:
application/json:
schema:
type: object
properties:
id:
type: number
result:
$ref: '#/components/schemas/{{self.__class__.__name__}}.put'
400:
$ref: '#/components/responses/400'
401:
$ref: '#/components/responses/401'
403:
$ref: '#/components/responses/403'
404:
$ref: '#/components/responses/404'
422:
$ref: '#/components/responses/422'
500:
$ref: '#/components/responses/500'
"""
if not request.is_json:
return self.response_400(message="Request is not JSON")
try:
item = self.edit_model_schema.load(request.json)
# This validates custom Schema with custom validations
except ValidationError as error:
return self.response_400(message=error.messages)
try:
changed_model = UpdateDatasetCommand(g.user, pk, item).run()
return self.response(200, id=changed_model.id, result=item)
except DatasetNotFoundError:
return self.response_404()
except DatasetForbiddenError:
return self.response_403()
except DatasetInvalidError as ex:
return self.response_422(message=ex.normalized_messages())
except DatasetUpdateFailedError as ex:
logger.error(
"Error updating model %s: %s", self.__class__.__name__, str(ex)
)
return self.response_422(message=str(ex))
@expose("/<pk>", methods=["DELETE"])
@protect()
@safe
@statsd_metrics
def delete(self, pk: int) -> Response: # pylint: disable=arguments-differ
"""Deletes a Dataset
---
delete:
description: >-
Deletes a Dataset
parameters:
- in: path
schema:
type: integer
name: pk
responses:
200:
description: Dataset delete
content:
application/json:
schema:
type: object
properties:
message:
type: string
401:
$ref: '#/components/responses/401'
403:
$ref: '#/components/responses/403'
404:
$ref: '#/components/responses/404'
422:
$ref: '#/components/responses/422'
500:
$ref: '#/components/responses/500'
"""
try:
DeleteDatasetCommand(g.user, pk).run()
return self.response(200, message="OK")
except DatasetNotFoundError:
return self.response_404()
except DatasetForbiddenError:
return self.response_403()
except DatasetDeleteFailedError as ex:
logger.error(
"Error deleting model %s: %s", self.__class__.__name__, str(ex)
)
return self.response_422(message=str(ex))
@expose("/export/", methods=["GET"])
@protect()
@safe
@statsd_metrics
@rison(get_export_ids_schema)
def export(self, **kwargs: Any) -> Response:
"""Export dashboards
---
get:
description: >-
Exports multiple datasets and downloads them as YAML files
parameters:
- in: query
name: q
content:
application/json:
schema:
type: array
items:
type: integer
responses:
200:
description: Dataset export
content:
text/plain:
schema:
type: string
400:
$ref: '#/components/responses/400'
401:
$ref: '#/components/responses/401'
404:
$ref: '#/components/responses/404'
500:
$ref: '#/components/responses/500'
"""
requested_ids = kwargs["rison"]
query = self.datamodel.session.query(SqlaTable).filter(
SqlaTable.id.in_(requested_ids)
)
query = self._base_filters.apply_all(query)
items = query.all()
ids = [item.id for item in items]
if len(ids) != len(requested_ids):
return self.response_404()
data = [t.export_to_dict() for t in items]
return Response(
yaml.safe_dump(data),
headers=generate_download_headers("yaml"),
mimetype="application/text",
)
@expose("/<pk>/refresh", methods=["PUT"])
@protect()
@safe
@statsd_metrics
def refresh(self, pk: int) -> Response:
"""Refresh a Dataset
---
put:
description: >-
Refreshes and updates columns of a dataset
parameters:
- in: path
schema:
type: integer
name: pk
responses:
200:
description: Dataset delete
content:
application/json:
schema:
type: object
properties:
message:
type: string
401:
$ref: '#/components/responses/401'
403:
$ref: '#/components/responses/403'
404:
$ref: '#/components/responses/404'
422:
$ref: '#/components/responses/422'
500:
$ref: '#/components/responses/500'
"""
try:
RefreshDatasetCommand(g.user, pk).run()
return self.response(200, message="OK")
except DatasetNotFoundError:
return self.response_404()
except DatasetForbiddenError:
return self.response_403()
except DatasetRefreshFailedError as ex:
logger.error(
"Error refreshing dataset %s: %s", self.__class__.__name__, str(ex)
)
return self.response_422(message=str(ex))
@expose("/<pk>/related_objects", methods=["GET"])
@protect()
@safe
@statsd_metrics
def related_objects(self, pk: int) -> Response:
"""Get charts and dashboards count associated to a dataset
---
get:
description:
Get charts and dashboards count associated to a dataset
parameters:
- in: path
name: pk
schema:
type: integer
responses:
200:
200:
description: Query result
content:
application/json:
schema:
$ref: "#/components/schemas/DatasetRelatedObjectsResponse"
401:
$ref: '#/components/responses/401'
404:
$ref: '#/components/responses/404'
500:
$ref: '#/components/responses/500'
"""
dataset = DatasetDAO.find_by_id(pk)
if not dataset:
return self.response_404()
data = DatasetDAO.get_related_objects(pk)
charts = [
{
"id": chart.id,
"slice_name": chart.slice_name,
"viz_type": chart.viz_type,
}
for chart in data["charts"]
]
dashboards = [
{
"id": dashboard.id,
"json_metadata": dashboard.json_metadata,
"slug": dashboard.slug,
"title": dashboard.dashboard_title,
}
for dashboard in data["dashboards"]
]
return self.response(
200,
charts={"count": len(charts), "result": charts},
dashboards={"count": len(dashboards), "result": dashboards},
)
| superset/datasets/api.py | 0 | https://github.com/apache/superset/commit/2b061fc64b88831574878b6bd470d700a1527dec | [
0.0059477356262505054,
0.0003557305608410388,
0.00016434615827165544,
0.00017152438522316515,
0.0009081828757189214
] |
{
"id": 3,
"code_window": [
" \"slice_name\",\n",
" \"url\",\n",
" \"description\",\n",
" \"changed_by_fk\",\n",
" \"created_by_fk\",\n",
" \"changed_by_name\",\n",
" \"changed_by_url\",\n",
" \"changed_by.first_name\",\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "superset/charts/api.py",
"type": "replace",
"edit_start_line_idx": 108
} | # 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 json
import logging
from typing import Any, Dict
import simplejson
from flask import g, make_response, redirect, request, Response, url_for
from flask_appbuilder.api import expose, protect, rison, safe
from flask_appbuilder.models.sqla.interface import SQLAInterface
from flask_babel import gettext as _, ngettext
from marshmallow import ValidationError
from werkzeug.wrappers import Response as WerkzeugResponse
from werkzeug.wsgi import FileWrapper
from superset import is_feature_enabled, thumbnail_cache
from superset.charts.commands.bulk_delete import BulkDeleteChartCommand
from superset.charts.commands.create import CreateChartCommand
from superset.charts.commands.delete import DeleteChartCommand
from superset.charts.commands.exceptions import (
ChartBulkDeleteFailedError,
ChartCreateFailedError,
ChartDeleteFailedError,
ChartForbiddenError,
ChartInvalidError,
ChartNotFoundError,
ChartUpdateFailedError,
)
from superset.charts.commands.update import UpdateChartCommand
from superset.charts.dao import ChartDAO
from superset.charts.filters import ChartFilter, ChartNameOrDescriptionFilter
from superset.charts.schemas import (
CHART_SCHEMAS,
ChartDataQueryContextSchema,
ChartPostSchema,
ChartPutSchema,
get_delete_ids_schema,
openapi_spec_methods_override,
screenshot_query_schema,
thumbnail_query_schema,
)
from superset.constants import RouteMethod
from superset.exceptions import SupersetSecurityException
from superset.extensions import event_logger
from superset.models.slice import Slice
from superset.tasks.thumbnails import cache_chart_thumbnail
from superset.utils.core import ChartDataResultFormat, json_int_dttm_ser
from superset.utils.screenshots import ChartScreenshot
from superset.utils.urls import get_url_path
from superset.views.base_api import (
BaseSupersetModelRestApi,
RelatedFieldFilter,
statsd_metrics,
)
from superset.views.core import CsvResponse, generate_download_headers
from superset.views.filters import FilterRelatedOwners
logger = logging.getLogger(__name__)
class ChartRestApi(BaseSupersetModelRestApi):
datamodel = SQLAInterface(Slice)
resource_name = "chart"
allow_browser_login = True
include_route_methods = RouteMethod.REST_MODEL_VIEW_CRUD_SET | {
RouteMethod.EXPORT,
RouteMethod.RELATED,
"bulk_delete", # not using RouteMethod since locally defined
"data",
"viz_types",
"datasources",
}
class_permission_name = "SliceModelView"
show_columns = [
"slice_name",
"description",
"owners.id",
"owners.username",
"owners.first_name",
"owners.last_name",
"dashboards.id",
"dashboards.dashboard_title",
"viz_type",
"params",
"cache_timeout",
]
show_select_columns = show_columns + ["table.id"]
list_columns = [
"id",
"slice_name",
"url",
"description",
"changed_by_fk",
"created_by_fk",
"changed_by_name",
"changed_by_url",
"changed_by.first_name",
"changed_by.last_name",
"changed_on_utc",
"changed_on_delta_humanized",
"datasource_id",
"datasource_type",
"datasource_name_text",
"datasource_url",
"table.default_endpoint",
"table.table_name",
"viz_type",
"params",
"cache_timeout",
]
list_select_columns = list_columns + ["changed_on"]
order_columns = [
"slice_name",
"viz_type",
"datasource_name",
"changed_by_fk",
"changed_on_delta_humanized",
]
search_columns = (
"slice_name",
"description",
"viz_type",
"datasource_name",
"datasource_id",
"datasource_type",
"owners",
)
base_order = ("changed_on", "desc")
base_filters = [["id", ChartFilter, lambda: []]]
search_filters = {"slice_name": [ChartNameOrDescriptionFilter]}
# Will just affect _info endpoint
edit_columns = ["slice_name"]
add_columns = edit_columns
add_model_schema = ChartPostSchema()
edit_model_schema = ChartPutSchema()
openapi_spec_tag = "Charts"
""" Override the name set for this collection of endpoints """
openapi_spec_component_schemas = CHART_SCHEMAS
apispec_parameter_schemas = {
"screenshot_query_schema": screenshot_query_schema,
"get_delete_ids_schema": get_delete_ids_schema,
}
""" Add extra schemas to the OpenAPI components schema section """
openapi_spec_methods = openapi_spec_methods_override
""" Overrides GET methods OpenApi descriptions """
order_rel_fields = {
"slices": ("slice_name", "asc"),
"owners": ("first_name", "asc"),
}
related_field_filters = {
"owners": RelatedFieldFilter("first_name", FilterRelatedOwners)
}
allowed_rel_fields = {"owners"}
def __init__(self) -> None:
if is_feature_enabled("THUMBNAILS"):
self.include_route_methods = self.include_route_methods | {
"thumbnail",
"screenshot",
"cache_screenshot",
}
super().__init__()
@expose("/", methods=["POST"])
@protect()
@safe
@statsd_metrics
def post(self) -> Response:
"""Creates a new Chart
---
post:
description: >-
Create a new Chart.
requestBody:
description: Chart schema
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/{{self.__class__.__name__}}.post'
responses:
201:
description: Chart added
content:
application/json:
schema:
type: object
properties:
id:
type: number
result:
$ref: '#/components/schemas/{{self.__class__.__name__}}.post'
400:
$ref: '#/components/responses/400'
401:
$ref: '#/components/responses/401'
422:
$ref: '#/components/responses/422'
500:
$ref: '#/components/responses/500'
"""
if not request.is_json:
return self.response_400(message="Request is not JSON")
try:
item = self.add_model_schema.load(request.json)
# This validates custom Schema with custom validations
except ValidationError as error:
return self.response_400(message=error.messages)
try:
new_model = CreateChartCommand(g.user, item).run()
return self.response(201, id=new_model.id, result=item)
except ChartInvalidError as ex:
return self.response_422(message=ex.normalized_messages())
except ChartCreateFailedError as ex:
logger.error(
"Error creating model %s: %s", self.__class__.__name__, str(ex)
)
return self.response_422(message=str(ex))
@expose("/<pk>", methods=["PUT"])
@protect()
@safe
@statsd_metrics
def put( # pylint: disable=too-many-return-statements, arguments-differ
self, pk: int
) -> Response:
"""Changes a Chart
---
put:
description: >-
Changes a Chart.
parameters:
- in: path
schema:
type: integer
name: pk
requestBody:
description: Chart schema
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/{{self.__class__.__name__}}.put'
responses:
200:
description: Chart changed
content:
application/json:
schema:
type: object
properties:
id:
type: number
result:
$ref: '#/components/schemas/{{self.__class__.__name__}}.put'
400:
$ref: '#/components/responses/400'
401:
$ref: '#/components/responses/401'
403:
$ref: '#/components/responses/403'
404:
$ref: '#/components/responses/404'
422:
$ref: '#/components/responses/422'
500:
$ref: '#/components/responses/500'
"""
if not request.is_json:
return self.response_400(message="Request is not JSON")
try:
item = self.edit_model_schema.load(request.json)
# This validates custom Schema with custom validations
except ValidationError as error:
return self.response_400(message=error.messages)
try:
changed_model = UpdateChartCommand(g.user, pk, item).run()
return self.response(200, id=changed_model.id, result=item)
except ChartNotFoundError:
return self.response_404()
except ChartForbiddenError:
return self.response_403()
except ChartInvalidError as ex:
return self.response_422(message=ex.normalized_messages())
except ChartUpdateFailedError as ex:
logger.error(
"Error updating model %s: %s", self.__class__.__name__, str(ex)
)
return self.response_422(message=str(ex))
@expose("/<pk>", methods=["DELETE"])
@protect()
@safe
@statsd_metrics
def delete(self, pk: int) -> Response: # pylint: disable=arguments-differ
"""Deletes a Chart
---
delete:
description: >-
Deletes a Chart.
parameters:
- in: path
schema:
type: integer
name: pk
responses:
200:
description: Chart delete
content:
application/json:
schema:
type: object
properties:
message:
type: string
401:
$ref: '#/components/responses/401'
403:
$ref: '#/components/responses/403'
404:
$ref: '#/components/responses/404'
422:
$ref: '#/components/responses/422'
500:
$ref: '#/components/responses/500'
"""
try:
DeleteChartCommand(g.user, pk).run()
return self.response(200, message="OK")
except ChartNotFoundError:
return self.response_404()
except ChartForbiddenError:
return self.response_403()
except ChartDeleteFailedError as ex:
logger.error(
"Error deleting model %s: %s", self.__class__.__name__, str(ex)
)
return self.response_422(message=str(ex))
@expose("/", methods=["DELETE"])
@protect()
@safe
@statsd_metrics
@rison(get_delete_ids_schema)
def bulk_delete(
self, **kwargs: Any
) -> Response: # pylint: disable=arguments-differ
"""Delete bulk Charts
---
delete:
description: >-
Deletes multiple Charts in a bulk operation.
parameters:
- in: query
name: q
content:
application/json:
schema:
$ref: '#/components/schemas/get_delete_ids_schema'
responses:
200:
description: Charts bulk delete
content:
application/json:
schema:
type: object
properties:
message:
type: string
401:
$ref: '#/components/responses/401'
403:
$ref: '#/components/responses/403'
404:
$ref: '#/components/responses/404'
422:
$ref: '#/components/responses/422'
500:
$ref: '#/components/responses/500'
"""
item_ids = kwargs["rison"]
try:
BulkDeleteChartCommand(g.user, item_ids).run()
return self.response(
200,
message=ngettext(
"Deleted %(num)d chart", "Deleted %(num)d charts", num=len(item_ids)
),
)
except ChartNotFoundError:
return self.response_404()
except ChartForbiddenError:
return self.response_403()
except ChartBulkDeleteFailedError as ex:
return self.response_422(message=str(ex))
@expose("/data", methods=["POST"])
@event_logger.log_this
@protect()
@safe
@statsd_metrics
def data(self) -> Response: # pylint: disable=too-many-return-statements
"""
Takes a query context constructed in the client and returns payload
data response for the given query.
---
post:
description: >-
Takes a query context constructed in the client and returns payload data
response for the given query.
requestBody:
description: >-
A query context consists of a datasource from which to fetch data
and one or many query objects.
required: true
content:
application/json:
schema:
$ref: "#/components/schemas/ChartDataQueryContextSchema"
responses:
200:
description: Query result
content:
application/json:
schema:
$ref: "#/components/schemas/ChartDataResponseSchema"
400:
$ref: '#/components/responses/400'
500:
$ref: '#/components/responses/500'
"""
if request.is_json:
json_body = request.json
elif request.form.get("form_data"):
# CSV export submits regular form data
json_body = json.loads(request.form["form_data"])
else:
return self.response_400(message="Request is not JSON")
try:
query_context = ChartDataQueryContextSchema().load(json_body)
except KeyError:
return self.response_400(message="Request is incorrect")
except ValidationError as error:
return self.response_400(
message=_("Request is incorrect: %(error)s", error=error.messages)
)
try:
query_context.raise_for_access()
except SupersetSecurityException:
return self.response_401()
payload = query_context.get_payload()
for query in payload:
if query.get("error"):
return self.response_400(message=f"Error: {query['error']}")
result_format = query_context.result_format
if result_format == ChartDataResultFormat.CSV:
# return the first result
result = payload[0]["data"]
return CsvResponse(
result,
status=200,
headers=generate_download_headers("csv"),
mimetype="application/csv",
)
if result_format == ChartDataResultFormat.JSON:
response_data = simplejson.dumps(
{"result": payload}, default=json_int_dttm_ser, ignore_nan=True
)
resp = make_response(response_data, 200)
resp.headers["Content-Type"] = "application/json; charset=utf-8"
return resp
return self.response_400(message=f"Unsupported result_format: {result_format}")
@expose("/<pk>/cache_screenshot/", methods=["GET"])
@protect()
@rison(screenshot_query_schema)
@safe
@statsd_metrics
def cache_screenshot(self, pk: int, **kwargs: Dict[str, bool]) -> WerkzeugResponse:
"""
---
get:
description: Compute and cache a screenshot.
parameters:
- in: path
schema:
type: integer
name: pk
- in: query
name: q
content:
application/json:
schema:
$ref: '#/components/schemas/screenshot_query_schema'
responses:
200:
description: Chart async result
content:
application/json:
schema:
$ref: "#/components/schemas/ChartCacheScreenshotResponseSchema"
302:
description: Redirects to the current digest
400:
$ref: '#/components/responses/400'
401:
$ref: '#/components/responses/401'
404:
$ref: '#/components/responses/404'
500:
$ref: '#/components/responses/500'
"""
rison_dict = kwargs["rison"]
window_size = rison_dict.get("window_size") or (800, 600)
# Don't shrink the image if thumb_size is not specified
thumb_size = rison_dict.get("thumb_size") or window_size
chart = self.datamodel.get(pk, self._base_filters)
if not chart:
return self.response_404()
chart_url = get_url_path("Superset.slice", slice_id=chart.id, standalone="true")
screenshot_obj = ChartScreenshot(chart_url, chart.digest)
cache_key = screenshot_obj.cache_key(window_size, thumb_size)
image_url = get_url_path(
"ChartRestApi.screenshot", pk=chart.id, digest=cache_key
)
def trigger_celery() -> WerkzeugResponse:
logger.info("Triggering screenshot ASYNC")
kwargs = {
"url": chart_url,
"digest": chart.digest,
"force": True,
"window_size": window_size,
"thumb_size": thumb_size,
}
cache_chart_thumbnail.delay(**kwargs)
return self.response(
202, cache_key=cache_key, chart_url=chart_url, image_url=image_url,
)
return trigger_celery()
@expose("/<pk>/screenshot/<digest>/", methods=["GET"])
@protect()
@rison(screenshot_query_schema)
@safe
@statsd_metrics
def screenshot(self, pk: int, digest: str) -> WerkzeugResponse:
"""Get Chart screenshot
---
get:
description: Get a computed screenshot from cache.
parameters:
- in: path
schema:
type: integer
name: pk
- in: path
schema:
type: string
name: digest
responses:
200:
description: Chart thumbnail image
content:
image/*:
schema:
type: string
format: binary
302:
description: Redirects to the current digest
400:
$ref: '#/components/responses/400'
401:
$ref: '#/components/responses/401'
404:
$ref: '#/components/responses/404'
500:
$ref: '#/components/responses/500'
"""
chart = self.datamodel.get(pk, self._base_filters)
# Making sure the chart still exists
if not chart:
return self.response_404()
# TODO make sure the user has access to the chart
# fetch the chart screenshot using the current user and cache if set
img = ChartScreenshot.get_from_cache_key(thumbnail_cache, digest)
if img:
return Response(
FileWrapper(img), mimetype="image/png", direct_passthrough=True
)
# TODO: return an empty image
return self.response_404()
@expose("/<pk>/thumbnail/<digest>/", methods=["GET"])
@protect()
@rison(thumbnail_query_schema)
@safe
@statsd_metrics
def thumbnail(
self, pk: int, digest: str, **kwargs: Dict[str, bool]
) -> WerkzeugResponse:
"""Get Chart thumbnail
---
get:
description: Compute or get already computed chart thumbnail from cache.
parameters:
- in: path
schema:
type: integer
name: pk
- in: path
schema:
type: string
name: digest
responses:
200:
description: Chart thumbnail image
/content:
image/*:
schema:
type: string
format: binary
302:
description: Redirects to the current digest
400:
$ref: '#/components/responses/400'
401:
$ref: '#/components/responses/401'
404:
$ref: '#/components/responses/404'
500:
$ref: '#/components/responses/500'
"""
chart = self.datamodel.get(pk, self._base_filters)
if not chart:
return self.response_404()
url = get_url_path("Superset.slice", slice_id=chart.id, standalone="true")
if kwargs["rison"].get("force", False):
logger.info(
"Triggering thumbnail compute (chart id: %s) ASYNC", str(chart.id)
)
cache_chart_thumbnail.delay(url, chart.digest, force=True)
return self.response(202, message="OK Async")
# fetch the chart screenshot using the current user and cache if set
screenshot = ChartScreenshot(url, chart.digest).get_from_cache(
cache=thumbnail_cache
)
# If not screenshot then send request to compute thumb to celery
if not screenshot:
logger.info(
"Triggering thumbnail compute (chart id: %s) ASYNC", str(chart.id)
)
cache_chart_thumbnail.delay(url, chart.digest, force=True)
return self.response(202, message="OK Async")
# If digests
if chart.digest != digest:
return redirect(
url_for(
f"{self.__class__.__name__}.thumbnail", pk=pk, digest=chart.digest
)
)
return Response(
FileWrapper(screenshot), mimetype="image/png", direct_passthrough=True
)
@expose("/datasources", methods=["GET"])
@protect()
@safe
def datasources(self) -> Response:
"""Get available datasources
---
get:
description: Get available datasources.
responses:
200:
description: Query result
content:
application/json:
schema:
$ref: "#/components/schemas/ChartGetDatasourceResponseSchema"
400:
$ref: '#/components/responses/400'
401:
$ref: '#/components/responses/401'
404:
$ref: '#/components/responses/404'
422:
$ref: '#/components/responses/422'
500:
$ref: '#/components/responses/500'
"""
datasources = ChartDAO.fetch_all_datasources()
if not datasources:
return self.response(200, count=0, result=[])
result = [
{
"label": str(ds),
"value": {"datasource_id": ds.id, "datasource_type": ds.type},
}
for ds in datasources
]
return self.response(200, count=len(result), result=result)
| superset/charts/api.py | 1 | https://github.com/apache/superset/commit/2b061fc64b88831574878b6bd470d700a1527dec | [
0.5763653516769409,
0.008675649762153625,
0.0001660761481616646,
0.00017171399667859077,
0.06654722988605499
] |
{
"id": 3,
"code_window": [
" \"slice_name\",\n",
" \"url\",\n",
" \"description\",\n",
" \"changed_by_fk\",\n",
" \"created_by_fk\",\n",
" \"changed_by_name\",\n",
" \"changed_by_url\",\n",
" \"changed_by.first_name\",\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "superset/charts/api.py",
"type": "replace",
"edit_start_line_idx": 108
} | /**
* 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 { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { t } from '@superset-ui/translation';
import ExploreChartPanel from './ExploreChartPanel';
import ControlPanelsContainer from './ControlPanelsContainer';
import SaveModal from './SaveModal';
import QueryAndSaveBtns from './QueryAndSaveBtns';
import { getExploreLongUrl } from '../exploreUtils';
import { areObjectsEqual } from '../../reduxUtils';
import { getFormDataFromControls } from '../controlUtils';
import { chartPropShape } from '../../dashboard/util/propShapes';
import * as exploreActions from '../actions/exploreActions';
import * as saveModalActions from '../actions/saveModalActions';
import * as chartActions from '../../chart/chartAction';
import { fetchDatasourceMetadata } from '../../dashboard/actions/datasources';
import * as logActions from '../../logger/actions/';
import {
LOG_ACTIONS_MOUNT_EXPLORER,
LOG_ACTIONS_CHANGE_EXPLORE_CONTROLS,
} from '../../logger/LogUtils';
import Hotkeys from '../../components/Hotkeys';
// Prolly need to move this to a global context
const keymap = {
RUN: 'ctrl + r, ctrl + enter',
SAVE: 'ctrl + s',
};
const getHotKeys = () =>
Object.keys(keymap).map(k => ({
name: k,
descr: keymap[k],
key: k,
}));
const propTypes = {
actions: PropTypes.object.isRequired,
datasource_type: PropTypes.string.isRequired,
isDatasourceMetaLoading: PropTypes.bool.isRequired,
chart: chartPropShape.isRequired,
slice: PropTypes.object,
sliceName: PropTypes.string,
controls: PropTypes.object.isRequired,
forcedHeight: PropTypes.string,
form_data: PropTypes.object.isRequired,
standalone: PropTypes.bool.isRequired,
timeout: PropTypes.number,
impressionId: PropTypes.string,
};
class ExploreViewContainer extends React.Component {
constructor(props) {
super(props);
this.state = {
height: this.getHeight(),
width: this.getWidth(),
showModal: false,
chartIsStale: false,
refreshOverlayVisible: false,
};
this.addHistory = this.addHistory.bind(this);
this.handleResize = this.handleResize.bind(this);
this.handlePopstate = this.handlePopstate.bind(this);
this.onStop = this.onStop.bind(this);
this.onQuery = this.onQuery.bind(this);
this.toggleModal = this.toggleModal.bind(this);
this.handleKeydown = this.handleKeydown.bind(this);
}
componentDidMount() {
window.addEventListener('resize', this.handleResize);
window.addEventListener('popstate', this.handlePopstate);
document.addEventListener('keydown', this.handleKeydown);
this.addHistory({ isReplace: true });
this.props.actions.logEvent(LOG_ACTIONS_MOUNT_EXPLORER);
// Trigger the chart if there are no errors
const { chart } = this.props;
if (!this.hasErrors()) {
this.props.actions.triggerQuery(true, this.props.chart.id);
}
}
UNSAFE_componentWillReceiveProps(nextProps) {
if (
nextProps.controls.viz_type.value !== this.props.controls.viz_type.value
) {
this.props.actions.resetControls();
}
if (
nextProps.controls.datasource &&
(this.props.controls.datasource == null ||
nextProps.controls.datasource.value !==
this.props.controls.datasource.value)
) {
fetchDatasourceMetadata(nextProps.form_data.datasource, true);
}
const changedControlKeys = this.findChangedControlKeys(
this.props.controls,
nextProps.controls,
);
if (this.hasDisplayControlChanged(changedControlKeys, nextProps.controls)) {
this.props.actions.updateQueryFormData(
getFormDataFromControls(nextProps.controls),
this.props.chart.id,
);
this.props.actions.renderTriggered(
new Date().getTime(),
this.props.chart.id,
);
}
if (this.hasQueryControlChanged(changedControlKeys, nextProps.controls)) {
this.props.actions.logEvent(LOG_ACTIONS_CHANGE_EXPLORE_CONTROLS);
this.setState({ chartIsStale: true, refreshOverlayVisible: true });
}
}
/* eslint no-unused-vars: 0 */
componentDidUpdate(prevProps, prevState) {
const changedControlKeys = this.findChangedControlKeys(
prevProps.controls,
this.props.controls,
);
if (
this.hasDisplayControlChanged(changedControlKeys, this.props.controls)
) {
this.addHistory({});
}
}
componentWillUnmount() {
window.removeEventListener('resize', this.handleResize);
window.removeEventListener('popstate', this.handlePopstate);
document.removeEventListener('keydown', this.handleKeydown);
}
onQuery() {
// remove alerts when query
this.props.actions.removeControlPanelAlert();
this.props.actions.triggerQuery(true, this.props.chart.id);
this.setState({ chartIsStale: false, refreshOverlayVisible: false });
this.addHistory({});
}
onStop() {
if (this.props.chart && this.props.chart.queryController) {
this.props.chart.queryController.abort();
}
}
getWidth() {
return `${window.innerWidth}px`;
}
getHeight() {
if (this.props.forcedHeight) {
return this.props.forcedHeight + 'px';
}
const navHeight = this.props.standalone ? 0 : 90;
return `${window.innerHeight - navHeight}px`;
}
handleKeydown(event) {
const controlOrCommand = event.ctrlKey || event.metaKey;
if (controlOrCommand) {
const isEnter = event.key === 'Enter' || event.keyCode === 13;
const isS = event.key === 's' || event.keyCode === 83;
if (isEnter) {
this.onQuery();
} else if (isS) {
if (this.props.slice) {
this.props.actions
.saveSlice(this.props.form_data, {
action: 'overwrite',
slice_id: this.props.slice.slice_id,
slice_name: this.props.slice.slice_name,
add_to_dash: 'noSave',
goto_dash: false,
})
.then(({ data }) => {
window.location = data.slice.slice_url;
});
}
}
}
}
findChangedControlKeys(prevControls, currentControls) {
return Object.keys(currentControls).filter(
key =>
typeof prevControls[key] !== 'undefined' &&
!areObjectsEqual(currentControls[key].value, prevControls[key].value),
);
}
hasDisplayControlChanged(changedControlKeys, currentControls) {
return changedControlKeys.some(key => currentControls[key].renderTrigger);
}
hasQueryControlChanged(changedControlKeys, currentControls) {
return changedControlKeys.some(
key =>
!currentControls[key].renderTrigger &&
!currentControls[key].dontRefreshOnChange,
);
}
addHistory({ isReplace = false, title }) {
const payload = { ...this.props.form_data };
const longUrl = getExploreLongUrl(this.props.form_data, null, false);
try {
if (isReplace) {
history.replaceState(payload, title, longUrl);
} else {
history.pushState(payload, title, longUrl);
}
} catch (e) {
// eslint-disable-next-line no-console
console.warn(
'Failed at altering browser history',
payload,
title,
longUrl,
);
}
// it seems some browsers don't support pushState title attribute
if (title) {
document.title = title;
}
}
handleResize() {
clearTimeout(this.resizeTimer);
this.resizeTimer = setTimeout(() => {
this.setState({ height: this.getHeight(), width: this.getWidth() });
}, 250);
}
handlePopstate() {
const formData = history.state;
if (formData && Object.keys(formData).length) {
this.props.actions.setExploreControls(formData);
this.props.actions.postChartFormData(
formData,
false,
this.props.timeout,
this.props.chart.id,
);
}
}
toggleModal() {
this.setState({ showModal: !this.state.showModal });
}
hasErrors() {
const ctrls = this.props.controls;
return Object.keys(ctrls).some(
k => ctrls[k].validationErrors && ctrls[k].validationErrors.length > 0,
);
}
renderErrorMessage() {
// Returns an error message as a node if any errors are in the store
const errors = [];
const ctrls = this.props.controls;
for (const controlName in this.props.controls) {
const control = this.props.controls[controlName];
if (control.validationErrors && control.validationErrors.length > 0) {
errors.push(
<div key={controlName}>
{t('Control labeled ')}
<strong>{` "${control.label}" `}</strong>
{control.validationErrors.join('. ')}
</div>,
);
}
}
let errorMessage;
if (errors.length > 0) {
errorMessage = <div style={{ textAlign: 'left' }}>{errors}</div>;
}
return errorMessage;
}
renderChartContainer() {
return (
<ExploreChartPanel
width={this.state.width}
height={this.state.height}
{...this.props}
errorMessage={this.renderErrorMessage()}
refreshOverlayVisible={this.state.refreshOverlayVisible}
addHistory={this.addHistory}
onQuery={this.onQuery}
/>
);
}
render() {
if (this.props.standalone) {
return this.renderChartContainer();
}
return (
<div
id="explore-container"
className="container-fluid"
style={{ height: this.state.height, overflow: 'hidden' }}
>
{this.state.showModal && (
<SaveModal
onHide={this.toggleModal}
actions={this.props.actions}
form_data={this.props.form_data}
sliceName={this.props.sliceName}
/>
)}
<div className="row">
<div className="col-sm-4">
<div
style={{
display: 'flex',
flexDirection: 'row',
alignItems: 'center',
}}
>
<QueryAndSaveBtns
canAdd={!!(this.props.can_add || this.props.can_overwrite)}
onQuery={this.onQuery}
onSave={this.toggleModal}
onStop={this.onStop}
loading={this.props.chart.chartStatus === 'loading'}
chartIsStale={this.state.chartIsStale}
errorMessage={this.renderErrorMessage()}
datasourceType={this.props.datasource_type}
/>
<div className="m-l-5 text-muted">
<Hotkeys
header="Keyboard shortcuts"
hotkeys={getHotKeys()}
placement="right"
/>
</div>
</div>
<br />
<ControlPanelsContainer
actions={this.props.actions}
form_data={this.props.form_data}
controls={this.props.controls}
datasource_type={this.props.datasource_type}
isDatasourceMetaLoading={this.props.isDatasourceMetaLoading}
/>
</div>
<div className="col-sm-8">{this.renderChartContainer()}</div>
</div>
</div>
);
}
}
ExploreViewContainer.propTypes = propTypes;
function mapStateToProps(state) {
const { explore, charts, impressionId } = state;
const form_data = getFormDataFromControls(explore.controls);
const chartKey = Object.keys(charts)[0];
const chart = charts[chartKey];
return {
isDatasourceMetaLoading: explore.isDatasourceMetaLoading,
datasource: explore.datasource,
datasource_type: explore.datasource.type,
datasourceId: explore.datasource_id,
controls: explore.controls,
can_overwrite: !!explore.can_overwrite,
can_add: !!explore.can_add,
can_download: !!explore.can_download,
column_formats: explore.datasource
? explore.datasource.column_formats
: null,
containerId: explore.slice
? `slice-container-${explore.slice.slice_id}`
: 'slice-container',
isStarred: explore.isStarred,
slice: explore.slice,
sliceName: explore.sliceName,
triggerRender: explore.triggerRender,
form_data,
table_name: form_data.datasource_name,
vizType: form_data.viz_type,
standalone: explore.standalone,
forcedHeight: explore.forced_height,
chart,
timeout: explore.common.conf.SUPERSET_WEBSERVER_TIMEOUT,
impressionId,
};
}
function mapDispatchToProps(dispatch) {
const actions = {
...exploreActions,
...saveModalActions,
...chartActions,
...logActions,
};
return {
actions: bindActionCreators(actions, dispatch),
};
}
export { ExploreViewContainer };
export default connect(
mapStateToProps,
mapDispatchToProps,
)(ExploreViewContainer);
| superset-frontend/src/explore/components/ExploreViewContainer.jsx | 0 | https://github.com/apache/superset/commit/2b061fc64b88831574878b6bd470d700a1527dec | [
0.0006326938746497035,
0.00018497550627216697,
0.00016544488607905805,
0.00017054681666195393,
0.00007107353303581476
] |
{
"id": 3,
"code_window": [
" \"slice_name\",\n",
" \"url\",\n",
" \"description\",\n",
" \"changed_by_fk\",\n",
" \"created_by_fk\",\n",
" \"changed_by_name\",\n",
" \"changed_by_url\",\n",
" \"changed_by.first_name\",\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "superset/charts/api.py",
"type": "replace",
"edit_start_line_idx": 108
} | # 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 superset.db_engine_specs.clickhouse import ClickHouseEngineSpec
from tests.db_engine_specs.base_tests import TestDbEngineSpec
class TestClickHouseDbEngineSpec(TestDbEngineSpec):
def test_convert_dttm(self):
dttm = self.get_dttm()
self.assertEqual(
ClickHouseEngineSpec.convert_dttm("DATE", dttm), "toDate('2019-01-02')"
)
self.assertEqual(
ClickHouseEngineSpec.convert_dttm("DATETIME", dttm),
"toDateTime('2019-01-02 03:04:05')",
)
| tests/db_engine_specs/clickhouse_tests.py | 0 | https://github.com/apache/superset/commit/2b061fc64b88831574878b6bd470d700a1527dec | [
0.0002045041910605505,
0.00018048848141916096,
0.00017009169096127152,
0.00017367902910336852,
0.000013950142601970583
] |
{
"id": 3,
"code_window": [
" \"slice_name\",\n",
" \"url\",\n",
" \"description\",\n",
" \"changed_by_fk\",\n",
" \"created_by_fk\",\n",
" \"changed_by_name\",\n",
" \"changed_by_url\",\n",
" \"changed_by.first_name\",\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "superset/charts/api.py",
"type": "replace",
"edit_start_line_idx": 108
} | /**
* 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 PropTypes from 'prop-types';
import { NavDropdown, MenuItem } from 'react-bootstrap';
const propTypes = {
locale: PropTypes.string.isRequired,
languages: PropTypes.object.isRequired,
};
export default function LanguagePicker({ locale, languages }) {
return (
<NavDropdown
id="locale-dropdown"
title={
<span className="f16">
<i className={`flag ${languages[locale].flag}`} />
</span>
}
>
{Object.keys(languages).map(langKey =>
langKey === locale ? null : (
<MenuItem key={langKey} href={languages[langKey].url}>
{' '}
<div className="f16">
<i className={`flag ${languages[langKey].flag}`} /> -{' '}
{languages[langKey].name}
</div>
</MenuItem>
),
)}
</NavDropdown>
);
}
LanguagePicker.propTypes = propTypes;
| superset-frontend/src/components/Menu/LanguagePicker.jsx | 0 | https://github.com/apache/superset/commit/2b061fc64b88831574878b6bd470d700a1527dec | [
0.00017363086226396263,
0.00017223118629772216,
0.00017006963025778532,
0.0001724264002405107,
0.0000012083431784049026
] |
{
"id": 4,
"code_window": [
" \"params\",\n",
" \"cache_timeout\",\n",
" ]\n",
" list_select_columns = list_columns + [\"changed_on\"]\n",
" order_columns = [\n",
" \"slice_name\",\n",
" \"viz_type\",\n",
" \"datasource_name\",\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" list_select_columns = list_columns + [\"changed_on\", \"changed_by_fk\"]\n"
],
"file_path": "superset/charts/api.py",
"type": "replace",
"edit_start_line_idx": 126
} | /**
* 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 { SupersetClient } from '@superset-ui/connection';
import { t } from '@superset-ui/translation';
import PropTypes from 'prop-types';
import React from 'react';
import rison from 'rison';
// @ts-ignore
import { Panel } from 'react-bootstrap';
import ConfirmStatusChange from 'src/components/ConfirmStatusChange';
import SubMenu from 'src/components/Menu/SubMenu';
import ListView from 'src/components/ListView/ListView';
import ExpandableList from 'src/components/ExpandableList';
import {
FetchDataConfig,
FilterOperatorMap,
Filters,
} from 'src/components/ListView/types';
import withToasts from 'src/messageToasts/enhancers/withToasts';
import PropertiesModal from 'src/dashboard/components/PropertiesModal';
import { isFeatureEnabled, FeatureFlag } from 'src/featureFlags';
const PAGE_SIZE = 25;
interface Props {
addDangerToast: (msg: string) => void;
addSuccessToast: (msg: string) => void;
}
interface State {
dashboards: any[];
dashboardCount: number;
loading: boolean;
filterOperators: FilterOperatorMap;
filters: Filters;
permissions: string[];
lastFetchDataConfig: FetchDataConfig | null;
dashboardToEdit: Dashboard | null;
}
interface Dashboard {
id: number;
changed_by: string;
changed_by_name: string;
changed_by_url: string;
changed_on_delta_humanized: string;
dashboard_title: string;
published: boolean;
url: string;
}
class DashboardList extends React.PureComponent<Props, State> {
static propTypes = {
addDangerToast: PropTypes.func.isRequired,
};
state: State = {
dashboardCount: 0,
dashboards: [],
filterOperators: {},
filters: [],
lastFetchDataConfig: null,
loading: true,
permissions: [],
dashboardToEdit: null,
};
componentDidMount() {
SupersetClient.get({
endpoint: `/api/v1/dashboard/_info`,
}).then(
({ json: infoJson = {} }) => {
this.setState(
{
filterOperators: infoJson.filters,
permissions: infoJson.permissions,
},
this.updateFilters,
);
},
e => {
this.props.addDangerToast(
t(
'An error occurred while fetching Dashboards: %s, %s',
e.statusText,
),
);
console.error(e);
},
);
}
get canEdit() {
return this.hasPerm('can_edit');
}
get canDelete() {
return this.hasPerm('can_delete');
}
get canExport() {
return this.hasPerm('can_mulexport');
}
get isSIP34FilterUIEnabled() {
return isFeatureEnabled(FeatureFlag.LIST_VIEWS_SIP34_FILTER_UI);
}
initialSort = [{ id: 'changed_on_delta_humanized', desc: true }];
columns = [
{
Cell: ({
row: {
original: { url, dashboard_title: dashboardTitle },
},
}: any) => <a href={url}>{dashboardTitle}</a>,
Header: t('Title'),
accessor: 'dashboard_title',
},
{
Cell: ({
row: {
original: { owners },
},
}: any) => (
<ExpandableList
items={owners.map(
({ first_name: firstName, last_name: lastName }: any) =>
`${firstName} ${lastName}`,
)}
display={2}
/>
),
Header: t('Owners'),
accessor: 'owners',
disableSortBy: true,
},
{
Cell: ({
row: {
original: {
changed_by_name: changedByName,
changed_by_url: changedByUrl,
},
},
}: any) => <a href={changedByUrl}>{changedByName}</a>,
Header: t('Creator'),
accessor: 'changed_by_fk',
},
{
Cell: ({
row: {
original: { published },
},
}: any) => (
<span className="no-wrap">
{published ? <i className="fa fa-check" /> : ''}
</span>
),
Header: t('Published'),
accessor: 'published',
},
{
Cell: ({
row: {
original: { changed_on_delta_humanized: changedOn },
},
}: any) => <span className="no-wrap">{changedOn}</span>,
Header: t('Modified'),
accessor: 'changed_on_delta_humanized',
},
{
accessor: 'slug',
hidden: true,
disableSortBy: true,
},
{
Cell: ({ row: { state, original } }: any) => {
const handleDelete = () => this.handleDashboardDelete(original);
const handleEdit = () => this.openDashboardEditModal(original);
const handleExport = () => this.handleBulkDashboardExport([original]);
if (!this.canEdit && !this.canDelete && !this.canExport) {
return null;
}
return (
<span
className={`actions ${state && state.hover ? '' : 'invisible'}`}
>
{this.canDelete && (
<ConfirmStatusChange
title={t('Please Confirm')}
description={
<>
{t('Are you sure you want to delete')}{' '}
<b>{original.dashboard_title}</b>?
</>
}
onConfirm={handleDelete}
>
{confirmDelete => (
<span
role="button"
tabIndex={0}
className="action-button"
onClick={confirmDelete}
>
<i className="fa fa-trash" />
</span>
)}
</ConfirmStatusChange>
)}
{this.canExport && (
<span
role="button"
tabIndex={0}
className="action-button"
onClick={handleExport}
>
<i className="fa fa-database" />
</span>
)}
{this.canEdit && (
<span
role="button"
tabIndex={0}
className="action-button"
onClick={handleEdit}
>
<i className="fa fa-pencil" />
</span>
)}
</span>
);
},
Header: t('Actions'),
id: 'actions',
disableSortBy: true,
},
];
hasPerm = (perm: string) => {
if (!this.state.permissions.length) {
return false;
}
return Boolean(this.state.permissions.find(p => p === perm));
};
openDashboardEditModal = (dashboard: Dashboard) => {
this.setState({
dashboardToEdit: dashboard,
});
};
handleDashboardEdit = (edits: any) => {
this.setState({ loading: true });
return SupersetClient.get({
endpoint: `/api/v1/dashboard/${edits.id}`,
})
.then(({ json = {} }) => {
this.setState({
dashboards: this.state.dashboards.map(dashboard => {
if (dashboard.id === json.id) {
return json.result;
}
return dashboard;
}),
loading: false,
});
})
.catch(e => {
this.props.addDangerToast(
t('An error occurred while fetching dashboards: %s', e.statusText),
);
});
};
handleDashboardDelete = ({
id,
dashboard_title: dashboardTitle,
}: Dashboard) =>
SupersetClient.delete({
endpoint: `/api/v1/dashboard/${id}`,
}).then(
() => {
const { lastFetchDataConfig } = this.state;
if (lastFetchDataConfig) {
this.fetchData(lastFetchDataConfig);
}
this.props.addSuccessToast(t('Deleted: %s', dashboardTitle));
},
(err: any) => {
console.error(err);
this.props.addDangerToast(
t('There was an issue deleting %s', dashboardTitle),
);
},
);
handleBulkDashboardDelete = (dashboards: Dashboard[]) => {
SupersetClient.delete({
endpoint: `/api/v1/dashboard/?q=${rison.encode(
dashboards.map(({ id }) => id),
)}`,
}).then(
({ json = {} }) => {
const { lastFetchDataConfig } = this.state;
if (lastFetchDataConfig) {
this.fetchData(lastFetchDataConfig);
}
this.props.addSuccessToast(json.message);
},
(err: any) => {
console.error(err);
this.props.addDangerToast(
t(
'There was an issue deleting the selected dashboards: ',
err.statusText,
),
);
},
);
};
handleBulkDashboardExport = (dashboards: Dashboard[]) => {
return window.location.assign(
`/api/v1/dashboard/export/?q=${rison.encode(
dashboards.map(({ id }) => id),
)}`,
);
};
fetchData = ({ pageIndex, pageSize, sortBy, filters }: FetchDataConfig) => {
// set loading state, cache the last config for fetching data in this component.
this.setState({
lastFetchDataConfig: {
filters,
pageIndex,
pageSize,
sortBy,
},
loading: true,
});
const filterExps = filters.map(({ id: col, operator: opr, value }) => ({
col,
opr,
value,
}));
const queryParams = rison.encode({
order_column: sortBy[0].id,
order_direction: sortBy[0].desc ? 'desc' : 'asc',
page: pageIndex,
page_size: pageSize,
...(filterExps.length ? { filters: filterExps } : {}),
});
return SupersetClient.get({
endpoint: `/api/v1/dashboard/?q=${queryParams}`,
})
.then(({ json = {} }) => {
this.setState({ dashboards: json.result, dashboardCount: json.count });
})
.catch(e => {
this.props.addDangerToast(
t('An error occurred while fetching dashboards: %s', e.statusText),
);
})
.finally(() => {
this.setState({ loading: false });
});
};
fetchOwners = async (
filterValue = '',
pageIndex?: number,
pageSize?: number,
) => {
const resource = '/api/v1/dashboard/related/owners';
try {
const queryParams = rison.encode({
...(pageIndex ? { page: pageIndex } : {}),
...(pageSize ? { page_ize: pageSize } : {}),
...(filterValue ? { filter: filterValue } : {}),
});
const { json = {} } = await SupersetClient.get({
endpoint: `${resource}?q=${queryParams}`,
});
return json?.result?.map(
({ text: label, value }: { text: string; value: any }) => ({
label,
value,
}),
);
} catch (e) {
console.error(e);
this.props.addDangerToast(
t(
'An error occurred while fetching chart owner values: %s',
e.statusText,
),
);
}
return [];
};
updateFilters = async () => {
const { filterOperators } = this.state;
if (this.isSIP34FilterUIEnabled) {
return this.setState({
filters: [
{
Header: 'Owner',
id: 'owners',
input: 'select',
operator: 'rel_m_m',
unfilteredLabel: 'All',
fetchSelects: this.fetchOwners,
paginate: true,
},
{
Header: 'Published',
id: 'published',
input: 'select',
operator: 'eq',
unfilteredLabel: 'Any',
selects: [
{ label: 'Published', value: true },
{ label: 'Unpublished', value: false },
],
},
{
Header: 'Search',
id: 'dashboard_title',
input: 'search',
operator: 'title_or_slug',
},
],
});
}
const convertFilter = ({
name: label,
operator,
}: {
name: string;
operator: string;
}) => ({ label, value: operator });
const owners = await this.fetchOwners();
return this.setState({
filters: [
{
Header: 'Dashboard',
id: 'dashboard_title',
operators: filterOperators.dashboard_title.map(convertFilter),
},
{
Header: 'Slug',
id: 'slug',
operators: filterOperators.slug.map(convertFilter),
},
{
Header: 'Owners',
id: 'owners',
input: 'select',
operators: filterOperators.owners.map(convertFilter),
selects: owners,
},
{
Header: 'Published',
id: 'published',
input: 'checkbox',
operators: filterOperators.published.map(convertFilter),
},
],
});
};
render() {
const {
dashboards,
dashboardCount,
loading,
filters,
dashboardToEdit,
} = this.state;
return (
<>
<SubMenu name={t('Dashboards')} />
<ConfirmStatusChange
title={t('Please confirm')}
description={t(
'Are you sure you want to delete the selected dashboards?',
)}
onConfirm={this.handleBulkDashboardDelete}
>
{confirmDelete => {
const bulkActions = [];
if (this.canDelete) {
bulkActions.push({
key: 'delete',
name: (
<>
<i className="fa fa-trash" /> {t('Delete')}
</>
),
onSelect: confirmDelete,
});
}
if (this.canExport) {
bulkActions.push({
key: 'export',
name: (
<>
<i className="fa fa-database" /> {t('Export')}
</>
),
onSelect: this.handleBulkDashboardExport,
});
}
return (
<>
{dashboardToEdit && (
<PropertiesModal
show
dashboardId={dashboardToEdit.id}
onHide={() => this.setState({ dashboardToEdit: null })}
onDashboardSave={this.handleDashboardEdit}
/>
)}
<ListView
className="dashboard-list-view"
columns={this.columns}
data={dashboards}
count={dashboardCount}
pageSize={PAGE_SIZE}
fetchData={this.fetchData}
loading={loading}
initialSort={this.initialSort}
filters={filters}
bulkActions={bulkActions}
isSIP34FilterUIEnabled={this.isSIP34FilterUIEnabled}
/>
</>
);
}}
</ConfirmStatusChange>
</>
);
}
}
export default withToasts(DashboardList);
| superset-frontend/src/views/dashboardList/DashboardList.tsx | 1 | https://github.com/apache/superset/commit/2b061fc64b88831574878b6bd470d700a1527dec | [
0.9924667477607727,
0.017319731414318085,
0.00016501823847647756,
0.0001719533174764365,
0.12916171550750732
] |
{
"id": 4,
"code_window": [
" \"params\",\n",
" \"cache_timeout\",\n",
" ]\n",
" list_select_columns = list_columns + [\"changed_on\"]\n",
" order_columns = [\n",
" \"slice_name\",\n",
" \"viz_type\",\n",
" \"datasource_name\",\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" list_select_columns = list_columns + [\"changed_on\", \"changed_by_fk\"]\n"
],
"file_path": "superset/charts/api.py",
"type": "replace",
"edit_start_line_idx": 126
} | /**
* 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.
*/
.dashboard-component-tabs {
width: 100%;
background-color: @lightest;
& .nav-tabs {
border-bottom: none;
/* by moving padding from <a/> to <li/> we can restrict the selected tab indicator to text width */
& > li {
margin: 0 16px;
& > a {
color: @almost-black;
border: none;
padding: 12px 0 14px 0;
font-size: @font-size-m;
margin-right: 0;
&:hover {
border: none;
background: inherit;
color: @almost-black;
}
&:focus {
outline: none;
background: @lightest;
}
}
& .dragdroppable-tab {
cursor: move;
}
& .drop-indicator {
top: -12px !important;
height: ~'calc(100% + 24px)' !important;
}
& .drop-indicator--left {
left: -12px !important;
}
& .drop-indicator--right {
right: -12px !important;
}
& .drop-indicator--bottom,
& .drop-indicator--top {
left: -12px !important;
width: ~'calc(100% + 24px)' !important; /* escape for .less */
opacity: 0.4;
}
& .fa-plus {
color: @gray-dark;
font-size: @font-size-m;
margin-top: 3px;
}
& .editable-title input[type='button'] {
cursor: pointer;
}
}
& li.active > a {
border: none;
&:after {
content: '';
position: absolute;
height: 3px;
width: 100%;
bottom: 0;
background: linear-gradient(
to right,
@indicator-color,
shade(@indicator-color, @colorstop-two)
);
}
}
}
& .dashboard-component-tabs-content {
min-height: 48px;
margin-top: 1px;
position: relative;
}
}
| superset-frontend/src/dashboard/stylesheets/components/tabs.less | 0 | https://github.com/apache/superset/commit/2b061fc64b88831574878b6bd470d700a1527dec | [
0.0001775266428012401,
0.0001756826532073319,
0.00017072669288609177,
0.0001760676095727831,
0.0000019385311134101357
] |
{
"id": 4,
"code_window": [
" \"params\",\n",
" \"cache_timeout\",\n",
" ]\n",
" list_select_columns = list_columns + [\"changed_on\"]\n",
" order_columns = [\n",
" \"slice_name\",\n",
" \"viz_type\",\n",
" \"datasource_name\",\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" list_select_columns = list_columns + [\"changed_on\", \"changed_by_fk\"]\n"
],
"file_path": "superset/charts/api.py",
"type": "replace",
"edit_start_line_idx": 126
} | /**
* 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 { t } from '@superset-ui/translation';
import { SMALL_HEADER, MEDIUM_HEADER, LARGE_HEADER } from './constants';
export default [
{
value: SMALL_HEADER,
label: t('Small'),
className: 'header-style-option header-small',
},
{
value: MEDIUM_HEADER,
label: t('Medium'),
className: 'header-style-option header-medium',
},
{
value: LARGE_HEADER,
label: t('Large'),
className: 'header-style-option header-large',
},
];
| superset-frontend/src/dashboard/util/headerStyleOptions.ts | 0 | https://github.com/apache/superset/commit/2b061fc64b88831574878b6bd470d700a1527dec | [
0.0001758253638399765,
0.0001742025197017938,
0.000173039166838862,
0.00017397277406416833,
0.0000010134729109267937
] |
{
"id": 4,
"code_window": [
" \"params\",\n",
" \"cache_timeout\",\n",
" ]\n",
" list_select_columns = list_columns + [\"changed_on\"]\n",
" order_columns = [\n",
" \"slice_name\",\n",
" \"viz_type\",\n",
" \"datasource_name\",\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" list_select_columns = list_columns + [\"changed_on\", \"changed_by_fk\"]\n"
],
"file_path": "superset/charts/api.py",
"type": "replace",
"edit_start_line_idx": 126
} | # 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 logging
from collections import Counter
from typing import Any, Dict, List, Optional
from flask_appbuilder.models.sqla import Model
from flask_appbuilder.security.sqla.models import User
from marshmallow import ValidationError
from superset.commands.base import BaseCommand
from superset.commands.utils import populate_owners
from superset.connectors.sqla.models import SqlaTable
from superset.dao.exceptions import DAOUpdateFailedError
from superset.datasets.commands.exceptions import (
DatabaseChangeValidationError,
DatasetColumnNotFoundValidationError,
DatasetColumnsDuplicateValidationError,
DatasetColumnsExistsValidationError,
DatasetExistsValidationError,
DatasetForbiddenError,
DatasetInvalidError,
DatasetMetricsDuplicateValidationError,
DatasetMetricsExistsValidationError,
DatasetMetricsNotFoundValidationError,
DatasetNotFoundError,
DatasetUpdateFailedError,
)
from superset.datasets.dao import DatasetDAO
from superset.exceptions import SupersetSecurityException
from superset.views.base import check_ownership
logger = logging.getLogger(__name__)
class UpdateDatasetCommand(BaseCommand):
def __init__(self, user: User, model_id: int, data: Dict[str, Any]):
self._actor = user
self._model_id = model_id
self._properties = data.copy()
self._model: Optional[SqlaTable] = None
def run(self) -> Model:
self.validate()
if self._model:
try:
dataset = DatasetDAO.update(self._model, self._properties)
return dataset
except DAOUpdateFailedError as ex:
logger.exception(ex.exception)
raise DatasetUpdateFailedError()
raise DatasetUpdateFailedError()
def validate(self) -> None:
exceptions: List[ValidationError] = list()
owner_ids: Optional[List[int]] = self._properties.get("owners")
# Validate/populate model exists
self._model = DatasetDAO.find_by_id(self._model_id)
if not self._model:
raise DatasetNotFoundError()
# Check ownership
try:
check_ownership(self._model)
except SupersetSecurityException:
raise DatasetForbiddenError()
database_id = self._properties.get("database", None)
table_name = self._properties.get("table_name", None)
# Validate uniqueness
if not DatasetDAO.validate_update_uniqueness(
self._model.database_id, self._model_id, table_name
):
exceptions.append(DatasetExistsValidationError(table_name))
# Validate/Populate database not allowed to change
if database_id and database_id != self._model:
exceptions.append(DatabaseChangeValidationError())
# Validate/Populate owner
try:
owners = populate_owners(self._actor, owner_ids)
self._properties["owners"] = owners
except ValidationError as ex:
exceptions.append(ex)
# Validate columns
columns = self._properties.get("columns")
if columns:
self._validate_columns(columns, exceptions)
# Validate metrics
metrics = self._properties.get("metrics")
if metrics:
self._validate_metrics(metrics, exceptions)
if exceptions:
exception = DatasetInvalidError()
exception.add_list(exceptions)
raise exception
def _validate_columns(
self, columns: List[Dict[str, Any]], exceptions: List[ValidationError]
) -> None:
# Validate duplicates on data
if self._get_duplicates(columns, "column_name"):
exceptions.append(DatasetColumnsDuplicateValidationError())
else:
# validate invalid id's
columns_ids: List[int] = [
column["id"] for column in columns if "id" in column
]
if not DatasetDAO.validate_columns_exist(self._model_id, columns_ids):
exceptions.append(DatasetColumnNotFoundValidationError())
# validate new column names uniqueness
columns_names: List[str] = [
column["column_name"] for column in columns if "id" not in column
]
if not DatasetDAO.validate_columns_uniqueness(
self._model_id, columns_names
):
exceptions.append(DatasetColumnsExistsValidationError())
def _validate_metrics(
self, metrics: List[Dict[str, Any]], exceptions: List[ValidationError]
) -> None:
if self._get_duplicates(metrics, "metric_name"):
exceptions.append(DatasetMetricsDuplicateValidationError())
else:
# validate invalid id's
metrics_ids: List[int] = [
metric["id"] for metric in metrics if "id" in metric
]
if not DatasetDAO.validate_metrics_exist(self._model_id, metrics_ids):
exceptions.append(DatasetMetricsNotFoundValidationError())
# validate new metric names uniqueness
metric_names: List[str] = [
metric["metric_name"] for metric in metrics if "id" not in metric
]
if not DatasetDAO.validate_metrics_uniqueness(self._model_id, metric_names):
exceptions.append(DatasetMetricsExistsValidationError())
@staticmethod
def _get_duplicates(data: List[Dict[str, Any]], key: str) -> List[str]:
duplicates = [
name
for name, count in Counter([item[key] for item in data]).items()
if count > 1
]
return duplicates
| superset/datasets/commands/update.py | 0 | https://github.com/apache/superset/commit/2b061fc64b88831574878b6bd470d700a1527dec | [
0.0003122315974906087,
0.00019037256424780935,
0.0001647698227316141,
0.0001747505011735484,
0.000041673232772154734
] |
{
"id": 5,
"code_window": [
" \"slice_name\",\n",
" \"viz_type\",\n",
" \"datasource_name\",\n",
" \"changed_by_fk\",\n",
" \"changed_on_delta_humanized\",\n",
" ]\n",
" search_columns = (\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"changed_by.first_name\",\n"
],
"file_path": "superset/charts/api.py",
"type": "replace",
"edit_start_line_idx": 131
} | # 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 logging
from typing import Any, Dict
from flask import g, make_response, redirect, request, Response, url_for
from flask_appbuilder.api import expose, protect, rison, safe
from flask_appbuilder.models.sqla.interface import SQLAInterface
from flask_babel import ngettext
from marshmallow import ValidationError
from werkzeug.wrappers import Response as WerkzeugResponse
from werkzeug.wsgi import FileWrapper
from superset import is_feature_enabled, thumbnail_cache
from superset.constants import RouteMethod
from superset.dashboards.commands.bulk_delete import BulkDeleteDashboardCommand
from superset.dashboards.commands.create import CreateDashboardCommand
from superset.dashboards.commands.delete import DeleteDashboardCommand
from superset.dashboards.commands.exceptions import (
DashboardBulkDeleteFailedError,
DashboardCreateFailedError,
DashboardDeleteFailedError,
DashboardForbiddenError,
DashboardInvalidError,
DashboardNotFoundError,
DashboardUpdateFailedError,
)
from superset.dashboards.commands.update import UpdateDashboardCommand
from superset.dashboards.filters import DashboardFilter, DashboardTitleOrSlugFilter
from superset.dashboards.schemas import (
DashboardPostSchema,
DashboardPutSchema,
get_delete_ids_schema,
get_export_ids_schema,
openapi_spec_methods_override,
thumbnail_query_schema,
)
from superset.models.dashboard import Dashboard
from superset.tasks.thumbnails import cache_dashboard_thumbnail
from superset.utils.screenshots import DashboardScreenshot
from superset.utils.urls import get_url_path
from superset.views.base import generate_download_headers
from superset.views.base_api import (
BaseSupersetModelRestApi,
RelatedFieldFilter,
statsd_metrics,
)
from superset.views.filters import FilterRelatedOwners
logger = logging.getLogger(__name__)
class DashboardRestApi(BaseSupersetModelRestApi):
datamodel = SQLAInterface(Dashboard)
include_route_methods = RouteMethod.REST_MODEL_VIEW_CRUD_SET | {
RouteMethod.EXPORT,
RouteMethod.RELATED,
"bulk_delete", # not using RouteMethod since locally defined
}
resource_name = "dashboard"
allow_browser_login = True
class_permission_name = "DashboardModelView"
show_columns = [
"id",
"charts",
"css",
"dashboard_title",
"json_metadata",
"owners.id",
"owners.username",
"owners.first_name",
"owners.last_name",
"changed_by_name",
"changed_by_url",
"changed_by.username",
"changed_on",
"position_json",
"published",
"url",
"slug",
"table_names",
"thumbnail_url",
]
list_columns = [
"id",
"published",
"slug",
"url",
"css",
"position_json",
"json_metadata",
"thumbnail_url",
"changed_by.first_name",
"changed_by.last_name",
"changed_by.username",
"changed_by.id",
"changed_by_name",
"changed_by_url",
"changed_on_utc",
"changed_on_delta_humanized",
"dashboard_title",
"owners.id",
"owners.username",
"owners.first_name",
"owners.last_name",
]
list_select_columns = list_columns + ["changed_on"]
order_columns = [
"dashboard_title",
"changed_on_delta_humanized",
"published",
"changed_by_fk",
]
add_columns = [
"dashboard_title",
"slug",
"owners",
"position_json",
"css",
"json_metadata",
"published",
]
edit_columns = add_columns
search_columns = ("dashboard_title", "slug", "owners", "published")
search_filters = {"dashboard_title": [DashboardTitleOrSlugFilter]}
base_order = ("changed_on", "desc")
add_model_schema = DashboardPostSchema()
edit_model_schema = DashboardPutSchema()
base_filters = [["slice", DashboardFilter, lambda: []]]
order_rel_fields = {
"slices": ("slice_name", "asc"),
"owners": ("first_name", "asc"),
}
related_field_filters = {
"owners": RelatedFieldFilter("first_name", FilterRelatedOwners)
}
allowed_rel_fields = {"owners"}
openapi_spec_tag = "Dashboards"
apispec_parameter_schemas = {
"get_delete_ids_schema": get_delete_ids_schema,
"get_export_ids_schema": get_export_ids_schema,
"thumbnail_query_schema": thumbnail_query_schema,
}
openapi_spec_methods = openapi_spec_methods_override
""" Overrides GET methods OpenApi descriptions """
def __init__(self) -> None:
if is_feature_enabled("THUMBNAILS"):
self.include_route_methods = self.include_route_methods | {"thumbnail"}
super().__init__()
@expose("/", methods=["POST"])
@protect()
@safe
@statsd_metrics
def post(self) -> Response:
"""Creates a new Dashboard
---
post:
description: >-
Create a new Dashboard.
requestBody:
description: Dashboard schema
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/{{self.__class__.__name__}}.post'
responses:
201:
description: Dashboard added
content:
application/json:
schema:
type: object
properties:
id:
type: number
result:
$ref: '#/components/schemas/{{self.__class__.__name__}}.post'
302:
description: Redirects to the current digest
400:
$ref: '#/components/responses/400'
401:
$ref: '#/components/responses/401'
404:
$ref: '#/components/responses/404'
500:
$ref: '#/components/responses/500'
"""
if not request.is_json:
return self.response_400(message="Request is not JSON")
try:
item = self.add_model_schema.load(request.json)
# This validates custom Schema with custom validations
except ValidationError as error:
return self.response_400(message=error.messages)
try:
new_model = CreateDashboardCommand(g.user, item).run()
return self.response(201, id=new_model.id, result=item)
except DashboardInvalidError as ex:
return self.response_422(message=ex.normalized_messages())
except DashboardCreateFailedError as ex:
logger.error(
"Error creating model %s: %s", self.__class__.__name__, str(ex)
)
return self.response_422(message=str(ex))
@expose("/<pk>", methods=["PUT"])
@protect()
@safe
@statsd_metrics
def put( # pylint: disable=too-many-return-statements, arguments-differ
self, pk: int
) -> Response:
"""Changes a Dashboard
---
put:
description: >-
Changes a Dashboard.
parameters:
- in: path
schema:
type: integer
name: pk
requestBody:
description: Dashboard schema
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/{{self.__class__.__name__}}.put'
responses:
200:
description: Dashboard changed
content:
application/json:
schema:
type: object
properties:
id:
type: number
result:
$ref: '#/components/schemas/{{self.__class__.__name__}}.put'
400:
$ref: '#/components/responses/400'
401:
$ref: '#/components/responses/401'
403:
$ref: '#/components/responses/403'
404:
$ref: '#/components/responses/404'
422:
$ref: '#/components/responses/422'
500:
$ref: '#/components/responses/500'
"""
if not request.is_json:
return self.response_400(message="Request is not JSON")
try:
item = self.edit_model_schema.load(request.json)
# This validates custom Schema with custom validations
except ValidationError as error:
return self.response_400(message=error.messages)
try:
changed_model = UpdateDashboardCommand(g.user, pk, item).run()
return self.response(200, id=changed_model.id, result=item)
except DashboardNotFoundError:
return self.response_404()
except DashboardForbiddenError:
return self.response_403()
except DashboardInvalidError as ex:
return self.response_422(message=ex.normalized_messages())
except DashboardUpdateFailedError as ex:
logger.error(
"Error updating model %s: %s", self.__class__.__name__, str(ex)
)
return self.response_422(message=str(ex))
@expose("/<pk>", methods=["DELETE"])
@protect()
@safe
@statsd_metrics
def delete(self, pk: int) -> Response: # pylint: disable=arguments-differ
"""Deletes a Dashboard
---
delete:
description: >-
Deletes a Dashboard.
parameters:
- in: path
schema:
type: integer
name: pk
responses:
200:
description: Dashboard deleted
content:
application/json:
schema:
type: object
properties:
message:
type: string
401:
$ref: '#/components/responses/401'
403:
$ref: '#/components/responses/403'
404:
$ref: '#/components/responses/404'
422:
$ref: '#/components/responses/422'
500:
$ref: '#/components/responses/500'
"""
try:
DeleteDashboardCommand(g.user, pk).run()
return self.response(200, message="OK")
except DashboardNotFoundError:
return self.response_404()
except DashboardForbiddenError:
return self.response_403()
except DashboardDeleteFailedError as ex:
logger.error(
"Error deleting model %s: %s", self.__class__.__name__, str(ex)
)
return self.response_422(message=str(ex))
@expose("/", methods=["DELETE"])
@protect()
@safe
@statsd_metrics
@rison(get_delete_ids_schema)
def bulk_delete(
self, **kwargs: Any
) -> Response: # pylint: disable=arguments-differ
"""Delete bulk Dashboards
---
delete:
description: >-
Deletes multiple Dashboards in a bulk operation.
parameters:
- in: query
name: q
content:
application/json:
schema:
$ref: '#/components/schemas/get_delete_ids_schema'
responses:
200:
description: Dashboard bulk delete
content:
application/json:
schema:
type: object
properties:
message:
type: string
401:
$ref: '#/components/responses/401'
403:
$ref: '#/components/responses/403'
404:
$ref: '#/components/responses/404'
422:
$ref: '#/components/responses/422'
500:
$ref: '#/components/responses/500'
"""
item_ids = kwargs["rison"]
try:
BulkDeleteDashboardCommand(g.user, item_ids).run()
return self.response(
200,
message=ngettext(
"Deleted %(num)d dashboard",
"Deleted %(num)d dashboards",
num=len(item_ids),
),
)
except DashboardNotFoundError:
return self.response_404()
except DashboardForbiddenError:
return self.response_403()
except DashboardBulkDeleteFailedError as ex:
return self.response_422(message=str(ex))
@expose("/export/", methods=["GET"])
@protect()
@safe
@statsd_metrics
@rison(get_export_ids_schema)
def export(self, **kwargs: Any) -> Response:
"""Export dashboards
---
get:
description: >-
Exports multiple Dashboards and downloads them as YAML files.
parameters:
- in: query
name: q
content:
application/json:
schema:
$ref: '#/components/schemas/get_export_ids_schema'
responses:
200:
description: Dashboard export
content:
text/plain:
schema:
type: string
400:
$ref: '#/components/responses/400'
401:
$ref: '#/components/responses/401'
404:
$ref: '#/components/responses/404'
422:
$ref: '#/components/responses/422'
500:
$ref: '#/components/responses/500'
"""
query = self.datamodel.session.query(Dashboard).filter(
Dashboard.id.in_(kwargs["rison"])
)
query = self._base_filters.apply_all(query)
ids = [item.id for item in query.all()]
if not ids:
return self.response_404()
export = Dashboard.export_dashboards(ids)
resp = make_response(export, 200)
resp.headers["Content-Disposition"] = generate_download_headers("json")[
"Content-Disposition"
]
return resp
@expose("/<pk>/thumbnail/<digest>/", methods=["GET"])
@protect()
@safe
@rison(thumbnail_query_schema)
def thumbnail(
self, pk: int, digest: str, **kwargs: Dict[str, bool]
) -> WerkzeugResponse:
"""Get Dashboard thumbnail
---
get:
description: >-
Compute async or get already computed dashboard thumbnail from cache.
parameters:
- in: path
schema:
type: integer
name: pk
- in: path
name: digest
description: A hex digest that makes this dashboard unique
schema:
type: string
- in: query
name: q
content:
application/json:
schema:
$ref: '#/components/schemas/thumbnail_query_schema'
responses:
200:
description: Dashboard thumbnail image
content:
image/*:
schema:
type: string
format: binary
202:
description: Thumbnail does not exist on cache, fired async to compute
content:
application/json:
schema:
type: object
properties:
message:
type: string
401:
$ref: '#/components/responses/401'
404:
$ref: '#/components/responses/404'
422:
$ref: '#/components/responses/422'
500:
$ref: '#/components/responses/500'
"""
dashboard = self.datamodel.get(pk, self._base_filters)
if not dashboard:
return self.response_404()
dashboard_url = get_url_path(
"Superset.dashboard", dashboard_id_or_slug=dashboard.id
)
# If force, request a screenshot from the workers
if kwargs["rison"].get("force", False):
cache_dashboard_thumbnail.delay(dashboard_url, dashboard.digest, force=True)
return self.response(202, message="OK Async")
# fetch the dashboard screenshot using the current user and cache if set
screenshot = DashboardScreenshot(
dashboard_url, dashboard.digest
).get_from_cache(cache=thumbnail_cache)
# If the screenshot does not exist, request one from the workers
if not screenshot:
cache_dashboard_thumbnail.delay(dashboard_url, dashboard.digest, force=True)
return self.response(202, message="OK Async")
# If digests
if dashboard.digest != digest:
return redirect(
url_for(
f"{self.__class__.__name__}.thumbnail",
pk=pk,
digest=dashboard.digest,
)
)
return Response(
FileWrapper(screenshot), mimetype="image/png", direct_passthrough=True
)
| superset/dashboards/api.py | 1 | https://github.com/apache/superset/commit/2b061fc64b88831574878b6bd470d700a1527dec | [
0.9910109043121338,
0.01972695253789425,
0.000168598722666502,
0.00017400973592884839,
0.13261407613754272
] |
{
"id": 5,
"code_window": [
" \"slice_name\",\n",
" \"viz_type\",\n",
" \"datasource_name\",\n",
" \"changed_by_fk\",\n",
" \"changed_on_delta_humanized\",\n",
" ]\n",
" search_columns = (\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"changed_by.first_name\",\n"
],
"file_path": "superset/charts/api.py",
"type": "replace",
"edit_start_line_idx": 131
} | {
"compilerOptions": {
"baseUrl": ".",
"paths": {
"src/*": ["./src/*"]
}
}
}
| superset-frontend/jsconfig.json | 0 | https://github.com/apache/superset/commit/2b061fc64b88831574878b6bd470d700a1527dec | [
0.0001737118436722085,
0.0001737118436722085,
0.0001737118436722085,
0.0001737118436722085,
0
] |
{
"id": 5,
"code_window": [
" \"slice_name\",\n",
" \"viz_type\",\n",
" \"datasource_name\",\n",
" \"changed_by_fk\",\n",
" \"changed_on_delta_humanized\",\n",
" ]\n",
" search_columns = (\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"changed_by.first_name\",\n"
],
"file_path": "superset/charts/api.py",
"type": "replace",
"edit_start_line_idx": 131
} | /**
* 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 PropTypes from 'prop-types';
import cx from 'classnames';
const propTypes = {
position: PropTypes.oneOf(['left', 'top']),
innerRef: PropTypes.func,
children: PropTypes.node,
};
const defaultProps = {
position: 'left',
innerRef: null,
children: null,
};
export default class HoverMenu extends React.PureComponent {
render() {
const { innerRef, position, children } = this.props;
return (
<div
ref={innerRef}
className={cx(
'hover-menu',
position === 'left' && 'hover-menu--left',
position === 'top' && 'hover-menu--top',
)}
>
{children}
</div>
);
}
}
HoverMenu.propTypes = propTypes;
HoverMenu.defaultProps = defaultProps;
| superset-frontend/src/dashboard/components/menu/HoverMenu.jsx | 0 | https://github.com/apache/superset/commit/2b061fc64b88831574878b6bd470d700a1527dec | [
0.00017770667909644544,
0.0001752354874042794,
0.000172877058503218,
0.00017502138507552445,
0.0000018128272358808317
] |
{
"id": 5,
"code_window": [
" \"slice_name\",\n",
" \"viz_type\",\n",
" \"datasource_name\",\n",
" \"changed_by_fk\",\n",
" \"changed_on_delta_humanized\",\n",
" ]\n",
" search_columns = (\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"changed_by.first_name\",\n"
],
"file_path": "superset/charts/api.py",
"type": "replace",
"edit_start_line_idx": 131
} | # 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_metadata_column_to_annotation_model.py
Revision ID: 55e910a74826
Revises: 1a1d627ebd8e
Create Date: 2018-08-29 14:35:20.407743
"""
# revision identifiers, used by Alembic.
revision = "55e910a74826"
down_revision = "1a1d627ebd8e"
import sqlalchemy as sa
from alembic import op
def upgrade():
op.add_column("annotation", sa.Column("json_metadata", sa.Text(), nullable=True))
def downgrade():
op.drop_column("annotation", "json_metadata")
| superset/migrations/versions/55e910a74826_add_metadata_column_to_annotation_model_.py | 0 | https://github.com/apache/superset/commit/2b061fc64b88831574878b6bd470d700a1527dec | [
0.00017649201618041843,
0.00017337808094453067,
0.0001670261553954333,
0.00017499706882517785,
0.000003718493644555565
] |
{
"id": 6,
"code_window": [
" \"owners.id\",\n",
" \"owners.username\",\n",
" \"owners.first_name\",\n",
" \"owners.last_name\",\n",
" ]\n",
" list_select_columns = list_columns + [\"changed_on\"]\n",
" order_columns = [\n",
" \"dashboard_title\",\n",
" \"changed_on_delta_humanized\",\n",
" \"published\",\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" list_select_columns = list_columns + [\"changed_on\", \"changed_by_fk\"]\n"
],
"file_path": "superset/dashboards/api.py",
"type": "replace",
"edit_start_line_idx": 121
} | /**
* 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 { SupersetClient } from '@superset-ui/connection';
import { t } from '@superset-ui/translation';
import PropTypes from 'prop-types';
import React from 'react';
import rison from 'rison';
// @ts-ignore
import { Panel } from 'react-bootstrap';
import ConfirmStatusChange from 'src/components/ConfirmStatusChange';
import SubMenu from 'src/components/Menu/SubMenu';
import ListView from 'src/components/ListView/ListView';
import ExpandableList from 'src/components/ExpandableList';
import {
FetchDataConfig,
FilterOperatorMap,
Filters,
} from 'src/components/ListView/types';
import withToasts from 'src/messageToasts/enhancers/withToasts';
import PropertiesModal from 'src/dashboard/components/PropertiesModal';
import { isFeatureEnabled, FeatureFlag } from 'src/featureFlags';
const PAGE_SIZE = 25;
interface Props {
addDangerToast: (msg: string) => void;
addSuccessToast: (msg: string) => void;
}
interface State {
dashboards: any[];
dashboardCount: number;
loading: boolean;
filterOperators: FilterOperatorMap;
filters: Filters;
permissions: string[];
lastFetchDataConfig: FetchDataConfig | null;
dashboardToEdit: Dashboard | null;
}
interface Dashboard {
id: number;
changed_by: string;
changed_by_name: string;
changed_by_url: string;
changed_on_delta_humanized: string;
dashboard_title: string;
published: boolean;
url: string;
}
class DashboardList extends React.PureComponent<Props, State> {
static propTypes = {
addDangerToast: PropTypes.func.isRequired,
};
state: State = {
dashboardCount: 0,
dashboards: [],
filterOperators: {},
filters: [],
lastFetchDataConfig: null,
loading: true,
permissions: [],
dashboardToEdit: null,
};
componentDidMount() {
SupersetClient.get({
endpoint: `/api/v1/dashboard/_info`,
}).then(
({ json: infoJson = {} }) => {
this.setState(
{
filterOperators: infoJson.filters,
permissions: infoJson.permissions,
},
this.updateFilters,
);
},
e => {
this.props.addDangerToast(
t(
'An error occurred while fetching Dashboards: %s, %s',
e.statusText,
),
);
console.error(e);
},
);
}
get canEdit() {
return this.hasPerm('can_edit');
}
get canDelete() {
return this.hasPerm('can_delete');
}
get canExport() {
return this.hasPerm('can_mulexport');
}
get isSIP34FilterUIEnabled() {
return isFeatureEnabled(FeatureFlag.LIST_VIEWS_SIP34_FILTER_UI);
}
initialSort = [{ id: 'changed_on_delta_humanized', desc: true }];
columns = [
{
Cell: ({
row: {
original: { url, dashboard_title: dashboardTitle },
},
}: any) => <a href={url}>{dashboardTitle}</a>,
Header: t('Title'),
accessor: 'dashboard_title',
},
{
Cell: ({
row: {
original: { owners },
},
}: any) => (
<ExpandableList
items={owners.map(
({ first_name: firstName, last_name: lastName }: any) =>
`${firstName} ${lastName}`,
)}
display={2}
/>
),
Header: t('Owners'),
accessor: 'owners',
disableSortBy: true,
},
{
Cell: ({
row: {
original: {
changed_by_name: changedByName,
changed_by_url: changedByUrl,
},
},
}: any) => <a href={changedByUrl}>{changedByName}</a>,
Header: t('Creator'),
accessor: 'changed_by_fk',
},
{
Cell: ({
row: {
original: { published },
},
}: any) => (
<span className="no-wrap">
{published ? <i className="fa fa-check" /> : ''}
</span>
),
Header: t('Published'),
accessor: 'published',
},
{
Cell: ({
row: {
original: { changed_on_delta_humanized: changedOn },
},
}: any) => <span className="no-wrap">{changedOn}</span>,
Header: t('Modified'),
accessor: 'changed_on_delta_humanized',
},
{
accessor: 'slug',
hidden: true,
disableSortBy: true,
},
{
Cell: ({ row: { state, original } }: any) => {
const handleDelete = () => this.handleDashboardDelete(original);
const handleEdit = () => this.openDashboardEditModal(original);
const handleExport = () => this.handleBulkDashboardExport([original]);
if (!this.canEdit && !this.canDelete && !this.canExport) {
return null;
}
return (
<span
className={`actions ${state && state.hover ? '' : 'invisible'}`}
>
{this.canDelete && (
<ConfirmStatusChange
title={t('Please Confirm')}
description={
<>
{t('Are you sure you want to delete')}{' '}
<b>{original.dashboard_title}</b>?
</>
}
onConfirm={handleDelete}
>
{confirmDelete => (
<span
role="button"
tabIndex={0}
className="action-button"
onClick={confirmDelete}
>
<i className="fa fa-trash" />
</span>
)}
</ConfirmStatusChange>
)}
{this.canExport && (
<span
role="button"
tabIndex={0}
className="action-button"
onClick={handleExport}
>
<i className="fa fa-database" />
</span>
)}
{this.canEdit && (
<span
role="button"
tabIndex={0}
className="action-button"
onClick={handleEdit}
>
<i className="fa fa-pencil" />
</span>
)}
</span>
);
},
Header: t('Actions'),
id: 'actions',
disableSortBy: true,
},
];
hasPerm = (perm: string) => {
if (!this.state.permissions.length) {
return false;
}
return Boolean(this.state.permissions.find(p => p === perm));
};
openDashboardEditModal = (dashboard: Dashboard) => {
this.setState({
dashboardToEdit: dashboard,
});
};
handleDashboardEdit = (edits: any) => {
this.setState({ loading: true });
return SupersetClient.get({
endpoint: `/api/v1/dashboard/${edits.id}`,
})
.then(({ json = {} }) => {
this.setState({
dashboards: this.state.dashboards.map(dashboard => {
if (dashboard.id === json.id) {
return json.result;
}
return dashboard;
}),
loading: false,
});
})
.catch(e => {
this.props.addDangerToast(
t('An error occurred while fetching dashboards: %s', e.statusText),
);
});
};
handleDashboardDelete = ({
id,
dashboard_title: dashboardTitle,
}: Dashboard) =>
SupersetClient.delete({
endpoint: `/api/v1/dashboard/${id}`,
}).then(
() => {
const { lastFetchDataConfig } = this.state;
if (lastFetchDataConfig) {
this.fetchData(lastFetchDataConfig);
}
this.props.addSuccessToast(t('Deleted: %s', dashboardTitle));
},
(err: any) => {
console.error(err);
this.props.addDangerToast(
t('There was an issue deleting %s', dashboardTitle),
);
},
);
handleBulkDashboardDelete = (dashboards: Dashboard[]) => {
SupersetClient.delete({
endpoint: `/api/v1/dashboard/?q=${rison.encode(
dashboards.map(({ id }) => id),
)}`,
}).then(
({ json = {} }) => {
const { lastFetchDataConfig } = this.state;
if (lastFetchDataConfig) {
this.fetchData(lastFetchDataConfig);
}
this.props.addSuccessToast(json.message);
},
(err: any) => {
console.error(err);
this.props.addDangerToast(
t(
'There was an issue deleting the selected dashboards: ',
err.statusText,
),
);
},
);
};
handleBulkDashboardExport = (dashboards: Dashboard[]) => {
return window.location.assign(
`/api/v1/dashboard/export/?q=${rison.encode(
dashboards.map(({ id }) => id),
)}`,
);
};
fetchData = ({ pageIndex, pageSize, sortBy, filters }: FetchDataConfig) => {
// set loading state, cache the last config for fetching data in this component.
this.setState({
lastFetchDataConfig: {
filters,
pageIndex,
pageSize,
sortBy,
},
loading: true,
});
const filterExps = filters.map(({ id: col, operator: opr, value }) => ({
col,
opr,
value,
}));
const queryParams = rison.encode({
order_column: sortBy[0].id,
order_direction: sortBy[0].desc ? 'desc' : 'asc',
page: pageIndex,
page_size: pageSize,
...(filterExps.length ? { filters: filterExps } : {}),
});
return SupersetClient.get({
endpoint: `/api/v1/dashboard/?q=${queryParams}`,
})
.then(({ json = {} }) => {
this.setState({ dashboards: json.result, dashboardCount: json.count });
})
.catch(e => {
this.props.addDangerToast(
t('An error occurred while fetching dashboards: %s', e.statusText),
);
})
.finally(() => {
this.setState({ loading: false });
});
};
fetchOwners = async (
filterValue = '',
pageIndex?: number,
pageSize?: number,
) => {
const resource = '/api/v1/dashboard/related/owners';
try {
const queryParams = rison.encode({
...(pageIndex ? { page: pageIndex } : {}),
...(pageSize ? { page_ize: pageSize } : {}),
...(filterValue ? { filter: filterValue } : {}),
});
const { json = {} } = await SupersetClient.get({
endpoint: `${resource}?q=${queryParams}`,
});
return json?.result?.map(
({ text: label, value }: { text: string; value: any }) => ({
label,
value,
}),
);
} catch (e) {
console.error(e);
this.props.addDangerToast(
t(
'An error occurred while fetching chart owner values: %s',
e.statusText,
),
);
}
return [];
};
updateFilters = async () => {
const { filterOperators } = this.state;
if (this.isSIP34FilterUIEnabled) {
return this.setState({
filters: [
{
Header: 'Owner',
id: 'owners',
input: 'select',
operator: 'rel_m_m',
unfilteredLabel: 'All',
fetchSelects: this.fetchOwners,
paginate: true,
},
{
Header: 'Published',
id: 'published',
input: 'select',
operator: 'eq',
unfilteredLabel: 'Any',
selects: [
{ label: 'Published', value: true },
{ label: 'Unpublished', value: false },
],
},
{
Header: 'Search',
id: 'dashboard_title',
input: 'search',
operator: 'title_or_slug',
},
],
});
}
const convertFilter = ({
name: label,
operator,
}: {
name: string;
operator: string;
}) => ({ label, value: operator });
const owners = await this.fetchOwners();
return this.setState({
filters: [
{
Header: 'Dashboard',
id: 'dashboard_title',
operators: filterOperators.dashboard_title.map(convertFilter),
},
{
Header: 'Slug',
id: 'slug',
operators: filterOperators.slug.map(convertFilter),
},
{
Header: 'Owners',
id: 'owners',
input: 'select',
operators: filterOperators.owners.map(convertFilter),
selects: owners,
},
{
Header: 'Published',
id: 'published',
input: 'checkbox',
operators: filterOperators.published.map(convertFilter),
},
],
});
};
render() {
const {
dashboards,
dashboardCount,
loading,
filters,
dashboardToEdit,
} = this.state;
return (
<>
<SubMenu name={t('Dashboards')} />
<ConfirmStatusChange
title={t('Please confirm')}
description={t(
'Are you sure you want to delete the selected dashboards?',
)}
onConfirm={this.handleBulkDashboardDelete}
>
{confirmDelete => {
const bulkActions = [];
if (this.canDelete) {
bulkActions.push({
key: 'delete',
name: (
<>
<i className="fa fa-trash" /> {t('Delete')}
</>
),
onSelect: confirmDelete,
});
}
if (this.canExport) {
bulkActions.push({
key: 'export',
name: (
<>
<i className="fa fa-database" /> {t('Export')}
</>
),
onSelect: this.handleBulkDashboardExport,
});
}
return (
<>
{dashboardToEdit && (
<PropertiesModal
show
dashboardId={dashboardToEdit.id}
onHide={() => this.setState({ dashboardToEdit: null })}
onDashboardSave={this.handleDashboardEdit}
/>
)}
<ListView
className="dashboard-list-view"
columns={this.columns}
data={dashboards}
count={dashboardCount}
pageSize={PAGE_SIZE}
fetchData={this.fetchData}
loading={loading}
initialSort={this.initialSort}
filters={filters}
bulkActions={bulkActions}
isSIP34FilterUIEnabled={this.isSIP34FilterUIEnabled}
/>
</>
);
}}
</ConfirmStatusChange>
</>
);
}
}
export default withToasts(DashboardList);
| superset-frontend/src/views/dashboardList/DashboardList.tsx | 1 | https://github.com/apache/superset/commit/2b061fc64b88831574878b6bd470d700a1527dec | [
0.7916297912597656,
0.015224473550915718,
0.000165629229741171,
0.00022444291971623898,
0.10290781408548355
] |
{
"id": 6,
"code_window": [
" \"owners.id\",\n",
" \"owners.username\",\n",
" \"owners.first_name\",\n",
" \"owners.last_name\",\n",
" ]\n",
" list_select_columns = list_columns + [\"changed_on\"]\n",
" order_columns = [\n",
" \"dashboard_title\",\n",
" \"changed_on_delta_humanized\",\n",
" \"published\",\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" list_select_columns = list_columns + [\"changed_on\", \"changed_by_fk\"]\n"
],
"file_path": "superset/dashboards/api.py",
"type": "replace",
"edit_start_line_idx": 121
} | # 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 json
from flask_appbuilder import expose, has_access
from flask_appbuilder.models.sqla.interface import SQLAInterface
from flask_babel import lazy_gettext as _
from superset import app, db
from superset.connectors.connector_registry import ConnectorRegistry
from superset.constants import RouteMethod
from superset.models.slice import Slice
from superset.typing import FlaskResponse
from superset.utils import core as utils
from superset.views.base import check_ownership, DeleteMixin, SupersetModelView
from superset.views.chart.mixin import SliceMixin
class SliceModelView(
SliceMixin, SupersetModelView, DeleteMixin
): # pylint: disable=too-many-ancestors
route_base = "/chart"
datamodel = SQLAInterface(Slice)
include_route_methods = RouteMethod.CRUD_SET | {
RouteMethod.DOWNLOAD,
RouteMethod.API_READ,
RouteMethod.API_DELETE,
}
def pre_add(self, item: "SliceModelView") -> None:
utils.validate_json(item.params)
def pre_update(self, item: "SliceModelView") -> None:
utils.validate_json(item.params)
check_ownership(item)
def pre_delete(self, item: "SliceModelView") -> None:
check_ownership(item)
@expose("/add", methods=["GET", "POST"])
@has_access
def add(self) -> FlaskResponse:
datasources = [
{"value": str(d.id) + "__" + d.type, "label": repr(d)}
for d in ConnectorRegistry.get_all_datasources(db.session)
]
return self.render_template(
"superset/add_slice.html",
bootstrap_data=json.dumps(
{"datasources": sorted(datasources, key=lambda d: d["label"])}
),
)
@expose("/list/")
@has_access
def list(self) -> FlaskResponse:
if not app.config["ENABLE_REACT_CRUD_VIEWS"]:
return super().list()
return super().render_app_template()
class SliceAsync(SliceModelView): # pylint: disable=too-many-ancestors
route_base = "/sliceasync"
include_route_methods = {RouteMethod.API_READ}
list_columns = [
"changed_on",
"changed_on_humanized",
"creator",
"datasource_id",
"datasource_link",
"datasource_name_text",
"datasource_type",
"description",
"description_markeddown",
"edit_url",
"icons",
"id",
"modified",
"owners",
"params",
"slice_link",
"slice_name",
"slice_url",
"viz_type",
]
label_columns = {"icons": " ", "slice_link": _("Chart")}
| superset/views/chart/views.py | 0 | https://github.com/apache/superset/commit/2b061fc64b88831574878b6bd470d700a1527dec | [
0.004270474426448345,
0.0007818046724423766,
0.00016264223086182028,
0.0001758929283823818,
0.0012896383414044976
] |
{
"id": 6,
"code_window": [
" \"owners.id\",\n",
" \"owners.username\",\n",
" \"owners.first_name\",\n",
" \"owners.last_name\",\n",
" ]\n",
" list_select_columns = list_columns + [\"changed_on\"]\n",
" order_columns = [\n",
" \"dashboard_title\",\n",
" \"changed_on_delta_humanized\",\n",
" \"published\",\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" list_select_columns = list_columns + [\"changed_on\", \"changed_by_fk\"]\n"
],
"file_path": "superset/dashboards/api.py",
"type": "replace",
"edit_start_line_idx": 121
} | #
# 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.
#
x-superset-build: &superset-build
args:
NPM_BUILD_CMD: build-dev
context: ./
dockerfile: Dockerfile-dev
x-superset-depends-on: &superset-depends-on
- db
- redis
x-superset-volumes: &superset-volumes
# /app/pythonpath_docker will be appended to the PYTHONPATH in the final container
- ./docker/docker-init.sh:/app/docker-init.sh
- ./docker/pythonpath_dev:/app/pythonpath
- ./superset:/app/superset
- ./superset-frontend:/app/superset-frontend
- superset_home:/app/superset_home
version: "3.7"
services:
redis:
image: redis:3.2
container_name: superset_cache
restart: unless-stopped
ports:
- "127.0.0.1:6379:6379"
volumes:
- redis:/data
db:
env_file: docker/.env
image: postgres:10
container_name: superset_db
restart: unless-stopped
ports:
- "127.0.0.1:5432:5432"
volumes:
- db_home:/var/lib/postgresql/data
superset:
env_file: docker/.env
build: *superset-build
container_name: superset_app
command: ["flask", "run", "-p", "8088", "--with-threads", "--reload", "--debugger", "--host=0.0.0.0"]
restart: unless-stopped
ports:
- 8088:8088
depends_on: *superset-depends-on
volumes: *superset-volumes
superset-init:
build: *superset-build
container_name: superset_init
command: ["/app/docker-init.sh"]
env_file: docker/.env
depends_on: *superset-depends-on
volumes: *superset-volumes
superset-node:
image: node:10-jessie
container_name: superset_node
command: ["bash", "-c", "cd /app/superset-frontend && npm install --global webpack webpack-cli && npm install && npm run dev"]
env_file: docker/.env
depends_on: *superset-depends-on
volumes: *superset-volumes
superset-worker:
build: *superset-build
container_name: superset_worker
command: ["celery", "worker", "--app=superset.tasks.celery_app:app", "-Ofair", "-l", "INFO"]
env_file: docker/.env
restart: unless-stopped
depends_on: *superset-depends-on
volumes: *superset-volumes
superset-tests-worker:
build: *superset-build
container_name: superset_tests_worker
command: ["celery", "worker", "--app=superset.tasks.celery_app:app", "-Ofair", "-l", "INFO"]
env_file: docker/.env
environment:
DATABASE_HOST: localhost
DATABASE_DB: test
REDIS_CELERY_DB: 2
REDIS_RESULTS_DB: 3
REDIS_HOST: localhost
network_mode: host
depends_on: *superset-depends-on
volumes: *superset-volumes
volumes:
superset_home:
external: false
db_home:
external: false
redis:
external: false
| docker-compose.yml | 0 | https://github.com/apache/superset/commit/2b061fc64b88831574878b6bd470d700a1527dec | [
0.00017747044330462813,
0.0001729173818603158,
0.0001611869956832379,
0.0001738304563332349,
0.0000039980668589123525
] |
{
"id": 6,
"code_window": [
" \"owners.id\",\n",
" \"owners.username\",\n",
" \"owners.first_name\",\n",
" \"owners.last_name\",\n",
" ]\n",
" list_select_columns = list_columns + [\"changed_on\"]\n",
" order_columns = [\n",
" \"dashboard_title\",\n",
" \"changed_on_delta_humanized\",\n",
" \"published\",\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" list_select_columns = list_columns + [\"changed_on\", \"changed_by_fk\"]\n"
],
"file_path": "superset/dashboards/api.py",
"type": "replace",
"edit_start_line_idx": 121
} | /**
* 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 { t } from '@superset-ui/translation';
import { validateNonEmpty } from '@superset-ui/validator';
import timeGrainSqlaAnimationOverrides from './timeGrainSqlaAnimationOverrides';
import {
filterNulls,
autozoom,
jsColumns,
jsDataMutator,
jsTooltip,
jsOnclickHref,
gridSize,
viewport,
spatial,
mapboxStyle,
} from './Shared_DeckGL';
export default {
controlPanelSections: [
{
label: t('Query'),
expanded: true,
controlSetRows: [
[spatial, 'size'],
['row_limit', filterNulls],
['adhoc_filters'],
],
},
{
label: t('Map'),
controlSetRows: [
[mapboxStyle, viewport],
[autozoom, null],
],
},
{
label: t('Grid'),
expanded: true,
controlSetRows: [[gridSize, 'color_picker']],
},
{
label: t('Advanced'),
controlSetRows: [
[jsColumns],
[jsDataMutator],
[jsTooltip],
[jsOnclickHref],
],
},
],
controlOverrides: {
size: {
label: t('Weight'),
description: t("Metric used as a weight for the grid's coloring"),
validators: [validateNonEmpty],
},
time_grain_sqla: timeGrainSqlaAnimationOverrides,
},
};
| superset-frontend/src/explore/controlPanels/DeckScreengrid.js | 0 | https://github.com/apache/superset/commit/2b061fc64b88831574878b6bd470d700a1527dec | [
0.00017625809414312243,
0.0001717318664304912,
0.00016649378812871873,
0.00017327116802334785,
0.0000031949509775586193
] |
{
"id": 7,
"code_window": [
" \"dashboard_title\",\n",
" \"changed_on_delta_humanized\",\n",
" \"published\",\n",
" \"changed_by_fk\",\n",
" ]\n",
"\n",
" add_columns = [\n",
" \"dashboard_title\",\n",
" \"slug\",\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"changed_by.first_name\",\n"
],
"file_path": "superset/dashboards/api.py",
"type": "replace",
"edit_start_line_idx": 126
} | # 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.
"""a collection of model-related helper classes and functions"""
import json
import logging
import re
from datetime import datetime, timedelta
from typing import Any, Dict, List, Optional, Set, Union
# isort and pylint disagree, isort should win
# pylint: disable=ungrouped-imports
import humanize
import pandas as pd
import pytz
import sqlalchemy as sa
import yaml
from flask import escape, g, Markup
from flask_appbuilder.models.decorators import renders
from flask_appbuilder.models.mixins import AuditMixin
from flask_appbuilder.security.sqla.models import User
from sqlalchemy import and_, or_, UniqueConstraint
from sqlalchemy.ext.declarative import declared_attr
from sqlalchemy.orm import Session
from sqlalchemy.orm.exc import MultipleResultsFound
from superset.utils.core import QueryStatus
logger = logging.getLogger(__name__)
def json_to_dict(json_str: str) -> Dict[Any, Any]:
if json_str:
val = re.sub(",[ \t\r\n]+}", "}", json_str)
val = re.sub(
",[ \t\r\n]+\]", "]", val # pylint: disable=anomalous-backslash-in-string
)
return json.loads(val)
return {}
class ImportMixin:
export_parent: Optional[str] = None
# The name of the attribute
# with the SQL Alchemy back reference
export_children: List[str] = []
# List of (str) names of attributes
# with the SQL Alchemy forward references
export_fields: List[str] = []
# The names of the attributes
# that are available for import and export
@classmethod
def _parent_foreign_key_mappings(cls) -> Dict[str, str]:
"""Get a mapping of foreign name to the local name of foreign keys"""
parent_rel = cls.__mapper__.relationships.get(cls.export_parent) # type: ignore
if parent_rel:
return {l.name: r.name for (l, r) in parent_rel.local_remote_pairs}
return {}
@classmethod
def _unique_constrains(cls) -> List[Set[str]]:
"""Get all (single column and multi column) unique constraints"""
unique = [
{c.name for c in u.columns}
for u in cls.__table_args__ # type: ignore
if isinstance(u, UniqueConstraint)
]
unique.extend(
{c.name} for c in cls.__table__.columns if c.unique # type: ignore
)
return unique
@classmethod
def export_schema(
cls, recursive: bool = True, include_parent_ref: bool = False
) -> Dict[str, Any]:
"""Export schema as a dictionary"""
parent_excludes = set()
if not include_parent_ref:
parent_ref = cls.__mapper__.relationships.get( # type: ignore
cls.export_parent
)
if parent_ref:
parent_excludes = {column.name for column in parent_ref.local_columns}
def formatter(column: sa.Column) -> str:
return (
"{0} Default ({1})".format(str(column.type), column.default.arg)
if column.default
else str(column.type)
)
schema: Dict[str, Any] = {
column.name: formatter(column)
for column in cls.__table__.columns # type: ignore
if (column.name in cls.export_fields and column.name not in parent_excludes)
}
if recursive:
for column in cls.export_children:
child_class = cls.__mapper__.relationships[ # type: ignore
column
].argument.class_
schema[column] = [
child_class.export_schema(
recursive=recursive, include_parent_ref=include_parent_ref
)
]
return schema
@classmethod
def import_from_dict( # pylint: disable=too-many-arguments,too-many-branches,too-many-locals
cls,
session: Session,
dict_rep: Dict[Any, Any],
parent: Optional[Any] = None,
recursive: bool = True,
sync: Optional[List[str]] = None,
) -> Any: # pylint: disable=too-many-arguments,too-many-locals,too-many-branches
"""Import obj from a dictionary"""
if sync is None:
sync = []
parent_refs = cls._parent_foreign_key_mappings()
export_fields = set(cls.export_fields) | set(parent_refs.keys())
new_children = {c: dict_rep[c] for c in cls.export_children if c in dict_rep}
unique_constrains = cls._unique_constrains()
filters = [] # Using these filters to check if obj already exists
# Remove fields that should not get imported
for k in list(dict_rep):
if k not in export_fields:
del dict_rep[k]
if not parent:
if cls.export_parent:
for prnt in parent_refs.keys():
if prnt not in dict_rep:
raise RuntimeError(
"{0}: Missing field {1}".format(cls.__name__, prnt)
)
else:
# Set foreign keys to parent obj
for k, v in parent_refs.items():
dict_rep[k] = getattr(parent, v)
# Add filter for parent obj
filters.extend([getattr(cls, k) == dict_rep.get(k) for k in parent_refs.keys()])
# Add filter for unique constraints
ucs = [
and_(
*[
getattr(cls, k) == dict_rep.get(k)
for k in cs
if dict_rep.get(k) is not None
]
)
for cs in unique_constrains
]
filters.append(or_(*ucs))
# Check if object already exists in DB, break if more than one is found
try:
obj_query = session.query(cls).filter(and_(*filters))
obj = obj_query.one_or_none()
except MultipleResultsFound as ex:
logger.error(
"Error importing %s \n %s \n %s",
cls.__name__,
str(obj_query),
yaml.safe_dump(dict_rep),
)
raise ex
if not obj:
is_new_obj = True
# Create new DB object
obj = cls(**dict_rep) # type: ignore
logger.info("Importing new %s %s", obj.__tablename__, str(obj))
if cls.export_parent and parent:
setattr(obj, cls.export_parent, parent)
session.add(obj)
else:
is_new_obj = False
logger.info("Updating %s %s", obj.__tablename__, str(obj))
# Update columns
for k, v in dict_rep.items():
setattr(obj, k, v)
# Recursively create children
if recursive:
for child in cls.export_children:
child_class = cls.__mapper__.relationships[ # type: ignore
child
].argument.class_
added = []
for c_obj in new_children.get(child, []):
added.append(
child_class.import_from_dict(
session=session, dict_rep=c_obj, parent=obj, sync=sync
)
)
# If children should get synced, delete the ones that did not
# get updated.
if child in sync and not is_new_obj:
back_refs = (
child_class._parent_foreign_key_mappings() # pylint: disable=protected-access
)
delete_filters = [
getattr(child_class, k) == getattr(obj, back_refs.get(k))
for k in back_refs.keys()
]
to_delete = set(
session.query(child_class).filter(and_(*delete_filters))
).difference(set(added))
for o in to_delete:
logger.info("Deleting %s %s", child, str(obj))
session.delete(o)
return obj
def export_to_dict(
self,
recursive: bool = True,
include_parent_ref: bool = False,
include_defaults: bool = False,
) -> Dict[Any, Any]:
"""Export obj to dictionary"""
cls = self.__class__
parent_excludes = set()
if recursive and not include_parent_ref:
parent_ref = cls.__mapper__.relationships.get( # type: ignore
cls.export_parent
)
if parent_ref:
parent_excludes = {c.name for c in parent_ref.local_columns}
dict_rep = {
c.name: getattr(self, c.name)
for c in cls.__table__.columns # type: ignore
if (
c.name in self.export_fields
and c.name not in parent_excludes
and (
include_defaults
or (
getattr(self, c.name) is not None
and (not c.default or getattr(self, c.name) != c.default.arg)
)
)
)
}
if recursive:
for cld in self.export_children:
# sorting to make lists of children stable
dict_rep[cld] = sorted(
[
child.export_to_dict(
recursive=recursive,
include_parent_ref=include_parent_ref,
include_defaults=include_defaults,
)
for child in getattr(self, cld)
],
key=lambda k: sorted(str(k.items())),
)
return dict_rep
def override(self, obj: Any) -> None:
"""Overrides the plain fields of the dashboard."""
for field in obj.__class__.export_fields:
setattr(self, field, getattr(obj, field))
def copy(self) -> Any:
"""Creates a copy of the dashboard without relationships."""
new_obj = self.__class__()
new_obj.override(self)
return new_obj
def alter_params(self, **kwargs: Any) -> None:
params = self.params_dict
params.update(kwargs)
self.params = json.dumps(params)
def remove_params(self, param_to_remove: str) -> None:
params = self.params_dict
params.pop(param_to_remove, None)
self.params = json.dumps(params)
def reset_ownership(self) -> None:
""" object will belong to the user the current user """
# make sure the object doesn't have relations to a user
# it will be filled by appbuilder on save
self.created_by = None
self.changed_by = None
# flask global context might not exist (in cli or tests for example)
try:
if g.user:
self.owners = [g.user]
except Exception: # pylint: disable=broad-except
self.owners = []
@property
def params_dict(self) -> Dict[Any, Any]:
return json_to_dict(self.params)
@property
def template_params_dict(self) -> Dict[Any, Any]:
return json_to_dict(self.template_params) # type: ignore
def _user_link(user: User) -> Union[Markup, str]: # pylint: disable=no-self-use
if not user:
return ""
url = "/superset/profile/{}/".format(user.username)
return Markup('<a href="{}">{}</a>'.format(url, escape(user) or ""))
class AuditMixinNullable(AuditMixin):
"""Altering the AuditMixin to use nullable fields
Allows creating objects programmatically outside of CRUD
"""
created_on = sa.Column(sa.DateTime, default=datetime.now, nullable=True)
changed_on = sa.Column(
sa.DateTime, default=datetime.now, onupdate=datetime.now, nullable=True
)
@declared_attr
def created_by_fk(self) -> sa.Column:
return sa.Column(
sa.Integer,
sa.ForeignKey("ab_user.id"),
default=self.get_user_id,
nullable=True,
)
@declared_attr
def changed_by_fk(self) -> sa.Column:
return sa.Column(
sa.Integer,
sa.ForeignKey("ab_user.id"),
default=self.get_user_id,
onupdate=self.get_user_id,
nullable=True,
)
@property
def changed_by_name(self) -> str:
if self.created_by:
return escape("{}".format(self.created_by))
return ""
@renders("created_by")
def creator(self) -> Union[Markup, str]:
return _user_link(self.created_by)
@property
def changed_by_(self) -> Union[Markup, str]:
return _user_link(self.changed_by)
@renders("changed_on")
def changed_on_(self) -> Markup:
return Markup(f'<span class="no-wrap">{self.changed_on}</span>')
@renders("changed_on")
def changed_on_delta_humanized(self) -> str:
return self.changed_on_humanized
@renders("changed_on")
def changed_on_utc(self) -> str:
# Convert naive datetime to UTC
return self.changed_on.astimezone(pytz.utc).strftime("%Y-%m-%dT%H:%M:%S.%f%z")
@property
def changed_on_humanized(self) -> str:
return humanize.naturaltime(datetime.now() - self.changed_on)
@renders("changed_on")
def modified(self) -> Markup:
return Markup(f'<span class="no-wrap">{self.changed_on_humanized}</span>')
class QueryResult: # pylint: disable=too-few-public-methods
"""Object returned by the query interface"""
def __init__( # pylint: disable=too-many-arguments
self,
df: pd.DataFrame,
query: str,
duration: timedelta,
status: str = QueryStatus.SUCCESS,
error_message: Optional[str] = None,
errors: Optional[List[Dict[str, Any]]] = None,
) -> None:
self.df = df
self.query = query
self.duration = duration
self.status = status
self.error_message = error_message
self.errors = errors or []
class ExtraJSONMixin:
"""Mixin to add an `extra` column (JSON) and utility methods"""
extra_json = sa.Column(sa.Text, default="{}")
@property
def extra(self) -> Dict[str, Any]:
try:
return json.loads(self.extra_json)
except Exception: # pylint: disable=broad-except
return {}
def set_extra_json(self, extras: Dict[str, Any]) -> None:
self.extra_json = json.dumps(extras)
def set_extra_json_key(self, key: str, value: Any) -> None:
extra = self.extra
extra[key] = value
self.extra_json = json.dumps(extra)
| superset/models/helpers.py | 1 | https://github.com/apache/superset/commit/2b061fc64b88831574878b6bd470d700a1527dec | [
0.021455373615026474,
0.00106250389944762,
0.0001671093050390482,
0.00017488784214947373,
0.0033163060434162617
] |
{
"id": 7,
"code_window": [
" \"dashboard_title\",\n",
" \"changed_on_delta_humanized\",\n",
" \"published\",\n",
" \"changed_by_fk\",\n",
" ]\n",
"\n",
" add_columns = [\n",
" \"dashboard_title\",\n",
" \"slug\",\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"changed_by.first_name\",\n"
],
"file_path": "superset/dashboards/api.py",
"type": "replace",
"edit_start_line_idx": 126
} | /**
* 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 PropTypes from 'prop-types';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import Dialog from 'react-bootstrap-dialog';
import { t } from '@superset-ui/translation';
import { InfoTooltipWithTrigger } from '@superset-ui/chart-controls';
import { exploreChart } from '../../explore/exploreUtils';
import * as actions from '../actions/sqlLab';
import Button from '../../components/Button';
const propTypes = {
actions: PropTypes.object.isRequired,
table: PropTypes.string.isRequired,
schema: PropTypes.string,
dbId: PropTypes.number.isRequired,
errorMessage: PropTypes.string,
templateParams: PropTypes.string,
};
const defaultProps = {
vizRequest: {},
};
class ExploreCtasResultsButton extends React.PureComponent {
constructor(props) {
super(props);
this.visualize = this.visualize.bind(this);
this.onClick = this.onClick.bind(this);
}
onClick() {
this.visualize();
}
buildVizOptions() {
return {
datasourceName: this.props.table,
schema: this.props.schema,
dbId: this.props.dbId,
templateParams: this.props.templateParams,
};
}
visualize() {
this.props.actions
.createCtasDatasource(this.buildVizOptions())
.then(data => {
const formData = {
datasource: `${data.table_id}__table`,
metrics: ['count'],
groupby: [],
viz_type: 'table',
since: '100 years ago',
all_columns: [],
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'),
);
});
}
render() {
return (
<>
<Button
bsSize="small"
onClick={this.onClick}
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;
}}
/>
</>
);
}
}
ExploreCtasResultsButton.propTypes = propTypes;
ExploreCtasResultsButton.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 { ExploreCtasResultsButton };
export default connect(
mapStateToProps,
mapDispatchToProps,
)(ExploreCtasResultsButton);
| superset/assets/src/SqlLab/components/ExploreCtasResultsButton.jsx | 0 | https://github.com/apache/superset/commit/2b061fc64b88831574878b6bd470d700a1527dec | [
0.0008279390749521554,
0.000218328190385364,
0.00016593480540905148,
0.000172609172295779,
0.0001690974459052086
] |
{
"id": 7,
"code_window": [
" \"dashboard_title\",\n",
" \"changed_on_delta_humanized\",\n",
" \"published\",\n",
" \"changed_by_fk\",\n",
" ]\n",
"\n",
" add_columns = [\n",
" \"dashboard_title\",\n",
" \"slug\",\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"changed_by.first_name\",\n"
],
"file_path": "superset/dashboards/api.py",
"type": "replace",
"edit_start_line_idx": 126
} | /**
* 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 { t } from '@superset-ui/translation';
import { SupersetClient } from '@superset-ui/connection';
import { addDangerToast } from '../../messageToasts/actions';
const FAVESTAR_BASE_URL = '/superset/favstar/slice';
export const SET_DATASOURCE_TYPE = 'SET_DATASOURCE_TYPE';
export function setDatasourceType(datasourceType) {
return { type: SET_DATASOURCE_TYPE, datasourceType };
}
export const SET_DATASOURCE = 'SET_DATASOURCE';
export function setDatasource(datasource) {
return { type: SET_DATASOURCE, datasource };
}
export const SET_DATASOURCES = 'SET_DATASOURCES';
export function setDatasources(datasources) {
return { type: SET_DATASOURCES, datasources };
}
export const POST_DATASOURCE_STARTED = 'POST_DATASOURCE_STARTED';
export const FETCH_DATASOURCE_SUCCEEDED = 'FETCH_DATASOURCE_SUCCEEDED';
export function fetchDatasourceSucceeded() {
return { type: FETCH_DATASOURCE_SUCCEEDED };
}
export const FETCH_DATASOURCES_STARTED = 'FETCH_DATASOURCES_STARTED';
export function fetchDatasourcesStarted() {
return { type: FETCH_DATASOURCES_STARTED };
}
export const FETCH_DATASOURCES_SUCCEEDED = 'FETCH_DATASOURCES_SUCCEEDED';
export function fetchDatasourcesSucceeded() {
return { type: FETCH_DATASOURCES_SUCCEEDED };
}
export const FETCH_DATASOURCES_FAILED = 'FETCH_DATASOURCES_FAILED';
export function fetchDatasourcesFailed(error) {
return { type: FETCH_DATASOURCES_FAILED, error };
}
export const POST_DATASOURCES_FAILED = 'POST_DATASOURCES_FAILED';
export function postDatasourcesFailed(error) {
return { type: POST_DATASOURCES_FAILED, error };
}
export const RESET_FIELDS = 'RESET_FIELDS';
export function resetControls() {
return { type: RESET_FIELDS };
}
export const TOGGLE_FAVE_STAR = 'TOGGLE_FAVE_STAR';
export function toggleFaveStar(isStarred) {
return { type: TOGGLE_FAVE_STAR, isStarred };
}
export const FETCH_FAVE_STAR = 'FETCH_FAVE_STAR';
export function fetchFaveStar(sliceId) {
return function (dispatch) {
SupersetClient.get({
endpoint: `${FAVESTAR_BASE_URL}/${sliceId}/count`,
}).then(({ json }) => {
if (json.count > 0) {
dispatch(toggleFaveStar(true));
}
});
};
}
export const SAVE_FAVE_STAR = 'SAVE_FAVE_STAR';
export function saveFaveStar(sliceId, isStarred) {
return function (dispatch) {
const urlSuffix = isStarred ? 'unselect' : 'select';
SupersetClient.get({
endpoint: `${FAVESTAR_BASE_URL}/${sliceId}/${urlSuffix}/`,
})
.then(() => dispatch(toggleFaveStar(!isStarred)))
.catch(() =>
dispatch(
addDangerToast(t('An error occurred while starring this chart')),
),
);
};
}
export const SET_FIELD_VALUE = 'SET_FIELD_VALUE';
export function setControlValue(controlName, value, validationErrors) {
return { type: SET_FIELD_VALUE, controlName, value, validationErrors };
}
export const UPDATE_EXPLORE_ENDPOINTS = 'UPDATE_EXPLORE_ENDPOINTS';
export function updateExploreEndpoints(jsonUrl, csvUrl, standaloneUrl) {
return { type: UPDATE_EXPLORE_ENDPOINTS, jsonUrl, csvUrl, standaloneUrl };
}
export const SET_EXPLORE_CONTROLS = 'UPDATE_EXPLORE_CONTROLS';
export function setExploreControls(formData) {
return { type: SET_EXPLORE_CONTROLS, formData };
}
export const REMOVE_CONTROL_PANEL_ALERT = 'REMOVE_CONTROL_PANEL_ALERT';
export function removeControlPanelAlert() {
return { type: REMOVE_CONTROL_PANEL_ALERT };
}
export const UPDATE_CHART_TITLE = 'UPDATE_CHART_TITLE';
export function updateChartTitle(sliceName) {
return { type: UPDATE_CHART_TITLE, sliceName };
}
export const CREATE_NEW_SLICE = 'CREATE_NEW_SLICE';
export function createNewSlice(
can_add,
can_download,
can_overwrite,
slice,
form_data,
) {
return {
type: CREATE_NEW_SLICE,
can_add,
can_download,
can_overwrite,
slice,
form_data,
};
}
export const SLICE_UPDATED = 'SLICE_UPDATED';
export function sliceUpdated(slice) {
return { type: SLICE_UPDATED, slice };
}
| superset-frontend/src/explore/actions/exploreActions.js | 0 | https://github.com/apache/superset/commit/2b061fc64b88831574878b6bd470d700a1527dec | [
0.00017902403487823904,
0.00017125302110798657,
0.00016720635176170617,
0.00017073622439056635,
0.0000031972574561223155
] |
{
"id": 7,
"code_window": [
" \"dashboard_title\",\n",
" \"changed_on_delta_humanized\",\n",
" \"published\",\n",
" \"changed_by_fk\",\n",
" ]\n",
"\n",
" add_columns = [\n",
" \"dashboard_title\",\n",
" \"slug\",\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"changed_by.first_name\",\n"
],
"file_path": "superset/dashboards/api.py",
"type": "replace",
"edit_start_line_idx": 126
} | #
# 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 python:3.6-jessie
RUN useradd --user-group --create-home --no-log-init --shell /bin/bash superset
# Configure environment
ENV LANG=C.UTF-8 \
LC_ALL=C.UTF-8
RUN apt-get update -y
# Install dependencies to fix `curl https support error` and `elaying package configuration warning`
RUN apt-get install -y apt-transport-https apt-utils
# Install superset dependencies
# https://superset.incubator.apache.org/installation.html#os-dependencies
RUN apt-get install -y build-essential libssl-dev \
libffi-dev python3-dev libsasl2-dev libldap2-dev libxi-dev
# Install nodejs for custom build
# https://superset.incubator.apache.org/installation.html#making-your-own-build
# https://nodejs.org/en/download/package-manager/
RUN curl -sL https://deb.nodesource.com/setup_12.x | bash - \
&& apt-get install -y nodejs
RUN mkdir -p /home/superset
RUN chown superset /home/superset
WORKDIR /home/superset
ARG VERSION
ARG SUPERSET_RELEASE_RC_TARBALL
# Can fetch source from svn or copy tarball from local mounted directory
COPY $SUPERSET_RELEASE_RC_TARBALL ./
RUN tar -xvf *.tar.gz
WORKDIR /home/superset/apache-superset-incubating-$VERSION/superset-frontend
RUN npm ci \
&& npm run build \
&& rm -rf node_modules
WORKDIR /home/superset/apache-superset-incubating-$VERSION
RUN pip install --upgrade setuptools pip \
&& pip install -r requirements.txt \
&& pip install --no-cache-dir .
RUN flask fab babel-compile --target superset/translations
ENV PATH=/home/superset/superset/bin:$PATH \
PYTHONPATH=/home/superset/superset/:$PYTHONPATH
COPY from_tarball_entrypoint.sh /entrypoint.sh
ENTRYPOINT ["/entrypoint.sh"]
| RELEASING/Dockerfile.from_local_tarball | 0 | https://github.com/apache/superset/commit/2b061fc64b88831574878b6bd470d700a1527dec | [
0.00017534602375235409,
0.0001686847972450778,
0.00016120557847898453,
0.00016799069999251515,
0.0000046243221731856465
] |
{
"id": 8,
"code_window": [
" nullable=True,\n",
" )\n",
"\n",
" @property\n",
" def changed_by_name(self) -> str:\n",
" if self.created_by:\n",
" return escape(\"{}\".format(self.created_by))\n",
" return \"\"\n",
"\n",
" @renders(\"created_by\")\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" if self.changed_by:\n",
" return escape(\"{}\".format(self.changed_by))\n"
],
"file_path": "superset/models/helpers.py",
"type": "replace",
"edit_start_line_idx": 368
} | # 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 logging
from typing import Any, Dict
from flask import g, make_response, redirect, request, Response, url_for
from flask_appbuilder.api import expose, protect, rison, safe
from flask_appbuilder.models.sqla.interface import SQLAInterface
from flask_babel import ngettext
from marshmallow import ValidationError
from werkzeug.wrappers import Response as WerkzeugResponse
from werkzeug.wsgi import FileWrapper
from superset import is_feature_enabled, thumbnail_cache
from superset.constants import RouteMethod
from superset.dashboards.commands.bulk_delete import BulkDeleteDashboardCommand
from superset.dashboards.commands.create import CreateDashboardCommand
from superset.dashboards.commands.delete import DeleteDashboardCommand
from superset.dashboards.commands.exceptions import (
DashboardBulkDeleteFailedError,
DashboardCreateFailedError,
DashboardDeleteFailedError,
DashboardForbiddenError,
DashboardInvalidError,
DashboardNotFoundError,
DashboardUpdateFailedError,
)
from superset.dashboards.commands.update import UpdateDashboardCommand
from superset.dashboards.filters import DashboardFilter, DashboardTitleOrSlugFilter
from superset.dashboards.schemas import (
DashboardPostSchema,
DashboardPutSchema,
get_delete_ids_schema,
get_export_ids_schema,
openapi_spec_methods_override,
thumbnail_query_schema,
)
from superset.models.dashboard import Dashboard
from superset.tasks.thumbnails import cache_dashboard_thumbnail
from superset.utils.screenshots import DashboardScreenshot
from superset.utils.urls import get_url_path
from superset.views.base import generate_download_headers
from superset.views.base_api import (
BaseSupersetModelRestApi,
RelatedFieldFilter,
statsd_metrics,
)
from superset.views.filters import FilterRelatedOwners
logger = logging.getLogger(__name__)
class DashboardRestApi(BaseSupersetModelRestApi):
datamodel = SQLAInterface(Dashboard)
include_route_methods = RouteMethod.REST_MODEL_VIEW_CRUD_SET | {
RouteMethod.EXPORT,
RouteMethod.RELATED,
"bulk_delete", # not using RouteMethod since locally defined
}
resource_name = "dashboard"
allow_browser_login = True
class_permission_name = "DashboardModelView"
show_columns = [
"id",
"charts",
"css",
"dashboard_title",
"json_metadata",
"owners.id",
"owners.username",
"owners.first_name",
"owners.last_name",
"changed_by_name",
"changed_by_url",
"changed_by.username",
"changed_on",
"position_json",
"published",
"url",
"slug",
"table_names",
"thumbnail_url",
]
list_columns = [
"id",
"published",
"slug",
"url",
"css",
"position_json",
"json_metadata",
"thumbnail_url",
"changed_by.first_name",
"changed_by.last_name",
"changed_by.username",
"changed_by.id",
"changed_by_name",
"changed_by_url",
"changed_on_utc",
"changed_on_delta_humanized",
"dashboard_title",
"owners.id",
"owners.username",
"owners.first_name",
"owners.last_name",
]
list_select_columns = list_columns + ["changed_on"]
order_columns = [
"dashboard_title",
"changed_on_delta_humanized",
"published",
"changed_by_fk",
]
add_columns = [
"dashboard_title",
"slug",
"owners",
"position_json",
"css",
"json_metadata",
"published",
]
edit_columns = add_columns
search_columns = ("dashboard_title", "slug", "owners", "published")
search_filters = {"dashboard_title": [DashboardTitleOrSlugFilter]}
base_order = ("changed_on", "desc")
add_model_schema = DashboardPostSchema()
edit_model_schema = DashboardPutSchema()
base_filters = [["slice", DashboardFilter, lambda: []]]
order_rel_fields = {
"slices": ("slice_name", "asc"),
"owners": ("first_name", "asc"),
}
related_field_filters = {
"owners": RelatedFieldFilter("first_name", FilterRelatedOwners)
}
allowed_rel_fields = {"owners"}
openapi_spec_tag = "Dashboards"
apispec_parameter_schemas = {
"get_delete_ids_schema": get_delete_ids_schema,
"get_export_ids_schema": get_export_ids_schema,
"thumbnail_query_schema": thumbnail_query_schema,
}
openapi_spec_methods = openapi_spec_methods_override
""" Overrides GET methods OpenApi descriptions """
def __init__(self) -> None:
if is_feature_enabled("THUMBNAILS"):
self.include_route_methods = self.include_route_methods | {"thumbnail"}
super().__init__()
@expose("/", methods=["POST"])
@protect()
@safe
@statsd_metrics
def post(self) -> Response:
"""Creates a new Dashboard
---
post:
description: >-
Create a new Dashboard.
requestBody:
description: Dashboard schema
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/{{self.__class__.__name__}}.post'
responses:
201:
description: Dashboard added
content:
application/json:
schema:
type: object
properties:
id:
type: number
result:
$ref: '#/components/schemas/{{self.__class__.__name__}}.post'
302:
description: Redirects to the current digest
400:
$ref: '#/components/responses/400'
401:
$ref: '#/components/responses/401'
404:
$ref: '#/components/responses/404'
500:
$ref: '#/components/responses/500'
"""
if not request.is_json:
return self.response_400(message="Request is not JSON")
try:
item = self.add_model_schema.load(request.json)
# This validates custom Schema with custom validations
except ValidationError as error:
return self.response_400(message=error.messages)
try:
new_model = CreateDashboardCommand(g.user, item).run()
return self.response(201, id=new_model.id, result=item)
except DashboardInvalidError as ex:
return self.response_422(message=ex.normalized_messages())
except DashboardCreateFailedError as ex:
logger.error(
"Error creating model %s: %s", self.__class__.__name__, str(ex)
)
return self.response_422(message=str(ex))
@expose("/<pk>", methods=["PUT"])
@protect()
@safe
@statsd_metrics
def put( # pylint: disable=too-many-return-statements, arguments-differ
self, pk: int
) -> Response:
"""Changes a Dashboard
---
put:
description: >-
Changes a Dashboard.
parameters:
- in: path
schema:
type: integer
name: pk
requestBody:
description: Dashboard schema
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/{{self.__class__.__name__}}.put'
responses:
200:
description: Dashboard changed
content:
application/json:
schema:
type: object
properties:
id:
type: number
result:
$ref: '#/components/schemas/{{self.__class__.__name__}}.put'
400:
$ref: '#/components/responses/400'
401:
$ref: '#/components/responses/401'
403:
$ref: '#/components/responses/403'
404:
$ref: '#/components/responses/404'
422:
$ref: '#/components/responses/422'
500:
$ref: '#/components/responses/500'
"""
if not request.is_json:
return self.response_400(message="Request is not JSON")
try:
item = self.edit_model_schema.load(request.json)
# This validates custom Schema with custom validations
except ValidationError as error:
return self.response_400(message=error.messages)
try:
changed_model = UpdateDashboardCommand(g.user, pk, item).run()
return self.response(200, id=changed_model.id, result=item)
except DashboardNotFoundError:
return self.response_404()
except DashboardForbiddenError:
return self.response_403()
except DashboardInvalidError as ex:
return self.response_422(message=ex.normalized_messages())
except DashboardUpdateFailedError as ex:
logger.error(
"Error updating model %s: %s", self.__class__.__name__, str(ex)
)
return self.response_422(message=str(ex))
@expose("/<pk>", methods=["DELETE"])
@protect()
@safe
@statsd_metrics
def delete(self, pk: int) -> Response: # pylint: disable=arguments-differ
"""Deletes a Dashboard
---
delete:
description: >-
Deletes a Dashboard.
parameters:
- in: path
schema:
type: integer
name: pk
responses:
200:
description: Dashboard deleted
content:
application/json:
schema:
type: object
properties:
message:
type: string
401:
$ref: '#/components/responses/401'
403:
$ref: '#/components/responses/403'
404:
$ref: '#/components/responses/404'
422:
$ref: '#/components/responses/422'
500:
$ref: '#/components/responses/500'
"""
try:
DeleteDashboardCommand(g.user, pk).run()
return self.response(200, message="OK")
except DashboardNotFoundError:
return self.response_404()
except DashboardForbiddenError:
return self.response_403()
except DashboardDeleteFailedError as ex:
logger.error(
"Error deleting model %s: %s", self.__class__.__name__, str(ex)
)
return self.response_422(message=str(ex))
@expose("/", methods=["DELETE"])
@protect()
@safe
@statsd_metrics
@rison(get_delete_ids_schema)
def bulk_delete(
self, **kwargs: Any
) -> Response: # pylint: disable=arguments-differ
"""Delete bulk Dashboards
---
delete:
description: >-
Deletes multiple Dashboards in a bulk operation.
parameters:
- in: query
name: q
content:
application/json:
schema:
$ref: '#/components/schemas/get_delete_ids_schema'
responses:
200:
description: Dashboard bulk delete
content:
application/json:
schema:
type: object
properties:
message:
type: string
401:
$ref: '#/components/responses/401'
403:
$ref: '#/components/responses/403'
404:
$ref: '#/components/responses/404'
422:
$ref: '#/components/responses/422'
500:
$ref: '#/components/responses/500'
"""
item_ids = kwargs["rison"]
try:
BulkDeleteDashboardCommand(g.user, item_ids).run()
return self.response(
200,
message=ngettext(
"Deleted %(num)d dashboard",
"Deleted %(num)d dashboards",
num=len(item_ids),
),
)
except DashboardNotFoundError:
return self.response_404()
except DashboardForbiddenError:
return self.response_403()
except DashboardBulkDeleteFailedError as ex:
return self.response_422(message=str(ex))
@expose("/export/", methods=["GET"])
@protect()
@safe
@statsd_metrics
@rison(get_export_ids_schema)
def export(self, **kwargs: Any) -> Response:
"""Export dashboards
---
get:
description: >-
Exports multiple Dashboards and downloads them as YAML files.
parameters:
- in: query
name: q
content:
application/json:
schema:
$ref: '#/components/schemas/get_export_ids_schema'
responses:
200:
description: Dashboard export
content:
text/plain:
schema:
type: string
400:
$ref: '#/components/responses/400'
401:
$ref: '#/components/responses/401'
404:
$ref: '#/components/responses/404'
422:
$ref: '#/components/responses/422'
500:
$ref: '#/components/responses/500'
"""
query = self.datamodel.session.query(Dashboard).filter(
Dashboard.id.in_(kwargs["rison"])
)
query = self._base_filters.apply_all(query)
ids = [item.id for item in query.all()]
if not ids:
return self.response_404()
export = Dashboard.export_dashboards(ids)
resp = make_response(export, 200)
resp.headers["Content-Disposition"] = generate_download_headers("json")[
"Content-Disposition"
]
return resp
@expose("/<pk>/thumbnail/<digest>/", methods=["GET"])
@protect()
@safe
@rison(thumbnail_query_schema)
def thumbnail(
self, pk: int, digest: str, **kwargs: Dict[str, bool]
) -> WerkzeugResponse:
"""Get Dashboard thumbnail
---
get:
description: >-
Compute async or get already computed dashboard thumbnail from cache.
parameters:
- in: path
schema:
type: integer
name: pk
- in: path
name: digest
description: A hex digest that makes this dashboard unique
schema:
type: string
- in: query
name: q
content:
application/json:
schema:
$ref: '#/components/schemas/thumbnail_query_schema'
responses:
200:
description: Dashboard thumbnail image
content:
image/*:
schema:
type: string
format: binary
202:
description: Thumbnail does not exist on cache, fired async to compute
content:
application/json:
schema:
type: object
properties:
message:
type: string
401:
$ref: '#/components/responses/401'
404:
$ref: '#/components/responses/404'
422:
$ref: '#/components/responses/422'
500:
$ref: '#/components/responses/500'
"""
dashboard = self.datamodel.get(pk, self._base_filters)
if not dashboard:
return self.response_404()
dashboard_url = get_url_path(
"Superset.dashboard", dashboard_id_or_slug=dashboard.id
)
# If force, request a screenshot from the workers
if kwargs["rison"].get("force", False):
cache_dashboard_thumbnail.delay(dashboard_url, dashboard.digest, force=True)
return self.response(202, message="OK Async")
# fetch the dashboard screenshot using the current user and cache if set
screenshot = DashboardScreenshot(
dashboard_url, dashboard.digest
).get_from_cache(cache=thumbnail_cache)
# If the screenshot does not exist, request one from the workers
if not screenshot:
cache_dashboard_thumbnail.delay(dashboard_url, dashboard.digest, force=True)
return self.response(202, message="OK Async")
# If digests
if dashboard.digest != digest:
return redirect(
url_for(
f"{self.__class__.__name__}.thumbnail",
pk=pk,
digest=dashboard.digest,
)
)
return Response(
FileWrapper(screenshot), mimetype="image/png", direct_passthrough=True
)
| superset/dashboards/api.py | 1 | https://github.com/apache/superset/commit/2b061fc64b88831574878b6bd470d700a1527dec | [
0.0004752486711367965,
0.0001784586056601256,
0.00016525189857929945,
0.00017208287317771465,
0.000041238967241952196
] |
{
"id": 8,
"code_window": [
" nullable=True,\n",
" )\n",
"\n",
" @property\n",
" def changed_by_name(self) -> str:\n",
" if self.created_by:\n",
" return escape(\"{}\".format(self.created_by))\n",
" return \"\"\n",
"\n",
" @renders(\"created_by\")\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" if self.changed_by:\n",
" return escape(\"{}\".format(self.changed_by))\n"
],
"file_path": "superset/models/helpers.py",
"type": "replace",
"edit_start_line_idx": 368
} | <!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd" d="M5 18.5058H9.24C9.5058 18.5073 9.76128 18.403 9.95 18.2158L16.87 11.2858L19.71 8.5058C19.8993 8.31803 20.0058 8.06244 20.0058 7.7958C20.0058 7.52916 19.8993 7.27356 19.71 7.0858L15.47 2.7958C15.2822 2.60649 15.0266 2.5 14.76 2.5C14.4934 2.5 14.2378 2.60649 14.05 2.7958L11.23 5.6258L4.29 12.5558C4.10281 12.7445 3.99846 13 4 13.2658V17.5058C4 18.0581 4.44772 18.5058 5 18.5058ZM14.76 4.9158L17.59 7.7458L16.17 9.1658L13.34 6.3358L14.76 4.9158ZM6 13.6758L11.93 7.7458L14.76 10.5758L8.83 16.5058H6V13.6758ZM21 20.5058H3C2.44772 20.5058 2 20.9535 2 21.5058C2 22.0581 2.44772 22.5058 3 22.5058H21C21.5523 22.5058 22 22.0581 22 21.5058C22 20.9535 21.5523 20.5058 21 20.5058Z" fill="currentColor"/>
</svg>
| superset-frontend/images/icons/pencil.svg | 0 | https://github.com/apache/superset/commit/2b061fc64b88831574878b6bd470d700a1527dec | [
0.00017619674326851964,
0.00017127033788710833,
0.00016551351291127503,
0.00017210077203344554,
0.000004400762463774299
] |
{
"id": 8,
"code_window": [
" nullable=True,\n",
" )\n",
"\n",
" @property\n",
" def changed_by_name(self) -> str:\n",
" if self.created_by:\n",
" return escape(\"{}\".format(self.created_by))\n",
" return \"\"\n",
"\n",
" @renders(\"created_by\")\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" if self.changed_by:\n",
" return escape(\"{}\".format(self.changed_by))\n"
],
"file_path": "superset/models/helpers.py",
"type": "replace",
"edit_start_line_idx": 368
} | # 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 Any, Dict
from flask_babel import gettext as _
from marshmallow import fields, post_load, Schema, validate
from marshmallow.validate import Length, Range
from superset.common.query_context import QueryContext
from superset.utils import schema as utils
from superset.utils.core import FilterOperator
#
# RISON/JSON schemas for query parameters
#
get_delete_ids_schema = {"type": "array", "items": {"type": "integer"}}
width_height_schema = {
"type": "array",
"items": [{"type": "integer"}, {"type": "integer"}],
}
thumbnail_query_schema = {
"type": "object",
"properties": {"force": {"type": "boolean"}},
}
screenshot_query_schema = {
"type": "object",
"properties": {
"force": {"type": "boolean"},
"window_size": width_height_schema,
"thumb_size": width_height_schema,
},
}
#
# Column schema descriptions
#
slice_name_description = "The name of the chart."
description_description = "A description of the chart propose."
viz_type_description = "The type of chart visualization used."
owners_description = (
"Owner are users ids allowed to delete or change this chart. "
"If left empty you will be one of the owners of the chart."
)
params_description = (
"Parameters are generated dynamically when clicking the save "
"or overwrite button in the explore view. "
"This JSON object for power users who may want to alter specific parameters."
)
cache_timeout_description = (
"Duration (in seconds) of the caching timeout "
"for this chart. Note this defaults to the datasource/table"
" timeout if undefined."
)
datasource_id_description = (
"The id of the dataset/datasource this new chart will use. "
"A complete datasource identification needs `datasouce_id` "
"and `datasource_type`."
)
datasource_type_description = (
"The type of dataset/datasource identified on `datasource_id`."
)
datasource_name_description = "The datasource name."
dashboards_description = "A list of dashboards to include this new chart to."
#
# OpenAPI method specification overrides
#
openapi_spec_methods_override = {
"get": {"get": {"description": "Get a chart detail information."}},
"get_list": {
"get": {
"description": "Get a list of charts, use Rison or JSON query "
"parameters for filtering, sorting, pagination and "
" for selecting specific columns and metadata.",
}
},
"info": {
"get": {
"description": "Several metadata information about chart API endpoints.",
}
},
"related": {
"get": {"description": "Get a list of all possible owners for a chart."}
},
}
class ChartPostSchema(Schema):
"""
Schema to add a new chart.
"""
slice_name = fields.String(
description=slice_name_description, required=True, validate=Length(1, 250)
)
description = fields.String(description=description_description, allow_none=True)
viz_type = fields.String(
description=viz_type_description,
validate=Length(0, 250),
example=["bar", "line_multi", "area", "table"],
)
owners = fields.List(fields.Integer(description=owners_description))
params = fields.String(
description=params_description, allow_none=True, validate=utils.validate_json
)
cache_timeout = fields.Integer(
description=cache_timeout_description, allow_none=True
)
datasource_id = fields.Integer(description=datasource_id_description, required=True)
datasource_type = fields.String(
description=datasource_type_description,
validate=validate.OneOf(choices=("druid", "table", "view")),
required=True,
)
datasource_name = fields.String(
description=datasource_name_description, allow_none=True
)
dashboards = fields.List(fields.Integer(description=dashboards_description))
class ChartPutSchema(Schema):
"""
Schema to update or patch a chart
"""
slice_name = fields.String(
description=slice_name_description, allow_none=True, validate=Length(0, 250)
)
description = fields.String(description=description_description, allow_none=True)
viz_type = fields.String(
description=viz_type_description,
allow_none=True,
validate=Length(0, 250),
example=["bar", "line_multi", "area", "table"],
)
owners = fields.List(fields.Integer(description=owners_description))
params = fields.String(description=params_description, allow_none=True)
cache_timeout = fields.Integer(
description=cache_timeout_description, allow_none=True
)
datasource_id = fields.Integer(
description=datasource_id_description, allow_none=True
)
datasource_type = fields.String(
description=datasource_type_description,
validate=validate.OneOf(choices=("druid", "table", "view")),
allow_none=True,
)
dashboards = fields.List(fields.Integer(description=dashboards_description))
class ChartGetDatasourceObjectDataResponseSchema(Schema):
datasource_id = fields.Integer(description="The datasource identifier")
datasource_type = fields.Integer(description="The datasource type")
class ChartGetDatasourceObjectResponseSchema(Schema):
label = fields.String(description="The name of the datasource")
value = fields.Nested(ChartGetDatasourceObjectDataResponseSchema)
class ChartGetDatasourceResponseSchema(Schema):
count = fields.Integer(description="The total number of datasources")
result = fields.Nested(ChartGetDatasourceObjectResponseSchema)
class ChartCacheScreenshotResponseSchema(Schema):
cache_key = fields.String(description="The cache key")
chart_url = fields.String(description="The url to render the chart")
image_url = fields.String(description="The url to fetch the screenshot")
class ChartDataColumnSchema(Schema):
column_name = fields.String(
description="The name of the target column", example="mycol",
)
type = fields.String(description="Type of target column", example="BIGINT")
class ChartDataAdhocMetricSchema(Schema):
"""
Ad-hoc metrics are used to define metrics outside the datasource.
"""
expressionType = fields.String(
description="Simple or SQL metric",
required=True,
validate=validate.OneOf(choices=("SIMPLE", "SQL")),
example="SQL",
)
aggregate = fields.String(
description="Aggregation operator. Only required for simple expression types.",
validate=validate.OneOf(
choices=("AVG", "COUNT", "COUNT_DISTINCT", "MAX", "MIN", "SUM")
),
)
column = fields.Nested(ChartDataColumnSchema)
sqlExpression = fields.String(
description="The metric as defined by a SQL aggregate expression. "
"Only required for SQL expression type.",
example="SUM(weight * observations) / SUM(weight)",
)
label = fields.String(
description="Label for the metric. Is automatically generated unless "
"hasCustomLabel is true, in which case label must be defined.",
example="Weighted observations",
)
hasCustomLabel = fields.Boolean(
description="When false, the label will be automatically generated based on "
"the aggregate expression. When true, a custom label has to be "
"specified.",
example=True,
)
optionName = fields.String(
description="Unique identifier. Can be any string value, as long as all "
"metrics have a unique identifier. If undefined, a random name "
"will be generated.",
example="metric_aec60732-fac0-4b17-b736-93f1a5c93e30",
)
class ChartDataAggregateConfigField(fields.Dict):
def __init__(self) -> None:
super().__init__(
description="The keys are the name of the aggregate column to be created, "
"and the values specify the details of how to apply the "
"aggregation. If an operator requires additional options, "
"these can be passed here to be unpacked in the operator call. The "
"following numpy operators are supported: average, argmin, argmax, cumsum, "
"cumprod, max, mean, median, nansum, nanmin, nanmax, nanmean, nanmedian, "
"min, percentile, prod, product, std, sum, var. Any options required by "
"the operator can be passed to the `options` object.\n"
"\n"
"In the example, a new column `first_quantile` is created based on values "
"in the column `my_col` using the `percentile` operator with "
"the `q=0.25` parameter.",
example={
"first_quantile": {
"operator": "percentile",
"column": "my_col",
"options": {"q": 0.25},
}
},
)
class ChartDataPostProcessingOperationOptionsSchema(Schema):
pass
class ChartDataAggregateOptionsSchema(ChartDataPostProcessingOperationOptionsSchema):
"""
Aggregate operation config.
"""
groupby = (
fields.List(
fields.String(
allow_none=False, description="Columns by which to group by",
),
minLength=1,
required=True,
),
)
aggregates = ChartDataAggregateConfigField()
class ChartDataRollingOptionsSchema(ChartDataPostProcessingOperationOptionsSchema):
"""
Rolling operation config.
"""
columns = (
fields.Dict(
description="columns on which to perform rolling, mapping source column to "
"target column. For instance, `{'y': 'y'}` will replace the "
"column `y` with the rolling value in `y`, while `{'y': 'y2'}` "
"will add a column `y2` based on rolling values calculated "
"from `y`, leaving the original column `y` unchanged.",
example={"weekly_rolling_sales": "sales"},
),
)
rolling_type = fields.String(
description="Type of rolling window. Any numpy function will work.",
validate=validate.OneOf(
choices=(
"average",
"argmin",
"argmax",
"cumsum",
"cumprod",
"max",
"mean",
"median",
"nansum",
"nanmin",
"nanmax",
"nanmean",
"nanmedian",
"min",
"percentile",
"prod",
"product",
"std",
"sum",
"var",
)
),
required=True,
example="percentile",
)
window = fields.Integer(
description="Size of the rolling window in days.", required=True, example=7,
)
rolling_type_options = fields.Dict(
desctiption="Optional options to pass to rolling method. Needed for "
"e.g. quantile operation.",
example={},
)
center = fields.Boolean(
description="Should the label be at the center of the window. Default: `false`",
example=False,
)
win_type = fields.String(
description="Type of window function. See "
"[SciPy window functions](https://docs.scipy.org/doc/scipy/reference"
"/signal.windows.html#module-scipy.signal.windows) "
"for more details. Some window functions require passing "
"additional parameters to `rolling_type_options`. For instance, "
"to use `gaussian`, the parameter `std` needs to be provided.",
validate=validate.OneOf(
choices=(
"boxcar",
"triang",
"blackman",
"hamming",
"bartlett",
"parzen",
"bohman",
"blackmanharris",
"nuttall",
"barthann",
"kaiser",
"gaussian",
"general_gaussian",
"slepian",
"exponential",
)
),
)
min_periods = fields.Integer(
description="The minimum amount of periods required for a row to be included "
"in the result set.",
example=7,
)
class ChartDataSelectOptionsSchema(ChartDataPostProcessingOperationOptionsSchema):
"""
Sort operation config.
"""
columns = fields.List(
fields.String(),
description="Columns which to select from the input data, in the desired "
"order. If columns are renamed, the original column name should be "
"referenced here.",
example=["country", "gender", "age"],
)
exclude = fields.List( # type: ignore
fields.String(),
description="Columns to exclude from selection.",
example=["my_temp_column"],
)
rename = fields.List(
fields.Dict(),
description="columns which to rename, mapping source column to target column. "
"For instance, `{'y': 'y2'}` will rename the column `y` to `y2`.",
example=[{"age": "average_age"}],
)
class ChartDataSortOptionsSchema(ChartDataPostProcessingOperationOptionsSchema):
"""
Sort operation config.
"""
columns = fields.Dict(
description="columns by by which to sort. The key specifies the column name, "
"value specifies if sorting in ascending order.",
example={"country": True, "gender": False},
required=True,
)
aggregates = ChartDataAggregateConfigField()
class ChartDataContributionOptionsSchema(ChartDataPostProcessingOperationOptionsSchema):
"""
Contribution operation config.
"""
orientation = fields.String(
description="Should cell values be calculated across the row or column.",
required=True,
validate=validate.OneOf(choices=("row", "column",)),
example="row",
)
class ChartDataPivotOptionsSchema(ChartDataPostProcessingOperationOptionsSchema):
"""
Pivot operation config.
"""
index = (
fields.List(
fields.String(
allow_none=False,
description="Columns to group by on the table index (=rows)",
),
minLength=1,
required=True,
),
)
columns = fields.List(
fields.String(
allow_none=False, description="Columns to group by on the table columns",
),
)
metric_fill_value = fields.Number(
description="Value to replace missing values with in aggregate calculations.",
)
column_fill_value = fields.String(
description="Value to replace missing pivot columns names with."
)
drop_missing_columns = fields.Boolean(
description="Do not include columns whose entries are all missing "
"(default: `true`).",
)
marginal_distributions = fields.Boolean(
description="Add totals for row/column. (default: `false`)",
)
marginal_distribution_name = fields.String(
description="Name of marginal distribution row/column. (default: `All`)",
)
aggregates = ChartDataAggregateConfigField()
class ChartDataGeohashDecodeOptionsSchema(
ChartDataPostProcessingOperationOptionsSchema
):
"""
Geohash decode operation config.
"""
geohash = fields.String(
description="Name of source column containing geohash string", required=True,
)
latitude = fields.String(
description="Name of target column for decoded latitude", required=True,
)
longitude = fields.String(
description="Name of target column for decoded longitude", required=True,
)
class ChartDataGeohashEncodeOptionsSchema(
ChartDataPostProcessingOperationOptionsSchema
):
"""
Geohash encode operation config.
"""
latitude = fields.String(
description="Name of source latitude column", required=True,
)
longitude = fields.String(
description="Name of source longitude column", required=True,
)
geohash = fields.String(
description="Name of target column for encoded geohash string", required=True,
)
class ChartDataGeodeticParseOptionsSchema(
ChartDataPostProcessingOperationOptionsSchema
):
"""
Geodetic point string parsing operation config.
"""
geodetic = fields.String(
description="Name of source column containing geodetic point strings",
required=True,
)
latitude = fields.String(
description="Name of target column for decoded latitude", required=True,
)
longitude = fields.String(
description="Name of target column for decoded longitude", required=True,
)
altitude = fields.String(
description="Name of target column for decoded altitude. If omitted, "
"altitude information in geodetic string is ignored.",
)
class ChartDataPostProcessingOperationSchema(Schema):
operation = fields.String(
description="Post processing operation type",
required=True,
validate=validate.OneOf(
choices=(
"aggregate",
"contribution",
"cum",
"geodetic_parse",
"geohash_decode",
"geohash_encode",
"pivot",
"rolling",
"select",
"sort",
)
),
example="aggregate",
)
options = fields.Dict(
description="Options specifying how to perform the operation. Please refer "
"to the respective post processing operation option schemas. "
"For example, `ChartDataPostProcessingOperationOptions` specifies "
"the required options for the pivot operation.",
example={
"groupby": ["country", "gender"],
"aggregates": {
"age_q1": {
"operator": "percentile",
"column": "age",
"options": {"q": 0.25},
},
"age_mean": {"operator": "mean", "column": "age",},
},
},
)
class ChartDataFilterSchema(Schema):
col = fields.String(
description="The column to filter.", required=True, example="country"
)
op = fields.String( # pylint: disable=invalid-name
description="The comparison operator.",
validate=utils.OneOfCaseInsensitive(
choices=[filter_op.value for filter_op in FilterOperator]
),
required=True,
example="IN",
)
val = fields.Raw(
description="The value or values to compare against. Can be a string, "
"integer, decimal or list, depending on the operator.",
example=["China", "France", "Japan"],
)
class ChartDataExtrasSchema(Schema):
time_range_endpoints = fields.List(
fields.String(
validate=validate.OneOf(choices=("INCLUSIVE", "EXCLUSIVE")),
description="A list with two values, stating if start/end should be "
"inclusive/exclusive.",
)
)
relative_start = fields.String(
description="Start time for relative time deltas. "
'Default: `config["DEFAULT_RELATIVE_START_TIME"]`',
validate=validate.OneOf(choices=("today", "now")),
)
relative_end = fields.String(
description="End time for relative time deltas. "
'Default: `config["DEFAULT_RELATIVE_START_TIME"]`',
validate=validate.OneOf(choices=("today", "now")),
)
where = fields.String(
description="WHERE clause to be added to queries using AND operator.",
)
having = fields.String(
description="HAVING clause to be added to aggregate queries using "
"AND operator.",
)
having_druid = fields.List(
fields.Nested(ChartDataFilterSchema),
description="HAVING filters to be added to legacy Druid datasource queries.",
)
time_grain_sqla = fields.String(
description="To what level of granularity should the temporal column be "
"aggregated. Supports "
"[ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#Durations) durations.",
validate=validate.OneOf(
choices=(
"PT1S",
"PT1M",
"PT5M",
"PT10M",
"PT15M",
"PT0.5H",
"PT1H",
"P1D",
"P1W",
"P1M",
"P0.25Y",
"P1Y",
"1969-12-28T00:00:00Z/P1W", # Week starting Sunday
"1969-12-29T00:00:00Z/P1W", # Week starting Monday
"P1W/1970-01-03T00:00:00Z", # Week ending Saturday
"P1W/1970-01-04T00:00:00Z", # Week ending Sunday
),
),
example="P1D",
allow_none=True,
)
druid_time_origin = fields.String(
description="Starting point for time grain counting on legacy Druid "
"datasources. Used to change e.g. Monday/Sunday first-day-of-week.",
allow_none=True,
)
class ChartDataQueryObjectSchema(Schema):
filters = fields.List(fields.Nested(ChartDataFilterSchema), required=False)
granularity = fields.String(
description="Name of temporal column used for time filtering. For legacy Druid "
"datasources this defines the time grain.",
)
granularity_sqla = fields.String(
description="Name of temporal column used for time filtering for SQL "
"datasources. This field is deprecated, use `granularity` "
"instead.",
deprecated=True,
)
groupby = fields.List(
fields.String(description="Columns by which to group the query.",),
)
metrics = fields.List(
fields.Raw(),
description="Aggregate expressions. Metrics can be passed as both "
"references to datasource metrics (strings), or ad-hoc metrics"
"which are defined only within the query object. See "
"`ChartDataAdhocMetricSchema` for the structure of ad-hoc metrics.",
)
post_processing = fields.List(
fields.Nested(ChartDataPostProcessingOperationSchema, allow_none=True),
description="Post processing operations to be applied to the result set. "
"Operations are applied to the result set in sequential order.",
)
time_range = fields.String(
description="A time rage, either expressed as a colon separated string "
"`since : until` or human readable freeform. Valid formats for "
"`since` and `until` are: \n"
"- ISO 8601\n"
"- X days/years/hours/day/year/weeks\n"
"- X days/years/hours/day/year/weeks ago\n"
"- X days/years/hours/day/year/weeks from now\n"
"\n"
"Additionally, the following freeform can be used:\n"
"\n"
"- Last day\n"
"- Last week\n"
"- Last month\n"
"- Last quarter\n"
"- Last year\n"
"- No filter\n"
"- Last X seconds/minutes/hours/days/weeks/months/years\n"
"- Next X seconds/minutes/hours/days/weeks/months/years\n",
example="Last week",
)
time_shift = fields.String(
description="A human-readable date/time string. "
"Please refer to [parsdatetime](https://github.com/bear/parsedatetime) "
"documentation for details on valid values.",
)
is_timeseries = fields.Boolean(
description="Is the `query_object` a timeseries.", required=False
)
timeseries_limit = fields.Integer(
description="Maximum row count for timeseries queries. Default: `0`",
)
timeseries_limit_metric = fields.Raw(
description="Metric used to limit timeseries queries by.", allow_none=True,
)
row_limit = fields.Integer(
description='Maximum row count. Default: `config["ROW_LIMIT"]`',
validate=[
Range(min=1, error=_("`row_limit` must be greater than or equal to 1"))
],
)
row_offset = fields.Integer(
description="Number of rows to skip. Default: `0`",
validate=[
Range(min=0, error=_("`row_offset` must be greater than or equal to 0"))
],
)
order_desc = fields.Boolean(
description="Reverse order. Default: `false`", required=False
)
extras = fields.Nested(ChartDataExtrasSchema, required=False)
columns = fields.List(fields.String(), description="",)
orderby = fields.List(
fields.List(fields.Raw()),
description="Expects a list of lists where the first element is the column "
"name which to sort by, and the second element is a boolean ",
example=[["my_col_1", False], ["my_col_2", True]],
)
where = fields.String(
description="WHERE clause to be added to queries using AND operator."
"This field is deprecated and should be passed to `extras`.",
deprecated=True,
)
having = fields.String(
description="HAVING clause to be added to aggregate queries using "
"AND operator. This field is deprecated and should be passed "
"to `extras`.",
deprecated=True,
)
having_filters = fields.List(
fields.Dict(),
description="HAVING filters to be added to legacy Druid datasource queries. "
"This field is deprecated and should be passed to `extras` "
"as `filters_druid`.",
deprecated=True,
)
class ChartDataDatasourceSchema(Schema):
description = "Chart datasource"
id = fields.Integer(description="Datasource id", required=True,)
type = fields.String(
description="Datasource type",
validate=validate.OneOf(choices=("druid", "table")),
)
class ChartDataQueryContextSchema(Schema):
datasource = fields.Nested(ChartDataDatasourceSchema)
queries = fields.List(fields.Nested(ChartDataQueryObjectSchema))
force = fields.Boolean(
description="Should the queries be forced to load from the source. "
"Default: `false`",
)
result_type = fields.String(
description="Type of results to return",
validate=validate.OneOf(choices=("full", "query", "results", "samples")),
)
result_format = fields.String(
description="Format of result payload",
validate=validate.OneOf(choices=("json", "csv")),
)
# pylint: disable=no-self-use,unused-argument
@post_load
def make_query_context(self, data: Dict[str, Any], **kwargs: Any) -> QueryContext:
query_context = QueryContext(**data)
return query_context
# pylint: enable=no-self-use,unused-argument
class ChartDataResponseResult(Schema):
cache_key = fields.String(
description="Unique cache key for query object", required=True, allow_none=True,
)
cached_dttm = fields.String(
description="Cache timestamp", required=True, allow_none=True,
)
cache_timeout = fields.Integer(
description="Cache timeout in following order: custom timeout, datasource "
"timeout, default config timeout.",
required=True,
allow_none=True,
)
error = fields.String(description="Error", allow_none=True,)
is_cached = fields.Boolean(
description="Is the result cached", required=True, allow_none=None,
)
query = fields.String(
description="The executed query statement", required=True, allow_none=False,
)
status = fields.String(
description="Status of the query",
validate=validate.OneOf(
choices=(
"stopped",
"failed",
"pending",
"running",
"scheduled",
"success",
"timed_out",
)
),
allow_none=False,
)
stacktrace = fields.String(
desciption="Stacktrace if there was an error", allow_none=True,
)
rowcount = fields.Integer(
description="Amount of rows in result set", allow_none=False,
)
data = fields.List(fields.Dict(), description="A list with results")
class ChartDataResponseSchema(Schema):
result = fields.List(
fields.Nested(ChartDataResponseResult),
description="A list of results for each corresponding query in the request.",
)
CHART_SCHEMAS = (
ChartDataQueryContextSchema,
ChartDataResponseSchema,
# TODO: These should optimally be included in the QueryContext schema as an `anyOf`
# in ChartDataPostPricessingOperation.options, but since `anyOf` is not
# by Marshmallow<3, this is not currently possible.
ChartDataAdhocMetricSchema,
ChartDataAggregateOptionsSchema,
ChartDataContributionOptionsSchema,
ChartDataPivotOptionsSchema,
ChartDataRollingOptionsSchema,
ChartDataSelectOptionsSchema,
ChartDataSortOptionsSchema,
ChartDataGeohashDecodeOptionsSchema,
ChartDataGeohashEncodeOptionsSchema,
ChartDataGeodeticParseOptionsSchema,
ChartGetDatasourceResponseSchema,
ChartCacheScreenshotResponseSchema,
)
| superset/charts/schemas.py | 0 | https://github.com/apache/superset/commit/2b061fc64b88831574878b6bd470d700a1527dec | [
0.06464944779872894,
0.001678698929026723,
0.0001632106868783012,
0.00017185078468173742,
0.007367373909801245
] |
{
"id": 8,
"code_window": [
" nullable=True,\n",
" )\n",
"\n",
" @property\n",
" def changed_by_name(self) -> str:\n",
" if self.created_by:\n",
" return escape(\"{}\".format(self.created_by))\n",
" return \"\"\n",
"\n",
" @renders(\"created_by\")\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" if self.changed_by:\n",
" return escape(\"{}\".format(self.changed_by))\n"
],
"file_path": "superset/models/helpers.py",
"type": "replace",
"edit_start_line_idx": 368
} | # 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 new field 'is_restricted' to SqlMetric and DruidMetric
Revision ID: d8bc074f7aad
Revises: 1226819ee0e3
Create Date: 2016-06-07 12:33:25.756640
"""
# revision identifiers, used by Alembic.
revision = "d8bc074f7aad"
down_revision = "1226819ee0e3"
import sqlalchemy as sa
from alembic import op
from sqlalchemy import Boolean, Column, Integer
from sqlalchemy.ext.declarative import declarative_base
from superset import db
Base = declarative_base()
class DruidMetric(Base):
"""Declarative class used to do query in upgrade"""
__tablename__ = "metrics"
id = Column(Integer, primary_key=True)
is_restricted = Column(Boolean, default=False, nullable=True)
class SqlMetric(Base):
"""Declarative class used to do query in upgrade"""
__tablename__ = "sql_metrics"
id = Column(Integer, primary_key=True)
is_restricted = Column(Boolean, default=False, nullable=True)
def upgrade():
op.add_column("metrics", sa.Column("is_restricted", sa.Boolean(), nullable=True))
op.add_column(
"sql_metrics", sa.Column("is_restricted", sa.Boolean(), nullable=True)
)
bind = op.get_bind()
session = db.Session(bind=bind)
# don't use models.DruidMetric
# because it assumes the context is consistent with the application
for obj in session.query(DruidMetric).all():
obj.is_restricted = False
for obj in session.query(SqlMetric).all():
obj.is_restricted = False
session.commit()
session.close()
def downgrade():
with op.batch_alter_table("sql_metrics", schema=None) as batch_op:
batch_op.drop_column("is_restricted")
with op.batch_alter_table("metrics", schema=None) as batch_op:
batch_op.drop_column("is_restricted")
| superset/migrations/versions/d8bc074f7aad_add_new_field_is_restricted_to_.py | 0 | https://github.com/apache/superset/commit/2b061fc64b88831574878b6bd470d700a1527dec | [
0.0011531624477356672,
0.00028191402088850737,
0.0001656327222008258,
0.0001744328619679436,
0.0003080457681789994
] |
{
"id": 0,
"code_window": [
"import React, { Fragment, useState } from 'react';\n",
"import { DatePicker } from 'material-ui-pickers';\n",
"\n",
"function YearMonthPicker(props) {\n",
" const [selectedDate, handleDateChange] = useState(new Date());\n",
"\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { DatePicker, InlineDatePicker } from 'material-ui-pickers';\n"
],
"file_path": "docs/pages/api/datepicker/ViewsDatePicker.example.jsx",
"type": "replace",
"edit_start_line_idx": 1
} | import clsx from 'clsx';
import * as PropTypes from 'prop-types';
import * as React from 'react';
import createStyles from '@material-ui/core/styles/createStyles';
import withStyles, { WithStyles } from '@material-ui/core/styles/withStyles';
import { isYearAndMonthViews, isYearOnlyView } from '../_helpers/date-utils';
import PickerToolbar from '../_shared/PickerToolbar';
import ToolbarButton from '../_shared/ToolbarButton';
import { withUtils, WithUtilsProps } from '../_shared/WithUtils';
import { DatePickerViewType } from '../constants/DatePickerView';
import { DateType, DomainPropTypes } from '../constants/prop-types';
import { MaterialUiPickersDate } from '../typings/date';
import Calendar, { RenderDay } from './components/Calendar';
import MonthSelection from './components/MonthSelection';
import YearSelection from './components/YearSelection';
export interface BaseDatePickerProps {
/** Min selectable date */
minDate?: DateType;
/** Max selectable date */
maxDate?: DateType;
/** Disable past dates */
disablePast?: boolean;
/** Disable future dates */
disableFuture?: boolean;
/** To animate scrolling to current year (with scrollIntoView) */
animateYearScrolling?: boolean;
/** Array of views to show. Order year -> month -> day */
views?: Array<'year' | 'month' | 'day'>;
/** Initial view to show when date picker is open */
openTo?: 'year' | 'month' | 'day';
/** @deprecated use openTo instead */
openToYearSelection?: boolean;
/** Left arrow icon */
leftArrowIcon?: React.ReactNode;
/** Right arrow icon */
rightArrowIcon?: React.ReactNode;
/** Custom renderer for day */
renderDay?: RenderDay;
/** Enables keyboard listener for moving between days in calendar */
allowKeyboardControl?: boolean;
/** Disable specific date */
shouldDisableDate?: (day: MaterialUiPickersDate) => boolean;
initialFocusedDate?: DateType;
}
export interface DatePickerProps
extends BaseDatePickerProps,
WithStyles<typeof styles>,
WithUtilsProps {
date: MaterialUiPickersDate;
onChange: (date: MaterialUiPickersDate, isFinished?: boolean) => void;
}
interface DatePickerState {
openView: DatePickerViewType;
}
export class DatePicker extends React.PureComponent<DatePickerProps> {
public static propTypes: any = {
views: PropTypes.arrayOf(DomainPropTypes.datePickerView),
openTo: DomainPropTypes.datePickerView,
openToYearSelection: PropTypes.bool,
};
public static defaultProps = {
minDate: new Date('1900-01-01'),
maxDate: new Date('2100-01-01'),
openToYearSelection: false,
views: ['year', 'day'] as DatePickerViewType[],
};
public state: DatePickerState = {
// TODO in v3 remove openToYearSelection
openView:
this.props.openTo || this.props.openToYearSelection!
? 'year'
: this.props.views![this.props.views!.length - 1],
};
get date() {
return this.props.date;
}
get minDate() {
return this.props.utils.date(this.props.minDate);
}
get maxDate() {
return this.props.utils.date(this.props.maxDate);
}
get isYearOnly() {
return isYearOnlyView(this.props.views!);
}
get isYearAndMonth() {
return isYearAndMonthViews(this.props.views!);
}
public handleYearSelect = (date: MaterialUiPickersDate) => {
this.props.onChange(date, this.isYearOnly);
if (this.isYearOnly) {
return;
}
if (this.props.views!.includes('month')) {
return this.openMonthSelection();
}
this.openCalendar();
};
public handleMonthSelect = (date: MaterialUiPickersDate) => {
const isFinish = !this.props.views!.includes('day');
this.props.onChange(date, isFinish);
if (!isFinish) {
this.openCalendar();
}
};
public openYearSelection = () => {
this.setState({ openView: 'year' });
};
public openCalendar = () => {
this.setState({ openView: 'day' });
};
public openMonthSelection = () => {
this.setState({ openView: 'month' });
};
public render() {
const { openView } = this.state;
const {
disablePast,
disableFuture,
onChange,
animateYearScrolling,
leftArrowIcon,
rightArrowIcon,
renderDay,
utils,
shouldDisableDate,
allowKeyboardControl,
classes,
} = this.props;
return (
<>
<PickerToolbar className={clsx({ [classes.toolbarCenter]: this.isYearOnly })}>
<ToolbarButton
variant={this.isYearOnly ? 'h3' : 'subtitle1'}
onClick={this.isYearOnly ? undefined : this.openYearSelection}
selected={openView === 'year'}
label={utils.getYearText(this.date)}
/>
{!this.isYearOnly &&
!this.isYearAndMonth && (
<ToolbarButton
variant="h4"
onClick={this.openCalendar}
selected={openView === 'day'}
label={utils.getDatePickerHeaderText(this.date)}
/>
)}
{this.isYearAndMonth && (
<ToolbarButton
variant="h4"
onClick={this.openMonthSelection}
selected={openView === 'month'}
label={utils.getMonthText(this.date)}
/>
)}
</PickerToolbar>
{this.props.children}
{openView === 'year' && (
<YearSelection
date={this.date}
onChange={this.handleYearSelect}
minDate={this.minDate}
maxDate={this.maxDate}
disablePast={disablePast}
disableFuture={disableFuture}
animateYearScrolling={animateYearScrolling}
/>
)}
{openView === 'month' && (
<MonthSelection
date={this.date}
onChange={this.handleMonthSelect}
minDate={this.minDate}
maxDate={this.maxDate}
disablePast={disablePast}
disableFuture={disableFuture}
/>
)}
{openView === 'day' && (
<Calendar
date={this.date}
onChange={onChange}
disablePast={disablePast}
disableFuture={disableFuture}
minDate={this.minDate}
maxDate={this.maxDate}
leftArrowIcon={leftArrowIcon}
rightArrowIcon={rightArrowIcon}
renderDay={renderDay}
shouldDisableDate={shouldDisableDate}
allowKeyboardControl={allowKeyboardControl}
/>
)}
</>
);
}
}
export const styles = () =>
createStyles({
toolbarCenter: {
flexDirection: 'row',
alignItems: 'center',
},
});
export default withStyles(styles)(withUtils()(DatePicker));
| lib/src/DatePicker/DatePicker.tsx | 1 | https://github.com/mui/material-ui/commit/f36f617f4b16bdc03964778764e17bd47247b086 | [
0.010741996578872204,
0.0016868490492925048,
0.00016612382023595273,
0.000340937142027542,
0.0028784105088561773
] |
{
"id": 0,
"code_window": [
"import React, { Fragment, useState } from 'react';\n",
"import { DatePicker } from 'material-ui-pickers';\n",
"\n",
"function YearMonthPicker(props) {\n",
" const [selectedDate, handleDateChange] = useState(new Date());\n",
"\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { DatePicker, InlineDatePicker } from 'material-ui-pickers';\n"
],
"file_path": "docs/pages/api/datepicker/ViewsDatePicker.example.jsx",
"type": "replace",
"edit_start_line_idx": 1
} | import { DateTimePickerInlineProps } from './DateTimePickerInline';
import { DateTimePickerModalProps } from './DateTimePickerModal';
export type DateTimePickerProps = DateTimePickerModalProps;
export type DateTimePickerInlineProps = DateTimePickerInlineProps;
export { default } from './DateTimePickerModal';
export { default as InlineDateTimePicker } from './DateTimePickerInline';
| lib/src/DateTimePicker/index.ts | 0 | https://github.com/mui/material-ui/commit/f36f617f4b16bdc03964778764e17bd47247b086 | [
0.00019238132517784834,
0.00018504646141082048,
0.0001777115830918774,
0.00018504646141082048,
0.000007334871042985469
] |
{
"id": 0,
"code_window": [
"import React, { Fragment, useState } from 'react';\n",
"import { DatePicker } from 'material-ui-pickers';\n",
"\n",
"function YearMonthPicker(props) {\n",
" const [selectedDate, handleDateChange] = useState(new Date());\n",
"\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { DatePicker, InlineDatePicker } from 'material-ui-pickers';\n"
],
"file_path": "docs/pages/api/datepicker/ViewsDatePicker.example.jsx",
"type": "replace",
"edit_start_line_idx": 1
} | import React from 'react';
import { DatePicker } from 'material-ui-pickers';
import { Formik, Form, Field } from 'formik';
import Code from '../../_shared/Code';
import { Grid } from '@material-ui/core';
const DatePickerField = ({ field, form, ...other }) => {
const currentError = form.errors[field.name];
return (
<DatePicker
keyboard
clearable
disablePast
name={field.name}
value={field.value}
format="dd/MM/yyyy"
helperText={currentError}
error={Boolean(currentError)}
onError={(_, error) => form.setFieldError(field.name, error)}
onChange={date => form.setFieldValue(field.name, date, true)}
mask={value => (value ? [/\d/, /\d/, '/', /\d/, /\d/, '/', /\d/, /\d/, /\d/, /\d/] : [])}
{...other}
/>
);
};
const FormikExample = () => {
return (
<Formik initialValues={{ date: new Date() }}>
{({ values, errors }) => (
<Form>
<Grid container>
<Grid item container justify="center" xs={12}>
<div className="picker">
<Field name="date" component={DatePickerField} />
</div>
</Grid>
<Grid item xs={12} sm={12} style={{ margin: '24px' }}>
<Code children={JSON.stringify({ errors, values }, null, 2)} />
</Grid>
</Grid>
</Form>
)}
</Formik>
);
};
export default FormikExample;
| docs/pages/guides/Formik.example.jsx | 0 | https://github.com/mui/material-ui/commit/f36f617f4b16bdc03964778764e17bd47247b086 | [
0.0004214607470203191,
0.00022137849009595811,
0.00016438111197203398,
0.0001747271599015221,
0.00010015466250479221
] |
{
"id": 0,
"code_window": [
"import React, { Fragment, useState } from 'react';\n",
"import { DatePicker } from 'material-ui-pickers';\n",
"\n",
"function YearMonthPicker(props) {\n",
" const [selectedDate, handleDateChange] = useState(new Date());\n",
"\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { DatePicker, InlineDatePicker } from 'material-ui-pickers';\n"
],
"file_path": "docs/pages/api/datepicker/ViewsDatePicker.example.jsx",
"type": "replace",
"edit_start_line_idx": 1
} | import { ShallowWrapper } from 'enzyme';
import * as React from 'react';
import { DateTimePicker, DateTimePickerProps } from '../../DateTimePicker/DateTimePicker';
import { shallow, utilsToUse } from '../test-utils';
describe('DateTimePicker', () => {
let component: ShallowWrapper<DateTimePickerProps>;
beforeEach(() => {
component = shallow(
<DateTimePicker
date={utilsToUse.date('01-01-2017')}
classes={{} as any}
utils={utilsToUse}
onChange={jest.fn()}
/>
);
});
it('Should renders', () => {
// console.log(component.debug());
expect(component).toBeTruthy();
});
});
| lib/src/__tests__/DateTimePicker/DateTimePicker.test.tsx | 0 | https://github.com/mui/material-ui/commit/f36f617f4b16bdc03964778764e17bd47247b086 | [
0.00018390972400084138,
0.0001751981326378882,
0.0001660503476159647,
0.00017563434084877372,
0.000007297581305465428
] |
{
"id": 1,
"code_window": [
" />\n",
" </div>\n",
"\n",
" <div className=\"picker\">\n",
" <DatePicker\n",
" views={['year', 'month']}\n",
" openTo=\"year\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep"
],
"after_edit": [
" <InlineDatePicker\n"
],
"file_path": "docs/pages/api/datepicker/ViewsDatePicker.example.jsx",
"type": "replace",
"edit_start_line_idx": 31
} | import React, { Fragment, useState } from 'react';
import { DatePicker } from 'material-ui-pickers';
function YearMonthPicker(props) {
const [selectedDate, handleDateChange] = useState(new Date());
return (
<Fragment>
<div className="picker">
<DatePicker
views={['year']}
label="Year only"
value={selectedDate}
onChange={handleDateChange}
animateYearScrolling
/>
</div>
<div className="picker">
<DatePicker
views={['year', 'month']}
label="Year and Month"
helperText="With min and max"
minDate={new Date('2018-03-01')}
maxDate={new Date('2018-06-01')}
value={selectedDate}
onChange={handleDateChange}
/>
</div>
<div className="picker">
<DatePicker
views={['year', 'month']}
openTo="year"
label="Year and Month"
helperText="Start from year selection"
value={selectedDate}
onChange={handleDateChange}
/>
</div>
</Fragment>
);
}
export default YearMonthPicker;
| docs/pages/api/datepicker/ViewsDatePicker.example.jsx | 1 | https://github.com/mui/material-ui/commit/f36f617f4b16bdc03964778764e17bd47247b086 | [
0.4040522575378418,
0.09036540240049362,
0.001172305317595601,
0.009835951030254364,
0.15728965401649475
] |
{
"id": 1,
"code_window": [
" />\n",
" </div>\n",
"\n",
" <div className=\"picker\">\n",
" <DatePicker\n",
" views={['year', 'month']}\n",
" openTo=\"year\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep"
],
"after_edit": [
" <InlineDatePicker\n"
],
"file_path": "docs/pages/api/datepicker/ViewsDatePicker.example.jsx",
"type": "replace",
"edit_start_line_idx": 31
} | import Example from '_shared/Example'
import PageMeta from '_shared/PageMeta'
import PropTypesTable from '_shared/PropTypesTable'
import * as BasicTimePicker from './BasicTimePicker.example'
import * as InlineTimePicker from './InlineTimePicker.example'
import * as SecondsTimePicker from './SecondsTimePicker.example'
import * as KeyboardTimePicker from './KeyboardTimePicker.example'
<PageMeta component="Timepicker" />
## Time Picker
Time pickers use a dialog to select a single time (in the hours:minutes format).
The selected time is indicated by the filled circle at the end of the clock hand.
#### Basic usage
A time picker should adjusts to a user’s preferred time setting, i.e. the 12-hour or 24-hour format.
<Example source={BasicTimePicker} />
#### Keyboard input
<Example source={KeyboardTimePicker} />
#### Inline mode
<Example source={InlineTimePicker} />
#### Seconds
Seconds input can be used for selection of precise time point
<Example source={SecondsTimePicker} />
<PropTypesTable src="TimePicker/TimePickerModal.tsx" />
| docs/pages/api/timepicker/index.mdx | 0 | https://github.com/mui/material-ui/commit/f36f617f4b16bdc03964778764e17bd47247b086 | [
0.00025416826247237623,
0.00018778498633764684,
0.0001630571496207267,
0.00016695726662874222,
0.00003836012911051512
] |
{
"id": 1,
"code_window": [
" />\n",
" </div>\n",
"\n",
" <div className=\"picker\">\n",
" <DatePicker\n",
" views={['year', 'month']}\n",
" openTo=\"year\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep"
],
"after_edit": [
" <InlineDatePicker\n"
],
"file_path": "docs/pages/api/datepicker/ViewsDatePicker.example.jsx",
"type": "replace",
"edit_start_line_idx": 31
} | import { ShallowWrapper } from 'enzyme';
import * as React from 'react';
import { DatePickerInline, DatePickerInlineProps } from '../../DatePicker/DatePickerInline';
import { shallow, utilsToUse } from '../test-utils';
describe('DatePicker', () => {
let component: ShallowWrapper<DatePickerInlineProps>;
beforeEach(() => {
component = shallow(
<DatePickerInline value={utilsToUse.date('01-01-2017')} onChange={jest.fn()} />
);
});
it('Should renders', () => {
// console.log(component.debug());
expect(component).toBeTruthy();
});
});
| lib/src/__tests__/DatePicker/DatePickerInline.test.tsx | 0 | https://github.com/mui/material-ui/commit/f36f617f4b16bdc03964778764e17bd47247b086 | [
0.00024217231839429587,
0.00021744775585830212,
0.00019272319332230836,
0.00021744775585830212,
0.000024724562535993755
] |
{
"id": 1,
"code_window": [
" />\n",
" </div>\n",
"\n",
" <div className=\"picker\">\n",
" <DatePicker\n",
" views={['year', 'month']}\n",
" openTo=\"year\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep"
],
"after_edit": [
" <InlineDatePicker\n"
],
"file_path": "docs/pages/api/datepicker/ViewsDatePicker.example.jsx",
"type": "replace",
"edit_start_line_idx": 31
} | import * as PropTypes from 'prop-types';
import * as React from 'react';
export interface DayWrapperProps {
children: React.ReactNode;
dayInCurrentMonth?: boolean;
disabled?: boolean;
onSelect: (value: any) => void;
value: any;
}
class DayWrapper extends React.PureComponent<DayWrapperProps> {
public static propTypes: any = {
children: PropTypes.node.isRequired,
dayInCurrentMonth: PropTypes.bool,
disabled: PropTypes.bool,
onSelect: PropTypes.func.isRequired,
value: PropTypes.any.isRequired,
};
public static defaultProps = {
dayInCurrentMonth: true,
disabled: false,
};
public handleClick = () => {
this.props.onSelect(this.props.value);
};
public render() {
const { children, value, dayInCurrentMonth, disabled, onSelect, ...other } = this.props;
return (
<div
onClick={dayInCurrentMonth && !disabled ? this.handleClick : undefined}
onKeyPress={dayInCurrentMonth && !disabled ? this.handleClick : undefined}
role="presentation"
{...other}
>
{children}
</div>
);
}
}
export default DayWrapper;
| lib/src/DatePicker/components/DayWrapper.tsx | 0 | https://github.com/mui/material-ui/commit/f36f617f4b16bdc03964778764e17bd47247b086 | [
0.0002585143956821412,
0.00021259431377984583,
0.00016784420586191118,
0.00022962535149417818,
0.000037302019336493686
] |
{
"id": 2,
"code_window": [
" openTo=\"year\"\n",
" label=\"Year and Month\"\n",
" helperText=\"Start from year selection\"\n",
" value={selectedDate}\n"
],
"labels": [
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" views={['year', 'month']}\n"
],
"file_path": "docs/pages/api/datepicker/ViewsDatePicker.example.jsx",
"type": "add",
"edit_start_line_idx": 34
} | import React, { Fragment, useState } from 'react';
import { DatePicker } from 'material-ui-pickers';
function YearMonthPicker(props) {
const [selectedDate, handleDateChange] = useState(new Date());
return (
<Fragment>
<div className="picker">
<DatePicker
views={['year']}
label="Year only"
value={selectedDate}
onChange={handleDateChange}
animateYearScrolling
/>
</div>
<div className="picker">
<DatePicker
views={['year', 'month']}
label="Year and Month"
helperText="With min and max"
minDate={new Date('2018-03-01')}
maxDate={new Date('2018-06-01')}
value={selectedDate}
onChange={handleDateChange}
/>
</div>
<div className="picker">
<DatePicker
views={['year', 'month']}
openTo="year"
label="Year and Month"
helperText="Start from year selection"
value={selectedDate}
onChange={handleDateChange}
/>
</div>
</Fragment>
);
}
export default YearMonthPicker;
| docs/pages/api/datepicker/ViewsDatePicker.example.jsx | 1 | https://github.com/mui/material-ui/commit/f36f617f4b16bdc03964778764e17bd47247b086 | [
0.4850648045539856,
0.09952406585216522,
0.0001672640792094171,
0.002286619506776333,
0.1927984207868576
] |
{
"id": 2,
"code_window": [
" openTo=\"year\"\n",
" label=\"Year and Month\"\n",
" helperText=\"Start from year selection\"\n",
" value={selectedDate}\n"
],
"labels": [
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" views={['year', 'month']}\n"
],
"file_path": "docs/pages/api/datepicker/ViewsDatePicker.example.jsx",
"type": "add",
"edit_start_line_idx": 34
} | import * as PropTypes from 'prop-types';
import * as React from 'react';
export interface DayWrapperProps {
children: React.ReactNode;
dayInCurrentMonth?: boolean;
disabled?: boolean;
onSelect: (value: any) => void;
value: any;
}
class DayWrapper extends React.PureComponent<DayWrapperProps> {
public static propTypes: any = {
children: PropTypes.node.isRequired,
dayInCurrentMonth: PropTypes.bool,
disabled: PropTypes.bool,
onSelect: PropTypes.func.isRequired,
value: PropTypes.any.isRequired,
};
public static defaultProps = {
dayInCurrentMonth: true,
disabled: false,
};
public handleClick = () => {
this.props.onSelect(this.props.value);
};
public render() {
const { children, value, dayInCurrentMonth, disabled, onSelect, ...other } = this.props;
return (
<div
onClick={dayInCurrentMonth && !disabled ? this.handleClick : undefined}
onKeyPress={dayInCurrentMonth && !disabled ? this.handleClick : undefined}
role="presentation"
{...other}
>
{children}
</div>
);
}
}
export default DayWrapper;
| lib/src/DatePicker/components/DayWrapper.tsx | 0 | https://github.com/mui/material-ui/commit/f36f617f4b16bdc03964778764e17bd47247b086 | [
0.00021008991461712867,
0.0001781988248694688,
0.00016632559709250927,
0.00017086805019062012,
0.00001609058199392166
] |
{
"id": 2,
"code_window": [
" openTo=\"year\"\n",
" label=\"Year and Month\"\n",
" helperText=\"Start from year selection\"\n",
" value={selectedDate}\n"
],
"labels": [
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" views={['year', 'month']}\n"
],
"file_path": "docs/pages/api/datepicker/ViewsDatePicker.example.jsx",
"type": "add",
"edit_start_line_idx": 34
} | {
"compilerOptions": {
"baseUrl": ".",
"allowJs": true,
"allowSyntheticDefaultImports": true,
"jsx": "preserve",
"lib": ["dom", "es2017"],
"module": "esnext",
"moduleResolution": "node",
"noEmit": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"preserveConstEnums": true,
"removeComments": false,
"skipLibCheck": true,
"sourceMap": true,
"strict": true,
"target": "esnext",
"checkJs": true,
"resolveJsonModule": true,
"paths": {
"material-ui-pickers": ["./material-ui-pickers-build"]
}
}
}
| docs/tsconfig.json | 0 | https://github.com/mui/material-ui/commit/f36f617f4b16bdc03964778764e17bd47247b086 | [
0.00017589394701644778,
0.00017441401723772287,
0.0001731989614199847,
0.0001741491723805666,
0.0000011160489066242008
] |
{
"id": 2,
"code_window": [
" openTo=\"year\"\n",
" label=\"Year and Month\"\n",
" helperText=\"Start from year selection\"\n",
" value={selectedDate}\n"
],
"labels": [
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" views={['year', 'month']}\n"
],
"file_path": "docs/pages/api/datepicker/ViewsDatePicker.example.jsx",
"type": "add",
"edit_start_line_idx": 34
} | import * as PropTypes from 'prop-types';
import * as React from 'react';
import IconButton, { IconButtonProps as MuiIconButtonProps } from '@material-ui/core/IconButton';
import { InputProps as InputPropsType } from '@material-ui/core/Input';
import InputAdornment, {
InputAdornmentProps as MuiInputAdornmentProps,
} from '@material-ui/core/InputAdornment';
import TextField, { BaseTextFieldProps, TextFieldProps } from '@material-ui/core/TextField';
import { MaskedInputProps } from 'react-text-mask';
import { getDisplayDate, getError } from '../_helpers/text-field-helper';
import { DateType, DomainPropTypes } from '../constants/prop-types';
import { MaterialUiPickersDate } from '../typings/date';
import { ExtendMui } from '../typings/extendMui';
import { KeyboardIcon } from './icons/KeyboardIcon';
import MaskedInput from './MaskedInput';
import { withUtils, WithUtilsProps } from './WithUtils';
export interface DateTextFieldProps
extends WithUtilsProps,
ExtendMui<BaseTextFieldProps, 'onError' | 'onChange' | 'value'> {
// Properly extend different variants from mui textfield
variant?: TextFieldProps['variant'];
InputProps?: TextFieldProps['InputProps'];
inputProps?: TextFieldProps['inputProps'];
value: DateType;
minDate?: DateType;
/** Error message, shown if date is less then minimal date */
minDateMessage?: React.ReactNode;
disablePast?: boolean;
disableFuture?: boolean;
maxDate?: DateType;
/** Error message, shown if date is more then maximal date */
maxDateMessage?: React.ReactNode;
/** Input mask, used in keyboard mode read more <a href="https://github.com/text-mask/text-mask/blob/master/componentDocumentation.md#readme">here</a> */
mask?: MaskedInputProps['mask'];
pipe?: any;
keepCharPositions?: boolean;
onChange: (date: MaterialUiPickersDate) => void;
onClear?: () => void;
/** On/off manual keyboard input mode */
keyboard?: boolean;
/** Format string */
format: string;
/** Message displaying in text field, if date is invalid (doesn't work in keyboard mode) */
invalidLabel?: string;
/** Message displaying in text field, if null passed (doesn't work in keyboard mode) */
emptyLabel?: string;
/** Do not open picker on enter keypress */
disableOpenOnEnter?: boolean;
/** Dynamic label generation function */
labelFunc?: (date: MaterialUiPickersDate, invalidLabel: string) => string;
/** Icon displayed for open picker button in keyboard mode */
keyboardIcon?: React.ReactNode;
/** Message, appearing when date cannot be parsed */
invalidDateMessage?: React.ReactNode;
/** Clearable mode (for inline pickers works only for clearing input) */
clearable?: boolean;
/** Component that should replace the default Material-UI TextField */
TextFieldComponent?:
| React.ComponentType<TextFieldProps>
| React.ReactType<React.HTMLAttributes<any>>;
/** Props to pass to keyboard input adornment */
InputAdornmentProps?: Partial<MuiInputAdornmentProps>;
/** Props to pass to keyboard adornment button */
KeyboardButtonProps?: Partial<MuiIconButtonProps>;
/** Specifies position of keyboard button adornment */
adornmentPosition?: MuiInputAdornmentProps['position'];
onClick: (e: React.SyntheticEvent) => void;
/* Callback firing when date that applied in the keyboard is invalid **/
onError?: (newValue: MaterialUiPickersDate, error: React.ReactNode) => void;
/* Callback firing on change input in keyboard mode **/
onInputChange?: (e: React.FormEvent<HTMLInputElement>) => void;
}
export class DateTextField extends React.PureComponent<DateTextFieldProps> {
public static propTypes: any = {
value: PropTypes.oneOfType([
PropTypes.object,
PropTypes.string,
PropTypes.number,
PropTypes.instanceOf(Date),
]),
minDate: DomainPropTypes.date,
maxDate: DomainPropTypes.date,
disablePast: PropTypes.bool,
disableFuture: PropTypes.bool,
format: PropTypes.string,
onBlur: PropTypes.func,
onChange: PropTypes.func.isRequired,
onClear: PropTypes.func,
onClick: PropTypes.func.isRequired,
clearable: PropTypes.bool,
utils: PropTypes.object.isRequired,
InputProps: PropTypes.shape({}),
mask: PropTypes.any,
minDateMessage: PropTypes.node,
maxDateMessage: PropTypes.node,
invalidLabel: PropTypes.string,
emptyLabel: PropTypes.string,
labelFunc: PropTypes.func,
keyboard: PropTypes.bool,
keyboardIcon: PropTypes.node,
disableOpenOnEnter: PropTypes.bool,
invalidDateMessage: PropTypes.node,
TextFieldComponent: PropTypes.oneOfType([PropTypes.string, PropTypes.func, PropTypes.node]),
InputAdornmentProps: PropTypes.object,
KeyboardButtonProps: PropTypes.object,
adornmentPosition: PropTypes.oneOf(['start', 'end']),
onError: PropTypes.func,
onInputChange: PropTypes.func,
pipe: PropTypes.func,
keepCharPositions: PropTypes.bool,
};
public static defaultProps = {
disabled: false,
invalidLabel: 'Unknown',
emptyLabel: '',
keyboard: false,
keyboardIcon: <KeyboardIcon />,
disableOpenOnEnter: false,
invalidDateMessage: 'Invalid Date Format',
clearable: false,
disablePast: false,
disableFuture: false,
minDate: new Date('1900-01-01'),
maxDate: new Date('2100-01-01'),
minDateMessage: 'Date should not be before minimal date',
maxDateMessage: 'Date should not be after maximal date',
TextFieldComponent: TextField,
InputAdornmentProps: {},
KeyboardButtonProps: {},
adornmentPosition: 'end' as MuiInputAdornmentProps['position'],
keepCharPositions: false,
};
public static getStateFromProps = (props: DateTextFieldProps) => ({
value: props.value,
displayValue: getDisplayDate(props),
error: getError(props.utils.date(props.value), props),
});
public state = DateTextField.getStateFromProps(this.props);
public componentDidUpdate(prevProps: DateTextFieldProps) {
const { utils } = this.props;
if (
!utils.isEqual(utils.date(this.props.value), utils.date(prevProps.value)) ||
prevProps.format !== this.props.format ||
prevProps.maxDate !== this.props.maxDate ||
prevProps.minDate !== this.props.minDate ||
prevProps.emptyLabel !== this.props.emptyLabel ||
prevProps.utils !== this.props.utils
) {
this.setState(DateTextField.getStateFromProps(this.props));
}
}
public commitUpdates = (value: string) => {
const { onChange, clearable, onClear, utils, format, onError } = this.props;
if (value === '') {
if (this.props.value === null) {
this.setState(DateTextField.getStateFromProps(this.props));
} else if (clearable && onClear) {
onClear();
}
return;
}
const oldValue = utils.date(this.state.value);
const newValue = utils.parse(value, format);
const error = getError(newValue, this.props);
this.setState(
{
error,
displayValue: value,
value: error ? newValue : oldValue,
},
() => {
if (!error && !utils.isEqual(newValue, oldValue)) {
onChange(newValue);
}
if (error && onError) {
onError(newValue, error);
}
}
);
};
public handleBlur = (e: React.ChangeEvent<HTMLInputElement>) => {
if (this.props.keyboard) {
e.preventDefault();
e.stopPropagation();
this.commitUpdates(e.target.value);
if (this.props.onBlur) {
this.props.onBlur(e);
}
}
};
public handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const { utils, format, onInputChange } = this.props;
const parsedValue = utils.parse(e.target.value, format);
if (onInputChange) {
onInputChange(e);
}
this.setState({
displayValue: e.target.value,
error: getError(parsedValue, this.props),
});
};
public handleFocus = (e: React.SyntheticEvent) => {
e.stopPropagation();
e.preventDefault();
if (!this.props.keyboard) {
this.openPicker(e);
}
};
public handleKeyPress = (e: React.KeyboardEvent<HTMLDivElement>) => {
if (e.key === 'Enter') {
if (!this.props.disableOpenOnEnter) {
this.openPicker(e);
} else {
// @ts-ignore TODO check me
this.commitUpdates(e.target.value);
}
}
};
public openPicker = (e: React.SyntheticEvent) => {
const { disabled, onClick } = this.props;
if (!disabled) {
onClick!(e);
}
};
public render() {
const {
adornmentPosition,
clearable,
disabled,
disableFuture,
disableOpenOnEnter,
disablePast,
emptyLabel,
format,
InputAdornmentProps,
InputProps,
invalidDateMessage,
invalidLabel,
keyboard,
KeyboardButtonProps,
keyboardIcon,
labelFunc,
mask,
maxDate,
maxDateMessage,
minDate,
minDateMessage,
onBlur,
onClear,
onClick,
pipe,
keepCharPositions,
TextFieldComponent,
utils,
value,
onInputChange,
...other
} = this.props;
const { displayValue, error } = this.state;
const localInputProps = {
inputComponent: MaskedInput,
inputProps: {
mask: !keyboard ? null : mask,
pipe: !keyboard ? null : pipe,
keepCharPositions: !keyboard ? undefined : keepCharPositions,
readOnly: !keyboard,
},
};
if (keyboard) {
localInputProps[`${adornmentPosition}Adornment`] = (
<InputAdornment position={adornmentPosition!} {...InputAdornmentProps}>
<IconButton disabled={disabled} onClick={this.openPicker} {...KeyboardButtonProps}>
{keyboardIcon}
</IconButton>
</InputAdornment>
);
}
const Component = TextFieldComponent! as React.ComponentType<any>;
const inputProps = {
...localInputProps,
...InputProps,
} as Partial<InputPropsType>;
return (
<Component
onClick={this.handleFocus}
error={!!error}
helperText={error}
onKeyPress={this.handleKeyPress}
onBlur={this.handleBlur}
disabled={disabled}
value={displayValue}
{...other}
onError={undefined}
onChange={this.handleChange}
InputProps={inputProps}
/>
);
}
}
export default withUtils()(DateTextField);
| lib/src/_shared/DateTextField.tsx | 0 | https://github.com/mui/material-ui/commit/f36f617f4b16bdc03964778764e17bd47247b086 | [
0.00017964320431929082,
0.00016980220971163362,
0.00016342884919140488,
0.00017049974121619016,
0.000003703365564433625
] |
{
"id": 3,
"code_window": [
" <Typography align=\"center\" variant=\"h5\" gutterBottom>\n",
" This page is using for the automate regression of material-ui-pickers.\n",
" </Typography>\n",
"\n",
" <Grid container justify=\"center\" wrap=\"wrap\">\n",
" <DatePicker id=\"basic-datepicker\" {...sharedProps} />\n",
" <DatePicker id=\"clearable-datepicker\" clearable {...sharedProps} />\n",
" <DatePicker id=\"keyboard-datepicker\" keyboard {...sharedProps} />\n",
" <DatePicker\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <Typography align=\"center\" variant=\"h4\" component=\"span\" gutterBottom>\n",
" DatePicker\n",
" </Typography>\n",
"\n"
],
"file_path": "docs/pages/regression/index.tsx",
"type": "add",
"edit_start_line_idx": 30
} | import clsx from 'clsx';
import * as PropTypes from 'prop-types';
import * as React from 'react';
import createStyles from '@material-ui/core/styles/createStyles';
import withStyles, { WithStyles } from '@material-ui/core/styles/withStyles';
import { isYearAndMonthViews, isYearOnlyView } from '../_helpers/date-utils';
import PickerToolbar from '../_shared/PickerToolbar';
import ToolbarButton from '../_shared/ToolbarButton';
import { withUtils, WithUtilsProps } from '../_shared/WithUtils';
import { DatePickerViewType } from '../constants/DatePickerView';
import { DateType, DomainPropTypes } from '../constants/prop-types';
import { MaterialUiPickersDate } from '../typings/date';
import Calendar, { RenderDay } from './components/Calendar';
import MonthSelection from './components/MonthSelection';
import YearSelection from './components/YearSelection';
export interface BaseDatePickerProps {
/** Min selectable date */
minDate?: DateType;
/** Max selectable date */
maxDate?: DateType;
/** Disable past dates */
disablePast?: boolean;
/** Disable future dates */
disableFuture?: boolean;
/** To animate scrolling to current year (with scrollIntoView) */
animateYearScrolling?: boolean;
/** Array of views to show. Order year -> month -> day */
views?: Array<'year' | 'month' | 'day'>;
/** Initial view to show when date picker is open */
openTo?: 'year' | 'month' | 'day';
/** @deprecated use openTo instead */
openToYearSelection?: boolean;
/** Left arrow icon */
leftArrowIcon?: React.ReactNode;
/** Right arrow icon */
rightArrowIcon?: React.ReactNode;
/** Custom renderer for day */
renderDay?: RenderDay;
/** Enables keyboard listener for moving between days in calendar */
allowKeyboardControl?: boolean;
/** Disable specific date */
shouldDisableDate?: (day: MaterialUiPickersDate) => boolean;
initialFocusedDate?: DateType;
}
export interface DatePickerProps
extends BaseDatePickerProps,
WithStyles<typeof styles>,
WithUtilsProps {
date: MaterialUiPickersDate;
onChange: (date: MaterialUiPickersDate, isFinished?: boolean) => void;
}
interface DatePickerState {
openView: DatePickerViewType;
}
export class DatePicker extends React.PureComponent<DatePickerProps> {
public static propTypes: any = {
views: PropTypes.arrayOf(DomainPropTypes.datePickerView),
openTo: DomainPropTypes.datePickerView,
openToYearSelection: PropTypes.bool,
};
public static defaultProps = {
minDate: new Date('1900-01-01'),
maxDate: new Date('2100-01-01'),
openToYearSelection: false,
views: ['year', 'day'] as DatePickerViewType[],
};
public state: DatePickerState = {
// TODO in v3 remove openToYearSelection
openView:
this.props.openTo || this.props.openToYearSelection!
? 'year'
: this.props.views![this.props.views!.length - 1],
};
get date() {
return this.props.date;
}
get minDate() {
return this.props.utils.date(this.props.minDate);
}
get maxDate() {
return this.props.utils.date(this.props.maxDate);
}
get isYearOnly() {
return isYearOnlyView(this.props.views!);
}
get isYearAndMonth() {
return isYearAndMonthViews(this.props.views!);
}
public handleYearSelect = (date: MaterialUiPickersDate) => {
this.props.onChange(date, this.isYearOnly);
if (this.isYearOnly) {
return;
}
if (this.props.views!.includes('month')) {
return this.openMonthSelection();
}
this.openCalendar();
};
public handleMonthSelect = (date: MaterialUiPickersDate) => {
const isFinish = !this.props.views!.includes('day');
this.props.onChange(date, isFinish);
if (!isFinish) {
this.openCalendar();
}
};
public openYearSelection = () => {
this.setState({ openView: 'year' });
};
public openCalendar = () => {
this.setState({ openView: 'day' });
};
public openMonthSelection = () => {
this.setState({ openView: 'month' });
};
public render() {
const { openView } = this.state;
const {
disablePast,
disableFuture,
onChange,
animateYearScrolling,
leftArrowIcon,
rightArrowIcon,
renderDay,
utils,
shouldDisableDate,
allowKeyboardControl,
classes,
} = this.props;
return (
<>
<PickerToolbar className={clsx({ [classes.toolbarCenter]: this.isYearOnly })}>
<ToolbarButton
variant={this.isYearOnly ? 'h3' : 'subtitle1'}
onClick={this.isYearOnly ? undefined : this.openYearSelection}
selected={openView === 'year'}
label={utils.getYearText(this.date)}
/>
{!this.isYearOnly &&
!this.isYearAndMonth && (
<ToolbarButton
variant="h4"
onClick={this.openCalendar}
selected={openView === 'day'}
label={utils.getDatePickerHeaderText(this.date)}
/>
)}
{this.isYearAndMonth && (
<ToolbarButton
variant="h4"
onClick={this.openMonthSelection}
selected={openView === 'month'}
label={utils.getMonthText(this.date)}
/>
)}
</PickerToolbar>
{this.props.children}
{openView === 'year' && (
<YearSelection
date={this.date}
onChange={this.handleYearSelect}
minDate={this.minDate}
maxDate={this.maxDate}
disablePast={disablePast}
disableFuture={disableFuture}
animateYearScrolling={animateYearScrolling}
/>
)}
{openView === 'month' && (
<MonthSelection
date={this.date}
onChange={this.handleMonthSelect}
minDate={this.minDate}
maxDate={this.maxDate}
disablePast={disablePast}
disableFuture={disableFuture}
/>
)}
{openView === 'day' && (
<Calendar
date={this.date}
onChange={onChange}
disablePast={disablePast}
disableFuture={disableFuture}
minDate={this.minDate}
maxDate={this.maxDate}
leftArrowIcon={leftArrowIcon}
rightArrowIcon={rightArrowIcon}
renderDay={renderDay}
shouldDisableDate={shouldDisableDate}
allowKeyboardControl={allowKeyboardControl}
/>
)}
</>
);
}
}
export const styles = () =>
createStyles({
toolbarCenter: {
flexDirection: 'row',
alignItems: 'center',
},
});
export default withStyles(styles)(withUtils()(DatePicker));
| lib/src/DatePicker/DatePicker.tsx | 1 | https://github.com/mui/material-ui/commit/f36f617f4b16bdc03964778764e17bd47247b086 | [
0.0030727803241461515,
0.0005005730781704187,
0.0001632665516808629,
0.0001690735516604036,
0.0007688698824495077
] |
{
"id": 3,
"code_window": [
" <Typography align=\"center\" variant=\"h5\" gutterBottom>\n",
" This page is using for the automate regression of material-ui-pickers.\n",
" </Typography>\n",
"\n",
" <Grid container justify=\"center\" wrap=\"wrap\">\n",
" <DatePicker id=\"basic-datepicker\" {...sharedProps} />\n",
" <DatePicker id=\"clearable-datepicker\" clearable {...sharedProps} />\n",
" <DatePicker id=\"keyboard-datepicker\" keyboard {...sharedProps} />\n",
" <DatePicker\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <Typography align=\"center\" variant=\"h4\" component=\"span\" gutterBottom>\n",
" DatePicker\n",
" </Typography>\n",
"\n"
],
"file_path": "docs/pages/regression/index.tsx",
"type": "add",
"edit_start_line_idx": 30
} | import withStyles from '@material-ui/core/styles/withStyles';
import clsx from 'clsx';
import * as PropTypes from 'prop-types';
import * as React from 'react';
import { WithStyles } from '@material-ui/core';
import createStyles from '@material-ui/core/styles/createStyles';
import { convertToMeridiem } from '../_helpers/time-utils';
import PickerToolbar from '../_shared/PickerToolbar';
import ToolbarButton from '../_shared/ToolbarButton';
import { withUtils, WithUtilsProps } from '../_shared/WithUtils';
import ClockType from '../constants/ClockType';
import { MeridiemMode } from '../DateTimePicker/components/DateTimePickerHeader';
import { MaterialUiPickersDate } from '../typings/date';
import TimePickerView from './components/TimePickerView';
export interface BaseTimePickerProps {
/** 12h/24h view for hour selection clock */
ampm?: boolean;
/** Show the seconds view */
seconds?: boolean;
/** Step over minutes */
minutesStep?: number;
}
export interface TimePickerProps
extends BaseTimePickerProps,
WithUtilsProps,
WithStyles<typeof styles, true> {
date: MaterialUiPickersDate;
onChange: (date: MaterialUiPickersDate, isFinished?: boolean) => void;
}
interface TimePickerState {
openView: ClockType;
meridiemMode: MeridiemMode;
}
export class TimePicker extends React.Component<TimePickerProps> {
public static propTypes: any = {
date: PropTypes.object.isRequired,
onChange: PropTypes.func.isRequired,
utils: PropTypes.object.isRequired,
ampm: PropTypes.bool,
seconds: PropTypes.bool,
minutesStep: PropTypes.number,
innerRef: PropTypes.any,
};
public static defaultProps = {
children: null,
ampm: true,
seconds: false,
minutesStep: 1,
};
public state: TimePickerState = {
openView: ClockType.HOURS,
meridiemMode: this.props.utils.getHours(this.props.date) >= 12 ? 'pm' : 'am',
};
public setMeridiemMode = (mode: MeridiemMode) => () => {
this.setState({ meridiemMode: mode }, () =>
this.handleChange({
time: this.props.date,
isFinish: false,
openMinutes: false,
openSeconds: false,
})
);
};
public handleChange = ({
time,
isFinish,
openMinutes,
openSeconds,
}: {
time: MaterialUiPickersDate;
isFinish?: boolean;
openMinutes: boolean;
openSeconds: boolean;
}) => {
const withMeridiem = convertToMeridiem(
time,
this.state.meridiemMode,
Boolean(this.props.ampm),
this.props.utils
);
if (isFinish) {
if (!openMinutes && !openSeconds) {
this.props.onChange(withMeridiem, isFinish);
return;
}
if (openMinutes) {
this.openMinutesView();
}
if (openSeconds) {
this.openSecondsView();
}
}
this.props.onChange(withMeridiem, false);
};
public handleHourChange = (time: MaterialUiPickersDate, isFinish?: boolean) => {
this.handleChange({
time,
isFinish,
openMinutes: true,
openSeconds: false,
});
};
public handleMinutesChange = (time: MaterialUiPickersDate, isFinish?: boolean) => {
this.handleChange({
time,
isFinish,
openMinutes: false,
openSeconds: Boolean(this.props.seconds),
});
};
public handleSecondsChange = (time: MaterialUiPickersDate, isFinish?: boolean) => {
this.handleChange({
time,
isFinish,
openMinutes: false,
openSeconds: false,
});
};
public openSecondsView = () => {
this.setState({ openView: ClockType.SECONDS });
};
public openMinutesView = () => {
this.setState({ openView: ClockType.MINUTES });
};
public openHourView = () => {
this.setState({ openView: ClockType.HOURS });
};
public render() {
const { classes, theme, date, utils, ampm, seconds, minutesStep } = this.props;
const { meridiemMode, openView } = this.state;
const rtl = theme.direction === 'rtl';
const hourMinuteClassName = rtl ? classes.hourMinuteLabelReverse : classes.hourMinuteLabel;
return (
<React.Fragment>
<PickerToolbar
className={clsx(classes.toolbar, {
[classes.toolbarLeftPadding]: ampm,
})}
>
<div className={hourMinuteClassName}>
<ToolbarButton
variant="h2"
onClick={this.openHourView}
selected={openView === ClockType.HOURS}
label={utils.getHourText(date, Boolean(ampm))}
/>
<ToolbarButton variant="h2" label=":" selected={false} className={classes.separator} />
<ToolbarButton
variant="h2"
onClick={this.openMinutesView}
selected={openView === ClockType.MINUTES}
label={utils.getMinuteText(date)}
/>
{seconds && (
<React.Fragment>
<ToolbarButton
variant="h2"
label=":"
selected={false}
className={classes.separator}
/>
<ToolbarButton
variant="h2"
onClick={this.openSecondsView}
selected={openView === ClockType.SECONDS}
label={utils.getSecondText(date)}
/>
</React.Fragment>
)}
</div>
{ampm && (
<div className={seconds ? classes.ampmSelectionWithSeconds : classes.ampmSelection}>
<ToolbarButton
className={classes.ampmLabel}
selected={meridiemMode === 'am'}
variant="subtitle1"
label={utils.getMeridiemText('am')}
onClick={this.setMeridiemMode('am')}
/>
<ToolbarButton
className={classes.ampmLabel}
selected={meridiemMode === 'pm'}
variant="subtitle1"
label={utils.getMeridiemText('pm')}
onClick={this.setMeridiemMode('pm')}
/>
</div>
)}
</PickerToolbar>
{this.props.children}
<TimePickerView
date={date}
type={this.state.openView}
ampm={ampm}
minutesStep={minutesStep}
onHourChange={this.handleHourChange}
onMinutesChange={this.handleMinutesChange}
onSecondsChange={this.handleSecondsChange}
/>
</React.Fragment>
);
}
}
export const styles = () =>
createStyles({
toolbar: {
flexDirection: 'row',
alignItems: 'center',
},
toolbarLeftPadding: {
paddingLeft: 50,
},
separator: {
margin: '0 4px 0 2px',
cursor: 'default',
},
ampmSelection: {
marginLeft: 20,
marginRight: -20,
},
ampmSelectionWithSeconds: {
marginLeft: 15,
marginRight: 10,
},
ampmLabel: {
fontSize: 18,
},
hourMinuteLabel: {
display: 'flex',
justifyContent: 'flex-end',
alignItems: 'flex-end',
},
hourMinuteLabelReverse: {
display: 'flex',
justifyContent: 'flex-end',
alignItems: 'flex-end',
flexDirection: 'row-reverse',
},
});
export default withStyles(styles, {
withTheme: true,
name: 'MuiPickersTimePicker',
})(withUtils()(TimePicker));
| lib/src/TimePicker/TimePicker.tsx | 0 | https://github.com/mui/material-ui/commit/f36f617f4b16bdc03964778764e17bd47247b086 | [
0.002387755550444126,
0.00028210951131768525,
0.00016518808843102306,
0.00016873601998668164,
0.00042022738489322364
] |
{
"id": 3,
"code_window": [
" <Typography align=\"center\" variant=\"h5\" gutterBottom>\n",
" This page is using for the automate regression of material-ui-pickers.\n",
" </Typography>\n",
"\n",
" <Grid container justify=\"center\" wrap=\"wrap\">\n",
" <DatePicker id=\"basic-datepicker\" {...sharedProps} />\n",
" <DatePicker id=\"clearable-datepicker\" clearable {...sharedProps} />\n",
" <DatePicker id=\"keyboard-datepicker\" keyboard {...sharedProps} />\n",
" <DatePicker\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <Typography align=\"center\" variant=\"h4\" component=\"span\" gutterBottom>\n",
" DatePicker\n",
" </Typography>\n",
"\n"
],
"file_path": "docs/pages/regression/index.tsx",
"type": "add",
"edit_start_line_idx": 30
} | import * as PropTypes from 'prop-types';
import * as React from 'react';
import { Theme } from '@material-ui/core';
import IconButton from '@material-ui/core/IconButton';
import createStyles from '@material-ui/core/styles/createStyles';
import withStyles, { WithStyles } from '@material-ui/core/styles/withStyles';
import Typography from '@material-ui/core/Typography';
import { ArrowLeftIcon } from '../../_shared/icons/ArrowLeftIcon';
import { ArrowRightIcon } from '../../_shared/icons/ArrowRightIcon';
import { withUtils, WithUtilsProps } from '../../_shared/WithUtils';
import { MaterialUiPickersDate } from '../../typings/date';
import SlideTransition, { SlideDirection } from './SlideTransition';
export interface CalendarHeaderProps extends WithUtilsProps, WithStyles<typeof styles, true> {
currentMonth: object;
onMonthChange: (date: MaterialUiPickersDate, direction: SlideDirection) => void;
leftArrowIcon?: React.ReactNode;
rightArrowIcon?: React.ReactNode;
disablePrevMonth?: boolean;
disableNextMonth?: boolean;
slideDirection: SlideDirection;
}
export const CalendarHeader: React.SFC<CalendarHeaderProps> = ({
classes,
theme,
currentMonth,
onMonthChange,
leftArrowIcon,
rightArrowIcon,
disablePrevMonth,
disableNextMonth,
utils,
slideDirection,
}) => {
const rtl = theme.direction === 'rtl';
const selectNextMonth = () => onMonthChange(utils.getNextMonth(currentMonth), 'left');
const selectPreviousMonth = () => onMonthChange(utils.getPreviousMonth(currentMonth), 'right');
return (
<div>
<div className={classes.switchHeader}>
<IconButton
disabled={disablePrevMonth}
onClick={selectPreviousMonth}
className={classes.iconButton}
>
{rtl ? rightArrowIcon : leftArrowIcon}
</IconButton>
<SlideTransition
slideDirection={slideDirection}
transKey={currentMonth.toString()}
className={classes.transitionContainer}
>
<Typography align="center" variant="body1">
{utils.getCalendarHeaderText(currentMonth)}
</Typography>
</SlideTransition>
<IconButton
disabled={disableNextMonth}
onClick={selectNextMonth}
className={classes.iconButton}
>
{rtl ? leftArrowIcon : rightArrowIcon}
</IconButton>
</div>
<div className={classes.daysHeader}>
{utils.getWeekdays().map((day, index) => (
<Typography
key={index} // eslint-disable-line react/no-array-index-key
variant="caption"
className={classes.dayLabel}
>
{day}
</Typography>
))}
</div>
</div>
);
};
(CalendarHeader as any).propTypes = {
currentMonth: PropTypes.object.isRequired,
onMonthChange: PropTypes.func.isRequired,
leftArrowIcon: PropTypes.node,
rightArrowIcon: PropTypes.node,
disablePrevMonth: PropTypes.bool,
disableNextMonth: PropTypes.bool,
slideDirection: PropTypes.oneOf(['right', 'left']).isRequired,
innerRef: PropTypes.any,
};
CalendarHeader.defaultProps = {
leftArrowIcon: <ArrowLeftIcon />,
rightArrowIcon: <ArrowRightIcon />,
disablePrevMonth: false,
disableNextMonth: false,
};
export const styles = (theme: Theme) =>
createStyles({
switchHeader: {
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
marginTop: theme.spacing.unit / 2,
marginBottom: theme.spacing.unit,
},
transitionContainer: {
width: '100%',
height: 20,
},
iconButton: {
zIndex: 2,
backgroundColor: theme.palette.background.paper,
'& > *': {
// label
backgroundColor: theme.palette.background.paper,
'& > *': {
// icon
zIndex: 1,
overflow: 'visible',
},
},
},
daysHeader: {
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
maxHeight: 16,
},
dayLabel: {
width: 36,
margin: '0 2px',
textAlign: 'center',
color: theme.palette.text.hint,
},
});
export default withStyles(styles, {
withTheme: true,
name: 'MuiPickersCalendarHeader',
})(withUtils()(CalendarHeader));
| lib/src/DatePicker/components/CalendarHeader.tsx | 0 | https://github.com/mui/material-ui/commit/f36f617f4b16bdc03964778764e17bd47247b086 | [
0.00022792375239077955,
0.00017673498950898647,
0.000166714919032529,
0.00016975095786619931,
0.00001914457061502617
] |
{
"id": 3,
"code_window": [
" <Typography align=\"center\" variant=\"h5\" gutterBottom>\n",
" This page is using for the automate regression of material-ui-pickers.\n",
" </Typography>\n",
"\n",
" <Grid container justify=\"center\" wrap=\"wrap\">\n",
" <DatePicker id=\"basic-datepicker\" {...sharedProps} />\n",
" <DatePicker id=\"clearable-datepicker\" clearable {...sharedProps} />\n",
" <DatePicker id=\"keyboard-datepicker\" keyboard {...sharedProps} />\n",
" <DatePicker\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <Typography align=\"center\" variant=\"h4\" component=\"span\" gutterBottom>\n",
" DatePicker\n",
" </Typography>\n",
"\n"
],
"file_path": "docs/pages/regression/index.tsx",
"type": "add",
"edit_start_line_idx": 30
} | import React from 'react';
import clsx from 'clsx';
import { withStyles, Theme, WithStyles } from '@material-ui/core';
import { highlight } from '../utils/prism';
const styles = (theme: Theme) => ({
root: {
margin: '0',
fontFamily: theme.typography.fontFamily,
fontSize: '1em',
color: theme.palette.text.primary,
padding: 10,
paddingBottom: 0,
backgroundColor: theme.palette.background.paper,
'& pre': {
borderRadius: 3,
overflow: 'auto !important',
margin: '0 !important',
backgroundColor: theme.palette.background.paper + ' !important',
},
},
margin: {
margin: '10px 0 30px',
},
});
type CodeProps = {
children: string;
withMargin?: boolean;
language?: 'jsx' | 'typescript' | 'markup';
} & WithStyles<typeof styles>;
const Code: React.SFC<CodeProps> = ({ classes, language = 'jsx', children, withMargin }) => {
const highlightedCode = highlight(children, language);
return (
<div className={clsx(classes.root, { [classes.margin]: withMargin })}>
<pre>
<code dangerouslySetInnerHTML={{ __html: highlightedCode }} />
</pre>
</div>
);
};
Code.defaultProps = {
withMargin: false,
language: 'jsx',
};
export default withStyles(styles)(Code);
| docs/_shared/Code.tsx | 0 | https://github.com/mui/material-ui/commit/f36f617f4b16bdc03964778764e17bd47247b086 | [
0.00017223914619535208,
0.00016778288409113884,
0.00016351458907593042,
0.00016819615848362446,
0.000002898206503232359
] |
{
"id": 4,
"code_window": [
" id=\"keyboard-mask-datepicker\"\n",
" format=\"MM/dd/yyyy\"\n",
" mask={[/\\d/, /\\d/, '/', /\\d/, /\\d/, '/', /\\d/, /\\d/, /\\d/, /\\d/]}\n",
" {...sharedProps}\n",
" />\n",
" </Grid>\n",
" </div>\n",
" );\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <DatePicker disabled id=\"disabled\" {...sharedProps} />\n"
],
"file_path": "docs/pages/regression/index.tsx",
"type": "add",
"edit_start_line_idx": 41
} | import clsx from 'clsx';
import * as PropTypes from 'prop-types';
import * as React from 'react';
import createStyles from '@material-ui/core/styles/createStyles';
import withStyles, { WithStyles } from '@material-ui/core/styles/withStyles';
import { isYearAndMonthViews, isYearOnlyView } from '../_helpers/date-utils';
import PickerToolbar from '../_shared/PickerToolbar';
import ToolbarButton from '../_shared/ToolbarButton';
import { withUtils, WithUtilsProps } from '../_shared/WithUtils';
import { DatePickerViewType } from '../constants/DatePickerView';
import { DateType, DomainPropTypes } from '../constants/prop-types';
import { MaterialUiPickersDate } from '../typings/date';
import Calendar, { RenderDay } from './components/Calendar';
import MonthSelection from './components/MonthSelection';
import YearSelection from './components/YearSelection';
export interface BaseDatePickerProps {
/** Min selectable date */
minDate?: DateType;
/** Max selectable date */
maxDate?: DateType;
/** Disable past dates */
disablePast?: boolean;
/** Disable future dates */
disableFuture?: boolean;
/** To animate scrolling to current year (with scrollIntoView) */
animateYearScrolling?: boolean;
/** Array of views to show. Order year -> month -> day */
views?: Array<'year' | 'month' | 'day'>;
/** Initial view to show when date picker is open */
openTo?: 'year' | 'month' | 'day';
/** @deprecated use openTo instead */
openToYearSelection?: boolean;
/** Left arrow icon */
leftArrowIcon?: React.ReactNode;
/** Right arrow icon */
rightArrowIcon?: React.ReactNode;
/** Custom renderer for day */
renderDay?: RenderDay;
/** Enables keyboard listener for moving between days in calendar */
allowKeyboardControl?: boolean;
/** Disable specific date */
shouldDisableDate?: (day: MaterialUiPickersDate) => boolean;
initialFocusedDate?: DateType;
}
export interface DatePickerProps
extends BaseDatePickerProps,
WithStyles<typeof styles>,
WithUtilsProps {
date: MaterialUiPickersDate;
onChange: (date: MaterialUiPickersDate, isFinished?: boolean) => void;
}
interface DatePickerState {
openView: DatePickerViewType;
}
export class DatePicker extends React.PureComponent<DatePickerProps> {
public static propTypes: any = {
views: PropTypes.arrayOf(DomainPropTypes.datePickerView),
openTo: DomainPropTypes.datePickerView,
openToYearSelection: PropTypes.bool,
};
public static defaultProps = {
minDate: new Date('1900-01-01'),
maxDate: new Date('2100-01-01'),
openToYearSelection: false,
views: ['year', 'day'] as DatePickerViewType[],
};
public state: DatePickerState = {
// TODO in v3 remove openToYearSelection
openView:
this.props.openTo || this.props.openToYearSelection!
? 'year'
: this.props.views![this.props.views!.length - 1],
};
get date() {
return this.props.date;
}
get minDate() {
return this.props.utils.date(this.props.minDate);
}
get maxDate() {
return this.props.utils.date(this.props.maxDate);
}
get isYearOnly() {
return isYearOnlyView(this.props.views!);
}
get isYearAndMonth() {
return isYearAndMonthViews(this.props.views!);
}
public handleYearSelect = (date: MaterialUiPickersDate) => {
this.props.onChange(date, this.isYearOnly);
if (this.isYearOnly) {
return;
}
if (this.props.views!.includes('month')) {
return this.openMonthSelection();
}
this.openCalendar();
};
public handleMonthSelect = (date: MaterialUiPickersDate) => {
const isFinish = !this.props.views!.includes('day');
this.props.onChange(date, isFinish);
if (!isFinish) {
this.openCalendar();
}
};
public openYearSelection = () => {
this.setState({ openView: 'year' });
};
public openCalendar = () => {
this.setState({ openView: 'day' });
};
public openMonthSelection = () => {
this.setState({ openView: 'month' });
};
public render() {
const { openView } = this.state;
const {
disablePast,
disableFuture,
onChange,
animateYearScrolling,
leftArrowIcon,
rightArrowIcon,
renderDay,
utils,
shouldDisableDate,
allowKeyboardControl,
classes,
} = this.props;
return (
<>
<PickerToolbar className={clsx({ [classes.toolbarCenter]: this.isYearOnly })}>
<ToolbarButton
variant={this.isYearOnly ? 'h3' : 'subtitle1'}
onClick={this.isYearOnly ? undefined : this.openYearSelection}
selected={openView === 'year'}
label={utils.getYearText(this.date)}
/>
{!this.isYearOnly &&
!this.isYearAndMonth && (
<ToolbarButton
variant="h4"
onClick={this.openCalendar}
selected={openView === 'day'}
label={utils.getDatePickerHeaderText(this.date)}
/>
)}
{this.isYearAndMonth && (
<ToolbarButton
variant="h4"
onClick={this.openMonthSelection}
selected={openView === 'month'}
label={utils.getMonthText(this.date)}
/>
)}
</PickerToolbar>
{this.props.children}
{openView === 'year' && (
<YearSelection
date={this.date}
onChange={this.handleYearSelect}
minDate={this.minDate}
maxDate={this.maxDate}
disablePast={disablePast}
disableFuture={disableFuture}
animateYearScrolling={animateYearScrolling}
/>
)}
{openView === 'month' && (
<MonthSelection
date={this.date}
onChange={this.handleMonthSelect}
minDate={this.minDate}
maxDate={this.maxDate}
disablePast={disablePast}
disableFuture={disableFuture}
/>
)}
{openView === 'day' && (
<Calendar
date={this.date}
onChange={onChange}
disablePast={disablePast}
disableFuture={disableFuture}
minDate={this.minDate}
maxDate={this.maxDate}
leftArrowIcon={leftArrowIcon}
rightArrowIcon={rightArrowIcon}
renderDay={renderDay}
shouldDisableDate={shouldDisableDate}
allowKeyboardControl={allowKeyboardControl}
/>
)}
</>
);
}
}
export const styles = () =>
createStyles({
toolbarCenter: {
flexDirection: 'row',
alignItems: 'center',
},
});
export default withStyles(styles)(withUtils()(DatePicker));
| lib/src/DatePicker/DatePicker.tsx | 1 | https://github.com/mui/material-ui/commit/f36f617f4b16bdc03964778764e17bd47247b086 | [
0.01954074576497078,
0.001056418870575726,
0.00016417779261246324,
0.00017076222866307944,
0.00386041565798223
] |
{
"id": 4,
"code_window": [
" id=\"keyboard-mask-datepicker\"\n",
" format=\"MM/dd/yyyy\"\n",
" mask={[/\\d/, /\\d/, '/', /\\d/, /\\d/, '/', /\\d/, /\\d/, /\\d/, /\\d/]}\n",
" {...sharedProps}\n",
" />\n",
" </Grid>\n",
" </div>\n",
" );\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <DatePicker disabled id=\"disabled\" {...sharedProps} />\n"
],
"file_path": "docs/pages/regression/index.tsx",
"type": "add",
"edit_start_line_idx": 41
} | <p align="center">
<a href="https://material-ui.com/" rel="noopener" target="_blank"><img width="200" src="https://material-ui-pickers.dev/static/meta-image.png" alt="Material-UI logo"></a></p>
</p>
<h1 align="center">Material-UI pickers</h1>
<div align="center">
Accessible, customizable, delightful date & time pickers for [@material-ui/core](https://material-ui.com/)
[](https://www.npmjs.org/package/material-ui-pickers)
[](https://www.npmjs.org/package/material-ui-pickers)
[](https://codecov.io/gh/dmtrKovalenko/material-ui-pickers)
[](https://unpkg.com/[email protected]/dist/material-ui-pickers.cjs.js)
[](https://travis-ci.org/dmtrKovalenko/material-ui-pickers)
[](https://github.com/prettier/prettier)
</div>
### Installation
Available as npm package.
```sh
npm i material-ui-pickers
// or via yarn
yarn add material-ui-pickers
```
Now choose the library that pickers will use to work with date. We are providing interfaces for [moment](https://momentjs.com/), [luxon](https://moment.github.io/luxon/), [dayjs](https://github.com/iamkun/dayjs) and [date-fns v2](https://date-fns.org/). If you are not using moment in the project (or dont have it in the bundle already) we suggest using date-fns or luxon, because they are much lighter and will be correctly tree-shaked from the bundle. Note, that we are fully relying on [date-io](https://github.com/dmtrKovalenko/date-io) for supporting different libraries.
```sh
npm i date-fns@next @date-io/date-fns
// or
npm i moment @date-io/moment
// or
npm i luxon @date-io/luxon
// or
npm i dayjs @date-io/dayjs
```
Then teach pickers which library to use with `MuiPickerUtilsProvider`. This component takes a utils property, and makes it available down the React tree thanks to React context. It should preferably be used at the root of your component tree.
```jsx
import MomentUtils from '@date-io/moment';
import DateFnsUtils from '@date-io/date-fns';
import LuxonUtils from '@date-io/luxon';
import { MuiPickersUtilsProvider } from 'material-ui-pickers';
function App() {
return (
<MuiPickersUtilsProvider utils={DateFnsUtils}>
<Root />
</MuiPickersUtilsProvider>
);
}
render(<App />, document.querySelector('#app'));
```
## Documentation
Check out the [documentation website](https://material-ui-pickers.dev/)
### Recently updated?
Changelog available [here](https://github.com/dmtrKovalenko/material-ui-pickers/releases)
### Contributing
For information about how to contribute, see the [CONTRIBUTING](https://github.com/dmtrKovalenko/material-ui-pickers/blob/master/CONTRIBUTING.md) file.
### LICENSE
The project is licensed under the terms of [MIT license](https://github.com/dmtrKovalenko/material-ui-pickers/blob/master/LICENSE)
| README.md | 0 | https://github.com/mui/material-ui/commit/f36f617f4b16bdc03964778764e17bd47247b086 | [
0.0005544788436964154,
0.0002149404026567936,
0.0001639861147850752,
0.00016700319247320294,
0.00012834793596994132
] |
{
"id": 4,
"code_window": [
" id=\"keyboard-mask-datepicker\"\n",
" format=\"MM/dd/yyyy\"\n",
" mask={[/\\d/, /\\d/, '/', /\\d/, /\\d/, '/', /\\d/, /\\d/, /\\d/, /\\d/]}\n",
" {...sharedProps}\n",
" />\n",
" </Grid>\n",
" </div>\n",
" );\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <DatePicker disabled id=\"disabled\" {...sharedProps} />\n"
],
"file_path": "docs/pages/regression/index.tsx",
"type": "add",
"edit_start_line_idx": 41
} | enum DateTimePickerView {
YEAR = 'year',
DATE = 'date',
HOUR = 'hours',
MINUTES = 'minutes',
}
export type DateTimePickerViewType = 'year' | 'date' | 'hours' | 'minutes';
export default DateTimePickerView;
| lib/src/constants/DateTimePickerView.ts | 0 | https://github.com/mui/material-ui/commit/f36f617f4b16bdc03964778764e17bd47247b086 | [
0.0010755627881735563,
0.0006816900568082929,
0.00028781729633919895,
0.0006816900568082929,
0.00039387273136526346
] |
{
"id": 4,
"code_window": [
" id=\"keyboard-mask-datepicker\"\n",
" format=\"MM/dd/yyyy\"\n",
" mask={[/\\d/, /\\d/, '/', /\\d/, /\\d/, '/', /\\d/, /\\d/, /\\d/, /\\d/]}\n",
" {...sharedProps}\n",
" />\n",
" </Grid>\n",
" </div>\n",
" );\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <DatePicker disabled id=\"disabled\" {...sharedProps} />\n"
],
"file_path": "docs/pages/regression/index.tsx",
"type": "add",
"edit_start_line_idx": 41
} | import { ReactWrapper } from 'enzyme';
import * as React from 'react';
import TimePicker, { TimePickerProps } from '../../TimePicker/TimePicker';
import { mount, utilsToUse } from '../test-utils';
describe('e2e - TimePicker', () => {
let component: ReactWrapper<TimePickerProps>;
const onChangeMock = jest.fn();
beforeEach(() => {
jest.clearAllMocks();
component = mount(
<TimePicker date={utilsToUse.date('2018-01-01T00:00:00.000Z')} onChange={onChangeMock} />
);
});
it('Should renders', () => {
expect(component).toBeTruthy();
});
it('Should submit onChange on moving', () => {
component.find('Clock div[role="menu"]').simulate('mouseMove', {
buttons: 1,
nativeEvent: {
offsetX: 20,
offsetY: 15,
},
});
expect(onChangeMock).toHaveBeenCalled();
});
it('Should submit hourview (mouse move)', () => {
component.find('Clock div[role="menu"]').simulate('mouseUp', {
nativeEvent: {
offsetX: 20,
offsetY: 15,
},
});
expect(onChangeMock).toHaveBeenCalled();
});
it('Should change minutes (touch)', () => {
component.setState({ openView: 'minutes' });
component.find('Clock div[role="menu"]').simulate('touchMove', {
buttons: 1,
changedTouches: [
{
clientX: 20,
clientY: 15,
},
],
});
expect(onChangeMock).toHaveBeenCalled();
component.find('Clock div[role="menu"]').simulate('touchEnd', {
buttons: 1,
changedTouches: [
{
clientX: 20,
clientY: 15,
},
],
});
expect(onChangeMock).toHaveBeenCalled();
});
});
| lib/src/__tests__/e2e/TimePicker.test.tsx | 0 | https://github.com/mui/material-ui/commit/f36f617f4b16bdc03964778764e17bd47247b086 | [
0.00023485420388169587,
0.00017995815142057836,
0.00016856320144142956,
0.00017242068133782595,
0.000020817793483729474
] |
{
"id": 5,
"code_window": [
" openTo: DomainPropTypes.datePickerView,\n",
" openToYearSelection: PropTypes.bool,\n",
" };\n",
"\n",
" public static defaultProps = {\n",
" minDate: new Date('1900-01-01'),\n",
" maxDate: new Date('2100-01-01'),\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
" openToYearSelection: false,\n"
],
"file_path": "lib/src/DatePicker/DatePicker.tsx",
"type": "add",
"edit_start_line_idx": 67
} | import React, { Fragment, useState } from 'react';
import { DatePicker } from 'material-ui-pickers';
function YearMonthPicker(props) {
const [selectedDate, handleDateChange] = useState(new Date());
return (
<Fragment>
<div className="picker">
<DatePicker
views={['year']}
label="Year only"
value={selectedDate}
onChange={handleDateChange}
animateYearScrolling
/>
</div>
<div className="picker">
<DatePicker
views={['year', 'month']}
label="Year and Month"
helperText="With min and max"
minDate={new Date('2018-03-01')}
maxDate={new Date('2018-06-01')}
value={selectedDate}
onChange={handleDateChange}
/>
</div>
<div className="picker">
<DatePicker
views={['year', 'month']}
openTo="year"
label="Year and Month"
helperText="Start from year selection"
value={selectedDate}
onChange={handleDateChange}
/>
</div>
</Fragment>
);
}
export default YearMonthPicker;
| docs/pages/api/datepicker/ViewsDatePicker.example.jsx | 1 | https://github.com/mui/material-ui/commit/f36f617f4b16bdc03964778764e17bd47247b086 | [
0.023718388751149178,
0.005002507008612156,
0.00021168765670154244,
0.0003332177584525198,
0.00935840792953968
] |
{
"id": 5,
"code_window": [
" openTo: DomainPropTypes.datePickerView,\n",
" openToYearSelection: PropTypes.bool,\n",
" };\n",
"\n",
" public static defaultProps = {\n",
" minDate: new Date('1900-01-01'),\n",
" maxDate: new Date('2100-01-01'),\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
" openToYearSelection: false,\n"
],
"file_path": "lib/src/DatePicker/DatePicker.tsx",
"type": "add",
"edit_start_line_idx": 67
} | import * as React from 'react';
import BasePicker, { BasePickerProps } from '../_shared/BasePicker';
import { ExtendWrapper } from '../wrappers/ExtendWrapper';
import InlineWrapper, { OuterInlineWrapperProps } from '../wrappers/InlineWrapper';
import DateTimePicker, { BaseDateTimePickerProps } from './DateTimePicker';
export interface DateTimePickerInlineProps
extends BasePickerProps,
BaseDateTimePickerProps,
ExtendWrapper<OuterInlineWrapperProps> {}
export const DateTimePickerInline: React.SFC<DateTimePickerInlineProps> = props => {
const {
value,
format,
autoOk,
openTo,
minDate,
maxDate,
initialFocusedDate,
showTabs,
autoSubmit,
disablePast,
disableFuture,
leftArrowIcon,
rightArrowIcon,
dateRangeIcon,
timeIcon,
renderDay,
ampm,
minutesStep,
shouldDisableDate,
animateYearScrolling,
forwardedRef,
allowKeyboardControl,
...other
} = props;
return (
<BasePicker {...props} autoOk>
{({
date,
utils,
handleChange,
handleTextFieldChange,
isAccepted,
pick12hOr24hFormat,
handleClear,
handleAccept,
}) => (
<InlineWrapper
wider
innerRef={forwardedRef}
disableFuture={disableFuture}
disablePast={disablePast}
maxDate={maxDate}
minDate={minDate}
onChange={handleTextFieldChange}
value={value}
isAccepted={isAccepted}
handleAccept={handleAccept}
onClear={handleClear}
format={pick12hOr24hFormat(utils.dateTime12hFormat, utils.dateTime24hFormat)}
{...other}
>
<DateTimePicker
allowKeyboardControl={allowKeyboardControl}
ampm={ampm}
minutesStep={minutesStep}
animateYearScrolling={animateYearScrolling}
autoSubmit={autoSubmit}
date={date}
dateRangeIcon={dateRangeIcon}
disableFuture={disableFuture}
disablePast={disablePast}
leftArrowIcon={leftArrowIcon}
maxDate={maxDate}
minDate={minDate}
onChange={handleChange}
openTo={openTo}
renderDay={renderDay}
rightArrowIcon={rightArrowIcon}
shouldDisableDate={shouldDisableDate}
showTabs={showTabs}
timeIcon={timeIcon}
/>
</InlineWrapper>
)}
</BasePicker>
);
};
export default React.forwardRef((props: DateTimePickerInlineProps, ref) => (
<DateTimePickerInline {...props} forwardedRef={ref} />
));
| lib/src/DateTimePicker/DateTimePickerInline.tsx | 0 | https://github.com/mui/material-ui/commit/f36f617f4b16bdc03964778764e17bd47247b086 | [
0.03252950683236122,
0.005290406756103039,
0.00016564344696234912,
0.0002220767200924456,
0.010359710082411766
] |
{
"id": 5,
"code_window": [
" openTo: DomainPropTypes.datePickerView,\n",
" openToYearSelection: PropTypes.bool,\n",
" };\n",
"\n",
" public static defaultProps = {\n",
" minDate: new Date('1900-01-01'),\n",
" maxDate: new Date('2100-01-01'),\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
" openToYearSelection: false,\n"
],
"file_path": "lib/src/DatePicker/DatePicker.tsx",
"type": "add",
"edit_start_line_idx": 67
} | import Head from 'next/head';
import { withRouter, WithRouterProps } from 'next/router';
import { LOGO_URL, HOST_URL } from '_constants';
interface PageMetaProps extends WithRouterProps {
title?: string;
component?: string;
description?: string;
}
export function PageMeta({ title, component, router, description }: PageMetaProps) {
if (component) {
title = `${component} - Material-ui-pickers component`;
description = `${component} usage examples and API of material-ui-pickers`;
}
if (!description) {
description = title;
}
return (
<Head>
<title>{title}</title>
<meta name="twitter:card" content="summary" />
<meta name="twitter:image" content={LOGO_URL} />
<meta name="description" content={description} />
<meta name="og:description" content={description} />
<meta name="twitter:description" content={description} />
<meta property="og:title" content={title} />
<meta property="og:description" content={description} />
<meta property="og:image" content={LOGO_URL} />
<meta property="og:type" content="website" />
{router && <meta property="og:url" content={HOST_URL + router.pathname} />}
</Head>
);
}
export default withRouter(PageMeta);
| docs/_shared/PageMeta.tsx | 0 | https://github.com/mui/material-ui/commit/f36f617f4b16bdc03964778764e17bd47247b086 | [
0.0002179272414650768,
0.00018338611698709428,
0.00016935018356889486,
0.00017623219173401594,
0.000017499445675639436
] |
{
"id": 5,
"code_window": [
" openTo: DomainPropTypes.datePickerView,\n",
" openToYearSelection: PropTypes.bool,\n",
" };\n",
"\n",
" public static defaultProps = {\n",
" minDate: new Date('1900-01-01'),\n",
" maxDate: new Date('2100-01-01'),\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
" openToYearSelection: false,\n"
],
"file_path": "lib/src/DatePicker/DatePicker.tsx",
"type": "add",
"edit_start_line_idx": 67
} | import { InlineDateTimePicker } from 'material-ui-pickers';
import React, { Fragment, useState } from 'react';
function InlineDateTimePickerDemo(props) {
const [selectedDate, handleDateChange] = useState('2018-01-01T00:00:00.000Z');
return (
<Fragment>
<div className="picker">
<InlineDateTimePicker
label="Basic example"
value={selectedDate}
onChange={handleDateChange}
/>
</div>
<div className="picker">
<InlineDateTimePicker
keyboard
ampm={false}
label="With keyboard"
value={selectedDate}
onChange={handleDateChange}
onError={console.log}
disablePast
format={props.getFormatString({
moment: 'YYYY/MM/DD hh:mm A',
dateFns: 'yyyy/MM/dd HH:mm',
})}
mask={[
/\d/,
/\d/,
/\d/,
/\d/,
'/',
/\d/,
/\d/,
'/',
/\d/,
/\d/,
' ',
/\d/,
/\d/,
':',
/\d/,
/\d/,
]}
/>
</div>
</Fragment>
);
}
export default InlineDateTimePickerDemo;
| docs/pages/api/datetime-picker/InlineDateTimePicker.example.jsx | 0 | https://github.com/mui/material-ui/commit/f36f617f4b16bdc03964778764e17bd47247b086 | [
0.04370155930519104,
0.0074900309555232525,
0.00016728689661249518,
0.0001779232989065349,
0.016194844618439674
] |
{
"id": 6,
"code_window": [
" minDate: new Date('1900-01-01'),\n",
" maxDate: new Date('2100-01-01'),\n",
" openToYearSelection: false,\n",
" views: ['year', 'day'] as DatePickerViewType[],\n",
" };\n",
"\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "lib/src/DatePicker/DatePicker.tsx",
"type": "replace",
"edit_start_line_idx": 69
} | import clsx from 'clsx';
import * as PropTypes from 'prop-types';
import * as React from 'react';
import createStyles from '@material-ui/core/styles/createStyles';
import withStyles, { WithStyles } from '@material-ui/core/styles/withStyles';
import { isYearAndMonthViews, isYearOnlyView } from '../_helpers/date-utils';
import PickerToolbar from '../_shared/PickerToolbar';
import ToolbarButton from '../_shared/ToolbarButton';
import { withUtils, WithUtilsProps } from '../_shared/WithUtils';
import { DatePickerViewType } from '../constants/DatePickerView';
import { DateType, DomainPropTypes } from '../constants/prop-types';
import { MaterialUiPickersDate } from '../typings/date';
import Calendar, { RenderDay } from './components/Calendar';
import MonthSelection from './components/MonthSelection';
import YearSelection from './components/YearSelection';
export interface BaseDatePickerProps {
/** Min selectable date */
minDate?: DateType;
/** Max selectable date */
maxDate?: DateType;
/** Disable past dates */
disablePast?: boolean;
/** Disable future dates */
disableFuture?: boolean;
/** To animate scrolling to current year (with scrollIntoView) */
animateYearScrolling?: boolean;
/** Array of views to show. Order year -> month -> day */
views?: Array<'year' | 'month' | 'day'>;
/** Initial view to show when date picker is open */
openTo?: 'year' | 'month' | 'day';
/** @deprecated use openTo instead */
openToYearSelection?: boolean;
/** Left arrow icon */
leftArrowIcon?: React.ReactNode;
/** Right arrow icon */
rightArrowIcon?: React.ReactNode;
/** Custom renderer for day */
renderDay?: RenderDay;
/** Enables keyboard listener for moving between days in calendar */
allowKeyboardControl?: boolean;
/** Disable specific date */
shouldDisableDate?: (day: MaterialUiPickersDate) => boolean;
initialFocusedDate?: DateType;
}
export interface DatePickerProps
extends BaseDatePickerProps,
WithStyles<typeof styles>,
WithUtilsProps {
date: MaterialUiPickersDate;
onChange: (date: MaterialUiPickersDate, isFinished?: boolean) => void;
}
interface DatePickerState {
openView: DatePickerViewType;
}
export class DatePicker extends React.PureComponent<DatePickerProps> {
public static propTypes: any = {
views: PropTypes.arrayOf(DomainPropTypes.datePickerView),
openTo: DomainPropTypes.datePickerView,
openToYearSelection: PropTypes.bool,
};
public static defaultProps = {
minDate: new Date('1900-01-01'),
maxDate: new Date('2100-01-01'),
openToYearSelection: false,
views: ['year', 'day'] as DatePickerViewType[],
};
public state: DatePickerState = {
// TODO in v3 remove openToYearSelection
openView:
this.props.openTo || this.props.openToYearSelection!
? 'year'
: this.props.views![this.props.views!.length - 1],
};
get date() {
return this.props.date;
}
get minDate() {
return this.props.utils.date(this.props.minDate);
}
get maxDate() {
return this.props.utils.date(this.props.maxDate);
}
get isYearOnly() {
return isYearOnlyView(this.props.views!);
}
get isYearAndMonth() {
return isYearAndMonthViews(this.props.views!);
}
public handleYearSelect = (date: MaterialUiPickersDate) => {
this.props.onChange(date, this.isYearOnly);
if (this.isYearOnly) {
return;
}
if (this.props.views!.includes('month')) {
return this.openMonthSelection();
}
this.openCalendar();
};
public handleMonthSelect = (date: MaterialUiPickersDate) => {
const isFinish = !this.props.views!.includes('day');
this.props.onChange(date, isFinish);
if (!isFinish) {
this.openCalendar();
}
};
public openYearSelection = () => {
this.setState({ openView: 'year' });
};
public openCalendar = () => {
this.setState({ openView: 'day' });
};
public openMonthSelection = () => {
this.setState({ openView: 'month' });
};
public render() {
const { openView } = this.state;
const {
disablePast,
disableFuture,
onChange,
animateYearScrolling,
leftArrowIcon,
rightArrowIcon,
renderDay,
utils,
shouldDisableDate,
allowKeyboardControl,
classes,
} = this.props;
return (
<>
<PickerToolbar className={clsx({ [classes.toolbarCenter]: this.isYearOnly })}>
<ToolbarButton
variant={this.isYearOnly ? 'h3' : 'subtitle1'}
onClick={this.isYearOnly ? undefined : this.openYearSelection}
selected={openView === 'year'}
label={utils.getYearText(this.date)}
/>
{!this.isYearOnly &&
!this.isYearAndMonth && (
<ToolbarButton
variant="h4"
onClick={this.openCalendar}
selected={openView === 'day'}
label={utils.getDatePickerHeaderText(this.date)}
/>
)}
{this.isYearAndMonth && (
<ToolbarButton
variant="h4"
onClick={this.openMonthSelection}
selected={openView === 'month'}
label={utils.getMonthText(this.date)}
/>
)}
</PickerToolbar>
{this.props.children}
{openView === 'year' && (
<YearSelection
date={this.date}
onChange={this.handleYearSelect}
minDate={this.minDate}
maxDate={this.maxDate}
disablePast={disablePast}
disableFuture={disableFuture}
animateYearScrolling={animateYearScrolling}
/>
)}
{openView === 'month' && (
<MonthSelection
date={this.date}
onChange={this.handleMonthSelect}
minDate={this.minDate}
maxDate={this.maxDate}
disablePast={disablePast}
disableFuture={disableFuture}
/>
)}
{openView === 'day' && (
<Calendar
date={this.date}
onChange={onChange}
disablePast={disablePast}
disableFuture={disableFuture}
minDate={this.minDate}
maxDate={this.maxDate}
leftArrowIcon={leftArrowIcon}
rightArrowIcon={rightArrowIcon}
renderDay={renderDay}
shouldDisableDate={shouldDisableDate}
allowKeyboardControl={allowKeyboardControl}
/>
)}
</>
);
}
}
export const styles = () =>
createStyles({
toolbarCenter: {
flexDirection: 'row',
alignItems: 'center',
},
});
export default withStyles(styles)(withUtils()(DatePicker));
| lib/src/DatePicker/DatePicker.tsx | 1 | https://github.com/mui/material-ui/commit/f36f617f4b16bdc03964778764e17bd47247b086 | [
0.6632197499275208,
0.02968764118850231,
0.0001663625444052741,
0.00024643726646900177,
0.1321835070848465
] |
{
"id": 6,
"code_window": [
" minDate: new Date('1900-01-01'),\n",
" maxDate: new Date('2100-01-01'),\n",
" openToYearSelection: false,\n",
" views: ['year', 'day'] as DatePickerViewType[],\n",
" };\n",
"\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "lib/src/DatePicker/DatePicker.tsx",
"type": "replace",
"edit_start_line_idx": 69
} | import { ReactWrapper } from 'enzyme';
import * as React from 'react';
import DateTimePickerModal, {
DateTimePickerModalProps,
} from '../../DateTimePicker/DateTimePickerModal';
import { mount, utilsToUse } from '../test-utils';
const format = process.env.UTILS === 'moment' ? 'MM/DD/YYYY HH:mm' : 'MM/dd/yyyy hh:mm';
describe('e2e - DateTimePickerModal', () => {
let component: ReactWrapper<DateTimePickerModalProps>;
const onCloseMock = jest.fn();
const onChangeMock = jest.fn();
beforeEach(() => {
component = mount(
<DateTimePickerModal
format={format}
onClose={onCloseMock}
onChange={onChangeMock}
value={utilsToUse.date('2018-01-01T00:00:00.000Z')}
/>
);
});
it('Should renders', () => {
expect(component).toBeTruthy();
});
it('Should open modal with picker on click', () => {
component.find('input').simulate('click');
expect(component.find('Dialog').props().open).toBeTruthy();
});
it('Should update state when passing new value from outside', () => {
component.setProps({ value: '2018-01-01T00:00:00.000Z' });
component.update(); // make additional react tick to update text field
const expectedString = utilsToUse.format(utilsToUse.date('2018-01-01T00:00:00.000Z'), format);
expect(component.find('input').props().value).toBe(expectedString);
});
it('Should change internal state on update', () => {
component.find('input').simulate('click');
component
.find('Day button')
.at(3)
.simulate('click');
expect(
component
.find('ToolbarButton')
.at(0)
.text()
).toBe('2018');
// expect(component.find('ToolbarButton').at(1).text()).toBe('Jan 3');
});
it('Should handle accept on enter', () => {
component.find('input').simulate('click');
const onKeyDown = component
.find('EventListener')
.at(0)
.props().onKeyDown;
if (!onKeyDown) {
throw new Error('Expected onKeyDown to be non-null');
}
onKeyDown({
key: 'Enter',
preventDefault: jest.fn(),
} as any);
expect(onCloseMock).toHaveBeenCalled();
expect(onChangeMock).toHaveBeenCalled();
});
});
describe('e2e - DateTimePickerModal keyboard', () => {
let component: ReactWrapper<DateTimePickerModalProps>;
const onChangeMock = jest.fn();
const onInputChangeMock = jest.fn();
beforeEach(() => {
component = mount(
<DateTimePickerModal
keyboard
format={format}
value={utilsToUse.date('2018-01-01T00:00:00.000')}
onChange={onChangeMock}
onInputChange={onInputChangeMock}
/>
);
});
it('Should apply keyboard input', () => {
component.find('input').simulate('change', { target: { value: '02/01/2018 10:00' } });
component.find('input').simulate('blur');
expect(onChangeMock).toHaveBeenCalled();
expect(onInputChangeMock).toHaveBeenCalled();
});
});
| lib/src/__tests__/e2e/DateTimePickerModal.test.tsx | 0 | https://github.com/mui/material-ui/commit/f36f617f4b16bdc03964778764e17bd47247b086 | [
0.0001791232352843508,
0.00017255749844480306,
0.00016463836072944105,
0.00017274689162150025,
0.000004696739324572263
] |
{
"id": 6,
"code_window": [
" minDate: new Date('1900-01-01'),\n",
" maxDate: new Date('2100-01-01'),\n",
" openToYearSelection: false,\n",
" views: ['year', 'day'] as DatePickerViewType[],\n",
" };\n",
"\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "lib/src/DatePicker/DatePicker.tsx",
"type": "replace",
"edit_start_line_idx": 69
} | import { ShallowWrapper } from 'enzyme';
import * as React from 'react';
import { Month, MonthProps } from '../../DatePicker/components/Month';
import { shallow, utilsToUse } from '../test-utils';
describe('Month', () => {
let component: ShallowWrapper<MonthProps>;
beforeEach(() => {
component = shallow(
<Month classes={{} as any} value={utilsToUse.date('01-01-2017')} onSelect={jest.fn()}>
Oct
</Month>
);
});
it('Should render', () => {
expect(component).toBeTruthy();
});
});
describe('Month - disabled state', () => {
let component: ShallowWrapper<MonthProps>;
beforeEach(() => {
component = shallow(
<Month
classes={{} as any}
disabled
value={utilsToUse.date('01-01-2017')}
onSelect={jest.fn()}
>
Oct
</Month>
);
});
it('Should render in disabled state', () => {
expect(component.prop('tabIndex')).toBe(-1);
});
});
| lib/src/__tests__/DatePicker/Month.test.tsx | 0 | https://github.com/mui/material-ui/commit/f36f617f4b16bdc03964778764e17bd47247b086 | [
0.00017785007366910577,
0.00017494703934062272,
0.00017072309856303036,
0.00017553089128341526,
0.0000023275108560483204
] |
{
"id": 6,
"code_window": [
" minDate: new Date('1900-01-01'),\n",
" maxDate: new Date('2100-01-01'),\n",
" openToYearSelection: false,\n",
" views: ['year', 'day'] as DatePickerViewType[],\n",
" };\n",
"\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "lib/src/DatePicker/DatePicker.tsx",
"type": "replace",
"edit_start_line_idx": 69
} | import { ShallowWrapper } from 'enzyme';
import * as React from 'react';
import { Calendar, CalendarProps } from '../../DatePicker/components/Calendar';
import { shallowRender, utilsToUse } from '../test-utils';
describe('Calendar', () => {
let component: ShallowWrapper<CalendarProps>;
beforeEach(() => {
component = shallowRender(props => (
<Calendar date={utilsToUse.date('01-01-2017')} onChange={jest.fn()} {...props} />
));
});
it('Should renders', () => {
// console.log(component.debug());
expect(component).toBeTruthy();
});
});
describe('Calendar - disabled selected date on mount', () => {
let component: ShallowWrapper<any, any, any>;
beforeEach(() => {
component = shallowRender(props => (
<Calendar
date={utilsToUse.date('01-01-2017')}
minDate={new Date('01-01-2018')}
onChange={jest.fn()}
utils={utilsToUse}
{...props}
/>
));
});
it('Should dispatch onDateSelect with isFinish = false on mount', () => {
const { onChange } = component.instance().props;
if (process.env.UTILS === 'moment') {
return expect(onChange).toHaveBeenCalled();
}
expect(onChange).toHaveBeenCalledWith(utilsToUse.date('01-01-2018'), false);
});
});
describe('Calendar - keyboard control', () => {
let component: ShallowWrapper;
const onChangeMock = jest.fn();
beforeEach(() => {
component = shallowRender(props => (
<Calendar
date={utilsToUse.date('01-01-2017')}
minDate={new Date('01-01-2018')}
onChange={onChangeMock}
theme={{ direction: 'ltr' } as any}
allowKeyboardControl
{...props}
/>
));
});
it('Should render go to prev week on up', () => {
component.find('EventListener').simulate('keyDown', { keyCode: 38, preventDefault: jest.fn() });
expect(onChangeMock).toHaveBeenCalled();
});
it('Should render go to next week on down', () => {
component.find('EventListener').simulate('keyDown', { keyCode: 40, preventDefault: jest.fn() });
expect(onChangeMock).toHaveBeenCalled();
});
it('Should render go to prev week on up', () => {
component.find('EventListener').simulate('keyDown', { keyCode: 37, preventDefault: jest.fn() });
expect(onChangeMock).toHaveBeenCalled();
});
it('Should render go to prev week on up', () => {
component.find('EventListener').simulate('keyDown', { keyCode: 39, preventDefault: jest.fn() });
expect(onChangeMock).toHaveBeenCalled();
});
});
| lib/src/__tests__/DatePicker/Calendar.test.tsx | 0 | https://github.com/mui/material-ui/commit/f36f617f4b16bdc03964778764e17bd47247b086 | [
0.00017698275041766465,
0.0001730375806801021,
0.00016692584904376417,
0.00017372690490446985,
0.000003635511802713154
] |
{
"id": 7,
"code_window": [
" };\n",
"\n",
" public state: DatePickerState = {\n",
" // TODO in v3 remove openToYearSelection\n",
" openView:\n",
" this.props.openTo || this.props.openToYearSelection!\n",
" ? 'year'\n",
" : this.props.views![this.props.views!.length - 1],\n",
" };\n",
"\n",
" get date() {\n",
" return this.props.date;\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" openView: this.props.openTo\n",
" ? this.props.openTo\n",
" : this.props.openToYearSelection\n",
" ? 'year'\n",
" : this.props.views![this.props.views!.length - 1],\n"
],
"file_path": "lib/src/DatePicker/DatePicker.tsx",
"type": "replace",
"edit_start_line_idx": 75
} | import clsx from 'clsx';
import * as PropTypes from 'prop-types';
import * as React from 'react';
import createStyles from '@material-ui/core/styles/createStyles';
import withStyles, { WithStyles } from '@material-ui/core/styles/withStyles';
import { isYearAndMonthViews, isYearOnlyView } from '../_helpers/date-utils';
import PickerToolbar from '../_shared/PickerToolbar';
import ToolbarButton from '../_shared/ToolbarButton';
import { withUtils, WithUtilsProps } from '../_shared/WithUtils';
import { DatePickerViewType } from '../constants/DatePickerView';
import { DateType, DomainPropTypes } from '../constants/prop-types';
import { MaterialUiPickersDate } from '../typings/date';
import Calendar, { RenderDay } from './components/Calendar';
import MonthSelection from './components/MonthSelection';
import YearSelection from './components/YearSelection';
export interface BaseDatePickerProps {
/** Min selectable date */
minDate?: DateType;
/** Max selectable date */
maxDate?: DateType;
/** Disable past dates */
disablePast?: boolean;
/** Disable future dates */
disableFuture?: boolean;
/** To animate scrolling to current year (with scrollIntoView) */
animateYearScrolling?: boolean;
/** Array of views to show. Order year -> month -> day */
views?: Array<'year' | 'month' | 'day'>;
/** Initial view to show when date picker is open */
openTo?: 'year' | 'month' | 'day';
/** @deprecated use openTo instead */
openToYearSelection?: boolean;
/** Left arrow icon */
leftArrowIcon?: React.ReactNode;
/** Right arrow icon */
rightArrowIcon?: React.ReactNode;
/** Custom renderer for day */
renderDay?: RenderDay;
/** Enables keyboard listener for moving between days in calendar */
allowKeyboardControl?: boolean;
/** Disable specific date */
shouldDisableDate?: (day: MaterialUiPickersDate) => boolean;
initialFocusedDate?: DateType;
}
export interface DatePickerProps
extends BaseDatePickerProps,
WithStyles<typeof styles>,
WithUtilsProps {
date: MaterialUiPickersDate;
onChange: (date: MaterialUiPickersDate, isFinished?: boolean) => void;
}
interface DatePickerState {
openView: DatePickerViewType;
}
export class DatePicker extends React.PureComponent<DatePickerProps> {
public static propTypes: any = {
views: PropTypes.arrayOf(DomainPropTypes.datePickerView),
openTo: DomainPropTypes.datePickerView,
openToYearSelection: PropTypes.bool,
};
public static defaultProps = {
minDate: new Date('1900-01-01'),
maxDate: new Date('2100-01-01'),
openToYearSelection: false,
views: ['year', 'day'] as DatePickerViewType[],
};
public state: DatePickerState = {
// TODO in v3 remove openToYearSelection
openView:
this.props.openTo || this.props.openToYearSelection!
? 'year'
: this.props.views![this.props.views!.length - 1],
};
get date() {
return this.props.date;
}
get minDate() {
return this.props.utils.date(this.props.minDate);
}
get maxDate() {
return this.props.utils.date(this.props.maxDate);
}
get isYearOnly() {
return isYearOnlyView(this.props.views!);
}
get isYearAndMonth() {
return isYearAndMonthViews(this.props.views!);
}
public handleYearSelect = (date: MaterialUiPickersDate) => {
this.props.onChange(date, this.isYearOnly);
if (this.isYearOnly) {
return;
}
if (this.props.views!.includes('month')) {
return this.openMonthSelection();
}
this.openCalendar();
};
public handleMonthSelect = (date: MaterialUiPickersDate) => {
const isFinish = !this.props.views!.includes('day');
this.props.onChange(date, isFinish);
if (!isFinish) {
this.openCalendar();
}
};
public openYearSelection = () => {
this.setState({ openView: 'year' });
};
public openCalendar = () => {
this.setState({ openView: 'day' });
};
public openMonthSelection = () => {
this.setState({ openView: 'month' });
};
public render() {
const { openView } = this.state;
const {
disablePast,
disableFuture,
onChange,
animateYearScrolling,
leftArrowIcon,
rightArrowIcon,
renderDay,
utils,
shouldDisableDate,
allowKeyboardControl,
classes,
} = this.props;
return (
<>
<PickerToolbar className={clsx({ [classes.toolbarCenter]: this.isYearOnly })}>
<ToolbarButton
variant={this.isYearOnly ? 'h3' : 'subtitle1'}
onClick={this.isYearOnly ? undefined : this.openYearSelection}
selected={openView === 'year'}
label={utils.getYearText(this.date)}
/>
{!this.isYearOnly &&
!this.isYearAndMonth && (
<ToolbarButton
variant="h4"
onClick={this.openCalendar}
selected={openView === 'day'}
label={utils.getDatePickerHeaderText(this.date)}
/>
)}
{this.isYearAndMonth && (
<ToolbarButton
variant="h4"
onClick={this.openMonthSelection}
selected={openView === 'month'}
label={utils.getMonthText(this.date)}
/>
)}
</PickerToolbar>
{this.props.children}
{openView === 'year' && (
<YearSelection
date={this.date}
onChange={this.handleYearSelect}
minDate={this.minDate}
maxDate={this.maxDate}
disablePast={disablePast}
disableFuture={disableFuture}
animateYearScrolling={animateYearScrolling}
/>
)}
{openView === 'month' && (
<MonthSelection
date={this.date}
onChange={this.handleMonthSelect}
minDate={this.minDate}
maxDate={this.maxDate}
disablePast={disablePast}
disableFuture={disableFuture}
/>
)}
{openView === 'day' && (
<Calendar
date={this.date}
onChange={onChange}
disablePast={disablePast}
disableFuture={disableFuture}
minDate={this.minDate}
maxDate={this.maxDate}
leftArrowIcon={leftArrowIcon}
rightArrowIcon={rightArrowIcon}
renderDay={renderDay}
shouldDisableDate={shouldDisableDate}
allowKeyboardControl={allowKeyboardControl}
/>
)}
</>
);
}
}
export const styles = () =>
createStyles({
toolbarCenter: {
flexDirection: 'row',
alignItems: 'center',
},
});
export default withStyles(styles)(withUtils()(DatePicker));
| lib/src/DatePicker/DatePicker.tsx | 1 | https://github.com/mui/material-ui/commit/f36f617f4b16bdc03964778764e17bd47247b086 | [
0.9983202815055847,
0.20970720052719116,
0.00016524780949112028,
0.00438840314745903,
0.34692490100860596
] |
{
"id": 7,
"code_window": [
" };\n",
"\n",
" public state: DatePickerState = {\n",
" // TODO in v3 remove openToYearSelection\n",
" openView:\n",
" this.props.openTo || this.props.openToYearSelection!\n",
" ? 'year'\n",
" : this.props.views![this.props.views!.length - 1],\n",
" };\n",
"\n",
" get date() {\n",
" return this.props.date;\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" openView: this.props.openTo\n",
" ? this.props.openTo\n",
" : this.props.openToYearSelection\n",
" ? 'year'\n",
" : this.props.views![this.props.views!.length - 1],\n"
],
"file_path": "lib/src/DatePicker/DatePicker.tsx",
"type": "replace",
"edit_start_line_idx": 75
} | import * as React from 'react';
import BasePicker, { BasePickerProps } from '../_shared/BasePicker';
import { ExtendWrapper } from '../wrappers/ExtendWrapper';
import InlineWrapper, { OuterInlineWrapperProps } from '../wrappers/InlineWrapper';
import DateTimePicker, { BaseDateTimePickerProps } from './DateTimePicker';
export interface DateTimePickerInlineProps
extends BasePickerProps,
BaseDateTimePickerProps,
ExtendWrapper<OuterInlineWrapperProps> {}
export const DateTimePickerInline: React.SFC<DateTimePickerInlineProps> = props => {
const {
value,
format,
autoOk,
openTo,
minDate,
maxDate,
initialFocusedDate,
showTabs,
autoSubmit,
disablePast,
disableFuture,
leftArrowIcon,
rightArrowIcon,
dateRangeIcon,
timeIcon,
renderDay,
ampm,
minutesStep,
shouldDisableDate,
animateYearScrolling,
forwardedRef,
allowKeyboardControl,
...other
} = props;
return (
<BasePicker {...props} autoOk>
{({
date,
utils,
handleChange,
handleTextFieldChange,
isAccepted,
pick12hOr24hFormat,
handleClear,
handleAccept,
}) => (
<InlineWrapper
wider
innerRef={forwardedRef}
disableFuture={disableFuture}
disablePast={disablePast}
maxDate={maxDate}
minDate={minDate}
onChange={handleTextFieldChange}
value={value}
isAccepted={isAccepted}
handleAccept={handleAccept}
onClear={handleClear}
format={pick12hOr24hFormat(utils.dateTime12hFormat, utils.dateTime24hFormat)}
{...other}
>
<DateTimePicker
allowKeyboardControl={allowKeyboardControl}
ampm={ampm}
minutesStep={minutesStep}
animateYearScrolling={animateYearScrolling}
autoSubmit={autoSubmit}
date={date}
dateRangeIcon={dateRangeIcon}
disableFuture={disableFuture}
disablePast={disablePast}
leftArrowIcon={leftArrowIcon}
maxDate={maxDate}
minDate={minDate}
onChange={handleChange}
openTo={openTo}
renderDay={renderDay}
rightArrowIcon={rightArrowIcon}
shouldDisableDate={shouldDisableDate}
showTabs={showTabs}
timeIcon={timeIcon}
/>
</InlineWrapper>
)}
</BasePicker>
);
};
export default React.forwardRef((props: DateTimePickerInlineProps, ref) => (
<DateTimePickerInline {...props} forwardedRef={ref} />
));
| lib/src/DateTimePicker/DateTimePickerInline.tsx | 0 | https://github.com/mui/material-ui/commit/f36f617f4b16bdc03964778764e17bd47247b086 | [
0.0068386392667889595,
0.0012933441903442144,
0.0001676286046858877,
0.0002492924686521292,
0.0020294352434575558
] |
{
"id": 7,
"code_window": [
" };\n",
"\n",
" public state: DatePickerState = {\n",
" // TODO in v3 remove openToYearSelection\n",
" openView:\n",
" this.props.openTo || this.props.openToYearSelection!\n",
" ? 'year'\n",
" : this.props.views![this.props.views!.length - 1],\n",
" };\n",
"\n",
" get date() {\n",
" return this.props.date;\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" openView: this.props.openTo\n",
" ? this.props.openTo\n",
" : this.props.openToYearSelection\n",
" ? 'year'\n",
" : this.props.views![this.props.views!.length - 1],\n"
],
"file_path": "lib/src/DatePicker/DatePicker.tsx",
"type": "replace",
"edit_start_line_idx": 75
} | {
"compilerOptions": {
"strict": true,
"baseUrl": "../node_modules",
"target": "es5",
"lib": ["es5", "dom"],
"types": ["cypress"]
},
"include": ["**/*.ts"]
}
| e2e/tsconfig.json | 0 | https://github.com/mui/material-ui/commit/f36f617f4b16bdc03964778764e17bd47247b086 | [
0.00038490546285174787,
0.00027868314646184444,
0.00017246084462385625,
0.00027868314646184444,
0.00010622230911394581
] |
{
"id": 7,
"code_window": [
" };\n",
"\n",
" public state: DatePickerState = {\n",
" // TODO in v3 remove openToYearSelection\n",
" openView:\n",
" this.props.openTo || this.props.openToYearSelection!\n",
" ? 'year'\n",
" : this.props.views![this.props.views!.length - 1],\n",
" };\n",
"\n",
" get date() {\n",
" return this.props.date;\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" openView: this.props.openTo\n",
" ? this.props.openTo\n",
" : this.props.openToYearSelection\n",
" ? 'year'\n",
" : this.props.views![this.props.views!.length - 1],\n"
],
"file_path": "lib/src/DatePicker/DatePicker.tsx",
"type": "replace",
"edit_start_line_idx": 75
} | import { ShallowWrapper } from 'enzyme';
import * as React from 'react';
import { ClockNumber, ClockNumberProps } from '../../TimePicker/components/ClockNumber';
import { shallow } from '../test-utils';
describe('ClockNumber', () => {
let component: ShallowWrapper<ClockNumberProps>;
beforeEach(() => {
component = shallow(<ClockNumber classes={{} as any} index={0} label="foo" selected />);
});
it('Should renders', () => {
// console.log(component.debug());
expect(component).toBeTruthy();
});
});
| lib/src/__tests__/TimePicker/ClockNumber.test.tsx | 0 | https://github.com/mui/material-ui/commit/f36f617f4b16bdc03964778764e17bd47247b086 | [
0.0001722570596029982,
0.00017146104073617607,
0.00017066502186935395,
0.00017146104073617607,
7.960188668221235e-7
] |
{
"id": 8,
"code_window": [
" label={utils.getYearText(this.date)}\n",
" />\n",
"\n",
" {!this.isYearOnly &&\n",
" !this.isYearAndMonth && (\n",
" <ToolbarButton\n",
" variant=\"h4\"\n",
" onClick={this.openCalendar}\n",
" selected={openView === 'day'}\n",
" label={utils.getDatePickerHeaderText(this.date)}\n",
" />\n",
" )}\n",
"\n",
" {this.isYearAndMonth && (\n",
" <ToolbarButton\n",
" variant=\"h4\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" {!this.isYearOnly && !this.isYearAndMonth && (\n",
" <ToolbarButton\n",
" variant=\"h4\"\n",
" onClick={this.openCalendar}\n",
" selected={openView === 'day'}\n",
" label={utils.getDatePickerHeaderText(this.date)}\n",
" />\n",
" )}\n"
],
"file_path": "lib/src/DatePicker/DatePicker.tsx",
"type": "replace",
"edit_start_line_idx": 162
} | import clsx from 'clsx';
import * as PropTypes from 'prop-types';
import * as React from 'react';
import createStyles from '@material-ui/core/styles/createStyles';
import withStyles, { WithStyles } from '@material-ui/core/styles/withStyles';
import { isYearAndMonthViews, isYearOnlyView } from '../_helpers/date-utils';
import PickerToolbar from '../_shared/PickerToolbar';
import ToolbarButton from '../_shared/ToolbarButton';
import { withUtils, WithUtilsProps } from '../_shared/WithUtils';
import { DatePickerViewType } from '../constants/DatePickerView';
import { DateType, DomainPropTypes } from '../constants/prop-types';
import { MaterialUiPickersDate } from '../typings/date';
import Calendar, { RenderDay } from './components/Calendar';
import MonthSelection from './components/MonthSelection';
import YearSelection from './components/YearSelection';
export interface BaseDatePickerProps {
/** Min selectable date */
minDate?: DateType;
/** Max selectable date */
maxDate?: DateType;
/** Disable past dates */
disablePast?: boolean;
/** Disable future dates */
disableFuture?: boolean;
/** To animate scrolling to current year (with scrollIntoView) */
animateYearScrolling?: boolean;
/** Array of views to show. Order year -> month -> day */
views?: Array<'year' | 'month' | 'day'>;
/** Initial view to show when date picker is open */
openTo?: 'year' | 'month' | 'day';
/** @deprecated use openTo instead */
openToYearSelection?: boolean;
/** Left arrow icon */
leftArrowIcon?: React.ReactNode;
/** Right arrow icon */
rightArrowIcon?: React.ReactNode;
/** Custom renderer for day */
renderDay?: RenderDay;
/** Enables keyboard listener for moving between days in calendar */
allowKeyboardControl?: boolean;
/** Disable specific date */
shouldDisableDate?: (day: MaterialUiPickersDate) => boolean;
initialFocusedDate?: DateType;
}
export interface DatePickerProps
extends BaseDatePickerProps,
WithStyles<typeof styles>,
WithUtilsProps {
date: MaterialUiPickersDate;
onChange: (date: MaterialUiPickersDate, isFinished?: boolean) => void;
}
interface DatePickerState {
openView: DatePickerViewType;
}
export class DatePicker extends React.PureComponent<DatePickerProps> {
public static propTypes: any = {
views: PropTypes.arrayOf(DomainPropTypes.datePickerView),
openTo: DomainPropTypes.datePickerView,
openToYearSelection: PropTypes.bool,
};
public static defaultProps = {
minDate: new Date('1900-01-01'),
maxDate: new Date('2100-01-01'),
openToYearSelection: false,
views: ['year', 'day'] as DatePickerViewType[],
};
public state: DatePickerState = {
// TODO in v3 remove openToYearSelection
openView:
this.props.openTo || this.props.openToYearSelection!
? 'year'
: this.props.views![this.props.views!.length - 1],
};
get date() {
return this.props.date;
}
get minDate() {
return this.props.utils.date(this.props.minDate);
}
get maxDate() {
return this.props.utils.date(this.props.maxDate);
}
get isYearOnly() {
return isYearOnlyView(this.props.views!);
}
get isYearAndMonth() {
return isYearAndMonthViews(this.props.views!);
}
public handleYearSelect = (date: MaterialUiPickersDate) => {
this.props.onChange(date, this.isYearOnly);
if (this.isYearOnly) {
return;
}
if (this.props.views!.includes('month')) {
return this.openMonthSelection();
}
this.openCalendar();
};
public handleMonthSelect = (date: MaterialUiPickersDate) => {
const isFinish = !this.props.views!.includes('day');
this.props.onChange(date, isFinish);
if (!isFinish) {
this.openCalendar();
}
};
public openYearSelection = () => {
this.setState({ openView: 'year' });
};
public openCalendar = () => {
this.setState({ openView: 'day' });
};
public openMonthSelection = () => {
this.setState({ openView: 'month' });
};
public render() {
const { openView } = this.state;
const {
disablePast,
disableFuture,
onChange,
animateYearScrolling,
leftArrowIcon,
rightArrowIcon,
renderDay,
utils,
shouldDisableDate,
allowKeyboardControl,
classes,
} = this.props;
return (
<>
<PickerToolbar className={clsx({ [classes.toolbarCenter]: this.isYearOnly })}>
<ToolbarButton
variant={this.isYearOnly ? 'h3' : 'subtitle1'}
onClick={this.isYearOnly ? undefined : this.openYearSelection}
selected={openView === 'year'}
label={utils.getYearText(this.date)}
/>
{!this.isYearOnly &&
!this.isYearAndMonth && (
<ToolbarButton
variant="h4"
onClick={this.openCalendar}
selected={openView === 'day'}
label={utils.getDatePickerHeaderText(this.date)}
/>
)}
{this.isYearAndMonth && (
<ToolbarButton
variant="h4"
onClick={this.openMonthSelection}
selected={openView === 'month'}
label={utils.getMonthText(this.date)}
/>
)}
</PickerToolbar>
{this.props.children}
{openView === 'year' && (
<YearSelection
date={this.date}
onChange={this.handleYearSelect}
minDate={this.minDate}
maxDate={this.maxDate}
disablePast={disablePast}
disableFuture={disableFuture}
animateYearScrolling={animateYearScrolling}
/>
)}
{openView === 'month' && (
<MonthSelection
date={this.date}
onChange={this.handleMonthSelect}
minDate={this.minDate}
maxDate={this.maxDate}
disablePast={disablePast}
disableFuture={disableFuture}
/>
)}
{openView === 'day' && (
<Calendar
date={this.date}
onChange={onChange}
disablePast={disablePast}
disableFuture={disableFuture}
minDate={this.minDate}
maxDate={this.maxDate}
leftArrowIcon={leftArrowIcon}
rightArrowIcon={rightArrowIcon}
renderDay={renderDay}
shouldDisableDate={shouldDisableDate}
allowKeyboardControl={allowKeyboardControl}
/>
)}
</>
);
}
}
export const styles = () =>
createStyles({
toolbarCenter: {
flexDirection: 'row',
alignItems: 'center',
},
});
export default withStyles(styles)(withUtils()(DatePicker));
| lib/src/DatePicker/DatePicker.tsx | 1 | https://github.com/mui/material-ui/commit/f36f617f4b16bdc03964778764e17bd47247b086 | [
0.9975767731666565,
0.05246133729815483,
0.00016317925474140793,
0.000607200781814754,
0.20247945189476013
] |
{
"id": 8,
"code_window": [
" label={utils.getYearText(this.date)}\n",
" />\n",
"\n",
" {!this.isYearOnly &&\n",
" !this.isYearAndMonth && (\n",
" <ToolbarButton\n",
" variant=\"h4\"\n",
" onClick={this.openCalendar}\n",
" selected={openView === 'day'}\n",
" label={utils.getDatePickerHeaderText(this.date)}\n",
" />\n",
" )}\n",
"\n",
" {this.isYearAndMonth && (\n",
" <ToolbarButton\n",
" variant=\"h4\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" {!this.isYearOnly && !this.isYearAndMonth && (\n",
" <ToolbarButton\n",
" variant=\"h4\"\n",
" onClick={this.openCalendar}\n",
" selected={openView === 'day'}\n",
" label={utils.getDatePickerHeaderText(this.date)}\n",
" />\n",
" )}\n"
],
"file_path": "lib/src/DatePicker/DatePicker.tsx",
"type": "replace",
"edit_start_line_idx": 162
} | <!-- Thanks so much for your time taking to contribute, your work is appreciated! ❤️ -->
This PR closes # <!-- Please refer issue number here, if exists -->
## Description
| .github/PULL_REQUEST_TEMPLATE.md | 0 | https://github.com/mui/material-ui/commit/f36f617f4b16bdc03964778764e17bd47247b086 | [
0.00017580222629476339,
0.00017580222629476339,
0.00017580222629476339,
0.00017580222629476339,
0
] |
{
"id": 8,
"code_window": [
" label={utils.getYearText(this.date)}\n",
" />\n",
"\n",
" {!this.isYearOnly &&\n",
" !this.isYearAndMonth && (\n",
" <ToolbarButton\n",
" variant=\"h4\"\n",
" onClick={this.openCalendar}\n",
" selected={openView === 'day'}\n",
" label={utils.getDatePickerHeaderText(this.date)}\n",
" />\n",
" )}\n",
"\n",
" {this.isYearAndMonth && (\n",
" <ToolbarButton\n",
" variant=\"h4\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" {!this.isYearOnly && !this.isYearAndMonth && (\n",
" <ToolbarButton\n",
" variant=\"h4\"\n",
" onClick={this.openCalendar}\n",
" selected={openView === 'day'}\n",
" label={utils.getDatePickerHeaderText(this.date)}\n",
" />\n",
" )}\n"
],
"file_path": "lib/src/DatePicker/DatePicker.tsx",
"type": "replace",
"edit_start_line_idx": 162
} | import { ShallowWrapper } from 'enzyme';
import * as React from 'react';
import { ClockNumber, ClockNumberProps } from '../../TimePicker/components/ClockNumber';
import { shallow } from '../test-utils';
describe('ClockNumber', () => {
let component: ShallowWrapper<ClockNumberProps>;
beforeEach(() => {
component = shallow(<ClockNumber classes={{} as any} index={0} label="foo" selected />);
});
it('Should renders', () => {
// console.log(component.debug());
expect(component).toBeTruthy();
});
});
| lib/src/__tests__/TimePicker/ClockNumber.test.tsx | 0 | https://github.com/mui/material-ui/commit/f36f617f4b16bdc03964778764e17bd47247b086 | [
0.00017431531159672886,
0.0001727637427393347,
0.00017121217388194054,
0.0001727637427393347,
0.0000015515688573941588
] |
{
"id": 8,
"code_window": [
" label={utils.getYearText(this.date)}\n",
" />\n",
"\n",
" {!this.isYearOnly &&\n",
" !this.isYearAndMonth && (\n",
" <ToolbarButton\n",
" variant=\"h4\"\n",
" onClick={this.openCalendar}\n",
" selected={openView === 'day'}\n",
" label={utils.getDatePickerHeaderText(this.date)}\n",
" />\n",
" )}\n",
"\n",
" {this.isYearAndMonth && (\n",
" <ToolbarButton\n",
" variant=\"h4\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" {!this.isYearOnly && !this.isYearAndMonth && (\n",
" <ToolbarButton\n",
" variant=\"h4\"\n",
" onClick={this.openCalendar}\n",
" selected={openView === 'day'}\n",
" label={utils.getDatePickerHeaderText(this.date)}\n",
" />\n",
" )}\n"
],
"file_path": "lib/src/DatePicker/DatePicker.tsx",
"type": "replace",
"edit_start_line_idx": 162
} | {
"extends": "../../tsconfig.json",
"include": ["./**/*.tsx"],
"exclude": []
}
| lib/src/__tests__/tsconfig.json | 0 | https://github.com/mui/material-ui/commit/f36f617f4b16bdc03964778764e17bd47247b086 | [
0.00017102601123042405,
0.00017102601123042405,
0.00017102601123042405,
0.00017102601123042405,
0
] |
{
"id": 9,
"code_window": [
" rightArrowIcon,\n",
" shouldDisableDate,\n",
" value,\n",
" autoOk,\n",
" onlyCalendar,\n",
" ...other\n",
" } = props;\n",
"\n",
" const ComponentToShow: any = onlyCalendar ? Calendar : DatePicker;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" views,\n",
" openTo,\n"
],
"file_path": "lib/src/DatePicker/DatePickerInline.tsx",
"type": "add",
"edit_start_line_idx": 37
} | import clsx from 'clsx';
import * as PropTypes from 'prop-types';
import * as React from 'react';
import createStyles from '@material-ui/core/styles/createStyles';
import withStyles, { WithStyles } from '@material-ui/core/styles/withStyles';
import { isYearAndMonthViews, isYearOnlyView } from '../_helpers/date-utils';
import PickerToolbar from '../_shared/PickerToolbar';
import ToolbarButton from '../_shared/ToolbarButton';
import { withUtils, WithUtilsProps } from '../_shared/WithUtils';
import { DatePickerViewType } from '../constants/DatePickerView';
import { DateType, DomainPropTypes } from '../constants/prop-types';
import { MaterialUiPickersDate } from '../typings/date';
import Calendar, { RenderDay } from './components/Calendar';
import MonthSelection from './components/MonthSelection';
import YearSelection from './components/YearSelection';
export interface BaseDatePickerProps {
/** Min selectable date */
minDate?: DateType;
/** Max selectable date */
maxDate?: DateType;
/** Disable past dates */
disablePast?: boolean;
/** Disable future dates */
disableFuture?: boolean;
/** To animate scrolling to current year (with scrollIntoView) */
animateYearScrolling?: boolean;
/** Array of views to show. Order year -> month -> day */
views?: Array<'year' | 'month' | 'day'>;
/** Initial view to show when date picker is open */
openTo?: 'year' | 'month' | 'day';
/** @deprecated use openTo instead */
openToYearSelection?: boolean;
/** Left arrow icon */
leftArrowIcon?: React.ReactNode;
/** Right arrow icon */
rightArrowIcon?: React.ReactNode;
/** Custom renderer for day */
renderDay?: RenderDay;
/** Enables keyboard listener for moving between days in calendar */
allowKeyboardControl?: boolean;
/** Disable specific date */
shouldDisableDate?: (day: MaterialUiPickersDate) => boolean;
initialFocusedDate?: DateType;
}
export interface DatePickerProps
extends BaseDatePickerProps,
WithStyles<typeof styles>,
WithUtilsProps {
date: MaterialUiPickersDate;
onChange: (date: MaterialUiPickersDate, isFinished?: boolean) => void;
}
interface DatePickerState {
openView: DatePickerViewType;
}
export class DatePicker extends React.PureComponent<DatePickerProps> {
public static propTypes: any = {
views: PropTypes.arrayOf(DomainPropTypes.datePickerView),
openTo: DomainPropTypes.datePickerView,
openToYearSelection: PropTypes.bool,
};
public static defaultProps = {
minDate: new Date('1900-01-01'),
maxDate: new Date('2100-01-01'),
openToYearSelection: false,
views: ['year', 'day'] as DatePickerViewType[],
};
public state: DatePickerState = {
// TODO in v3 remove openToYearSelection
openView:
this.props.openTo || this.props.openToYearSelection!
? 'year'
: this.props.views![this.props.views!.length - 1],
};
get date() {
return this.props.date;
}
get minDate() {
return this.props.utils.date(this.props.minDate);
}
get maxDate() {
return this.props.utils.date(this.props.maxDate);
}
get isYearOnly() {
return isYearOnlyView(this.props.views!);
}
get isYearAndMonth() {
return isYearAndMonthViews(this.props.views!);
}
public handleYearSelect = (date: MaterialUiPickersDate) => {
this.props.onChange(date, this.isYearOnly);
if (this.isYearOnly) {
return;
}
if (this.props.views!.includes('month')) {
return this.openMonthSelection();
}
this.openCalendar();
};
public handleMonthSelect = (date: MaterialUiPickersDate) => {
const isFinish = !this.props.views!.includes('day');
this.props.onChange(date, isFinish);
if (!isFinish) {
this.openCalendar();
}
};
public openYearSelection = () => {
this.setState({ openView: 'year' });
};
public openCalendar = () => {
this.setState({ openView: 'day' });
};
public openMonthSelection = () => {
this.setState({ openView: 'month' });
};
public render() {
const { openView } = this.state;
const {
disablePast,
disableFuture,
onChange,
animateYearScrolling,
leftArrowIcon,
rightArrowIcon,
renderDay,
utils,
shouldDisableDate,
allowKeyboardControl,
classes,
} = this.props;
return (
<>
<PickerToolbar className={clsx({ [classes.toolbarCenter]: this.isYearOnly })}>
<ToolbarButton
variant={this.isYearOnly ? 'h3' : 'subtitle1'}
onClick={this.isYearOnly ? undefined : this.openYearSelection}
selected={openView === 'year'}
label={utils.getYearText(this.date)}
/>
{!this.isYearOnly &&
!this.isYearAndMonth && (
<ToolbarButton
variant="h4"
onClick={this.openCalendar}
selected={openView === 'day'}
label={utils.getDatePickerHeaderText(this.date)}
/>
)}
{this.isYearAndMonth && (
<ToolbarButton
variant="h4"
onClick={this.openMonthSelection}
selected={openView === 'month'}
label={utils.getMonthText(this.date)}
/>
)}
</PickerToolbar>
{this.props.children}
{openView === 'year' && (
<YearSelection
date={this.date}
onChange={this.handleYearSelect}
minDate={this.minDate}
maxDate={this.maxDate}
disablePast={disablePast}
disableFuture={disableFuture}
animateYearScrolling={animateYearScrolling}
/>
)}
{openView === 'month' && (
<MonthSelection
date={this.date}
onChange={this.handleMonthSelect}
minDate={this.minDate}
maxDate={this.maxDate}
disablePast={disablePast}
disableFuture={disableFuture}
/>
)}
{openView === 'day' && (
<Calendar
date={this.date}
onChange={onChange}
disablePast={disablePast}
disableFuture={disableFuture}
minDate={this.minDate}
maxDate={this.maxDate}
leftArrowIcon={leftArrowIcon}
rightArrowIcon={rightArrowIcon}
renderDay={renderDay}
shouldDisableDate={shouldDisableDate}
allowKeyboardControl={allowKeyboardControl}
/>
)}
</>
);
}
}
export const styles = () =>
createStyles({
toolbarCenter: {
flexDirection: 'row',
alignItems: 'center',
},
});
export default withStyles(styles)(withUtils()(DatePicker));
| lib/src/DatePicker/DatePicker.tsx | 1 | https://github.com/mui/material-ui/commit/f36f617f4b16bdc03964778764e17bd47247b086 | [
0.9981561303138733,
0.0828731581568718,
0.00016779842553660274,
0.000384086073609069,
0.27012908458709717
] |
{
"id": 9,
"code_window": [
" rightArrowIcon,\n",
" shouldDisableDate,\n",
" value,\n",
" autoOk,\n",
" onlyCalendar,\n",
" ...other\n",
" } = props;\n",
"\n",
" const ComponentToShow: any = onlyCalendar ? Calendar : DatePicker;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" views,\n",
" openTo,\n"
],
"file_path": "lib/src/DatePicker/DatePickerInline.tsx",
"type": "add",
"edit_start_line_idx": 37
} | import React, { PureComponent, Fragment } from 'react';
import { DateTimePicker } from 'material-ui-pickers';
import { IconButton, InputAdornment } from '@material-ui/core';
import AlarmIcon from '@material-ui/icons/AddAlarm';
import SnoozeIcon from '@material-ui/icons/Snooze';
class CustomDateTimePicker extends PureComponent {
state = {
selectedDate: new Date('2019-01-01T18:54'),
clearedDate: null,
};
handleDateChange = date => {
this.setState({ selectedDate: date });
};
handleClearedDateChange = date => {
this.setState({ clearedDate: date });
};
render() {
const { selectedDate, clearedDate } = this.state;
return (
<Fragment>
<div className="picker">
<DateTimePicker
autoOk
ampm={false}
showTabs={false}
autoSubmit={false}
allowKeyboardControl={false}
disableFuture
minDate={new Date('2018-01-01')}
value={selectedDate}
onChange={this.handleDateChange}
helperText="Hardcoded helper text"
leftArrowIcon={<AlarmIcon />}
rightArrowIcon={<SnoozeIcon />}
InputProps={{
endAdornment: (
<InputAdornment position="end">
<IconButton>
<AlarmIcon />
</IconButton>
</InputAdornment>
),
}}
/>
</div>
<div className="picker">
<DateTimePicker
keyboard
label="Keyboard with error handler"
onError={console.log}
minDate={new Date('2018-01-01T00:00')}
value={selectedDate}
onChange={this.handleDateChange}
format={this.props.getFormatString({
moment: 'YYYY/MM/DD hh:mm A',
dateFns: 'yyyy/MM/dd hh:mm a',
})}
disableOpenOnEnter
mask={[
/\d/,
/\d/,
/\d/,
/\d/,
'/',
/\d/,
/\d/,
'/',
/\d/,
/\d/,
' ',
/\d/,
/\d/,
':',
/\d/,
/\d/,
' ',
/a|p/i,
'M',
]}
/>
</div>
<div className="picker">
<DateTimePicker
value={clearedDate}
onChange={this.handleClearedDateChange}
helperText="Clear Initial State"
clearable
/>
</div>
</Fragment>
);
}
}
export default CustomDateTimePicker;
| docs/pages/api/datetime-picker/CustomDateTimePicker.example.jsx | 0 | https://github.com/mui/material-ui/commit/f36f617f4b16bdc03964778764e17bd47247b086 | [
0.014385223388671875,
0.0019307669717818499,
0.00016882667841855437,
0.0001896192115964368,
0.004064786713570356
] |
{
"id": 9,
"code_window": [
" rightArrowIcon,\n",
" shouldDisableDate,\n",
" value,\n",
" autoOk,\n",
" onlyCalendar,\n",
" ...other\n",
" } = props;\n",
"\n",
" const ComponentToShow: any = onlyCalendar ? Calendar : DatePicker;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" views,\n",
" openTo,\n"
],
"file_path": "lib/src/DatePicker/DatePickerInline.tsx",
"type": "add",
"edit_start_line_idx": 37
} | import createStyles from '@material-ui/core/styles/createStyles';
import withStyles, { WithStyles } from '@material-ui/core/styles/withStyles';
import * as PropTypes from 'prop-types';
import * as React from 'react';
import { findDOMNode } from 'react-dom';
import { withUtils, WithUtilsProps } from '../../_shared/WithUtils';
import { DateType, DomainPropTypes } from '../../constants/prop-types';
import { MaterialUiPickersDate } from '../../typings/date';
import Year from './Year';
export interface YearSelectionProps extends WithUtilsProps, WithStyles<typeof styles> {
date: MaterialUiPickersDate;
minDate?: DateType;
maxDate?: DateType;
onChange: (date: MaterialUiPickersDate) => void;
disablePast?: boolean | null | undefined;
disableFuture?: boolean | null | undefined;
animateYearScrolling?: boolean | null | undefined;
}
export class YearSelection extends React.PureComponent<YearSelectionProps> {
public static propTypes: any = {
date: PropTypes.shape({}).isRequired,
minDate: DomainPropTypes.date,
maxDate: DomainPropTypes.date,
onChange: PropTypes.func.isRequired,
animateYearScrolling: PropTypes.bool,
innerRef: PropTypes.any,
};
public static defaultProps = {
animateYearScrolling: false,
minDate: new Date('1900-01-01'),
maxDate: new Date('2100-01-01'),
};
public selectedYearRef?: React.ReactInstance = undefined;
public getSelectedYearRef = (ref?: React.ReactInstance) => {
this.selectedYearRef = ref;
};
public scrollToCurrentYear = (domNode: React.ReactInstance) => {
const { animateYearScrolling } = this.props;
const currentYearElement = findDOMNode(domNode) as Element;
if (currentYearElement && currentYearElement.scrollIntoView) {
if (animateYearScrolling) {
setTimeout(() => currentYearElement.scrollIntoView({ behavior: 'smooth' }), 100);
} else {
currentYearElement.scrollIntoView();
}
}
};
public componentDidMount() {
if (this.selectedYearRef) {
this.scrollToCurrentYear(this.selectedYearRef);
}
}
public onYearSelect = (year: number) => {
const { date, onChange, utils } = this.props;
const newDate = utils.setYear(date, year);
onChange(newDate);
};
public render() {
const { minDate, maxDate, date, classes, disablePast, disableFuture, utils } = this.props;
const currentYear = utils.getYear(date);
return (
<div className={classes.container}>
{utils.getYearRange(minDate, maxDate).map(year => {
const yearNumber = utils.getYear(year);
const selected = yearNumber === currentYear;
return (
<Year
key={utils.getYearText(year)}
selected={selected}
value={yearNumber}
onSelect={this.onYearSelect}
ref={selected ? this.getSelectedYearRef : undefined}
disabled={
(disablePast && utils.isBeforeYear(year, utils.date())) ||
(disableFuture && utils.isAfterYear(year, utils.date()))
}
>
{utils.getYearText(year)}
</Year>
);
})}
</div>
);
}
}
export const styles = createStyles({
container: {
maxHeight: 300,
overflowY: 'auto',
justifyContent: 'center',
},
});
export default withStyles(styles, { name: 'MuiPickersYearSelection' })(withUtils()(YearSelection));
| lib/src/DatePicker/components/YearSelection.tsx | 0 | https://github.com/mui/material-ui/commit/f36f617f4b16bdc03964778764e17bd47247b086 | [
0.002707146806642413,
0.0004929560818709433,
0.00016890073311515152,
0.0001749977673171088,
0.0007248856709338725
] |
{
"id": 9,
"code_window": [
" rightArrowIcon,\n",
" shouldDisableDate,\n",
" value,\n",
" autoOk,\n",
" onlyCalendar,\n",
" ...other\n",
" } = props;\n",
"\n",
" const ComponentToShow: any = onlyCalendar ? Calendar : DatePicker;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" views,\n",
" openTo,\n"
],
"file_path": "lib/src/DatePicker/DatePickerInline.tsx",
"type": "add",
"edit_start_line_idx": 37
} | import { IUtils } from '@date-io/core/IUtils';
import * as React from 'react';
import { MaterialUiPickersDate } from '../../typings/date';
import ClockNumber from './ClockNumber';
export const getHourNumbers = ({
ampm,
utils,
date,
}: {
ampm: boolean;
utils: IUtils<MaterialUiPickersDate>;
date: MaterialUiPickersDate;
}) => {
const currentHours = utils.getHours(date);
const hourNumbers: JSX.Element[] = [];
const startHour = ampm ? 1 : 0;
const endHour = ampm ? 12 : 23;
const isSelected = (hour: number) => {
if (ampm) {
if (hour === 12) {
return currentHours === 12 || currentHours === 0;
}
return currentHours === hour || currentHours - 12 === hour;
}
return currentHours === hour;
};
for (let hour = startHour; hour <= endHour; hour += 1) {
let label = hour.toString();
if (hour === 0) {
label = '00';
}
const props = {
index: hour,
label: utils.formatNumber(label),
selected: isSelected(hour),
isInner: !ampm && (hour === 0 || hour > 12),
};
hourNumbers.push(<ClockNumber key={hour} {...props} />);
}
return hourNumbers;
};
export const getMinutesNumbers = ({
value,
utils,
}: {
value: number;
utils: IUtils<MaterialUiPickersDate>;
}) => {
const f = utils.formatNumber;
return [
<ClockNumber label={f('00')} selected={value === 0} index={12} key={12} />,
<ClockNumber label={f('05')} selected={value === 5} index={1} key={1} />,
<ClockNumber label={f('10')} selected={value === 10} index={2} key={2} />,
<ClockNumber label={f('15')} selected={value === 15} index={3} key={3} />,
<ClockNumber label={f('20')} selected={value === 20} index={4} key={4} />,
<ClockNumber label={f('25')} selected={value === 25} index={5} key={5} />,
<ClockNumber label={f('30')} selected={value === 30} index={6} key={6} />,
<ClockNumber label={f('35')} selected={value === 35} index={7} key={7} />,
<ClockNumber label={f('40')} selected={value === 40} index={8} key={8} />,
<ClockNumber label={f('45')} selected={value === 45} index={9} key={9} />,
<ClockNumber label={f('50')} selected={value === 50} index={10} key={10} />,
<ClockNumber label={f('55')} selected={value === 55} index={11} key={11} />,
];
};
| lib/src/TimePicker/components/ClockNumbers.tsx | 0 | https://github.com/mui/material-ui/commit/f36f617f4b16bdc03964778764e17bd47247b086 | [
0.0019337787525728345,
0.0003929876838810742,
0.00016744025924708694,
0.00017368592671118677,
0.000582375330850482
] |
{
"id": 10,
"code_window": [
" >\n",
" <ComponentToShow\n",
" date={date}\n",
" allowKeyboardControl={allowKeyboardControl}\n",
" animateYearScrolling={animateYearScrolling}\n",
" disableFuture={disableFuture}\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" views={views}\n",
" openTo={openTo}\n"
],
"file_path": "lib/src/DatePicker/DatePickerInline.tsx",
"type": "add",
"edit_start_line_idx": 70
} | import React, { useState, useContext } from 'react';
import { Grid, Typography } from '@material-ui/core';
import { DatePicker } from 'material-ui-pickers';
import { createRegressionDay as createRegressionDayRenderer } from './RegressionDay';
import { MuiPickersContext } from 'material-ui-pickers';
import LeftArrowIcon from '@material-ui/icons/KeyboardArrowLeft';
import RightArrowIcon from '@material-ui/icons/KeyboardArrowRight';
function Regression() {
const utils = useContext(MuiPickersContext);
const [date, changeDate] = useState(new Date('2019-01-01T00:00:00.000Z'));
const sharedProps = {
value: date,
onChange: changeDate,
style: { margin: '0 10px' },
leftArrowIcon: <LeftArrowIcon data-arrow="left" />,
rightArrowIcon: <RightArrowIcon data-arrow="right" />,
renderDay: createRegressionDayRenderer(utils!),
KeyboardButtonProps: {
className: 'keyboard-btn',
},
};
return (
<div style={{ marginTop: 30 }}>
<Typography align="center" variant="h5" gutterBottom>
This page is using for the automate regression of material-ui-pickers.
</Typography>
<Grid container justify="center" wrap="wrap">
<DatePicker id="basic-datepicker" {...sharedProps} />
<DatePicker id="clearable-datepicker" clearable {...sharedProps} />
<DatePicker id="keyboard-datepicker" keyboard {...sharedProps} />
<DatePicker
keyboard
id="keyboard-mask-datepicker"
format="MM/dd/yyyy"
mask={[/\d/, /\d/, '/', /\d/, /\d/, '/', /\d/, /\d/, /\d/, /\d/]}
{...sharedProps}
/>
</Grid>
</div>
);
}
export default Regression;
| docs/pages/regression/index.tsx | 1 | https://github.com/mui/material-ui/commit/f36f617f4b16bdc03964778764e17bd47247b086 | [
0.0019711132626980543,
0.0005432321922853589,
0.00016573160246480256,
0.00017377661424688995,
0.0007143588154576719
] |
{
"id": 10,
"code_window": [
" >\n",
" <ComponentToShow\n",
" date={date}\n",
" allowKeyboardControl={allowKeyboardControl}\n",
" animateYearScrolling={animateYearScrolling}\n",
" disableFuture={disableFuture}\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" views={views}\n",
" openTo={openTo}\n"
],
"file_path": "lib/src/DatePicker/DatePickerInline.tsx",
"type": "add",
"edit_start_line_idx": 70
} | import dynamic from 'next/dynamic';
export default dynamic(() => import('./PropTypesTableLazy'));
| docs/_shared/PropTypesTable.jsx | 0 | https://github.com/mui/material-ui/commit/f36f617f4b16bdc03964778764e17bd47247b086 | [
0.000176304136402905,
0.000176304136402905,
0.000176304136402905,
0.000176304136402905,
0
] |
{
"id": 10,
"code_window": [
" >\n",
" <ComponentToShow\n",
" date={date}\n",
" allowKeyboardControl={allowKeyboardControl}\n",
" animateYearScrolling={animateYearScrolling}\n",
" disableFuture={disableFuture}\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" views={views}\n",
" openTo={openTo}\n"
],
"file_path": "lib/src/DatePicker/DatePickerInline.tsx",
"type": "add",
"edit_start_line_idx": 70
} | import { Theme } from '@material-ui/core';
import { StyleRules } from '@material-ui/core/styles';
export const createOverrides = (theme: Theme): StyleRules => ({
body: {
fontFamily: 'roboto',
'-webkit-font-smoothing:': 'antialiased',
backgroundColor: theme.palette.background.default,
},
h1: theme.typography.h1,
h2: {
...theme.typography.h2,
margin: '32px 0 16px',
},
h3: {
...theme.typography.h3,
margin: '32px 0 16px',
},
h4: {
...theme.typography.h4,
margin: '32px 0 8px',
},
h5: theme.typography.h5,
h6: theme.typography.h6,
p: {
lineHeight: 1.4,
color: theme.palette.text.primary,
},
a: {
color: theme.palette.secondary.main,
},
pre: {
margin: '24px 0',
padding: '12px 18px',
overflow: 'auto',
borderRadius: 4,
backgroundColor: theme.palette.background.paper + ' !important',
},
ul: {
color: theme.palette.text.primary,
},
code: {
fontSize: 16,
lineHeight: 1.4,
fontFamily: "Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace",
color: theme.palette.type === 'dark' ? theme.palette.text.primary : 'black',
whiteSpace: 'pre',
wordSpacing: 'normal',
wordBreak: 'normal',
wordWrap: 'normal',
backgroundColor: theme.palette.background.paper + ' !important',
},
'h1, h2, h3, h4, h5': {
position: 'relative',
'& a.anchor-link': {
position: 'absolute',
top: -80,
},
'& a.anchor-link-style': {
visibility: 'hidden',
marginLeft: 4,
fontSize: '80%',
textDecoration: 'none',
color: theme.palette.text.secondary,
fontFamily: '-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto',
},
'&:hover a.anchor-link-style': {
visibility: 'visible',
},
},
});
| docs/layout/styleOverrides.ts | 0 | https://github.com/mui/material-ui/commit/f36f617f4b16bdc03964778764e17bd47247b086 | [
0.00017806114919949323,
0.00017707806546241045,
0.00017541224951855838,
0.0001774939737515524,
9.618569265512633e-7
] |
{
"id": 10,
"code_window": [
" >\n",
" <ComponentToShow\n",
" date={date}\n",
" allowKeyboardControl={allowKeyboardControl}\n",
" animateYearScrolling={animateYearScrolling}\n",
" disableFuture={disableFuture}\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" views={views}\n",
" openTo={openTo}\n"
],
"file_path": "lib/src/DatePicker/DatePickerInline.tsx",
"type": "add",
"edit_start_line_idx": 70
} | import React from 'react';
import PropTypes from 'prop-types';
import { List } from '@material-ui/core';
import NavItem from './NavItem';
const navItems = [
{
title: 'Getting Started',
children: [
{ title: 'Installation', href: '/getting-started/installation' },
{ title: 'Usage', href: '/getting-started/usage' },
{ title: 'Parsing dates', href: '/getting-started/parsing' },
],
},
{
title: 'Localization',
children: [
{ title: 'Using date-fns', href: '/localization/date-fns' },
{ title: 'Using moment', href: '/localization/moment' },
{ title: 'Persian Calendar System', href: '/localization/persian' },
],
},
{
title: 'Components',
children: [
{ title: 'Date Picker', href: '/api/datepicker' },
{ title: 'Time Picker', href: '/api/timepicker' },
{ title: 'Date & Time Picker', href: '/api/datetime-picker' },
],
},
{
title: 'Guides',
children: [
{ title: 'Form integration', href: '/guides/form-integration' },
{ title: 'CSS overrides', href: '/guides/css-overrides' },
{ title: 'Global format customization', href: '/guides/formats' },
{
title: 'Open pickers programmatically',
href: '/guides/controlling-programmatically',
},
{ title: 'Static picker`s components', href: '/guides/static-components' },
],
},
];
class NavigationMenu extends React.Component {
mapNavigation(depth) {
return ({ title, children, href }) => {
const { location } = this.props;
const open =
children && children.length > 0 ? children.some(item => item.href === true) : false;
return (
<NavItem key={href || title} title={title} depth={depth} href={href} open={open}>
{children && children.length > 0 && children.map(this.mapNavigation(depth + 1))}
</NavItem>
);
};
}
render() {
return <List component="nav">{navItems.map(this.mapNavigation(0))}</List>;
}
}
export default NavigationMenu;
| docs/layout/components/NavigationMenu.jsx | 0 | https://github.com/mui/material-ui/commit/f36f617f4b16bdc03964778764e17bd47247b086 | [
0.00017666342318989336,
0.00017351066344417632,
0.00016410202078986913,
0.00017421063967049122,
0.000004071249350090511
] |
{
"id": 0,
"code_window": [
"\tcolor: inherit;\n",
"\tcursor: text;\n",
"\ttext-decoration: none;\n",
"}\n",
"\n",
".monaco-workbench .panel.integrated-terminal.ctrl-held .xterm a:hover {\n",
"\tcursor: pointer;\n",
"\ttext-decoration: underline;\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
".monaco-workbench .panel.integrated-terminal.ctrlcmd-held .xterm a:hover {\n"
],
"file_path": "src/vs/workbench/parts/terminal/electron-browser/media/xterm.css",
"type": "replace",
"edit_start_line_idx": 58
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import DOM = require('vs/base/browser/dom');
import nls = require('vs/nls');
import platform = require('vs/base/common/platform');
import { Action, IAction } from 'vs/base/common/actions';
import { Builder, Dimension } from 'vs/base/browser/builder';
import { IActionItem, Separator } from 'vs/base/browser/ui/actionbar/actionbar';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IContextMenuService } from 'vs/platform/contextview/browser/contextView';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { ITerminalService, ITerminalFont, TERMINAL_PANEL_ID } from 'vs/workbench/parts/terminal/common/terminal';
import { IThemeService, ITheme } from 'vs/platform/theme/common/themeService';
import { ansiColorIdentifiers } from './terminalColorRegistry';
import { ColorIdentifier } from 'vs/platform/theme/common/colorRegistry';
import { KillTerminalAction, CreateNewTerminalAction, SwitchTerminalInstanceAction, SwitchTerminalInstanceActionItem, CopyTerminalSelectionAction, TerminalPasteAction, ClearTerminalAction } from 'vs/workbench/parts/terminal/electron-browser/terminalActions';
import { Panel } from 'vs/workbench/browser/panel';
import { StandardMouseEvent } from 'vs/base/browser/mouseEvent';
import { TPromise } from 'vs/base/common/winjs.base';
export class TerminalPanel extends Panel {
private _actions: IAction[];
private _contextMenuActions: IAction[];
private _cancelContextMenu: boolean = false;
private _font: ITerminalFont;
private _fontStyleElement: HTMLElement;
private _parentDomElement: HTMLElement;
private _terminalContainer: HTMLElement;
private _themeStyleElement: HTMLElement;
constructor(
@IConfigurationService private _configurationService: IConfigurationService,
@IContextMenuService private _contextMenuService: IContextMenuService,
@IInstantiationService private _instantiationService: IInstantiationService,
@IKeybindingService private _keybindingService: IKeybindingService,
@ITerminalService private _terminalService: ITerminalService,
@IThemeService protected themeService: IThemeService,
@ITelemetryService telemetryService: ITelemetryService
) {
super(TERMINAL_PANEL_ID, telemetryService, themeService);
}
public create(parent: Builder): TPromise<any> {
super.create(parent);
this._parentDomElement = parent.getHTMLElement();
DOM.addClass(this._parentDomElement, 'integrated-terminal');
this._themeStyleElement = document.createElement('style');
this._fontStyleElement = document.createElement('style');
this._terminalContainer = document.createElement('div');
DOM.addClass(this._terminalContainer, 'terminal-outer-container');
this._parentDomElement.appendChild(this._themeStyleElement);
this._parentDomElement.appendChild(this._fontStyleElement);
this._parentDomElement.appendChild(this._terminalContainer);
this._attachEventListeners();
this._terminalService.setContainers(this.getContainer().getHTMLElement(), this._terminalContainer);
this._register(this.themeService.onThemeChange(theme => this._updateTheme(theme)));
this._register(this._configurationService.onDidUpdateConfiguration(() => this._updateFont()));
this._updateFont();
this._updateTheme();
// Force another layout (first is setContainers) since config has changed
this.layout(new Dimension(this._terminalContainer.offsetWidth, this._terminalContainer.offsetHeight));
return TPromise.as(void 0);
}
public layout(dimension?: Dimension): void {
if (!dimension) {
return;
}
this._terminalService.terminalInstances.forEach((t) => {
t.layout(dimension);
});
}
public setVisible(visible: boolean): TPromise<void> {
if (visible) {
if (this._terminalService.terminalInstances.length > 0) {
this._updateFont();
this._updateTheme();
} else {
return super.setVisible(visible).then(() => {
const instance = this._terminalService.createInstance();
if (instance) {
this._updateFont();
this._updateTheme();
}
return TPromise.as(void 0);
});
}
}
return super.setVisible(visible);
}
public getActions(): IAction[] {
if (!this._actions) {
this._actions = [
this._instantiationService.createInstance(SwitchTerminalInstanceAction, SwitchTerminalInstanceAction.ID, SwitchTerminalInstanceAction.LABEL),
this._instantiationService.createInstance(CreateNewTerminalAction, CreateNewTerminalAction.ID, CreateNewTerminalAction.PANEL_LABEL),
this._instantiationService.createInstance(KillTerminalAction, KillTerminalAction.ID, KillTerminalAction.PANEL_LABEL)
];
this._actions.forEach(a => {
this._register(a);
});
}
return this._actions;
}
private _getContextMenuActions(): IAction[] {
if (!this._contextMenuActions) {
this._contextMenuActions = [
this._instantiationService.createInstance(CreateNewTerminalAction, CreateNewTerminalAction.ID, nls.localize('createNewTerminal', "New Terminal")),
new Separator(),
this._instantiationService.createInstance(CopyTerminalSelectionAction, CopyTerminalSelectionAction.ID, nls.localize('copy', "Copy")),
this._instantiationService.createInstance(TerminalPasteAction, TerminalPasteAction.ID, nls.localize('paste', "Paste")),
new Separator(),
this._instantiationService.createInstance(ClearTerminalAction, ClearTerminalAction.ID, nls.localize('clear', "Clear"))
];
this._contextMenuActions.forEach(a => {
this._register(a);
});
}
return this._contextMenuActions;
}
public getActionItem(action: Action): IActionItem {
if (action.id === SwitchTerminalInstanceAction.ID) {
return this._instantiationService.createInstance(SwitchTerminalInstanceActionItem, action);
}
return super.getActionItem(action);
}
public focus(): void {
const activeInstance = this._terminalService.getActiveInstance();
if (activeInstance) {
activeInstance.focus(true);
}
}
private _attachEventListeners(): void {
this._register(DOM.addDisposableListener(window, DOM.EventType.KEY_DOWN, (e: KeyboardEvent) => this._refreshCtrlHeld(e.ctrlKey)));
this._register(DOM.addDisposableListener(window, DOM.EventType.KEY_UP, (e: KeyboardEvent) => this._refreshCtrlHeld(e.ctrlKey)));
this._register(DOM.addDisposableListener(window, DOM.EventType.FOCUS, (e: KeyboardEvent) => this._refreshCtrlHeld(e.ctrlKey)));
this._register(DOM.addDisposableListener(this._parentDomElement, 'mousedown', (event: MouseEvent) => {
if (this._terminalService.terminalInstances.length === 0) {
return;
}
if (event.which === 2 && platform.isLinux) {
// Drop selection and focus terminal on Linux to enable middle button paste when click
// occurs on the selection itself.
this._terminalService.getActiveInstance().focus();
} else if (event.which === 3) {
if (this._terminalService.configHelper.config.rightClickCopyPaste) {
let terminal = this._terminalService.getActiveInstance();
if (terminal.hasSelection()) {
terminal.copySelection();
terminal.clearSelection();
} else {
terminal.paste();
}
this._cancelContextMenu = true;
}
}
}));
this._register(DOM.addDisposableListener(this._parentDomElement, 'contextmenu', (event: MouseEvent) => {
if (!this._cancelContextMenu) {
const standardEvent = new StandardMouseEvent(event);
let anchor: { x: number, y: number } = { x: standardEvent.posx, y: standardEvent.posy };
this._contextMenuService.showContextMenu({
getAnchor: () => anchor,
getActions: () => TPromise.as(this._getContextMenuActions()),
getActionsContext: () => this._parentDomElement,
getKeyBinding: (action) => this._keybindingService.lookupKeybinding(action.id)
});
}
this._cancelContextMenu = false;
}));
this._register(DOM.addDisposableListener(this._parentDomElement, 'click', (event) => {
if (this._terminalService.terminalInstances.length === 0) {
return;
}
if (event.which !== 3) {
this._terminalService.getActiveInstance().focus();
}
}));
this._register(DOM.addDisposableListener(this._parentDomElement, 'keyup', (event: KeyboardEvent) => {
if (event.keyCode === 27) {
// Keep terminal open on escape
event.stopPropagation();
}
}));
}
private _refreshCtrlHeld(ctrlKey: boolean): void {
this._parentDomElement.classList.toggle('ctrl-held', ctrlKey);
}
private _updateTheme(theme?: ITheme): void {
if (!theme) {
theme = this.themeService.getTheme();
}
let css = '';
ansiColorIdentifiers.forEach((colorId: ColorIdentifier, index: number) => {
if (colorId) { // should not happen, all indices should have a color defined.
let color = theme.getColor(colorId);
let rgba = color.transparent(0.996);
css += `.monaco-workbench .panel.integrated-terminal .xterm .xterm-color-${index} { color: ${color}; }` +
`.monaco-workbench .panel.integrated-terminal .xterm .xterm-color-${index}::selection { background-color: ${rgba}; }` +
`.monaco-workbench .panel.integrated-terminal .xterm .xterm-bg-color-${index} { background-color: ${color}; }` +
`.monaco-workbench .panel.integrated-terminal .xterm .xterm-bg-color-${index}::selection { color: ${color}; }`;
}
});
this._themeStyleElement.innerHTML = css;
}
private _updateFont(): void {
if (this._terminalService.terminalInstances.length === 0) {
return;
}
let newFont = this._terminalService.configHelper.getFont();
DOM.toggleClass(this._parentDomElement, 'enable-ligatures', this._terminalService.configHelper.config.fontLigatures);
DOM.toggleClass(this._parentDomElement, 'disable-bold', !this._terminalService.configHelper.config.enableBold);
if (!this._font || this._fontsDiffer(this._font, newFont)) {
this._fontStyleElement.innerHTML = '.monaco-workbench .panel.integrated-terminal .xterm {' +
`font-family: ${newFont.fontFamily};` +
`font-size: ${newFont.fontSize};` +
`line-height: ${newFont.lineHeight};` +
'}';
this._font = newFont;
}
this.layout(new Dimension(this._parentDomElement.offsetWidth, this._parentDomElement.offsetHeight));
}
private _fontsDiffer(a: ITerminalFont, b: ITerminalFont): boolean {
return a.charHeight !== b.charHeight ||
a.charWidth !== b.charWidth ||
a.fontFamily !== b.fontFamily ||
a.fontSize !== b.fontSize ||
a.lineHeight !== b.lineHeight;
}
}
| src/vs/workbench/parts/terminal/electron-browser/terminalPanel.ts | 1 | https://github.com/microsoft/vscode/commit/55732e69e5861bac06e34c0101b1881028f2edf6 | [
0.0015535969287157059,
0.0002324080851394683,
0.00016282238357234746,
0.0001717071863822639,
0.0002665298234205693
] |
{
"id": 0,
"code_window": [
"\tcolor: inherit;\n",
"\tcursor: text;\n",
"\ttext-decoration: none;\n",
"}\n",
"\n",
".monaco-workbench .panel.integrated-terminal.ctrl-held .xterm a:hover {\n",
"\tcursor: pointer;\n",
"\ttext-decoration: underline;\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
".monaco-workbench .panel.integrated-terminal.ctrlcmd-held .xterm a:hover {\n"
],
"file_path": "src/vs/workbench/parts/terminal/electron-browser/media/xterm.css",
"type": "replace",
"edit_start_line_idx": 58
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as assert from 'assert';
import uri from 'vs/base/common/uri';
import { Source } from 'vs/workbench/parts/debug/common/debugSource';
suite('Debug - Source', () => {
test('from raw source', () => {
const rawSource = {
name: 'zz',
path: '/xx/yy/zz',
sourceReference: 0
};
const source = new Source(rawSource, 'label');
assert.equal(source.presenationHint, 'label');
assert.equal(source.name, rawSource.name);
assert.equal(source.inMemory, false);
assert.equal(source.reference, rawSource.sourceReference);
assert.equal(source.uri.toString(), uri.file(rawSource.path).toString());
});
test('from raw internal source', () => {
const rawSource = {
name: 'internalModule.js',
sourceReference: 11
};
const source = new Source(rawSource, 'deemphasize');
assert.equal(source.presenationHint, 'deemphasize');
assert.equal(source.name, rawSource.name);
assert.equal(source.inMemory, true);
assert.equal(source.reference, rawSource.sourceReference);
});
});
| src/vs/workbench/parts/debug/test/common/debugSource.test.ts | 0 | https://github.com/microsoft/vscode/commit/55732e69e5861bac06e34c0101b1881028f2edf6 | [
0.0001808973029255867,
0.00017716408183332533,
0.00017154731904156506,
0.00017810583813115954,
0.000003609581654018257
] |
{
"id": 0,
"code_window": [
"\tcolor: inherit;\n",
"\tcursor: text;\n",
"\ttext-decoration: none;\n",
"}\n",
"\n",
".monaco-workbench .panel.integrated-terminal.ctrl-held .xterm a:hover {\n",
"\tcursor: pointer;\n",
"\ttext-decoration: underline;\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
".monaco-workbench .panel.integrated-terminal.ctrlcmd-held .xterm a:hover {\n"
],
"file_path": "src/vs/workbench/parts/terminal/electron-browser/media/xterm.css",
"type": "replace",
"edit_start_line_idx": 58
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import * as lifecycle from 'vs/base/common/lifecycle';
import * as errors from 'vs/base/common/errors';
import { IAction, IActionRunner } from 'vs/base/common/actions';
import { KeyCode } from 'vs/base/common/keyCodes';
import * as dom from 'vs/base/browser/dom';
import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { SelectBox } from 'vs/base/browser/ui/selectBox/selectBox';
import { SelectActionItem, IActionItem } from 'vs/base/browser/ui/actionbar/actionbar';
import { EventEmitter } from 'vs/base/common/eventEmitter';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { ICommandService } from 'vs/platform/commands/common/commands';
import { IDebugService } from 'vs/workbench/parts/debug/common/debug';
import { IThemeService } from "vs/platform/theme/common/themeService";
import { attachSelectBoxStyler } from "vs/platform/theme/common/styler";
import { SIDE_BAR_BACKGROUND } from "vs/workbench/common/theme";
const $ = dom.$;
export class StartDebugActionItem extends EventEmitter implements IActionItem {
private static ADD_CONFIGURATION = nls.localize('addConfiguration', "Add Configuration...");
private static SEPARATOR = '─────────';
public actionRunner: IActionRunner;
private container: HTMLElement;
private start: HTMLElement;
private selectBox: SelectBox;
private toDispose: lifecycle.IDisposable[];
constructor(
private context: any,
private action: IAction,
@IDebugService private debugService: IDebugService,
@IThemeService themeService: IThemeService,
@IConfigurationService private configurationService: IConfigurationService,
@ICommandService private commandService: ICommandService
) {
super();
this.toDispose = [];
this.selectBox = new SelectBox([], -1);
this.toDispose.push(attachSelectBoxStyler(this.selectBox, themeService, {
selectBackground: SIDE_BAR_BACKGROUND
}));
this.registerListeners();
}
private registerListeners(): void {
this.toDispose.push(this.configurationService.onDidUpdateConfiguration(e => {
if (e.sourceConfig.launch) {
this.updateOptions();
}
}));
this.toDispose.push(this.selectBox.onDidSelect(configurationName => {
if (configurationName === StartDebugActionItem.ADD_CONFIGURATION) {
this.selectBox.select(this.debugService.getConfigurationManager().getConfigurationNames().indexOf(this.debugService.getViewModel().selectedConfigurationName));
this.commandService.executeCommand('debug.addConfiguration').done(undefined, errors.onUnexpectedError);
} else {
this.debugService.getViewModel().setSelectedConfigurationName(configurationName);
}
}));
this.toDispose.push(this.debugService.getViewModel().onDidSelectConfiguration(configurationName => {
const manager = this.debugService.getConfigurationManager();
this.selectBox.select(manager.getConfigurationNames().indexOf(configurationName));
}));
}
public render(container: HTMLElement): void {
this.container = container;
dom.addClass(container, 'start-debug-action-item');
this.start = dom.append(container, $('.icon'));
this.start.title = this.action.label;
this.start.tabIndex = 0;
this.toDispose.push(dom.addDisposableListener(this.start, dom.EventType.CLICK, () => {
this.start.blur();
this.actionRunner.run(this.action, this.context).done(null, errors.onUnexpectedError);
}));
this.toDispose.push(dom.addDisposableListener(this.start, dom.EventType.MOUSE_DOWN, (e: MouseEvent) => {
if (this.action.enabled && e.button === 0) {
dom.addClass(this.start, 'active');
}
}));
this.toDispose.push(dom.addDisposableListener(this.start, dom.EventType.MOUSE_UP, () => {
dom.removeClass(this.start, 'active');
}));
this.toDispose.push(dom.addDisposableListener(this.start, dom.EventType.MOUSE_OUT, () => {
dom.removeClass(this.start, 'active');
}));
this.toDispose.push(dom.addDisposableListener(this.start, dom.EventType.KEY_DOWN, (e: KeyboardEvent) => {
const event = new StandardKeyboardEvent(e);
if (event.equals(KeyCode.Enter)) {
this.actionRunner.run(this.action, this.context).done(null, errors.onUnexpectedError);
}
if (event.equals(KeyCode.RightArrow)) {
this.selectBox.focus();
event.stopPropagation();
}
}));
const selectBoxContainer = $('.configuration');
this.selectBox.render(dom.append(container, selectBoxContainer));
this.toDispose.push(dom.addDisposableListener(selectBoxContainer, dom.EventType.KEY_DOWN, (e: KeyboardEvent) => {
const event = new StandardKeyboardEvent(e);
if (event.equals(KeyCode.LeftArrow)) {
this.start.focus();
event.stopPropagation();
}
}));
this.updateOptions();
}
public setActionContext(context: any): void {
this.context = context;
}
public isEnabled(): boolean {
return true;
}
public focus(fromRight?: boolean): void {
if (fromRight) {
this.selectBox.focus();
} else {
this.start.focus();
}
}
public blur(): void {
this.container.blur();
}
public dispose(): void {
this.toDispose = lifecycle.dispose(this.toDispose);
}
private updateOptions(): void {
const options = this.debugService.getConfigurationManager().getConfigurationNames();
if (options.length === 0) {
options.push(nls.localize('noConfigurations', "No Configurations"));
}
const selected = options.indexOf(this.debugService.getViewModel().selectedConfigurationName);
options.push(StartDebugActionItem.SEPARATOR);
options.push(StartDebugActionItem.ADD_CONFIGURATION);
this.selectBox.setOptions(options, selected, options.length - 2);
}
}
export class FocusProcessActionItem extends SelectActionItem {
constructor(
action: IAction,
@IDebugService private debugService: IDebugService,
@IThemeService themeService: IThemeService
) {
super(null, action, [], -1);
this.toDispose.push(attachSelectBoxStyler(this.selectBox, themeService));
this.debugService.getViewModel().onDidFocusStackFrame(() => {
const process = this.debugService.getViewModel().focusedProcess;
if (process) {
const names = this.debugService.getModel().getProcesses().map(p => p.name);
this.select(names.indexOf(process.name));
}
});
this.debugService.getModel().onDidChangeCallStack(() => {
const process = this.debugService.getViewModel().focusedProcess;
const names = this.debugService.getModel().getProcesses().map(p => p.name);
this.setOptions(names, process ? names.indexOf(process.name) : undefined);
});
}
}
| src/vs/workbench/parts/debug/browser/debugActionItems.ts | 0 | https://github.com/microsoft/vscode/commit/55732e69e5861bac06e34c0101b1881028f2edf6 | [
0.00017996775568462908,
0.0001744962064549327,
0.00016870952094905078,
0.00017449258302804083,
0.000002402825884928461
] |
{
"id": 0,
"code_window": [
"\tcolor: inherit;\n",
"\tcursor: text;\n",
"\ttext-decoration: none;\n",
"}\n",
"\n",
".monaco-workbench .panel.integrated-terminal.ctrl-held .xterm a:hover {\n",
"\tcursor: pointer;\n",
"\ttext-decoration: underline;\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
".monaco-workbench .panel.integrated-terminal.ctrlcmd-held .xterm a:hover {\n"
],
"file_path": "src/vs/workbench/parts/terminal/electron-browser/media/xterm.css",
"type": "replace",
"edit_start_line_idx": 58
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import lifecycle = require('vs/base/common/lifecycle');
import { TPromise } from 'vs/base/common/winjs.base';
import types = require('vs/base/common/types');
import { ProgressBar } from 'vs/base/browser/ui/progressbar/progressbar';
import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet';
import { IPanelService } from 'vs/workbench/services/panel/common/panelService';
import { IProgressService, IProgressRunner } from 'vs/platform/progress/common/progress';
interface ProgressState {
infinite?: boolean;
total?: number;
worked?: number;
done?: boolean;
whilePromise?: TPromise<any>;
}
export abstract class ScopedService {
protected toDispose: lifecycle.IDisposable[];
constructor(private viewletService: IViewletService, private panelService: IPanelService, private scopeId: string) {
this.toDispose = [];
this.registerListeners();
}
public registerListeners(): void {
this.toDispose.push(this.viewletService.onDidViewletOpen(viewlet => this.onScopeOpened(viewlet.getId())));
this.toDispose.push(this.panelService.onDidPanelOpen(panel => this.onScopeOpened(panel.getId())));
this.toDispose.push(this.viewletService.onDidViewletClose(viewlet => this.onScopeClosed(viewlet.getId())));
this.toDispose.push(this.panelService.onDidPanelClose(panel => this.onScopeClosed(panel.getId())));
}
private onScopeClosed(scopeId: string) {
if (scopeId === this.scopeId) {
this.onScopeDeactivated();
}
}
private onScopeOpened(scopeId: string) {
if (scopeId === this.scopeId) {
this.onScopeActivated();
}
}
public abstract onScopeActivated(): void;
public abstract onScopeDeactivated(): void;
}
export class WorkbenchProgressService extends ScopedService implements IProgressService {
public _serviceBrand: any;
private isActive: boolean;
private progressbar: ProgressBar;
private progressState: ProgressState;
constructor(
progressbar: ProgressBar,
scopeId: string,
isActive: boolean,
@IViewletService viewletService: IViewletService,
@IPanelService panelService: IPanelService
) {
super(viewletService, panelService, scopeId);
this.progressbar = progressbar;
this.isActive = isActive || types.isUndefinedOrNull(scopeId); // If service is unscoped, enable by default
this.progressState = Object.create(null);
}
public onScopeDeactivated(): void {
this.isActive = false;
}
public onScopeActivated(): void {
this.isActive = true;
// Return early if progress state indicates that progress is done
if (this.progressState.done) {
return;
}
// Replay Infinite Progress from Promise
if (this.progressState.whilePromise) {
this.doShowWhile();
}
// Replay Infinite Progress
else if (this.progressState.infinite) {
this.progressbar.infinite().getContainer().show();
}
// Replay Finite Progress (Total & Worked)
else {
if (this.progressState.total) {
this.progressbar.total(this.progressState.total).getContainer().show();
}
if (this.progressState.worked) {
this.progressbar.worked(this.progressState.worked).getContainer().show();
}
}
}
private clearProgressState(): void {
this.progressState.infinite = void 0;
this.progressState.done = void 0;
this.progressState.worked = void 0;
this.progressState.total = void 0;
this.progressState.whilePromise = void 0;
}
public show(infinite: boolean, delay?: number): IProgressRunner;
public show(total: number, delay?: number): IProgressRunner;
public show(infiniteOrTotal: any, delay?: number): IProgressRunner {
let infinite: boolean;
let total: number;
// Sort out Arguments
if (infiniteOrTotal === false || infiniteOrTotal === true) {
infinite = infiniteOrTotal;
} else {
total = infiniteOrTotal;
}
// Reset State
this.clearProgressState();
// Keep in State
this.progressState.infinite = infinite;
this.progressState.total = total;
// Active: Show Progress
if (this.isActive) {
// Infinite: Start Progressbar and Show after Delay
if (!types.isUndefinedOrNull(infinite)) {
if (types.isUndefinedOrNull(delay)) {
this.progressbar.infinite().getContainer().show();
} else {
this.progressbar.infinite().getContainer().showDelayed(delay);
}
}
// Finite: Start Progressbar and Show after Delay
else if (!types.isUndefinedOrNull(total)) {
if (types.isUndefinedOrNull(delay)) {
this.progressbar.total(total).getContainer().show();
} else {
this.progressbar.total(total).getContainer().showDelayed(delay);
}
}
}
return {
total: (total: number) => {
this.progressState.infinite = false;
this.progressState.total = total;
if (this.isActive) {
this.progressbar.total(total);
}
},
worked: (worked: number) => {
// Verify first that we are either not active or the progressbar has a total set
if (!this.isActive || this.progressbar.hasTotal()) {
this.progressState.infinite = false;
if (this.progressState.worked) {
this.progressState.worked += worked;
} else {
this.progressState.worked = worked;
}
if (this.isActive) {
this.progressbar.worked(worked);
}
}
// Otherwise the progress bar does not support worked(), we fallback to infinite() progress
else {
this.progressState.infinite = true;
this.progressState.worked = void 0;
this.progressState.total = void 0;
this.progressbar.infinite().getContainer().show();
}
},
done: () => {
this.progressState.infinite = false;
this.progressState.done = true;
if (this.isActive) {
this.progressbar.stop().getContainer().hide();
}
}
};
}
public showWhile(promise: TPromise<any>, delay?: number): TPromise<void> {
let stack: boolean = !!this.progressState.whilePromise;
// Reset State
if (!stack) {
this.clearProgressState();
}
// Otherwise join with existing running promise to ensure progress is accurate
else {
promise = TPromise.join([promise, this.progressState.whilePromise]);
}
// Keep Promise in State
this.progressState.whilePromise = promise;
let stop = () => {
// If this is not the last promise in the list of joined promises, return early
if (!!this.progressState.whilePromise && this.progressState.whilePromise !== promise) {
return;
}
// The while promise is either null or equal the promise we last hooked on
this.clearProgressState();
if (this.isActive) {
this.progressbar.stop().getContainer().hide();
}
};
this.doShowWhile(delay);
return promise.then(stop, stop);
}
private doShowWhile(delay?: number): void {
// Show Progress when active
if (this.isActive) {
if (types.isUndefinedOrNull(delay)) {
this.progressbar.infinite().getContainer().show();
} else {
this.progressbar.infinite().getContainer().showDelayed(delay);
}
}
}
public dispose(): void {
this.toDispose = lifecycle.dispose(this.toDispose);
}
} | src/vs/workbench/services/progress/browser/progressService.ts | 0 | https://github.com/microsoft/vscode/commit/55732e69e5861bac06e34c0101b1881028f2edf6 | [
0.00017924692656379193,
0.00017442720127291977,
0.0001676700048847124,
0.00017543669673614204,
0.000003195518729626201
] |
{
"id": 3,
"code_window": [
"\t\t\t}\n",
"\t\t}));\n",
"\t}\n",
"\n",
"\tprivate _refreshCtrlHeld(ctrlKey: boolean): void {\n",
"\t\tthis._parentDomElement.classList.toggle('ctrl-held', ctrlKey);\n",
"\t}\n",
"\n",
"\tprivate _updateTheme(theme?: ITheme): void {\n",
"\t\tif (!theme) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tprivate _refreshCtrlHeld(e: KeyboardEvent): void {\n",
"\t\tthis._parentDomElement.classList.toggle('ctrlcmd-held', platform.isMacintosh ? e.metaKey : e.ctrlKey);\n"
],
"file_path": "src/vs/workbench/parts/terminal/electron-browser/terminalPanel.ts",
"type": "replace",
"edit_start_line_idx": 205
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import DOM = require('vs/base/browser/dom');
import nls = require('vs/nls');
import platform = require('vs/base/common/platform');
import { Action, IAction } from 'vs/base/common/actions';
import { Builder, Dimension } from 'vs/base/browser/builder';
import { IActionItem, Separator } from 'vs/base/browser/ui/actionbar/actionbar';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IContextMenuService } from 'vs/platform/contextview/browser/contextView';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { ITerminalService, ITerminalFont, TERMINAL_PANEL_ID } from 'vs/workbench/parts/terminal/common/terminal';
import { IThemeService, ITheme } from 'vs/platform/theme/common/themeService';
import { ansiColorIdentifiers } from './terminalColorRegistry';
import { ColorIdentifier } from 'vs/platform/theme/common/colorRegistry';
import { KillTerminalAction, CreateNewTerminalAction, SwitchTerminalInstanceAction, SwitchTerminalInstanceActionItem, CopyTerminalSelectionAction, TerminalPasteAction, ClearTerminalAction } from 'vs/workbench/parts/terminal/electron-browser/terminalActions';
import { Panel } from 'vs/workbench/browser/panel';
import { StandardMouseEvent } from 'vs/base/browser/mouseEvent';
import { TPromise } from 'vs/base/common/winjs.base';
export class TerminalPanel extends Panel {
private _actions: IAction[];
private _contextMenuActions: IAction[];
private _cancelContextMenu: boolean = false;
private _font: ITerminalFont;
private _fontStyleElement: HTMLElement;
private _parentDomElement: HTMLElement;
private _terminalContainer: HTMLElement;
private _themeStyleElement: HTMLElement;
constructor(
@IConfigurationService private _configurationService: IConfigurationService,
@IContextMenuService private _contextMenuService: IContextMenuService,
@IInstantiationService private _instantiationService: IInstantiationService,
@IKeybindingService private _keybindingService: IKeybindingService,
@ITerminalService private _terminalService: ITerminalService,
@IThemeService protected themeService: IThemeService,
@ITelemetryService telemetryService: ITelemetryService
) {
super(TERMINAL_PANEL_ID, telemetryService, themeService);
}
public create(parent: Builder): TPromise<any> {
super.create(parent);
this._parentDomElement = parent.getHTMLElement();
DOM.addClass(this._parentDomElement, 'integrated-terminal');
this._themeStyleElement = document.createElement('style');
this._fontStyleElement = document.createElement('style');
this._terminalContainer = document.createElement('div');
DOM.addClass(this._terminalContainer, 'terminal-outer-container');
this._parentDomElement.appendChild(this._themeStyleElement);
this._parentDomElement.appendChild(this._fontStyleElement);
this._parentDomElement.appendChild(this._terminalContainer);
this._attachEventListeners();
this._terminalService.setContainers(this.getContainer().getHTMLElement(), this._terminalContainer);
this._register(this.themeService.onThemeChange(theme => this._updateTheme(theme)));
this._register(this._configurationService.onDidUpdateConfiguration(() => this._updateFont()));
this._updateFont();
this._updateTheme();
// Force another layout (first is setContainers) since config has changed
this.layout(new Dimension(this._terminalContainer.offsetWidth, this._terminalContainer.offsetHeight));
return TPromise.as(void 0);
}
public layout(dimension?: Dimension): void {
if (!dimension) {
return;
}
this._terminalService.terminalInstances.forEach((t) => {
t.layout(dimension);
});
}
public setVisible(visible: boolean): TPromise<void> {
if (visible) {
if (this._terminalService.terminalInstances.length > 0) {
this._updateFont();
this._updateTheme();
} else {
return super.setVisible(visible).then(() => {
const instance = this._terminalService.createInstance();
if (instance) {
this._updateFont();
this._updateTheme();
}
return TPromise.as(void 0);
});
}
}
return super.setVisible(visible);
}
public getActions(): IAction[] {
if (!this._actions) {
this._actions = [
this._instantiationService.createInstance(SwitchTerminalInstanceAction, SwitchTerminalInstanceAction.ID, SwitchTerminalInstanceAction.LABEL),
this._instantiationService.createInstance(CreateNewTerminalAction, CreateNewTerminalAction.ID, CreateNewTerminalAction.PANEL_LABEL),
this._instantiationService.createInstance(KillTerminalAction, KillTerminalAction.ID, KillTerminalAction.PANEL_LABEL)
];
this._actions.forEach(a => {
this._register(a);
});
}
return this._actions;
}
private _getContextMenuActions(): IAction[] {
if (!this._contextMenuActions) {
this._contextMenuActions = [
this._instantiationService.createInstance(CreateNewTerminalAction, CreateNewTerminalAction.ID, nls.localize('createNewTerminal', "New Terminal")),
new Separator(),
this._instantiationService.createInstance(CopyTerminalSelectionAction, CopyTerminalSelectionAction.ID, nls.localize('copy', "Copy")),
this._instantiationService.createInstance(TerminalPasteAction, TerminalPasteAction.ID, nls.localize('paste', "Paste")),
new Separator(),
this._instantiationService.createInstance(ClearTerminalAction, ClearTerminalAction.ID, nls.localize('clear', "Clear"))
];
this._contextMenuActions.forEach(a => {
this._register(a);
});
}
return this._contextMenuActions;
}
public getActionItem(action: Action): IActionItem {
if (action.id === SwitchTerminalInstanceAction.ID) {
return this._instantiationService.createInstance(SwitchTerminalInstanceActionItem, action);
}
return super.getActionItem(action);
}
public focus(): void {
const activeInstance = this._terminalService.getActiveInstance();
if (activeInstance) {
activeInstance.focus(true);
}
}
private _attachEventListeners(): void {
this._register(DOM.addDisposableListener(window, DOM.EventType.KEY_DOWN, (e: KeyboardEvent) => this._refreshCtrlHeld(e.ctrlKey)));
this._register(DOM.addDisposableListener(window, DOM.EventType.KEY_UP, (e: KeyboardEvent) => this._refreshCtrlHeld(e.ctrlKey)));
this._register(DOM.addDisposableListener(window, DOM.EventType.FOCUS, (e: KeyboardEvent) => this._refreshCtrlHeld(e.ctrlKey)));
this._register(DOM.addDisposableListener(this._parentDomElement, 'mousedown', (event: MouseEvent) => {
if (this._terminalService.terminalInstances.length === 0) {
return;
}
if (event.which === 2 && platform.isLinux) {
// Drop selection and focus terminal on Linux to enable middle button paste when click
// occurs on the selection itself.
this._terminalService.getActiveInstance().focus();
} else if (event.which === 3) {
if (this._terminalService.configHelper.config.rightClickCopyPaste) {
let terminal = this._terminalService.getActiveInstance();
if (terminal.hasSelection()) {
terminal.copySelection();
terminal.clearSelection();
} else {
terminal.paste();
}
this._cancelContextMenu = true;
}
}
}));
this._register(DOM.addDisposableListener(this._parentDomElement, 'contextmenu', (event: MouseEvent) => {
if (!this._cancelContextMenu) {
const standardEvent = new StandardMouseEvent(event);
let anchor: { x: number, y: number } = { x: standardEvent.posx, y: standardEvent.posy };
this._contextMenuService.showContextMenu({
getAnchor: () => anchor,
getActions: () => TPromise.as(this._getContextMenuActions()),
getActionsContext: () => this._parentDomElement,
getKeyBinding: (action) => this._keybindingService.lookupKeybinding(action.id)
});
}
this._cancelContextMenu = false;
}));
this._register(DOM.addDisposableListener(this._parentDomElement, 'click', (event) => {
if (this._terminalService.terminalInstances.length === 0) {
return;
}
if (event.which !== 3) {
this._terminalService.getActiveInstance().focus();
}
}));
this._register(DOM.addDisposableListener(this._parentDomElement, 'keyup', (event: KeyboardEvent) => {
if (event.keyCode === 27) {
// Keep terminal open on escape
event.stopPropagation();
}
}));
}
private _refreshCtrlHeld(ctrlKey: boolean): void {
this._parentDomElement.classList.toggle('ctrl-held', ctrlKey);
}
private _updateTheme(theme?: ITheme): void {
if (!theme) {
theme = this.themeService.getTheme();
}
let css = '';
ansiColorIdentifiers.forEach((colorId: ColorIdentifier, index: number) => {
if (colorId) { // should not happen, all indices should have a color defined.
let color = theme.getColor(colorId);
let rgba = color.transparent(0.996);
css += `.monaco-workbench .panel.integrated-terminal .xterm .xterm-color-${index} { color: ${color}; }` +
`.monaco-workbench .panel.integrated-terminal .xterm .xterm-color-${index}::selection { background-color: ${rgba}; }` +
`.monaco-workbench .panel.integrated-terminal .xterm .xterm-bg-color-${index} { background-color: ${color}; }` +
`.monaco-workbench .panel.integrated-terminal .xterm .xterm-bg-color-${index}::selection { color: ${color}; }`;
}
});
this._themeStyleElement.innerHTML = css;
}
private _updateFont(): void {
if (this._terminalService.terminalInstances.length === 0) {
return;
}
let newFont = this._terminalService.configHelper.getFont();
DOM.toggleClass(this._parentDomElement, 'enable-ligatures', this._terminalService.configHelper.config.fontLigatures);
DOM.toggleClass(this._parentDomElement, 'disable-bold', !this._terminalService.configHelper.config.enableBold);
if (!this._font || this._fontsDiffer(this._font, newFont)) {
this._fontStyleElement.innerHTML = '.monaco-workbench .panel.integrated-terminal .xterm {' +
`font-family: ${newFont.fontFamily};` +
`font-size: ${newFont.fontSize};` +
`line-height: ${newFont.lineHeight};` +
'}';
this._font = newFont;
}
this.layout(new Dimension(this._parentDomElement.offsetWidth, this._parentDomElement.offsetHeight));
}
private _fontsDiffer(a: ITerminalFont, b: ITerminalFont): boolean {
return a.charHeight !== b.charHeight ||
a.charWidth !== b.charWidth ||
a.fontFamily !== b.fontFamily ||
a.fontSize !== b.fontSize ||
a.lineHeight !== b.lineHeight;
}
}
| src/vs/workbench/parts/terminal/electron-browser/terminalPanel.ts | 1 | https://github.com/microsoft/vscode/commit/55732e69e5861bac06e34c0101b1881028f2edf6 | [
0.9990825653076172,
0.18935802578926086,
0.00016413505363743752,
0.0002354203606955707,
0.3872974216938019
] |
{
"id": 3,
"code_window": [
"\t\t\t}\n",
"\t\t}));\n",
"\t}\n",
"\n",
"\tprivate _refreshCtrlHeld(ctrlKey: boolean): void {\n",
"\t\tthis._parentDomElement.classList.toggle('ctrl-held', ctrlKey);\n",
"\t}\n",
"\n",
"\tprivate _updateTheme(theme?: ITheme): void {\n",
"\t\tif (!theme) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tprivate _refreshCtrlHeld(e: KeyboardEvent): void {\n",
"\t\tthis._parentDomElement.classList.toggle('ctrlcmd-held', platform.isMacintosh ? e.metaKey : e.ctrlKey);\n"
],
"file_path": "src/vs/workbench/parts/terminal/electron-browser/terminalPanel.ts",
"type": "replace",
"edit_start_line_idx": 205
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import * as assert from 'assert';
import { EditOperation } from 'vs/editor/common/core/editOperation';
import { Position } from 'vs/editor/common/core/position';
import { Range } from 'vs/editor/common/core/range';
import {
EventType, IModelContentChangedEvent, IModelContentChangedLineChangedEvent,
IModelContentChangedLinesDeletedEvent, IModelContentChangedLinesInsertedEvent
} from 'vs/editor/common/editorCommon';
import { Model } from 'vs/editor/common/model/model';
// --------- utils
var LINE1 = 'My First Line';
var LINE2 = '\t\tMy Second Line';
var LINE3 = ' Third Line';
var LINE4 = '';
var LINE5 = '1';
suite('Editor Model - Model', () => {
var thisModel: Model;
setup(() => {
var text =
LINE1 + '\r\n' +
LINE2 + '\n' +
LINE3 + '\n' +
LINE4 + '\r\n' +
LINE5;
thisModel = Model.createFromString(text);
});
teardown(() => {
thisModel.dispose();
});
// --------- insert text
test('model getValue', () => {
assert.equal(thisModel.getValue(), 'My First Line\n\t\tMy Second Line\n Third Line\n\n1');
});
test('model insert empty text', () => {
thisModel.applyEdits([EditOperation.insert(new Position(1, 1), '')]);
assert.equal(thisModel.getLineCount(), 5);
assert.equal(thisModel.getLineContent(1), 'My First Line');
});
test('model insert text without newline 1', () => {
thisModel.applyEdits([EditOperation.insert(new Position(1, 1), 'foo ')]);
assert.equal(thisModel.getLineCount(), 5);
assert.equal(thisModel.getLineContent(1), 'foo My First Line');
});
test('model insert text without newline 2', () => {
thisModel.applyEdits([EditOperation.insert(new Position(1, 3), ' foo')]);
assert.equal(thisModel.getLineCount(), 5);
assert.equal(thisModel.getLineContent(1), 'My foo First Line');
});
test('model insert text with one newline', () => {
thisModel.applyEdits([EditOperation.insert(new Position(1, 3), ' new line\nNo longer')]);
assert.equal(thisModel.getLineCount(), 6);
assert.equal(thisModel.getLineContent(1), 'My new line');
assert.equal(thisModel.getLineContent(2), 'No longer First Line');
});
test('model insert text with two newlines', () => {
thisModel.applyEdits([EditOperation.insert(new Position(1, 3), ' new line\nOne more line in the middle\nNo longer')]);
assert.equal(thisModel.getLineCount(), 7);
assert.equal(thisModel.getLineContent(1), 'My new line');
assert.equal(thisModel.getLineContent(2), 'One more line in the middle');
assert.equal(thisModel.getLineContent(3), 'No longer First Line');
});
test('model insert text with many newlines', () => {
thisModel.applyEdits([EditOperation.insert(new Position(1, 3), '\n\n\n\n')]);
assert.equal(thisModel.getLineCount(), 9);
assert.equal(thisModel.getLineContent(1), 'My');
assert.equal(thisModel.getLineContent(2), '');
assert.equal(thisModel.getLineContent(3), '');
assert.equal(thisModel.getLineContent(4), '');
assert.equal(thisModel.getLineContent(5), ' First Line');
});
// --------- insert text eventing
test('model insert empty text does not trigger eventing', () => {
thisModel.onDidChangeRawContent((e) => {
assert.ok(false, 'was not expecting event');
});
thisModel.applyEdits([EditOperation.insert(new Position(1, 1), '')]);
});
test('model insert text without newline eventing', () => {
var listenerCalls = 0;
thisModel.onDidChangeRawContent((e) => {
listenerCalls++;
assert.equal(e.changeType, EventType.ModelRawContentChangedLineChanged);
assert.equal((<IModelContentChangedLineChangedEvent>e).lineNumber, 1);
});
thisModel.applyEdits([EditOperation.insert(new Position(1, 1), 'foo ')]);
assert.equal(listenerCalls, 1, 'listener calls');
});
test('model insert text with one newline eventing', () => {
var listenerCalls = 0;
var order = 0;
thisModel.onDidChangeRawContent((e) => {
listenerCalls++;
if (e.changeType === EventType.ModelRawContentChangedLineChanged) {
if (order === 0) {
assert.equal(++order, 1, 'ModelContentChangedLineChanged first');
assert.equal((<IModelContentChangedLineChangedEvent>e).lineNumber, 1, 'ModelContentChangedLineChanged line number 1');
} else {
assert.equal(++order, 2, 'ModelContentChangedLineChanged first');
assert.equal((<IModelContentChangedLineChangedEvent>e).lineNumber, 1, 'ModelContentChangedLineChanged line number 1');
}
} else if (e.changeType === EventType.ModelRawContentChangedLinesInserted) {
assert.equal(++order, 3, 'ModelContentChangedLinesInserted second');
assert.equal((<IModelContentChangedLinesInsertedEvent>e).fromLineNumber, 2, 'ModelContentChangedLinesInserted fromLineNumber');
assert.equal((<IModelContentChangedLinesInsertedEvent>e).toLineNumber, 2, 'ModelContentChangedLinesInserted toLineNumber');
} else {
assert.ok(false);
}
});
thisModel.applyEdits([EditOperation.insert(new Position(1, 3), ' new line\nNo longer')]);
assert.equal(listenerCalls, 3, 'listener calls');
});
// --------- delete text
test('model delete empty text', () => {
thisModel.applyEdits([EditOperation.delete(new Range(1, 1, 1, 1))]);
assert.equal(thisModel.getLineCount(), 5);
assert.equal(thisModel.getLineContent(1), 'My First Line');
});
test('model delete text from one line', () => {
thisModel.applyEdits([EditOperation.delete(new Range(1, 1, 1, 2))]);
assert.equal(thisModel.getLineCount(), 5);
assert.equal(thisModel.getLineContent(1), 'y First Line');
});
test('model delete text from one line 2', () => {
thisModel.applyEdits([EditOperation.insert(new Position(1, 1), 'a')]);
assert.equal(thisModel.getLineContent(1), 'aMy First Line');
thisModel.applyEdits([EditOperation.delete(new Range(1, 2, 1, 4))]);
assert.equal(thisModel.getLineCount(), 5);
assert.equal(thisModel.getLineContent(1), 'a First Line');
});
test('model delete all text from a line', () => {
thisModel.applyEdits([EditOperation.delete(new Range(1, 1, 1, 14))]);
assert.equal(thisModel.getLineCount(), 5);
assert.equal(thisModel.getLineContent(1), '');
});
test('model delete text from two lines', () => {
thisModel.applyEdits([EditOperation.delete(new Range(1, 4, 2, 6))]);
assert.equal(thisModel.getLineCount(), 4);
assert.equal(thisModel.getLineContent(1), 'My Second Line');
});
test('model delete text from many lines', () => {
thisModel.applyEdits([EditOperation.delete(new Range(1, 4, 3, 5))]);
assert.equal(thisModel.getLineCount(), 3);
assert.equal(thisModel.getLineContent(1), 'My Third Line');
});
test('model delete everything', () => {
thisModel.applyEdits([EditOperation.delete(new Range(1, 1, 5, 2))]);
assert.equal(thisModel.getLineCount(), 1);
assert.equal(thisModel.getLineContent(1), '');
});
// --------- delete text eventing
test('model delete empty text does not trigger eventing', () => {
thisModel.onDidChangeRawContent((e) => {
assert.ok(false, 'was not expecting event');
});
thisModel.applyEdits([EditOperation.delete(new Range(1, 1, 1, 1))]);
});
test('model delete text from one line eventing', () => {
var listenerCalls = 0;
thisModel.onDidChangeRawContent((e) => {
listenerCalls++;
assert.equal(e.changeType, EventType.ModelRawContentChangedLineChanged);
assert.equal((<IModelContentChangedLineChangedEvent>e).lineNumber, 1);
});
thisModel.applyEdits([EditOperation.delete(new Range(1, 1, 1, 2))]);
assert.equal(listenerCalls, 1, 'listener calls');
});
test('model delete all text from a line eventing', () => {
var listenerCalls = 0;
thisModel.onDidChangeRawContent((e) => {
listenerCalls++;
assert.equal(e.changeType, EventType.ModelRawContentChangedLineChanged);
assert.equal((<IModelContentChangedLineChangedEvent>e).lineNumber, 1);
});
thisModel.applyEdits([EditOperation.delete(new Range(1, 1, 1, 14))]);
assert.equal(listenerCalls, 1, 'listener calls');
});
test('model delete text from two lines eventing', () => {
var listenerCalls = 0;
var order = 0;
thisModel.onDidChangeRawContent((e) => {
listenerCalls++;
if (e.changeType === EventType.ModelRawContentChangedLineChanged) {
if (order === 0) {
assert.equal(++order, 1);
assert.equal((<IModelContentChangedLineChangedEvent>e).lineNumber, 1);
} else {
assert.equal(++order, 2);
assert.equal((<IModelContentChangedLineChangedEvent>e).lineNumber, 1);
}
} else if (e.changeType === EventType.ModelRawContentChangedLinesDeleted) {
assert.equal(++order, 3);
assert.equal((<IModelContentChangedLinesDeletedEvent>e).fromLineNumber, 2);
assert.equal((<IModelContentChangedLinesDeletedEvent>e).toLineNumber, 2);
} else {
assert.ok(false);
}
});
thisModel.applyEdits([EditOperation.delete(new Range(1, 4, 2, 6))]);
assert.equal(listenerCalls, 3, 'listener calls');
});
test('model delete text from many lines eventing', () => {
var listenerCalls = 0;
var order = 0;
thisModel.onDidChangeRawContent((e) => {
listenerCalls++;
if (e.changeType === EventType.ModelRawContentChangedLineChanged) {
if (order === 0) {
assert.equal(++order, 1);
assert.equal((<IModelContentChangedLineChangedEvent>e).lineNumber, 1);
} else {
assert.equal(++order, 2);
assert.equal((<IModelContentChangedLineChangedEvent>e).lineNumber, 1);
}
} else if (e.changeType === EventType.ModelRawContentChangedLinesDeleted) {
assert.equal(++order, 3);
assert.equal((<IModelContentChangedLinesDeletedEvent>e).fromLineNumber, 2);
assert.equal((<IModelContentChangedLinesDeletedEvent>e).toLineNumber, 3);
} else {
assert.ok(false);
}
});
thisModel.applyEdits([EditOperation.delete(new Range(1, 4, 3, 5))]);
assert.equal(listenerCalls, 3, 'listener calls');
});
// --------- getValueInRange
test('getValueInRange', () => {
assert.equal(thisModel.getValueInRange(new Range(1, 1, 1, 1)), '');
assert.equal(thisModel.getValueInRange(new Range(1, 1, 1, 2)), 'M');
assert.equal(thisModel.getValueInRange(new Range(1, 2, 1, 3)), 'y');
assert.equal(thisModel.getValueInRange(new Range(1, 1, 1, 14)), 'My First Line');
assert.equal(thisModel.getValueInRange(new Range(1, 1, 2, 1)), 'My First Line\n');
assert.equal(thisModel.getValueInRange(new Range(1, 1, 2, 2)), 'My First Line\n\t');
assert.equal(thisModel.getValueInRange(new Range(1, 1, 2, 3)), 'My First Line\n\t\t');
assert.equal(thisModel.getValueInRange(new Range(1, 1, 2, 17)), 'My First Line\n\t\tMy Second Line');
assert.equal(thisModel.getValueInRange(new Range(1, 1, 3, 1)), 'My First Line\n\t\tMy Second Line\n');
assert.equal(thisModel.getValueInRange(new Range(1, 1, 4, 1)), 'My First Line\n\t\tMy Second Line\n Third Line\n');
});
// --------- getValueLengthInRange
test('getValueLengthInRange', () => {
assert.equal(thisModel.getValueLengthInRange(new Range(1, 1, 1, 1)), ''.length);
assert.equal(thisModel.getValueLengthInRange(new Range(1, 1, 1, 2)), 'M'.length);
assert.equal(thisModel.getValueLengthInRange(new Range(1, 2, 1, 3)), 'y'.length);
assert.equal(thisModel.getValueLengthInRange(new Range(1, 1, 1, 14)), 'My First Line'.length);
assert.equal(thisModel.getValueLengthInRange(new Range(1, 1, 2, 1)), 'My First Line\n'.length);
assert.equal(thisModel.getValueLengthInRange(new Range(1, 1, 2, 2)), 'My First Line\n\t'.length);
assert.equal(thisModel.getValueLengthInRange(new Range(1, 1, 2, 3)), 'My First Line\n\t\t'.length);
assert.equal(thisModel.getValueLengthInRange(new Range(1, 1, 2, 17)), 'My First Line\n\t\tMy Second Line'.length);
assert.equal(thisModel.getValueLengthInRange(new Range(1, 1, 3, 1)), 'My First Line\n\t\tMy Second Line\n'.length);
assert.equal(thisModel.getValueLengthInRange(new Range(1, 1, 4, 1)), 'My First Line\n\t\tMy Second Line\n Third Line\n'.length);
});
// --------- setValue
test('setValue eventing', () => {
var listenerCalls = 0;
thisModel.onDidChangeRawContent((e: IModelContentChangedEvent) => {
listenerCalls++;
assert.equal(e.changeType, EventType.ModelRawContentChangedFlush);
});
thisModel.setValue('new value');
assert.equal(listenerCalls, 1, 'listener calls');
});
// var LINE1 = 'My First Line';
// var LINE2 = '\t\tMy Second Line';
// var LINE3 = ' Third Line';
// var LINE4 = '';
// var LINE5 = '1';
});
// --------- Special Unicode LINE SEPARATOR character
suite('Editor Model - Model Line Separators', () => {
var thisModel: Model;
setup(() => {
var text =
LINE1 + '\u2028' +
LINE2 + '\n' +
LINE3 + '\u2028' +
LINE4 + '\r\n' +
LINE5;
thisModel = Model.createFromString(text);
});
teardown(() => {
thisModel.dispose();
});
test('model getValue', () => {
assert.equal(thisModel.getValue(), 'My First Line\u2028\t\tMy Second Line\n Third Line\u2028\n1');
});
test('model lines', () => {
assert.equal(thisModel.getLineCount(), 3);
});
test('Bug 13333:Model should line break on lonely CR too', () => {
var model = Model.createFromString('Hello\rWorld!\r\nAnother line');
assert.equal(model.getLineCount(), 3);
assert.equal(model.getValue(), 'Hello\r\nWorld!\r\nAnother line');
model.dispose();
});
});
// --------- Words
suite('Editor Model - Words', () => {
var thisModel: Model;
setup(() => {
var text = ['This text has some words. '];
thisModel = Model.createFromString(text.join('\n'));
});
teardown(() => {
thisModel.dispose();
});
test('Get word at position', () => {
assert.deepEqual(thisModel.getWordAtPosition(new Position(1, 1)), { word: 'This', startColumn: 1, endColumn: 5 });
assert.deepEqual(thisModel.getWordAtPosition(new Position(1, 2)), { word: 'This', startColumn: 1, endColumn: 5 });
assert.deepEqual(thisModel.getWordAtPosition(new Position(1, 4)), { word: 'This', startColumn: 1, endColumn: 5 });
assert.deepEqual(thisModel.getWordAtPosition(new Position(1, 5)), { word: 'This', startColumn: 1, endColumn: 5 });
assert.deepEqual(thisModel.getWordAtPosition(new Position(1, 6)), { word: 'text', startColumn: 6, endColumn: 10 });
assert.deepEqual(thisModel.getWordAtPosition(new Position(1, 19)), { word: 'some', startColumn: 15, endColumn: 19 });
assert.deepEqual(thisModel.getWordAtPosition(new Position(1, 20)), null);
assert.deepEqual(thisModel.getWordAtPosition(new Position(1, 21)), { word: 'words', startColumn: 21, endColumn: 26 });
assert.deepEqual(thisModel.getWordAtPosition(new Position(1, 26)), { word: 'words', startColumn: 21, endColumn: 26 });
assert.deepEqual(thisModel.getWordAtPosition(new Position(1, 27)), null);
assert.deepEqual(thisModel.getWordAtPosition(new Position(1, 28)), null);
});
});
| src/vs/editor/test/common/model/model.test.ts | 0 | https://github.com/microsoft/vscode/commit/55732e69e5861bac06e34c0101b1881028f2edf6 | [
0.0001786114153219387,
0.00017538576503284276,
0.00016780658916104585,
0.00017546312301419675,
0.0000019792116745520616
] |
{
"id": 3,
"code_window": [
"\t\t\t}\n",
"\t\t}));\n",
"\t}\n",
"\n",
"\tprivate _refreshCtrlHeld(ctrlKey: boolean): void {\n",
"\t\tthis._parentDomElement.classList.toggle('ctrl-held', ctrlKey);\n",
"\t}\n",
"\n",
"\tprivate _updateTheme(theme?: ITheme): void {\n",
"\t\tif (!theme) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tprivate _refreshCtrlHeld(e: KeyboardEvent): void {\n",
"\t\tthis._parentDomElement.classList.toggle('ctrlcmd-held', platform.isMacintosh ? e.metaKey : e.ctrlKey);\n"
],
"file_path": "src/vs/workbench/parts/terminal/electron-browser/terminalPanel.ts",
"type": "replace",
"edit_start_line_idx": 205
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"expandAbbreviationAction": "Emmet: 略語の展開"
} | i18n/jpn/src/vs/workbench/parts/emmet/node/actions/expandAbbreviation.i18n.json | 0 | https://github.com/microsoft/vscode/commit/55732e69e5861bac06e34c0101b1881028f2edf6 | [
0.00017585066962055862,
0.00017585066962055862,
0.00017585066962055862,
0.00017585066962055862,
0
] |
{
"id": 3,
"code_window": [
"\t\t\t}\n",
"\t\t}));\n",
"\t}\n",
"\n",
"\tprivate _refreshCtrlHeld(ctrlKey: boolean): void {\n",
"\t\tthis._parentDomElement.classList.toggle('ctrl-held', ctrlKey);\n",
"\t}\n",
"\n",
"\tprivate _updateTheme(theme?: ITheme): void {\n",
"\t\tif (!theme) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tprivate _refreshCtrlHeld(e: KeyboardEvent): void {\n",
"\t\tthis._parentDomElement.classList.toggle('ctrlcmd-held', platform.isMacintosh ? e.metaKey : e.ctrlKey);\n"
],
"file_path": "src/vs/workbench/parts/terminal/electron-browser/terminalPanel.ts",
"type": "replace",
"edit_start_line_idx": 205
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"defineKeybinding.initial": "Premere la combinazione di tasti desiderata e INVIO. Premere ESC per annullare."
} | i18n/ita/src/vs/workbench/parts/preferences/browser/keybindingWidgets.i18n.json | 0 | https://github.com/microsoft/vscode/commit/55732e69e5861bac06e34c0101b1881028f2edf6 | [
0.0001748955255607143,
0.0001748955255607143,
0.0001748955255607143,
0.0001748955255607143,
0
] |
{
"id": 0,
"code_window": [
"})\n",
"\n",
"// Special Elements (can contain anything)\n",
"const isPlainTextElement = makeMap('script,style,textarea', true)\n",
"const reCache = {}\n",
"\n",
"const decodingMap = {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"export const isPlainTextElement = makeMap('script,style,textarea', true)\n"
],
"file_path": "src/compiler/parser/html-parser.js",
"type": "replace",
"edit_start_line_idx": 48
} | /**
* Not type-checking this file because it's mostly vendor code.
*/
/*!
* HTML Parser By John Resig (ejohn.org)
* Modified by Juriy "kangax" Zaytsev
* Original code by Erik Arvidsson, Mozilla Public License
* http://erik.eae.net/simplehtmlparser/simplehtmlparser.js
*/
import { makeMap, no } from 'shared/util'
import { isNonPhrasingTag } from 'web/compiler/util'
// Regular Expressions for parsing tags and attributes
const singleAttrIdentifier = /([^\s"'<>/=]+)/
const singleAttrAssign = /(?:=)/
const singleAttrValues = [
// attr value double quotes
/"([^"]*)"+/.source,
// attr value, single quotes
/'([^']*)'+/.source,
// attr value, no quotes
/([^\s"'=<>`]+)/.source
]
const attribute = new RegExp(
'^\\s*' + singleAttrIdentifier.source +
'(?:\\s*(' + singleAttrAssign.source + ')' +
'\\s*(?:' + singleAttrValues.join('|') + '))?'
)
// could use https://www.w3.org/TR/1999/REC-xml-names-19990114/#NT-QName
// but for Vue templates we can enforce a simple charset
const ncname = '[a-zA-Z_][\\w\\-\\.]*'
const qnameCapture = '((?:' + ncname + '\\:)?' + ncname + ')'
const startTagOpen = new RegExp('^<' + qnameCapture)
const startTagClose = /^\s*(\/?)>/
const endTag = new RegExp('^<\\/' + qnameCapture + '[^>]*>')
const doctype = /^<!DOCTYPE [^>]+>/i
const comment = /^<!--/
const conditionalComment = /^<!\[/
let IS_REGEX_CAPTURING_BROKEN = false
'x'.replace(/x(.)?/g, function (m, g) {
IS_REGEX_CAPTURING_BROKEN = g === ''
})
// Special Elements (can contain anything)
const isPlainTextElement = makeMap('script,style,textarea', true)
const reCache = {}
const decodingMap = {
'<': '<',
'>': '>',
'"': '"',
'&': '&',
' ': '\n'
}
const encodedAttr = /&(?:lt|gt|quot|amp);/g
const encodedAttrWithNewLines = /&(?:lt|gt|quot|amp|#10);/g
function decodeAttr (value, shouldDecodeNewlines) {
const re = shouldDecodeNewlines ? encodedAttrWithNewLines : encodedAttr
return value.replace(re, match => decodingMap[match])
}
export function parseHTML (html, options) {
const stack = []
const expectHTML = options.expectHTML
const isUnaryTag = options.isUnaryTag || no
const canBeLeftOpenTag = options.canBeLeftOpenTag || no
let index = 0
let last, lastTag
while (html) {
last = html
// Make sure we're not in a plaintext content element like script/style
if (!lastTag || !isPlainTextElement(lastTag)) {
let textEnd = html.indexOf('<')
if (textEnd === 0) {
// Comment:
if (comment.test(html)) {
const commentEnd = html.indexOf('-->')
if (commentEnd >= 0) {
advance(commentEnd + 3)
continue
}
}
// http://en.wikipedia.org/wiki/Conditional_comment#Downlevel-revealed_conditional_comment
if (conditionalComment.test(html)) {
const conditionalEnd = html.indexOf(']>')
if (conditionalEnd >= 0) {
advance(conditionalEnd + 2)
continue
}
}
// Doctype:
const doctypeMatch = html.match(doctype)
if (doctypeMatch) {
advance(doctypeMatch[0].length)
continue
}
// End tag:
const endTagMatch = html.match(endTag)
if (endTagMatch) {
const curIndex = index
advance(endTagMatch[0].length)
parseEndTag(endTagMatch[1], curIndex, index)
continue
}
// Start tag:
const startTagMatch = parseStartTag()
if (startTagMatch) {
handleStartTag(startTagMatch)
continue
}
}
let text, rest, next
if (textEnd >= 0) {
rest = html.slice(textEnd)
while (
!endTag.test(rest) &&
!startTagOpen.test(rest) &&
!comment.test(rest) &&
!conditionalComment.test(rest)
) {
// < in plain text, be forgiving and treat it as text
next = rest.indexOf('<', 1)
if (next < 0) break
textEnd += next
rest = html.slice(textEnd)
}
text = html.substring(0, textEnd)
advance(textEnd)
}
if (textEnd < 0) {
text = html
html = ''
}
if (options.chars && text) {
options.chars(text)
}
} else {
var stackedTag = lastTag.toLowerCase()
var reStackedTag = reCache[stackedTag] || (reCache[stackedTag] = new RegExp('([\\s\\S]*?)(</' + stackedTag + '[^>]*>)', 'i'))
var endTagLength = 0
var rest = html.replace(reStackedTag, function (all, text, endTag) {
endTagLength = endTag.length
if (!isPlainTextElement(stackedTag) && stackedTag !== 'noscript') {
text = text
.replace(/<!--([\s\S]*?)-->/g, '$1')
.replace(/<!\[CDATA\[([\s\S]*?)]]>/g, '$1')
}
if (options.chars) {
options.chars(text)
}
return ''
})
index += html.length - rest.length
html = rest
parseEndTag(stackedTag, index - endTagLength, index)
}
if (html === last) {
options.chars && options.chars(html)
if (process.env.NODE_ENV !== 'production' && !stack.length && options.warn) {
options.warn(`Mal-formatted tag at end of template: "${html}"`)
}
break
}
}
// Clean up any remaining tags
parseEndTag()
function advance (n) {
index += n
html = html.substring(n)
}
function parseStartTag () {
const start = html.match(startTagOpen)
if (start) {
const match = {
tagName: start[1],
attrs: [],
start: index
}
advance(start[0].length)
let end, attr
while (!(end = html.match(startTagClose)) && (attr = html.match(attribute))) {
advance(attr[0].length)
match.attrs.push(attr)
}
if (end) {
match.unarySlash = end[1]
advance(end[0].length)
match.end = index
return match
}
}
}
function handleStartTag (match) {
const tagName = match.tagName
const unarySlash = match.unarySlash
if (expectHTML) {
if (lastTag === 'p' && isNonPhrasingTag(tagName)) {
parseEndTag(lastTag)
}
if (canBeLeftOpenTag(tagName) && lastTag === tagName) {
parseEndTag(tagName)
}
}
const unary = isUnaryTag(tagName) || tagName === 'html' && lastTag === 'head' || !!unarySlash
const l = match.attrs.length
const attrs = new Array(l)
for (let i = 0; i < l; i++) {
const args = match.attrs[i]
// hackish work around FF bug https://bugzilla.mozilla.org/show_bug.cgi?id=369778
if (IS_REGEX_CAPTURING_BROKEN && args[0].indexOf('""') === -1) {
if (args[3] === '') { delete args[3] }
if (args[4] === '') { delete args[4] }
if (args[5] === '') { delete args[5] }
}
const value = args[3] || args[4] || args[5] || ''
attrs[i] = {
name: args[1],
value: decodeAttr(
value,
options.shouldDecodeNewlines
)
}
}
if (!unary) {
stack.push({ tag: tagName, lowerCasedTag: tagName.toLowerCase(), attrs: attrs })
lastTag = tagName
}
if (options.start) {
options.start(tagName, attrs, unary, match.start, match.end)
}
}
function parseEndTag (tagName, start, end) {
let pos, lowerCasedTagName
if (start == null) start = index
if (end == null) end = index
if (tagName) {
lowerCasedTagName = tagName.toLowerCase()
}
// Find the closest opened tag of the same type
if (tagName) {
for (pos = stack.length - 1; pos >= 0; pos--) {
if (stack[pos].lowerCasedTag === lowerCasedTagName) {
break
}
}
} else {
// If no tag name is provided, clean shop
pos = 0
}
if (pos >= 0) {
// Close all the open elements, up the stack
for (let i = stack.length - 1; i >= pos; i--) {
if (process.env.NODE_ENV !== 'production' &&
(i > pos || !tagName) &&
options.warn) {
options.warn(
`tag <${stack[i].tag}> has no matching end tag.`
)
}
if (options.end) {
options.end(stack[i].tag, start, end)
}
}
// Remove the open elements from the stack
stack.length = pos
lastTag = pos && stack[pos - 1].tag
} else if (lowerCasedTagName === 'br') {
if (options.start) {
options.start(tagName, [], true, start, end)
}
} else if (lowerCasedTagName === 'p') {
if (options.start) {
options.start(tagName, [], false, start, end)
}
if (options.end) {
options.end(tagName, start, end)
}
}
}
}
| src/compiler/parser/html-parser.js | 1 | https://github.com/vuejs/vue/commit/d8315c42ef5b6b739100fad5f20e8b0c41f78eef | [
0.9992334842681885,
0.16084808111190796,
0.00016345284529961646,
0.00016892507846932858,
0.36637964844703674
] |
{
"id": 0,
"code_window": [
"})\n",
"\n",
"// Special Elements (can contain anything)\n",
"const isPlainTextElement = makeMap('script,style,textarea', true)\n",
"const reCache = {}\n",
"\n",
"const decodingMap = {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"export const isPlainTextElement = makeMap('script,style,textarea', true)\n"
],
"file_path": "src/compiler/parser/html-parser.js",
"type": "replace",
"edit_start_line_idx": 48
} | /* @flow */
import config from 'core/config'
/**
* Runtime helper for checking keyCodes from config.
*/
export function checkKeyCodes (
eventKeyCode: number,
key: string,
builtInAlias: number | Array<number> | void
): boolean {
const keyCodes = config.keyCodes[key] || builtInAlias
if (Array.isArray(keyCodes)) {
return keyCodes.indexOf(eventKeyCode) === -1
} else {
return keyCodes !== eventKeyCode
}
}
| src/core/instance/render-helpers/check-keycodes.js | 0 | https://github.com/vuejs/vue/commit/d8315c42ef5b6b739100fad5f20e8b0c41f78eef | [
0.00017281228792853653,
0.00017221851157955825,
0.00017162472067866474,
0.00017221851157955825,
5.937836249358952e-7
] |
{
"id": 0,
"code_window": [
"})\n",
"\n",
"// Special Elements (can contain anything)\n",
"const isPlainTextElement = makeMap('script,style,textarea', true)\n",
"const reCache = {}\n",
"\n",
"const decodingMap = {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"export const isPlainTextElement = makeMap('script,style,textarea', true)\n"
],
"file_path": "src/compiler/parser/html-parser.js",
"type": "replace",
"edit_start_line_idx": 48
} | # Vue.js SSR benchmark
This benchmark renders a table of 1000 rows with 10 columns (10k components), with around 30k normal elements on the page. Note this is not something likely to be seen in a typical app. This benchmark is mostly for stress/regression testing and comparing between `renderToString` and `renderToStream`.
To view the results follow the run section. Note that the overall completion time for the results are variable, this is due to other system related variants at run time (available memory, processing ect). In ideal circumstances both should finish within similar results.
`renderToStream` pipes the content through a stream which provides considerable performance benefits (faster time-to-first-byte and non-event-loop-blocking) over renderToString. This can be observed through the benchmark.
### run
``` bash
npm run bench:ssr
```
| benchmarks/ssr/README.md | 0 | https://github.com/vuejs/vue/commit/d8315c42ef5b6b739100fad5f20e8b0c41f78eef | [
0.00017682199541013688,
0.0001729740179143846,
0.00016912604041863233,
0.0001729740179143846,
0.000003847977495752275
] |
{
"id": 0,
"code_window": [
"})\n",
"\n",
"// Special Elements (can contain anything)\n",
"const isPlainTextElement = makeMap('script,style,textarea', true)\n",
"const reCache = {}\n",
"\n",
"const decodingMap = {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"export const isPlainTextElement = makeMap('script,style,textarea', true)\n"
],
"file_path": "src/compiler/parser/html-parser.js",
"type": "replace",
"edit_start_line_idx": 48
} | /* @flow */
const MAX_STACK_DEPTH = 1000
export function createWriteFunction (
write: (text: string, next: Function) => boolean,
onError: Function
): Function {
let stackDepth = 0
const cachedWrite = (text, next) => {
if (text && cachedWrite.caching) {
cachedWrite.cacheBuffer[cachedWrite.cacheBuffer.length - 1] += text
}
const waitForNext = write(text, next)
if (waitForNext !== true) {
if (stackDepth >= MAX_STACK_DEPTH) {
process.nextTick(() => {
try { next() } catch (e) {
onError(e)
}
})
} else {
stackDepth++
next()
stackDepth--
}
}
}
cachedWrite.caching = false
cachedWrite.cacheBuffer = []
cachedWrite.componentBuffer = []
return cachedWrite
}
| src/server/write.js | 0 | https://github.com/vuejs/vue/commit/d8315c42ef5b6b739100fad5f20e8b0c41f78eef | [
0.00017370587738696486,
0.00017097459931392223,
0.00016885083459783345,
0.00017067085718736053,
0.0000017939528333954513
] |
{
"id": 1,
"code_window": [
" currentParent.attrsMap.placeholder === text) {\n",
" return\n",
" }\n",
" const children = currentParent.children\n",
" text = inPre || text.trim()\n",
" ? decodeHTMLCached(text)\n",
" // only preserve whitespace if its not right after a starting tag\n",
" : preserveWhitespace && children.length ? ' ' : ''\n",
" if (text) {\n",
" let expression\n",
" if (!inVPre && text !== ' ' && (expression = parseText(text, delimiters))) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" ? isTextTag(currentParent) ? text : decodeHTMLCached(text)\n"
],
"file_path": "src/compiler/parser/index.js",
"type": "replace",
"edit_start_line_idx": 254
} | /* @flow */
import { decode } from 'he'
import { parseHTML } from './html-parser'
import { parseText } from './text-parser'
import { parseFilters } from './filter-parser'
import { cached, no, camelize } from 'shared/util'
import { genAssignmentCode } from '../directives/model'
import { isIE, isEdge, isServerRendering } from 'core/util/env'
import {
addProp,
addAttr,
baseWarn,
addHandler,
addDirective,
getBindingAttr,
getAndRemoveAttr,
pluckModuleFunction
} from '../helpers'
export const onRE = /^@|^v-on:/
export const dirRE = /^v-|^@|^:/
export const forAliasRE = /(.*?)\s+(?:in|of)\s+(.*)/
export const forIteratorRE = /\((\{[^}]*\}|[^,]*),([^,]*)(?:,([^,]*))?\)/
const argRE = /:(.*)$/
const bindRE = /^:|^v-bind:/
const modifierRE = /\.[^.]+/g
const decodeHTMLCached = cached(decode)
// configurable state
export let warn
let delimiters
let transforms
let preTransforms
let postTransforms
let platformIsPreTag
let platformMustUseProp
let platformGetTagNamespace
/**
* Convert HTML string to AST.
*/
export function parse (
template: string,
options: CompilerOptions
): ASTElement | void {
warn = options.warn || baseWarn
platformGetTagNamespace = options.getTagNamespace || no
platformMustUseProp = options.mustUseProp || no
platformIsPreTag = options.isPreTag || no
preTransforms = pluckModuleFunction(options.modules, 'preTransformNode')
transforms = pluckModuleFunction(options.modules, 'transformNode')
postTransforms = pluckModuleFunction(options.modules, 'postTransformNode')
delimiters = options.delimiters
const stack = []
const preserveWhitespace = options.preserveWhitespace !== false
let root
let currentParent
let inVPre = false
let inPre = false
let warned = false
function warnOnce (msg) {
if (!warned) {
warned = true
warn(msg)
}
}
function endPre (element) {
// check pre state
if (element.pre) {
inVPre = false
}
if (platformIsPreTag(element.tag)) {
inPre = false
}
}
parseHTML(template, {
warn,
expectHTML: options.expectHTML,
isUnaryTag: options.isUnaryTag,
canBeLeftOpenTag: options.canBeLeftOpenTag,
shouldDecodeNewlines: options.shouldDecodeNewlines,
start (tag, attrs, unary) {
// check namespace.
// inherit parent ns if there is one
const ns = (currentParent && currentParent.ns) || platformGetTagNamespace(tag)
// handle IE svg bug
/* istanbul ignore if */
if (isIE && ns === 'svg') {
attrs = guardIESVGBug(attrs)
}
const element: ASTElement = {
type: 1,
tag,
attrsList: attrs,
attrsMap: makeAttrsMap(attrs),
parent: currentParent,
children: []
}
if (ns) {
element.ns = ns
}
if (isForbiddenTag(element) && !isServerRendering()) {
element.forbidden = true
process.env.NODE_ENV !== 'production' && warn(
'Templates should only be responsible for mapping the state to the ' +
'UI. Avoid placing tags with side-effects in your templates, such as ' +
`<${tag}>` + ', as they will not be parsed.'
)
}
// apply pre-transforms
for (let i = 0; i < preTransforms.length; i++) {
preTransforms[i](element, options)
}
if (!inVPre) {
processPre(element)
if (element.pre) {
inVPre = true
}
}
if (platformIsPreTag(element.tag)) {
inPre = true
}
if (inVPre) {
processRawAttrs(element)
} else {
processFor(element)
processIf(element)
processOnce(element)
processKey(element)
// determine whether this is a plain element after
// removing structural attributes
element.plain = !element.key && !attrs.length
processRef(element)
processSlot(element)
processComponent(element)
for (let i = 0; i < transforms.length; i++) {
transforms[i](element, options)
}
processAttrs(element)
}
function checkRootConstraints (el) {
if (process.env.NODE_ENV !== 'production') {
if (el.tag === 'slot' || el.tag === 'template') {
warnOnce(
`Cannot use <${el.tag}> as component root element because it may ` +
'contain multiple nodes.'
)
}
if (el.attrsMap.hasOwnProperty('v-for')) {
warnOnce(
'Cannot use v-for on stateful component root element because ' +
'it renders multiple elements.'
)
}
}
}
// tree management
if (!root) {
root = element
checkRootConstraints(root)
} else if (!stack.length) {
// allow root elements with v-if, v-else-if and v-else
if (root.if && (element.elseif || element.else)) {
checkRootConstraints(element)
addIfCondition(root, {
exp: element.elseif,
block: element
})
} else if (process.env.NODE_ENV !== 'production') {
warnOnce(
`Component template should contain exactly one root element. ` +
`If you are using v-if on multiple elements, ` +
`use v-else-if to chain them instead.`
)
}
}
if (currentParent && !element.forbidden) {
if (element.elseif || element.else) {
processIfConditions(element, currentParent)
} else if (element.slotScope) { // scoped slot
currentParent.plain = false
const name = element.slotTarget || '"default"'
;(currentParent.scopedSlots || (currentParent.scopedSlots = {}))[name] = element
} else {
currentParent.children.push(element)
element.parent = currentParent
}
}
if (!unary) {
currentParent = element
stack.push(element)
} else {
endPre(element)
}
// apply post-transforms
for (let i = 0; i < postTransforms.length; i++) {
postTransforms[i](element, options)
}
},
end () {
// remove trailing whitespace
const element = stack[stack.length - 1]
const lastNode = element.children[element.children.length - 1]
if (lastNode && lastNode.type === 3 && lastNode.text === ' ' && !inPre) {
element.children.pop()
}
// pop stack
stack.length -= 1
currentParent = stack[stack.length - 1]
endPre(element)
},
chars (text: string) {
if (!currentParent) {
if (process.env.NODE_ENV !== 'production') {
if (text === template) {
warnOnce(
'Component template requires a root element, rather than just text.'
)
} else if ((text = text.trim())) {
warnOnce(
`text "${text}" outside root element will be ignored.`
)
}
}
return
}
// IE textarea placeholder bug
/* istanbul ignore if */
if (isIE &&
currentParent.tag === 'textarea' &&
currentParent.attrsMap.placeholder === text) {
return
}
const children = currentParent.children
text = inPre || text.trim()
? decodeHTMLCached(text)
// only preserve whitespace if its not right after a starting tag
: preserveWhitespace && children.length ? ' ' : ''
if (text) {
let expression
if (!inVPre && text !== ' ' && (expression = parseText(text, delimiters))) {
children.push({
type: 2,
expression,
text
})
} else if (text !== ' ' || !children.length || children[children.length - 1].text !== ' ') {
children.push({
type: 3,
text
})
}
}
}
})
return root
}
function processPre (el) {
if (getAndRemoveAttr(el, 'v-pre') != null) {
el.pre = true
}
}
function processRawAttrs (el) {
const l = el.attrsList.length
if (l) {
const attrs = el.attrs = new Array(l)
for (let i = 0; i < l; i++) {
attrs[i] = {
name: el.attrsList[i].name,
value: JSON.stringify(el.attrsList[i].value)
}
}
} else if (!el.pre) {
// non root node in pre blocks with no attributes
el.plain = true
}
}
function processKey (el) {
const exp = getBindingAttr(el, 'key')
if (exp) {
if (process.env.NODE_ENV !== 'production' && el.tag === 'template') {
warn(`<template> cannot be keyed. Place the key on real elements instead.`)
}
el.key = exp
}
}
function processRef (el) {
const ref = getBindingAttr(el, 'ref')
if (ref) {
el.ref = ref
el.refInFor = checkInFor(el)
}
}
function processFor (el) {
let exp
if ((exp = getAndRemoveAttr(el, 'v-for'))) {
const inMatch = exp.match(forAliasRE)
if (!inMatch) {
process.env.NODE_ENV !== 'production' && warn(
`Invalid v-for expression: ${exp}`
)
return
}
el.for = inMatch[2].trim()
const alias = inMatch[1].trim()
const iteratorMatch = alias.match(forIteratorRE)
if (iteratorMatch) {
el.alias = iteratorMatch[1].trim()
el.iterator1 = iteratorMatch[2].trim()
if (iteratorMatch[3]) {
el.iterator2 = iteratorMatch[3].trim()
}
} else {
el.alias = alias
}
}
}
function processIf (el) {
const exp = getAndRemoveAttr(el, 'v-if')
if (exp) {
el.if = exp
addIfCondition(el, {
exp: exp,
block: el
})
} else {
if (getAndRemoveAttr(el, 'v-else') != null) {
el.else = true
}
const elseif = getAndRemoveAttr(el, 'v-else-if')
if (elseif) {
el.elseif = elseif
}
}
}
function processIfConditions (el, parent) {
const prev = findPrevElement(parent.children)
if (prev && prev.if) {
addIfCondition(prev, {
exp: el.elseif,
block: el
})
} else if (process.env.NODE_ENV !== 'production') {
warn(
`v-${el.elseif ? ('else-if="' + el.elseif + '"') : 'else'} ` +
`used on element <${el.tag}> without corresponding v-if.`
)
}
}
function findPrevElement (children: Array<any>): ASTElement | void {
let i = children.length
while (i--) {
if (children[i].type === 1) {
return children[i]
} else {
if (process.env.NODE_ENV !== 'production' && children[i].text !== ' ') {
warn(
`text "${children[i].text.trim()}" between v-if and v-else(-if) ` +
`will be ignored.`
)
}
children.pop()
}
}
}
function addIfCondition (el, condition) {
if (!el.ifConditions) {
el.ifConditions = []
}
el.ifConditions.push(condition)
}
function processOnce (el) {
const once = getAndRemoveAttr(el, 'v-once')
if (once != null) {
el.once = true
}
}
function processSlot (el) {
if (el.tag === 'slot') {
el.slotName = getBindingAttr(el, 'name')
if (process.env.NODE_ENV !== 'production' && el.key) {
warn(
`\`key\` does not work on <slot> because slots are abstract outlets ` +
`and can possibly expand into multiple elements. ` +
`Use the key on a wrapping element instead.`
)
}
} else {
const slotTarget = getBindingAttr(el, 'slot')
if (slotTarget) {
el.slotTarget = slotTarget === '""' ? '"default"' : slotTarget
}
if (el.tag === 'template') {
el.slotScope = getAndRemoveAttr(el, 'scope')
}
}
}
function processComponent (el) {
let binding
if ((binding = getBindingAttr(el, 'is'))) {
el.component = binding
}
if (getAndRemoveAttr(el, 'inline-template') != null) {
el.inlineTemplate = true
}
}
function processAttrs (el) {
const list = el.attrsList
let i, l, name, rawName, value, modifiers, isProp
for (i = 0, l = list.length; i < l; i++) {
name = rawName = list[i].name
value = list[i].value
if (dirRE.test(name)) {
// mark element as dynamic
el.hasBindings = true
// modifiers
modifiers = parseModifiers(name)
if (modifiers) {
name = name.replace(modifierRE, '')
}
if (bindRE.test(name)) { // v-bind
name = name.replace(bindRE, '')
value = parseFilters(value)
isProp = false
if (modifiers) {
if (modifiers.prop) {
isProp = true
name = camelize(name)
if (name === 'innerHtml') name = 'innerHTML'
}
if (modifiers.camel) {
name = camelize(name)
}
if (modifiers.sync) {
addHandler(
el,
`update:${camelize(name)}`,
genAssignmentCode(value, `$event`)
)
}
}
if (isProp || platformMustUseProp(el.tag, el.attrsMap.type, name)) {
addProp(el, name, value)
} else {
addAttr(el, name, value)
}
} else if (onRE.test(name)) { // v-on
name = name.replace(onRE, '')
addHandler(el, name, value, modifiers, false, warn)
} else { // normal directives
name = name.replace(dirRE, '')
// parse arg
const argMatch = name.match(argRE)
const arg = argMatch && argMatch[1]
if (arg) {
name = name.slice(0, -(arg.length + 1))
}
addDirective(el, name, rawName, value, arg, modifiers)
if (process.env.NODE_ENV !== 'production' && name === 'model') {
checkForAliasModel(el, value)
}
}
} else {
// literal attribute
if (process.env.NODE_ENV !== 'production') {
const expression = parseText(value, delimiters)
if (expression) {
warn(
`${name}="${value}": ` +
'Interpolation inside attributes has been removed. ' +
'Use v-bind or the colon shorthand instead. For example, ' +
'instead of <div id="{{ val }}">, use <div :id="val">.'
)
}
}
addAttr(el, name, JSON.stringify(value))
}
}
}
function checkInFor (el: ASTElement): boolean {
let parent = el
while (parent) {
if (parent.for !== undefined) {
return true
}
parent = parent.parent
}
return false
}
function parseModifiers (name: string): Object | void {
const match = name.match(modifierRE)
if (match) {
const ret = {}
match.forEach(m => { ret[m.slice(1)] = true })
return ret
}
}
function makeAttrsMap (attrs: Array<Object>): Object {
const map = {}
for (let i = 0, l = attrs.length; i < l; i++) {
if (
process.env.NODE_ENV !== 'production' &&
map[attrs[i].name] && !isIE && !isEdge
) {
warn('duplicate attribute: ' + attrs[i].name)
}
map[attrs[i].name] = attrs[i].value
}
return map
}
function isForbiddenTag (el): boolean {
return (
el.tag === 'style' ||
(el.tag === 'script' && (
!el.attrsMap.type ||
el.attrsMap.type === 'text/javascript'
))
)
}
const ieNSBug = /^xmlns:NS\d+/
const ieNSPrefix = /^NS\d+:/
/* istanbul ignore next */
function guardIESVGBug (attrs) {
const res = []
for (let i = 0; i < attrs.length; i++) {
const attr = attrs[i]
if (!ieNSBug.test(attr.name)) {
attr.name = attr.name.replace(ieNSPrefix, '')
res.push(attr)
}
}
return res
}
function checkForAliasModel (el, value) {
let _el = el
while (_el) {
if (_el.for && _el.alias === value) {
warn(
`<${el.tag} v-model="${value}">: ` +
`You are binding v-model directly to a v-for iteration alias. ` +
`This will not be able to modify the v-for source array because ` +
`writing to the alias is like modifying a function local variable. ` +
`Consider using an array of objects and use v-model on an object property instead.`
)
}
_el = _el.parent
}
}
| src/compiler/parser/index.js | 1 | https://github.com/vuejs/vue/commit/d8315c42ef5b6b739100fad5f20e8b0c41f78eef | [
0.998391330242157,
0.06545553356409073,
0.00016245747974608094,
0.0001740613515721634,
0.23956044018268585
] |
{
"id": 1,
"code_window": [
" currentParent.attrsMap.placeholder === text) {\n",
" return\n",
" }\n",
" const children = currentParent.children\n",
" text = inPre || text.trim()\n",
" ? decodeHTMLCached(text)\n",
" // only preserve whitespace if its not right after a starting tag\n",
" : preserveWhitespace && children.length ? ' ' : ''\n",
" if (text) {\n",
" let expression\n",
" if (!inVPre && text !== ' ' && (expression = parseText(text, delimiters))) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" ? isTextTag(currentParent) ? text : decodeHTMLCached(text)\n"
],
"file_path": "src/compiler/parser/index.js",
"type": "replace",
"edit_start_line_idx": 254
} | import Vue from 'vue'
import { hasSymbol } from 'core/util/env'
describe('Options props', () => {
it('array syntax', done => {
const vm = new Vue({
data: {
b: 'bar'
},
template: '<test v-bind:b="b" ref="child"></test>',
components: {
test: {
props: ['b'],
template: '<div>{{b}}</div>'
}
}
}).$mount()
expect(vm.$el.innerHTML).toBe('bar')
vm.b = 'baz'
waitForUpdate(() => {
expect(vm.$el.innerHTML).toBe('baz')
vm.$refs.child.b = 'qux'
}).then(() => {
expect(vm.$el.innerHTML).toBe('qux')
expect('Avoid mutating a prop directly').toHaveBeenWarned()
}).then(done)
})
it('object syntax', done => {
const vm = new Vue({
data: {
b: 'bar'
},
template: '<test v-bind:b="b" ref="child"></test>',
components: {
test: {
props: { b: String },
template: '<div>{{b}}</div>'
}
}
}).$mount()
expect(vm.$el.innerHTML).toBe('bar')
vm.b = 'baz'
waitForUpdate(() => {
expect(vm.$el.innerHTML).toBe('baz')
vm.$refs.child.b = 'qux'
}).then(() => {
expect(vm.$el.innerHTML).toBe('qux')
expect('Avoid mutating a prop directly').toHaveBeenWarned()
}).then(done)
})
it('warn mixed syntax', () => {
new Vue({
props: [{ b: String }]
})
expect('props must be strings when using array syntax').toHaveBeenWarned()
})
it('default values', () => {
const vm = new Vue({
data: {
b: undefined
},
template: '<test :b="b"></test>',
components: {
test: {
props: {
a: {
default: 'A' // absent
},
b: {
default: 'B' // undefined
}
},
template: '<div>{{a}}{{b}}</div>'
}
}
}).$mount()
expect(vm.$el.textContent).toBe('AB')
})
it('default value reactivity', done => {
const vm = new Vue({
props: {
a: {
default: () => ({ b: 1 })
}
},
propsData: {
a: undefined
},
template: '<div>{{ a.b }}</div>'
}).$mount()
expect(vm.$el.textContent).toBe('1')
vm.a.b = 2
waitForUpdate(() => {
expect(vm.$el.textContent).toBe('2')
}).then(done)
})
it('default value Function', () => {
const func = () => 132
const vm = new Vue({
props: {
a: {
type: Function,
default: func
}
},
propsData: {
a: undefined
}
})
expect(vm.a).toBe(func)
})
it('warn object/array default values', () => {
new Vue({
props: {
a: {
default: { b: 1 }
}
},
propsData: {
a: undefined
}
})
expect('Props with type Object/Array must use a factory function').toHaveBeenWarned()
})
it('warn missing required', () => {
new Vue({
template: '<test></test>',
components: {
test: {
props: { a: { required: true }},
template: '<div>{{a}}</div>'
}
}
}).$mount()
expect('Missing required prop: "a"').toHaveBeenWarned()
})
describe('assertions', () => {
function makeInstance (value, type, validator, required) {
return new Vue({
template: '<test :test="val"></test>',
data: {
val: value
},
components: {
test: {
template: '<div></div>',
props: {
test: {
type,
validator,
required
}
}
}
}
}).$mount()
}
it('string', () => {
makeInstance('hello', String)
expect(console.error.calls.count()).toBe(0)
makeInstance(123, String)
expect('Expected String').toHaveBeenWarned()
})
it('number', () => {
makeInstance(123, Number)
expect(console.error.calls.count()).toBe(0)
makeInstance('123', Number)
expect('Expected Number').toHaveBeenWarned()
})
it('boolean', () => {
makeInstance(true, Boolean)
expect(console.error.calls.count()).toBe(0)
makeInstance('123', Boolean)
expect('Expected Boolean').toHaveBeenWarned()
})
it('function', () => {
makeInstance(() => {}, Function)
expect(console.error.calls.count()).toBe(0)
makeInstance(123, Function)
expect('Expected Function').toHaveBeenWarned()
})
it('object', () => {
makeInstance({}, Object)
expect(console.error.calls.count()).toBe(0)
makeInstance([], Object)
expect('Expected Object').toHaveBeenWarned()
})
it('array', () => {
makeInstance([], Array)
expect(console.error.calls.count()).toBe(0)
makeInstance({}, Array)
expect('Expected Array').toHaveBeenWarned()
})
if (hasSymbol) {
it('symbol', () => {
makeInstance(Symbol('foo'), Symbol)
expect(console.error.calls.count()).toBe(0)
makeInstance({}, Symbol)
expect('Expected Symbol').toHaveBeenWarned()
})
}
it('custom constructor', () => {
function Class () {}
makeInstance(new Class(), Class)
expect(console.error.calls.count()).toBe(0)
makeInstance({}, Class)
expect('type check failed').toHaveBeenWarned()
})
it('multiple types', () => {
makeInstance([], [Array, Number, Boolean])
expect(console.error.calls.count()).toBe(0)
makeInstance({}, [Array, Number, Boolean])
expect('Expected Array, Number, Boolean, got Object').toHaveBeenWarned()
})
it('custom validator', () => {
makeInstance(123, null, v => v === 123)
expect(console.error.calls.count()).toBe(0)
makeInstance(123, null, v => v === 234)
expect('custom validator check failed').toHaveBeenWarned()
})
it('type check + custom validator', () => {
makeInstance(123, Number, v => v === 123)
expect(console.error.calls.count()).toBe(0)
makeInstance(123, Number, v => v === 234)
expect('custom validator check failed').toHaveBeenWarned()
makeInstance(123, String, v => v === 123)
expect('Expected String').toHaveBeenWarned()
})
it('multiple types + custom validator', () => {
makeInstance(123, [Number, String, Boolean], v => v === 123)
expect(console.error.calls.count()).toBe(0)
makeInstance(123, [Number, String, Boolean], v => v === 234)
expect('custom validator check failed').toHaveBeenWarned()
makeInstance(123, [String, Boolean], v => v === 123)
expect('Expected String, Boolean').toHaveBeenWarned()
})
it('optional with type + null/undefined', () => {
makeInstance(undefined, String)
expect(console.error.calls.count()).toBe(0)
makeInstance(null, String)
expect(console.error.calls.count()).toBe(0)
})
it('required with type + null/undefined', () => {
makeInstance(undefined, String, null, true)
expect(console.error.calls.count()).toBe(1)
expect('Expected String').toHaveBeenWarned()
makeInstance(null, Boolean, null, true)
expect(console.error.calls.count()).toBe(2)
expect('Expected Boolean').toHaveBeenWarned()
})
it('optional prop of any type (type: true or prop: true)', () => {
makeInstance(1, true)
expect(console.error.calls.count()).toBe(0)
makeInstance('any', true)
expect(console.error.calls.count()).toBe(0)
makeInstance({}, true)
expect(console.error.calls.count()).toBe(0)
makeInstance(undefined, true)
expect(console.error.calls.count()).toBe(0)
makeInstance(null, true)
expect(console.error.calls.count()).toBe(0)
})
})
it('should work with v-bind', () => {
const vm = new Vue({
template: `<test v-bind="{ a: 1, b: 2 }"></test>`,
components: {
test: {
props: ['a', 'b'],
template: '<div>{{ a }} {{ b }}</div>'
}
}
}).$mount()
expect(vm.$el.textContent).toBe('1 2')
})
it('should warn data fields already defined as a prop', () => {
new Vue({
template: '<test a="1"></test>',
components: {
test: {
template: '<div></div>',
data: function () {
return { a: 123 }
},
props: {
a: null
}
}
}
}).$mount()
expect('already declared as a prop').toHaveBeenWarned()
})
it('should warn methods already defined as a prop', () => {
new Vue({
template: '<test a="1"></test>',
components: {
test: {
template: '<div></div>',
props: {
a: null
},
methods: {
a () {
}
}
}
}
}).$mount()
expect(`method "a" has already been defined as a prop`).toHaveBeenWarned()
expect(`Avoid mutating a prop directly`).toHaveBeenWarned()
})
it('treat boolean props properly', () => {
const vm = new Vue({
template: '<comp ref="child" prop-a prop-b="prop-b"></comp>',
components: {
comp: {
template: '<div></div>',
props: {
propA: Boolean,
propB: Boolean,
propC: Boolean
}
}
}
}).$mount()
expect(vm.$refs.child.propA).toBe(true)
expect(vm.$refs.child.propB).toBe(true)
expect(vm.$refs.child.propC).toBe(false)
})
it('should respect default value of a Boolean prop', function () {
const vm = new Vue({
template: '<test></test>',
components: {
test: {
props: {
prop: {
type: Boolean,
default: true
}
},
template: '<div>{{prop}}</div>'
}
}
}).$mount()
expect(vm.$el.textContent).toBe('true')
})
it('non reactive values passed down as prop should not be converted', done => {
const a = Object.freeze({
nested: {
msg: 'hello'
}
})
const parent = new Vue({
template: '<comp :a="a.nested"></comp>',
data: {
a: a
},
components: {
comp: {
template: '<div></div>',
props: ['a']
}
}
}).$mount()
const child = parent.$children[0]
expect(child.a.msg).toBe('hello')
expect(child.a.__ob__).toBeUndefined() // should not be converted
parent.a = Object.freeze({
nested: {
msg: 'yo'
}
})
waitForUpdate(() => {
expect(child.a.msg).toBe('yo')
expect(child.a.__ob__).toBeUndefined()
}).then(done)
})
it('should not warn for non-required, absent prop', function () {
new Vue({
template: '<test></test>',
components: {
test: {
template: '<div></div>',
props: {
prop: {
type: String
}
}
}
}
}).$mount()
expect(console.error.calls.count()).toBe(0)
})
// #3453
it('should not fire watcher on object/array props when parent re-renders', done => {
const spy = jasmine.createSpy()
const vm = new Vue({
data: {
arr: []
},
template: '<test :prop="arr">hi</test>',
components: {
test: {
props: ['prop'],
watch: {
prop: spy
},
template: '<div><slot></slot></div>'
}
}
}).$mount()
vm.$forceUpdate()
waitForUpdate(() => {
expect(spy).not.toHaveBeenCalled()
}).then(done)
})
// #4090
it('should not trigger watcher on default value', done => {
const spy = jasmine.createSpy()
const vm = new Vue({
template: `<test :value="a" :test="b"></test>`,
data: {
a: 1,
b: undefined
},
components: {
test: {
template: '<div>{{ value }}</div>',
props: {
value: { type: Number },
test: {
type: Object,
default: () => ({})
}
},
watch: {
test: spy
}
}
}
}).$mount()
vm.a++
waitForUpdate(() => {
expect(spy).not.toHaveBeenCalled()
vm.b = {}
}).then(() => {
expect(spy.calls.count()).toBe(1)
}).then(() => {
vm.b = undefined
}).then(() => {
expect(spy.calls.count()).toBe(2)
vm.a++
}).then(() => {
expect(spy.calls.count()).toBe(2)
}).then(done)
})
it('warn reserved props', () => {
new Vue({
props: {
key: String
}
})
expect(`"key" is a reserved attribute`).toHaveBeenWarned()
})
})
| test/unit/features/options/props.spec.js | 0 | https://github.com/vuejs/vue/commit/d8315c42ef5b6b739100fad5f20e8b0c41f78eef | [
0.00017856815247796476,
0.0001747889764374122,
0.00016392249381169677,
0.00017574758385308087,
0.00000311958547172253
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.