ExploreViewContainer.jsx 17.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
19
/* eslint camelcase: 0 */
20
import React, { useEffect, useState } from 'react';
21
import PropTypes from 'prop-types';
22 23
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
24 25
import { styled, t, supersetTheme, css } from '@superset-ui/core';
import { debounce } from 'lodash';
26
import { Resizable } from 're-resizable';
27 28

import { useDynamicPluginContext } from 'src/components/DynamicPlugins';
29 30
import { Global } from '@emotion/core';
import { Tooltip } from 'src/common/components/Tooltip';
31
import { usePrevious } from 'src/common/hooks/usePrevious';
32
import Icon from 'src/components/Icon';
G
Grace Guo 已提交
33
import ExploreChartPanel from './ExploreChartPanel';
34
import ConnectedControlPanelsContainer from './ControlPanelsContainer';
35
import SaveModal from './SaveModal';
36
import QueryAndSaveBtns from './QueryAndSaveBtns';
37
import DataSourcePanel from './DatasourcePanel';
38
import { getExploreLongUrl } from '../exploreUtils';
39
import { areObjectsEqual } from '../../reduxUtils';
40
import { getFormDataFromControls } from '../controlUtils';
41
import { chartPropShape } from '../../dashboard/util/propShapes';
42 43
import * as exploreActions from '../actions/exploreActions';
import * as saveModalActions from '../actions/saveModalActions';
G
Grace Guo 已提交
44
import * as chartActions from '../../chart/chartAction';
45
import { fetchDatasourceMetadata } from '../../dashboard/actions/datasources';
46
import * as logActions from '../../logger/actions';
G
Grace Guo 已提交
47 48 49 50
import {
  LOG_ACTIONS_MOUNT_EXPLORER,
  LOG_ACTIONS_CHANGE_EXPLORE_CONTROLS,
} from '../../logger/LogUtils';
51

52
const propTypes = {
53
  ...ExploreChartPanel.propTypes,
54 55
  height: PropTypes.string,
  width: PropTypes.string,
56 57
  actions: PropTypes.object.isRequired,
  datasource_type: PropTypes.string.isRequired,
58
  dashboardId: PropTypes.number,
59
  isDatasourceMetaLoading: PropTypes.bool.isRequired,
60
  chart: chartPropShape.isRequired,
61
  slice: PropTypes.object,
62
  sliceName: PropTypes.string,
63
  controls: PropTypes.object.isRequired,
64 65 66
  forcedHeight: PropTypes.string,
  form_data: PropTypes.object.isRequired,
  standalone: PropTypes.bool.isRequired,
67
  timeout: PropTypes.number,
68
  impressionId: PropTypes.string,
69
  vizType: PropTypes.string,
70 71
};

72
const Styles = styled.div`
73
  background: ${({ theme }) => theme.colors.grayscale.light5};
74 75 76
  text-align: left;
  position: relative;
  width: 100%;
77
  height: 100%;
78 79 80 81
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  align-items: stretch;
82 83
  border-top: 1px solid ${({ theme }) => theme.colors.grayscale.light2};
  .explore-column {
84 85
    display: flex;
    flex-direction: column;
86
    padding: ${({ theme }) => 2 * theme.gridUnit}px 0;
87 88
    max-height: 100%;
  }
89 90 91 92 93 94
  .data-source-selection {
    background-color: ${({ theme }) => theme.colors.grayscale.light4};
    padding: ${({ theme }) => 2 * theme.gridUnit}px 0;
    border-right: 1px solid ${({ theme }) => theme.colors.grayscale.light2};
  }
  .main-explore-content {
95 96
    flex: 1;
    min-width: ${({ theme }) => theme.gridUnit * 128}px;
97
    border-left: 1px solid ${({ theme }) => theme.colors.grayscale.light2};
98 99 100
    .panel {
      margin-bottom: 0;
    }
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
  }
  .controls-column {
    align-self: flex-start;
    padding: 0;
  }
  .title-container {
    position: relative;
    display: flex;
    flex-direction: row;
    padding: 0 ${({ theme }) => 2 * theme.gridUnit}px;
    justify-content: space-between;
    .horizontal-text {
      text-transform: uppercase;
      color: ${({ theme }) => theme.colors.grayscale.light1};
      font-size: ${({ theme }) => 4 * theme.typography.sizes.s};
    }
  }
  .no-show {
    display: none;
  }
  .vertical-text {
    writing-mode: vertical-rl;
    text-orientation: mixed;
  }
  .sidebar {
    height: 100%;
    background-color: ${({ theme }) => theme.colors.grayscale.light4};
    padding: ${({ theme }) => 2 * theme.gridUnit}px;
    width: ${({ theme }) => 8 * theme.gridUnit}px;
  }
  .callpase-icon > svg {
    color: ${({ theme }) => theme.colors.primary.base};
  }
134 135
`;

