"Add Slices" modal on dashboard page (#678)

* Add slice modal

* use datatables, filter by slice creator

* tests & landscaping

* code review + react-bootstrap-table + modularity
This commit is contained in:
George Ke 2016-07-07 21:40:33 -07:00 committed by GitHub
parent afff78868f
commit 04f3e3bc8f
10 changed files with 602 additions and 254 deletions

View File

@ -1,196 +1,22 @@
var $ = window.$ = require('jquery');
var jQuery = window.jQuery = $;
var px = require('./modules/caravel.js');
var px = require('../modules/caravel.js');
var d3 = require('d3');
var showModal = require('./modules/utils.js').showModal;
require('bootstrap');
var showModal = require('../modules/utils.js').showModal;
import React from 'react';
import { render } from 'react-dom';
import SliceAdder from './components/SliceAdder.jsx';
import GridLayout from './components/GridLayout.jsx';
var ace = require('brace');
require('bootstrap');
require('brace/mode/css');
require('brace/theme/crimson_editor');
require('./caravel-select2.js');
require('../node_modules/react-grid-layout/css/styles.css');
require('../node_modules/react-resizable/css/styles.css');
require('../stylesheets/dashboard.css');
import { Responsive, WidthProvider } from "react-grid-layout";
const ResponsiveReactGridLayout = WidthProvider(Responsive);
class SliceCell extends React.Component {
render() {
const slice = this.props.slice,
createMarkup = function () {
return { __html: slice.description_markeddown };
};
return (
<div>
<div className="chart-header">
<div className="row">
<div className="col-md-12 text-center header">
{slice.slice_name}
</div>
<div className="col-md-12 chart-controls">
<div className="pull-left">
<a title="Move chart" data-toggle="tooltip">
<i className="fa fa-arrows drag"/>
</a>
<a className="refresh" title="Force refresh data" data-toggle="tooltip">
<i className="fa fa-repeat"/>
</a>
</div>
<div className="pull-right">
{slice.description ?
<a title="Toggle chart description">
<i className="fa fa-info-circle slice_info" title={slice.description} data-toggle="tooltip"/>
</a>
: ""}
<a href={slice.edit_url} title="Edit chart" data-toggle="tooltip">
<i className="fa fa-pencil"/>
</a>
<a href={slice.slice_url} title="Explore chart" data-toggle="tooltip">
<i className="fa fa-share"/>
</a>
<a className="remove-chart" title="Remove chart from dashboard" data-toggle="tooltip">
<i className="fa fa-close" onClick={this.props.removeSlice.bind(null, slice.slice_id)}/>
</a>
</div>
</div>
</div>
</div>
<div
className="slice_description bs-callout bs-callout-default"
style={this.props.expandedSlices && this.props.expandedSlices[String(slice.slice_id)] ? {} : { display: "none" }}
dangerouslySetInnerHTML={createMarkup()}>
</div>
<div className="row chart-container">
<input type="hidden" value="false"/>
<div id={slice.token} className="token col-md-12">
<img src={"/static/assets/images/loading.gif"} className="loading" alt="loading"/>
<div className="slice_container" id={slice.token + "_con"}></div>
</div>
</div>
</div>
);
}
}
class GridLayout extends React.Component {
removeSlice(sliceId) {
$('[data-toggle="tooltip"]').tooltip("hide");
this.setState({
layout: this.state.layout.filter(function (reactPos) {
return reactPos.i !== String(sliceId);
}),
slices: this.state.slices.filter(function (slice) {
return slice.slice_id !== sliceId;
}),
sliceElements: this.state.sliceElements.filter(function (sliceElement) {
return sliceElement.key !== String(sliceId);
})
});
}
onResizeStop(layout, oldItem, newItem) {
if (oldItem.w != newItem.w || oldItem.h != newItem.h) {
this.setState({
layout: layout
}, function () {
this.props.dashboard.getSlice(newItem.i).resize();
});
}
}
onDragStop(layout) {
this.setState({
layout: layout
});
}
serialize() {
return this.state.layout.map(function (reactPos) {
return {
slice_id: reactPos.i,
col: reactPos.x + 1,
row: reactPos.y,
size_x: reactPos.w,
size_y: reactPos.h
};
});
}
componentWillMount() {
var layout = [],
sliceElements = [];
this.props.slices.forEach(function (slice, index) {
var pos = this.props.posDict[slice.slice_id];
if (!pos) {
pos = {
col: (index * 4 + 1) % 12,
row: Math.floor((index) / 3) * 4,
size_x: 4,
size_y: 4
};
}
sliceElements.push(
<div
id={"slice_" + slice.slice_id}
key={slice.slice_id}
data-slice-id={slice.slice_id}
className={"widget " + slice.viz_name}>
<SliceCell
slice={slice}
removeSlice={this.removeSlice.bind(this)}
expandedSlices={this.props.dashboard.metadata.expanded_slices}/>
</div>
);
layout.push({
i: String(slice.slice_id),
x: pos.col - 1,
y: pos.row,
w: pos.size_x,
minW: 2,
h: pos.size_y
});
}, this);
this.setState({
layout: layout,
sliceElements: sliceElements,
slices: this.props.slices
});
}
render() {
return (
<ResponsiveReactGridLayout
className="layout"
layouts={{ lg: this.state.layout }}
onResizeStop={this.onResizeStop.bind(this)}
onDragStop={this.onDragStop.bind(this)}
cols={{ lg: 12, md: 12, sm: 10, xs: 8, xxs: 6 }}
rowHeight={100}
autoSize={true}
margin={[20, 20]}
useCSSTransforms={false}
draggableHandle=".drag">
{this.state.sliceElements}
</ResponsiveReactGridLayout>
);
}
}
require('../caravel-select2.js');
require('../../stylesheets/dashboard.css');
var Dashboard = function (dashboardData) {
var reactGridLayout;
var dashboard = $.extend(dashboardData, {
filters: {},
init: function () {
@ -202,10 +28,10 @@ var Dashboard = function (dashboardData) {
dashboard.slices.forEach(function (data) {
if (data.error) {
var html = '<div class="alert alert-danger">' + data.error + '</div>';
$("#slice_" + data.slice_id).find('.token').html(html);
$('#slice_' + data.slice_id).find('.token').html(html);
} else {
var slice = px.Slice(data, dash);
$("#slice_" + data.slice_id).find('a.refresh').click(function () {
$('#slice_' + data.slice_id).find('a.refresh').click(function () {
slice.render(true);
});
sliceObjects.push(slice);
@ -315,17 +141,90 @@ var Dashboard = function (dashboardData) {
}
}
},
initDashboardView: function () {
var posDict = {}
this.position_json.forEach(function (position) {
posDict[position.slice_id] = position;
});
showAddSlice: function () {
var slicesOnDashMap = {};
this.reactGridLayout.serialize().forEach(function (position) {
slicesOnDashMap[position.slice_id] = true;
}, this);
reactGridLayout = render(
<GridLayout slices={this.slices} posDict={posDict} dashboard={dashboard}/>,
render(
<SliceAdder dashboard={dashboard} slicesOnDashMap={slicesOnDashMap} caravel={px} />,
document.getElementById("add-slice-container")
);
},
getAjaxErrorMsg: function (error) {
var respJSON = error.responseJSON;
return (respJSON && respJSON.message) ? respJSON.message :
error.responseText;
},
addSlicesToDashboard: function (sliceIds) {
$.ajax({
type: "POST",
url: '/caravel/add_slices/' + dashboard.id + '/',
data: {
data: JSON.stringify({ slice_ids: sliceIds })
},
success: function () {
// Refresh page to allow for slices to re-render
window.location.reload();
},
error: function (error) {
var errorMsg = this.getAjaxErrorMsg(error);
showModal({
title: "Error",
body: "Sorry, there was an error adding slices to this dashboard: </ br>" + errorMsg
});
}.bind(this)
});
},
saveDashboard: function () {
var expandedSlices = {};
$.each($(".slice_info"), function (i, d) {
var widget = $(this).parents('.widget');
var sliceDescription = widget.find('.slice_description');
if (sliceDescription.is(":visible")) {
expandedSlices[$(widget).attr('data-slice-id')] = true;
}
});
var data = {
positions: this.reactGridLayout.serialize(),
css: this.editor.getValue(),
expanded_slices: expandedSlices
};
$.ajax({
type: "POST",
url: '/caravel/save_dash/' + dashboard.id + '/',
data: {
data: JSON.stringify(data)
},
success: function () {
showModal({
title: "Success",
body: "This dashboard was saved successfully."
});
},
error: function (error) {
var errorMsg = this.getAjaxErrorMsg(error);
showModal({
title: "Error",
body: "Sorry, there was an error saving this dashboard: </ br>" + errorMsg
});
}
});
},
initDashboardView: function () {
this.posDict = {};
this.position_json.forEach(function (position) {
this.posDict[position.slice_id] = position;
}, this);
this.reactGridLayout = render(
<GridLayout slices={this.slices} posDict={this.posDict} dashboard={dashboard}/>,
document.getElementById("grid-container")
);
this.curUserId = $('.dashboard').data('user');
dashboard = this;
// Displaying widget controls on hover
@ -338,46 +237,11 @@ var Dashboard = function (dashboardData) {
}
);
$("div.grid-container").css('visibility', 'visible');
$("#savedash").click(function () {
var expanded_slices = {};
$.each($(".slice_info"), function (i, d) {
var widget = $(this).parents('.widget');
var slice_description = widget.find('.slice_description');
if (slice_description.is(":visible")) {
expanded_slices[$(widget).attr('data-slice-id')] = true;
}
});
var data = {
positions: reactGridLayout.serialize(),
css: editor.getValue(),
expanded_slices: expanded_slices
};
$.ajax({
type: "POST",
url: '/caravel/save_dash/' + dashboard.id + '/',
data: {
data: JSON.stringify(data)
},
success: function () {
showModal({
title: "Success",
body: "This dashboard was saved successfully."
});
},
error: function (error) {
var respJSON = error.responseJSON;
var errorMsg = (respJSON && respJSON.message) ? respJSON.message :
error.responseText;
showModal({
title: "Error",
body: "Sorry, there was an error saving this dashboard:<br />" + errorMsg
});
console.warn("Save dashboard error", error);
}
});
});
$("#savedash").click(this.saveDashboard.bind(this));
$("#add-slice").click(this.showAddSlice.bind(this));
var editor = ace.edit("dash_css");
this.editor = editor;
editor.$blockScrolling = Infinity;
editor.setTheme("ace/theme/crimson_editor");

View File

@ -0,0 +1,186 @@
import React, { PropTypes } from 'react';
import { Responsive, WidthProvider } from 'react-grid-layout';
const ResponsiveReactGridLayout = WidthProvider(Responsive);
require('../../../node_modules/react-grid-layout/css/styles.css');
require('../../../node_modules/react-resizable/css/styles.css');
const sliceCellPropTypes = {
slice: PropTypes.object.isRequired,
removeSlice: PropTypes.func.isRequired,
expandedSlices: PropTypes.object
};
const gridLayoutPropTypes = {
dashboard: PropTypes.object.isRequired,
slices: PropTypes.arrayOf(PropTypes.object).isRequired,
posDict: PropTypes.object.isRequired
};
class SliceCell extends React.Component {
render() {
const slice = this.props.slice,
createMarkup = function () {
return { __html: slice.description_markeddown };
};
return (
<div>
<div className="chart-header">
<div className="row">
<div className="col-md-12 text-center header">
{slice.slice_name}
</div>
<div className="col-md-12 chart-controls">
<div className="pull-left">
<a title="Move chart" data-toggle="tooltip">
<i className="fa fa-arrows drag"/>
</a>
<a className="refresh" title="Force refresh data" data-toggle="tooltip">
<i className="fa fa-repeat"/>
</a>
</div>
<div className="pull-right">
{slice.description ?
<a title="Toggle chart description">
<i className="fa fa-info-circle slice_info" title={slice.description} data-toggle="tooltip"/>
</a>
: ""}
<a href={slice.edit_url} title="Edit chart" data-toggle="tooltip">
<i className="fa fa-pencil"/>
</a>
<a href={slice.slice_url} title="Explore chart" data-toggle="tooltip">
<i className="fa fa-share"/>
</a>
<a className="remove-chart" title="Remove chart from dashboard" data-toggle="tooltip">
<i className="fa fa-close" onClick={this.props.removeSlice.bind(null, slice.slice_id)}/>
</a>
</div>
</div>
</div>
</div>
<div
className="slice_description bs-callout bs-callout-default"
style={this.props.expandedSlices && this.props.expandedSlices[String(slice.slice_id)] ? {} : { display: "none" }}
dangerouslySetInnerHTML={createMarkup()}>
</div>
<div className="row chart-container">
<input type="hidden" value="false"/>
<div id={slice.token} className="token col-md-12">
<img src="/static/assets/images/loading.gif" className="loading" alt="loading"/>
<div className="slice_container" id={slice.token + "_con"}></div>
</div>
</div>
</div>
);
}
}
class GridLayout extends React.Component {
removeSlice(sliceId) {
$('[data-toggle="tooltip"]').tooltip("hide");
this.setState({
layout: this.state.layout.filter(function (reactPos) {
return reactPos.i !== String(sliceId);
}),
slices: this.state.slices.filter(function (slice) {
return slice.slice_id !== sliceId;
})
});
}
onResizeStop(layout, oldItem, newItem) {
if (oldItem.w !== newItem.w || oldItem.h !== newItem.h) {
this.setState({
layout: layout
}, function () {
this.props.dashboard.getSlice(newItem.i).resize();
});
}
}
onDragStop(layout) {
this.setState({
layout: layout
});
}
serialize() {
return this.state.layout.map(function (reactPos) {
return {
slice_id: reactPos.i,
col: reactPos.x + 1,
row: reactPos.y,
size_x: reactPos.w,
size_y: reactPos.h
};
});
}
componentWillMount() {
var layout = [];
this.props.slices.forEach(function (slice, index) {
var pos = this.props.posDict[slice.slice_id];
if (!pos) {
pos = {
col: (index * 4 + 1) % 12,
row: Math.floor((index) / 3) * 4,
size_x: 4,
size_y: 4
};
}
layout.push({
i: String(slice.slice_id),
x: pos.col - 1,
y: pos.row,
w: pos.size_x,
minW: 2,
h: pos.size_y
});
}, this);
this.setState({
layout: layout,
slices: this.props.slices
});
}
render() {
return (
<ResponsiveReactGridLayout
className="layout"
layouts={{ lg: this.state.layout }}
onResizeStop={this.onResizeStop.bind(this)}
onDragStop={this.onDragStop.bind(this)}
cols={{ lg: 12, md: 12, sm: 10, xs: 8, xxs: 6 }}
rowHeight={100}
autoSize={true}
margin={[20, 20]}
useCSSTransforms={false}
draggableHandle=".drag">
{this.state.slices.map((slice) => {
return (
<div
id="slice_${slice.slice_id}"
key={slice.slice_id}
data-slice-id={slice.slice_id}
className={"widget " + slice.viz_name}>
<SliceCell
slice={slice}
removeSlice={this.removeSlice.bind(this)}
expandedSlices={this.props.dashboard.metadata.expanded_slices}/>
</div>
);
})}
</ResponsiveReactGridLayout>
);
}
}
SliceCell.propTypes = sliceCellPropTypes;
GridLayout.propTypes = gridLayoutPropTypes;
export default GridLayout;

View File

@ -0,0 +1,42 @@
import React, { PropTypes } from 'react';
const propTypes = {
modalId: PropTypes.string.isRequired,
title: PropTypes.string,
modalContent: PropTypes.node,
customButtons: PropTypes.node
};
class Modal extends React.Component {
render() {
return (
<div className="modal fade" id={this.props.modalId} role="dialog">
<div className="modal-dialog" role="document">
<div className="modal-content">
<div className="modal-header">
<button type="button" className="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
<h4 className="modal-title">{this.props.title}</h4>
</div>
<div className="modal-body">
{this.props.modalContent}
</div>
<div className="modal-footer">
<button type="button"
className="btn btn-default"
data-dismiss="modal">
Cancel
</button>
{this.props.customButtons}
</div>
</div>
</div>
</div>
);
}
}
Modal.propTypes = propTypes;
export default Modal;

View File

@ -0,0 +1,190 @@
import React, { PropTypes } from 'react';
import update from 'immutability-helper';
import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table';
import Modal from './Modal.jsx';
require('../../../node_modules/react-bootstrap-table/css/react-bootstrap-table.css');
const propTypes = {
dashboard: PropTypes.object.isRequired,
caravel: PropTypes.object.isRequired
};
class SliceAdder extends React.Component {
constructor(props) {
super(props);
this.state = {
slices: []
};
this.addSlices = this.addSlices.bind(this);
this.toggleSlice = this.toggleSlice.bind(this);
this.toggleAllSlices = this.toggleAllSlices.bind(this);
this.slicesLoaded = false;
this.selectRowProp = {
mode: "checkbox",
clickToSelect: true,
onSelect: this.toggleSlice,
onSelectAll: this.toggleAllSlices
};
this.options = {
defaultSortOrder: "desc",
defaultSortName: "modified",
sizePerPage: 10
};
}
componentDidMount() {
var uri = "/sliceaddview/api/read?_flt_0_created_by=" + this.props.dashboard.curUserId;
this.slicesRequest = $.ajax({
url: uri,
type: 'GET',
success: function (response) {
this.slicesLoaded = true;
// Prepare slice data for table
let slices = response.result;
slices.forEach(function (slice) {
slice.id = slice.data.slice_id;
slice.sliceName = slice.data.slice_name;
slice.vizType = slice.viz_type;
slice.modified = slice.modified;
});
this.setState({
slices: slices,
selectionMap: {}
});
}.bind(this),
error: function (error) {
this.errored = true;
this.setState({
errorMsg: this.props.dashboard.getAjaxErrorMsg(error)
});
}.bind(this)
});
}
componentWillUnmount() {
this.slicesRequest.abort();
}
addSlices() {
var slices = this.state.slices.filter(function (slice) {
return this.state.selectionMap[slice.id];
}, this);
slices.forEach(function (slice) {
var sliceObj = this.props.caravel.Slice(slice.data, this.props.dashboard);
$("#slice_" + slice.data.slice_id).find('a.refresh').click(function () {
sliceObj.render(true);
});
this.props.dashboard.slices.push(sliceObj);
}, this);
this.props.dashboard.addSlicesToDashboard(Object.keys(this.state.selectionMap));
}
toggleSlice(slice) {
this.setState({
selectionMap: update(this.state.selectionMap, {
[slice.id]: {
$set: !this.state.selectionMap[slice.id]
}
})
});
}
toggleAllSlices(value) {
let updatePayload = {};
this.state.slices.forEach(function (slice) {
updatePayload[slice.id] = {
$set: value
};
}, this);
this.setState({
selectionMap: update(this.state.selectionMap, updatePayload)
});
}
modifiedDateComparator(a, b, order) {
if (order === 'desc') {
if (a.changed_on > b.changed_on) {
return -1;
} else if (a.changed_on < b.changed_on) {
return 1;
}
return 0;
}
if (a.changed_on < b.changed_on) {
return -1;
} else if (a.changed_on > b.changed_on) {
return 1;
}
return 0;
}
render() {
const hideLoad = this.slicesLoaded || this.errored;
const enableAddSlice = this.state.selectionMap && Object.keys(this.state.selectionMap).some(function (key) {
return this.state.selectionMap[key];
}, this);
const modalContent = (
<div>
<img src="/static/assets/images/loading.gif"
className={"loading " + (hideLoad ? "hidden" : "")}
alt={hideLoad ? "" : "loading"}/>
<div className={this.errored ? "" : "hidden"}>
{this.state.errorMsg}
</div>
<div className={this.slicesLoaded ? "" : "hidden"}>
<BootstrapTable
ref="table"
data={this.state.slices}
selectRow={this.selectRowProp}
options={this.options}
hover
search
pagination
height="auto">
<TableHeaderColumn dataField="sliceName" isKey={true} dataSort={true}>Name</TableHeaderColumn>
<TableHeaderColumn dataField="vizType" dataSort={true}>Viz</TableHeaderColumn>
<TableHeaderColumn
dataField="modified"
dataSort={true}
sortFunc={this.modifiedDateComparator}
// Will cause react-bootstrap-table to interpret the HTML returned
dataFormat={modified => modified}>
Modified
</TableHeaderColumn>
</BootstrapTable>
</div>
</div>
);
const customButtons = [
<button key={0}
type="button"
className="btn btn-default"
data-dismiss="modal"
onClick={this.addSlices}
disabled={!enableAddSlice}>
Add Slices
</button>
];
return (
<Modal modalId='add_slice_modal'
modalContent={modalContent}
title='Add New Slices'
customButtons={customButtons}
/>
);
}
}
SliceAdder.propTypes = propTypes;
export default SliceAdder;

View File

@ -58,6 +58,7 @@
"exports-loader": "^0.6.3",
"font-awesome": "^4.5.0",
"gridster": "^0.5.6",
"immutability-helper": "^2.0.0",
"imports-loader": "^0.6.5",
"jquery": "^2.2.1",
"jquery-ui": "^1.10.5",
@ -69,6 +70,7 @@
"nvd3": "1.8.3",
"react": "^15.2.0",
"react-bootstrap": "^0.28.3",
"react-bootstrap-table": "^2.3.7",
"react-dom": "^0.14.8",
"react-grid-layout": "^0.12.3",
"react-map-gl": "^1.0.0-beta-10",

View File

@ -44,3 +44,18 @@
.dashboard div.nvtooltip {
z-index: 888; /* this lets tool tips go on top of other slices */
}
.modal img.loading {
width: 50px;
margin: 0;
position: relative;
}
.react-bs-container-body {
max-height: 400px;
overflow-y: auto;
}
.hidden, #pageDropDown {
display: none;
}

View File

@ -6,7 +6,7 @@ var config = {
// for now generate one compiled js file per entry point / html page
entry: {
'css-theme': APP_DIR + '/javascripts/css-theme.js',
dashboard: APP_DIR + '/javascripts/dashboard.jsx',
dashboard: APP_DIR + '/javascripts/dashboard/Dashboard.jsx',
explore: APP_DIR + '/javascripts/explore/explore.jsx',
welcome: APP_DIR + '/javascripts/welcome.js',
sql: APP_DIR + '/javascripts/sql.js',

View File

@ -7,7 +7,7 @@
{% block title %}[dashboard] {{ dashboard.dashboard_title }}{% endblock %}
{% block body %}
<div class="dashboard container-fluid" data-dashboard="{{ dashboard.json_data }}" data-css="{{ dashboard.css }}">
<div class="dashboard container-fluid" data-dashboard="{{ dashboard.json_data }}" data-css="{{ dashboard.css }}" data-user="{{ user_id }}">
{% include 'caravel/flash_wrapper.html' %}
<!-- Modal -->
@ -64,6 +64,7 @@
</div>
</div>
</div>
<div id="add-slice-container"></div>
<div class="title">
<div class="row">
@ -75,28 +76,29 @@
</h2>
</div>
<div class="col-md-3">
{% if dash_edit_perm %}
<div class="btn-group pull-right" role="group" >
<button type="button" id="refresh_dash" class="btn btn-default" data-toggle="tooltip" title="Force refresh the whole dashboard">
<i class="fa fa-refresh"></i>
</button>
<button type="button" id="refresh_dash_periodic" class="btn btn-default" data-toggle="modal" data-target="#refresh_modal">
<i class="fa fa-clock-o" data-toggle="tooltip" title="Decide how frequent should the dashboard refresh"></i>
</button>
<button type="button" id="filters" class="btn btn-default" data-toggle="tooltip" title="View the list of active filters">
<i class="fa fa-filter"></i>
</button>
<button type="button" id="css" class="btn btn-default {{ "disabled disabledButton" if not dash_edit_perm }} " data-toggle="modal" data-target="#css_modal">
<i class="fa fa-css3" data-toggle="tooltip" title="Edit the dashboard's CSS"></i>
</button>
<a id="editdash" class="btn btn-default {{ "disabled disabledButton" if not dash_edit_perm }} " href="/dashboardmodelview/edit/{{ dashboard.id }}" title="Edit this dashboard's property" data-toggle="tooltip" >
<i class="fa fa-edit"></i>
</a>
<button type="button" id="savedash" class="btn btn-default {{ "disabled disabledButton" if not dash_save_perm }}" data-toggle="tooltip" title="Save the current positioning and CSS">
<i class="fa fa-save"></i>
</button>
</div>
{% endif %}
<div class="btn-group pull-right" role="group" >
<button type="button" id="refresh_dash" class="btn btn-default" data-toggle="tooltip" title="Force refresh the whole dashboard">
<i class="fa fa-refresh"></i>
</button>
<button type="button" id="add-slice" class="btn btn-default" data-toggle="modal" data-target="#add_slice_modal">
<i class="fa fa-plus" data-toggle="tooltip" title="Add a new slice to the dashboard"></i>
</button>
<button type="button" id="refresh_dash_periodic" class="btn btn-default" data-toggle="modal" data-target="#refresh_modal">
<i class="fa fa-clock-o" data-toggle="tooltip" title="Decide how frequent should the dashboard refresh"></i>
</button>
<button type="button" id="filters" class="btn btn-default" data-toggle="tooltip" title="View the list of active filters">
<i class="fa fa-filter"></i>
</button>
<button type="button" id="css" class="btn btn-default {{ "disabled disabledButton" if not dash_edit_perm }} " data-toggle="modal" data-target="#css_modal">
<i class="fa fa-css3" data-toggle="tooltip" title="Edit the dashboard's CSS"></i>
</button>
<a id="editdash" class="btn btn-default {{ "disabled disabledButton" if not dash_edit_perm }} " href="/dashboardmodelview/edit/{{ dashboard.id }}" title="Edit this dashboard's property" data-toggle="tooltip" >
<i class="fa fa-edit"></i>
</a>
<button type="button" id="savedash" class="btn btn-default {{ "disabled disabledButton" if not dash_save_perm }}" data-toggle="tooltip" title="Save the current positioning and CSS">
<i class="fa fa-save"></i>
</button>
</div>
</div>
</div>
</div>

View File

@ -565,7 +565,6 @@ class SliceAsync(SliceModelView): # noqa
'creator', 'modified', 'icons']
label_columns = {
'icons': ' ',
'viz_type': _('Type'),
'slice_link': _('Slice'),
'viz_type': _('Visualization Type'),
}
@ -573,6 +572,19 @@ class SliceAsync(SliceModelView): # noqa
appbuilder.add_view_no_menu(SliceAsync)
class SliceAddView(SliceModelView): # noqa
list_columns = [
'slice_link', 'viz_type',
'owners', 'modified', 'data', 'changed_on']
label_columns = {
'icons': ' ',
'slice_link': _('Slice'),
'viz_type': _('Visualization Type'),
}
appbuilder.add_view_no_menu(SliceAddView)
class DashboardModelView(CaravelModelView, DeleteMixin): # noqa
datamodel = SQLAInterface(models.Dashboard)
list_columns = ['dashboard_link', 'creator', 'modified']
@ -1020,6 +1032,23 @@ class Caravel(BaseCaravelView):
session.close()
return "SUCCESS"
@api
@has_access_api
@expose("/add_slices/<dashboard_id>/", methods=['POST'])
def add_slices(self, dashboard_id):
"""Add and save slices to a dashboard"""
data = json.loads(request.form.get('data'))
session = db.session()
Slice = models.Slice # noqa
dash = session.query(models.Dashboard).filter_by(id=dashboard_id).first()
check_ownership(dash, raise_if_false=True)
new_slices = session.query(Slice).filter(Slice.id.in_(data['slice_ids']))
dash.slices += new_slices
session.merge(dash)
session.commit()
session.close()
return "SLICES ADDED"
@api
@has_access_api
@expose("/testconn", methods=["POST", "GET"])
@ -1100,6 +1129,7 @@ class Caravel(BaseCaravelView):
return self.render_template(
"caravel/dashboard.html", dashboard=dash,
user_id=g.user.get_id(),
templates=templates,
dash_save_perm=self.can_access('can_save_dash', 'Caravel'),
dash_edit_perm=check_ownership(dash, raise_if_false=False))

View File

@ -201,6 +201,23 @@ class CoreTests(CaravelTestCase):
resp = self.client.post(url, data=dict(data=json.dumps(data)))
assert "SUCCESS" in resp.data.decode('utf-8')
def test_add_slices(self, username='admin'):
self.login(username=username)
dash = db.session.query(models.Dashboard).filter_by(slug="births").first()
new_slice = db.session.query(models.Slice).filter_by(slice_name="Mapbox Long/Lat").first()
existing_slice = db.session.query(models.Slice).filter_by(slice_name="Name Cloud").first()
data = {
"slice_ids": [new_slice.data["slice_id"], existing_slice.data["slice_id"]]
}
url = '/caravel/add_slices/{}/'.format(dash.id)
resp = self.client.post(url, data=dict(data=json.dumps(data)))
assert "SLICES ADDED" in resp.data.decode('utf-8')
dash = db.session.query(models.Dashboard).filter_by(slug="births").first()
new_slice = db.session.query(models.Slice).filter_by(slice_name="Mapbox Long/Lat").first()
assert new_slice in dash.slices
assert len(set(dash.slices)) == len(dash.slices)
def test_gamma(self):
self.login(username='gamma')
resp = self.client.get('/slicemodelview/list/')