136 137 138 139
const getWindowSize = () => ({
  height: window.innerHeight,
  width: window.innerWidth,
});
140

141 142
function useWindowSize({ delayMs = 250 } = {}) {
  const [size, setSize] = useState(getWindowSize());
143

144 145 146 147 148
  useEffect(() => {
    const onWindowResize = debounce(() => setSize(getWindowSize()), delayMs);
    window.addEventListener('resize', onWindowResize);
    return () => window.removeEventListener('resize', onWindowResize);
  }, []);
149

150 151
  return size;
}
152

153 154 155 156 157
function ExploreViewContainer(props) {
  const dynamicPluginContext = useDynamicPluginContext();
  const dynamicPlugin = dynamicPluginContext.plugins[props.vizType];
  const isDynamicPluginLoading = dynamicPlugin && dynamicPlugin.loading;
  const wasDynamicPluginLoading = usePrevious(isDynamicPluginLoading);
158

159 160
  const previousControls = usePrevious(props.controls);
  const windowSize = useWindowSize();
161

162 163
  const [showingModal, setShowingModal] = useState(false);
  const [chartIsStale, setChartIsStale] = useState(false);
164
  const [isCollapsed, setIsCollapsed] = useState(false);
165

166 167 168 169 170
  const width = `${windowSize.width}px`;
  const navHeight = props.standalone ? 0 : 90;
  const height = props.forcedHeight
    ? `${props.forcedHeight}px`
    : `${windowSize.height - navHeight}px`;
171

172 173 174 175 176 177 178 179 180 181
  const storageKeys = {
    controlsWidth: 'controls_width',
    dataSourceWidth: 'datasource_width',
  };

  const defaultSidebarsWidth = {
    controls_width: 320,
    datasource_width: 300,
  };

182 183
  function addHistory({ isReplace = false, title } = {}) {
    const payload = { ...props.form_data };
184 185 186 187 188
    const longUrl = getExploreLongUrl(
      props.form_data,
      props.standalone ? 'standalone' : null,
      false,
    );
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
    try {
      if (isReplace) {
        window.history.replaceState(payload, title, longUrl);
      } else {
        window.history.pushState(payload, title, longUrl);
      }
    } catch (e) {
      // eslint-disable-next-line no-console
      console.warn(
        'Failed at altering browser history',
        payload,
        title,
        longUrl,
      );
    }
204 205
  }

206 207 208 209 210 211 212 213 214 215
  function handlePopstate() {
    const formData = window.history.state;
    if (formData && Object.keys(formData).length) {
      props.actions.setExploreControls(formData);
      props.actions.postChartFormData(
        formData,
        false,
        props.timeout,
        props.chart.id,
      );
216
    }
217 218
  }

219 220 221 222
  function onQuery() {
    // remove alerts when query
    props.actions.removeControlPanelAlert();
    props.actions.triggerQuery(true, props.chart.id);
223

224 225
    setChartIsStale(false);
    addHistory();
226 227
  }

228
  function handleKeydown(event) {
229 230 231 232 233
    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) {
234
        onQuery();
235
      } else if (isS) {
236 237 238
        if (props.slice) {
          props.actions
            .saveSlice(props.form_data, {
239
              action: 'overwrite',
240 241
              slice_id: props.slice.slice_id,
              slice_name: props.slice.slice_name,
242 243
              add_to_dash: 'noSave',
              goto_dash: false,
E
Erik Ritter 已提交
244 245
            })
            .then(({ data }) => {
246 247 248 249
              window.location = data.slice.slice_url;
            });
        }
      }
E
Erik Ritter 已提交
250
    }
251 252
  }

253 254 255 256
  function onStop() {
    if (props.chart && props.chart.queryController) {
      props.chart.queryController.abort();
    }
257 258
  }

259 260
  function toggleModal() {
    setShowingModal(!showingModal);
261 262
  }

263 264
  function toggleCollapse() {
    setIsCollapsed(!isCollapsed);
265 266
  }

267 268 269 270 271 272 273 274 275 276 277
  // effect to run on mount
  useEffect(() => {
    props.actions.logEvent(LOG_ACTIONS_MOUNT_EXPLORER);
    addHistory({ isReplace: true });
    window.addEventListener('popstate', handlePopstate);
    document.addEventListener('keydown', handleKeydown);
    return () => {
      window.removeEventListener('popstate', handlePopstate);
      document.removeEventListener('keydown', handleKeydown);
    };
  }, []);
278

279 280 281 282
  useEffect(() => {
    if (wasDynamicPluginLoading && !isDynamicPluginLoading) {
      // reload the controls now that we actually have the control config
      props.actions.dynamicPluginControlsReady();
283
    }
284
  }, [isDynamicPluginLoading]);
285

286 287 288 289 290 291 292 293
  useEffect(() => {
    const hasError = Object.values(props.controls).some(
      control =>
        control.validationErrors && control.validationErrors.length > 0,
    );
    if (!hasError) {
      props.actions.triggerQuery(true, props.chart.id);
    }
294
  }, []);
295

296 297
  // effect to run when controls change
  useEffect(() => {
298 299 300 301 302 303 304 305 306 307 308 309
    if (previousControls) {
      if (props.controls.viz_type.value !== previousControls.viz_type.value) {
        props.actions.resetControls();
      }
      if (
        props.controls.datasource &&
        (previousControls.datasource == null ||
          props.controls.datasource.value !== previousControls.datasource.value)
      ) {
        // this should really be handled by actions
        fetchDatasourceMetadata(props.form_data.datasource, true);
      }
310

311 312 313 314 315 316 317
      const changedControlKeys = Object.keys(props.controls).filter(
        key =>
          typeof previousControls[key] !== 'undefined' &&
          !areObjectsEqual(
            props.controls[key].value,
            previousControls[key].value,
          ),
E
Erik Ritter 已提交
318
      );
319

320 321 322 323 324 325 326 327 328 329 330 331
      // this should also be handled by the actions that are actually changing the controls
      const hasDisplayControlChanged = changedControlKeys.some(
        key => props.controls[key].renderTrigger,
      );
      if (hasDisplayControlChanged) {
        props.actions.updateQueryFormData(
          getFormDataFromControls(props.controls),
          props.chart.id,
        );
        props.actions.renderTriggered(new Date().getTime(), props.chart.id);
        addHistory();
      }
332

333 334 335 336 337 338 339 340 341 342 343 344
      // this should be handled inside actions too
      const hasQueryControlChanged = changedControlKeys.some(
        key =>
          !props.controls[key].renderTrigger &&
          !props.controls[key].dontRefreshOnChange,
      );
      if (hasQueryControlChanged) {
        props.actions.logEvent(LOG_ACTIONS_CHANGE_EXPLORE_CONTROLS);
        setChartIsStale(true);
      }
    }
  }, [props.controls]);
345

346
  function renderErrorMessage() {
347
    // Returns an error message as a node if any errors are in the store
348
    const errors = Object.entries(props.controls)
349 350 351 352 353 354 355 356 357 358 359
      .filter(
        ([, control]) =>
          control.validationErrors && control.validationErrors.length > 0,
      )
      .map(([key, control]) => (
        <div key={key}>
          {t('Control labeled ')}
          <strong>{` "${control.label}" `}</strong>
          {control.validationErrors.join('. ')}
        </div>
      ));
360 361
    let errorMessage;
    if (errors.length > 0) {
362
      errorMessage = <div style={{ textAlign: 'left' }}>{errors}</div>;
363 364 365
    }
    return errorMessage;
  }
366

367
  function renderChartContainer() {
368
    return (
G
Grace Guo 已提交
369
      <ExploreChartPanel
370 371 372 373 374 375 376
        width={width}
        height={height}
        {...props}
        errorMessage={renderErrorMessage()}
        refreshOverlayVisible={chartIsStale}
        addHistory={addHistory}
        onQuery={onQuery}
377 378
      />
    );
379
  }
380

381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
  function getSidebarWidths(key) {
    try {
      return localStorage.getItem(key) || defaultSidebarsWidth[key];
    } catch {
      return defaultSidebarsWidth[key];
    }
  }

  function setSidebarWidths(key, dimension) {
    try {
      const newDimension = Number(getSidebarWidths(key)) + dimension.width;
      localStorage.setItem(key, newDimension);
    } catch {
      // Catch in case localStorage is unavailable
    }
  }

398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
  if (props.standalone) {
    return renderChartContainer();
  }

  return (
    <Styles id="explore-container" height={height}>
      <Global
        styles={css`
          .navbar {
            margin-bottom: 0;
          }
          body {
            max-height: 100vh;
            overflow: hidden;
          }
          #app-menu,
          #app {
            flex: 1 1 auto;
          }
          #app {
            flex-basis: 100%;
            overflow: hidden;
            height: 100vh;
          }
          #app-menu {
            flex-shrink: 0;
          }
        `}
      />
      {showingModal && (
        <SaveModal
          onHide={toggleModal}
          actions={props.actions}
          form_data={props.form_data}
          sliceName={props.sliceName}
          dashboardId={props.dashboardId}
        />
      )}
436
      <Resizable
437 438 439 440 441 442 443 444
        onResizeStop={(evt, direction, ref, d) =>
          setSidebarWidths(storageKeys.dataSourceWidth, d)
        }
        defaultSize={{
          width: getSidebarWidths(storageKeys.dataSourceWidth),
          height: '100%',
        }}
        minWidth={defaultSidebarsWidth[storageKeys.dataSourceWidth]}
445 446
        maxWidth="33%"
        enable={{ right: true }}
447
        className={
448
          isCollapsed ? 'no-show' : 'explore-column data-source-selection'
449 450 451
        }
      >
        <div className="title-container">
452
          <span className="horizont al-text">{t('Dataset')}</span>
453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
          <span
            role="button"
            tabIndex={0}
            className="action-button"
            onClick={toggleCollapse}
          >
            <Icon
              name="expand"
              color={supersetTheme.colors.primary.base}
              className="collapse-icon"
              width={16}
            />
          </span>
        </div>
        <DataSourcePanel
          datasource={props.datasource}
          controls={props.controls}
          actions={props.actions}
471
        />
472
      </Resizable>
473
      {isCollapsed ? (
474
        <div
475 476 477 478 479
          className="sidebar"
          onClick={toggleCollapse}
          data-test="open-datasource-tab"
          role="button"
          tabIndex={0}
480
        >
481
          <span role="button" tabIndex={0} className="action-button">
482
            <Tooltip title={t('Open Datasource tab')}>
483
              <Icon
484
                name="collapse"
485 486 487 488
                color={supersetTheme.colors.primary.base}
                className="collapse-icon"
                width={16}
              />
489 490 491
            </Tooltip>
          </span>
          <Icon name="dataset-physical" width={16} />
492
        </div>
493
      ) : null}
494
      <Resizable
495 496 497 498 499 500 501 502
        onResizeStop={(evt, direction, ref, d) =>
          setSidebarWidths(storageKeys.controlsWidth, d)
        }
        defaultSize={{
          width: getSidebarWidths(storageKeys.controlsWidth),
          height: '100%',
        }}
        minWidth={defaultSidebarsWidth[storageKeys.controlsWidth]}
503 504 505 506
        maxWidth="33%"
        enable={{ right: true }}
        className="col-sm-3 explore-column controls-column"
      >
507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523
        <QueryAndSaveBtns
          canAdd={!!(props.can_add || props.can_overwrite)}
          onQuery={onQuery}
          onSave={toggleModal}
          onStop={onStop}
          loading={props.chart.chartStatus === 'loading'}
          chartIsStale={chartIsStale}
          errorMessage={renderErrorMessage()}
          datasourceType={props.datasource_type}
        />
        <ConnectedControlPanelsContainer
          actions={props.actions}
          form_data={props.form_data}
          controls={props.controls}
          datasource_type={props.datasource_type}
          isDatasourceMetaLoading={props.isDatasourceMetaLoading}
        />
524
      </Resizable>
525 526 527 528 529 530 531 532 533
      <div
        className={`main-explore-content ${
          isCollapsed ? 'col-sm-9' : 'col-sm-7'
        }`}
      >
        {renderChartContainer()}
      </div>
    </Styles>
  );
534
}
535 536 537

ExploreViewContainer.propTypes = propTypes;

538 539
function mapStateToProps(state) {
  const { explore, charts, impressionId } = state;
540
  const form_data = getFormDataFromControls(explore.controls);
G
Grace Guo 已提交
541 542
  const chartKey = Object.keys(charts)[0];
  const chart = charts[chartKey];
543
  return {
544
    isDatasourceMetaLoading: explore.isDatasourceMetaLoading,
G
Grace Guo 已提交
545
    datasource: explore.datasource,
546
    datasource_type: explore.datasource.type,
G
Grace Guo 已提交
547
    datasourceId: explore.datasource_id,
548
    dashboardId: explore.form_data ? explore.form_data.dashboardId : undefined,
549
    controls: explore.controls,
G
Grace Guo 已提交
550
    can_overwrite: !!explore.can_overwrite,
551
    can_add: !!explore.can_add,
G
Grace Guo 已提交
552
    can_download: !!explore.can_download,
E
Erik Ritter 已提交
553 554 555 556 557 558
    column_formats: explore.datasource
      ? explore.datasource.column_formats
      : null,
    containerId: explore.slice
      ? `slice-container-${explore.slice.slice_id}`
      : 'slice-container',
G
Grace Guo 已提交
559 560
    isStarred: explore.isStarred,
    slice: explore.slice,
561
    sliceName: explore.sliceName,
562
    triggerRender: explore.triggerRender,
563
    form_data,
G
Grace Guo 已提交
564 565
    table_name: form_data.datasource_name,
    vizType: form_data.viz_type,
566 567
    standalone: explore.standalone,
    forcedHeight: explore.forced_height,
G
Grace Guo 已提交
568
    chart,
569
    timeout: explore.common.conf.SUPERSET_WEBSERVER_TIMEOUT,
570
    impressionId,
571 572 573 574
  };
}

function mapDispatchToProps(dispatch) {
575 576 577 578 579 580
  const actions = {
    ...exploreActions,
    ...saveModalActions,
    ...chartActions,
    ...logActions,
  };
581 582 583 584 585
  return {
    actions: bindActionCreators(actions, dispatch),
  };
}

E
Erik Ritter 已提交
586 587 588 589
export default connect(
  mapStateToProps,
  mapDispatchToProps,
)(ExploreViewContainer);