Compare commits

..

31 Commits

Author SHA1 Message Date
Gabriel Dutra
19343a0520 Clear QueryBasedParameterInput 2020-11-23 19:18:35 -03:00
Gabriel Dutra
c1ed8848f0 Merge branch 'master' into query-based-dropdown--parameters 2020-11-23 16:42:06 -03:00
Gabriel Dutra
b40070d7f5 Use LabeledValues for parameterized queries 2020-11-23 16:40:18 -03:00
Gabriel Dutra
bd9ce68f68 Don't filter out values when param has search 2020-11-20 15:14:17 -03:00
Gabriel Dutra
0c0b62ae1a Remove searchTerm from structure 2020-11-20 15:13:47 -03:00
Gabriel Dutra
08bcdf77d0 Mock query instead of query_has_parameters 2020-11-12 09:11:54 -03:00
Gabriel Dutra
aa2064b1ab Fix other dropdown_values usages to use query obj 2020-11-11 13:58:01 -03:00
Gabriel Dutra
d0a787cab1 Make NoResultFound invalid parameters 2020-11-10 22:10:47 -03:00
Gabriel Dutra
a741341938 Oops 2020-11-10 20:46:51 -03:00
Gabriel Dutra
53385fa24b Merge branch 'master' into query-based-dropdown--parameters 2020-11-10 15:19:43 -03:00
Gabriel Dutra
f396c96457 Merge branch 'master' into query-based-dropdown--parameters 2020-02-25 07:49:36 -03:00
Gabriel Dutra
8bfcbf21e3 Remove redundant import 2020-02-24 11:44:28 -03:00
Gabriel Dutra
8a1640c4e7 Separate InputPopover component 2020-02-24 11:44:18 -03:00
Gabriel Dutra
a37e7f93dc Add is_safe test for queries with params 2020-02-22 15:47:29 -03:00
Gabriel Dutra
cc34e781d3 Small updates
- Change searchTerm separator
- Add cy.wait
2020-02-22 15:23:43 -03:00
Gabriel Dutra
6aa0ea715e Invert tooltip messages order 2020-02-22 14:08:19 -03:00
Gabriel Dutra
6c27619671 Make Parameter Mapping required in UI 2020-02-21 23:00:26 -03:00
Gabriel Dutra
6eeb3b3eb2 Separate UI components 2020-02-21 15:49:23 -03:00
Gabriel Dutra
d40edb81c2 Fix backend tests 2020-02-21 14:18:59 -03:00
Gabriel Dutra
f128b4b85f Only allow search for Text Parameters 2020-02-21 13:36:06 -03:00
Gabriel Dutra
264fb5798d Merge branch 'master' into query-based-dropdown--parameters 2020-02-21 13:31:49 -03:00
Gabriel Dutra
90023ac435 Make sure Table updates correctly 2020-02-21 11:03:37 -03:00
Gabriel Dutra
df755fbc17 Add try except for NoResultFound 2020-02-21 09:40:52 -03:00
Gabriel Dutra
e555642844 Add is_safe check for parameterized query based 2020-02-21 09:27:12 -03:00
Gabriel Dutra
bdd7b146ae Change stored mapping attributes 2020-02-20 21:59:19 -03:00
Gabriel Dutra
b7478defec Don't validade query params with params 2020-02-20 19:29:43 -03:00
Gabriel Dutra
bb0d7830c9 Fixes + temp remove validation for Query param 2020-02-20 18:49:29 -03:00
Gabriel Dutra
137aa22dd4 Parameter Mapping UI (2/2) 2020-02-18 17:55:27 -03:00
Gabriel Dutra
9cf396599a Parameter Mapping UI (1/2) 2020-02-17 23:32:10 -03:00
Gabriel Dutra
b70f0fa921 Iterate over backend verification 2020-02-16 13:39:05 -03:00
Gabriel Dutra
5e3613d6cb Start experiements with a 'search' parameter 2020-02-13 16:29:50 -03:00
735 changed files with 49000 additions and 46604 deletions

View File

@@ -1,12 +0,0 @@
FROM cypress/browsers:node16.18.0-chrome90-ff88
ENV APP /usr/src/app
WORKDIR $APP
COPY package.json yarn.lock .yarnrc $APP/
COPY viz-lib $APP/viz-lib
RUN npm install yarn@1.22.19 -g && yarn --frozen-lockfile --network-concurrency 1 > /dev/null
COPY . $APP
RUN ./node_modules/.bin/cypress verify

View File

@@ -1,39 +0,0 @@
#!/bin/bash
# This script only needs to run on the main Redash repo
if [ "${GITHUB_REPOSITORY}" != "getredash/redash" ]; then
echo "Skipping image build for Docker Hub, as this isn't the main Redash repository"
exit 0
fi
if [ "${GITHUB_REF_NAME}" != "master" ] && [ "${GITHUB_REF_NAME}" != "preview-image" ]; then
echo "Skipping image build for Docker Hub, as this isn't the 'master' nor 'preview-image' branch"
exit 0
fi
if [ "x${DOCKER_USER}" = "x" ] || [ "x${DOCKER_PASS}" = "x" ]; then
echo "Skipping image build for Docker Hub, as the login details aren't available"
exit 0
fi
set -e
VERSION=$(jq -r .version package.json)
VERSION_TAG="$VERSION.b${GITHUB_RUN_ID}.${GITHUB_RUN_NUMBER}"
export DOCKER_BUILDKIT=1
export COMPOSE_DOCKER_CLI_BUILD=1
docker login -u "${DOCKER_USER}" -p "${DOCKER_PASS}"
DOCKERHUB_REPO="redash/redash"
DOCKER_TAGS="-t redash/redash:preview -t redash/preview:${VERSION_TAG}"
# Build the docker container
docker build --build-arg install_groups="main,all_ds,dev" ${DOCKER_TAGS} .
# Push the container to the preview build locations
docker push "${DOCKERHUB_REPO}:preview"
docker push "redash/preview:${VERSION_TAG}"
echo "Built: ${VERSION_TAG}"

View File

@@ -1,6 +0,0 @@
#!/bin/bash
VERSION=$(jq -r .version package.json)
FULL_VERSION=${VERSION}+b${GITHUB_RUN_ID}.${GITHUB_RUN_NUMBER}
sed -ri "s/^__version__ = '([A-Za-z0-9.-]*)'/__version__ = '${FULL_VERSION}'/" redash/__init__.py
sed -i "s/dev/${GITHUB_SHA}/" client/app/version.json

View File

@@ -0,0 +1,12 @@
FROM cypress/browsers:node14.0.0-chrome84
ENV APP /usr/src/app
WORKDIR $APP
COPY package.json package-lock.json $APP/
COPY viz-lib $APP/viz-lib
RUN npm ci > /dev/null
COPY . $APP
RUN ./node_modules/.bin/cypress verify

177
.circleci/config.yml Normal file
View File

@@ -0,0 +1,177 @@
version: 2.0
build-docker-image-job: &build-docker-image-job
docker:
- image: circleci/node:12
steps:
- setup_remote_docker
- checkout
- run: sudo apt update
- run: sudo apt install python3-pip
- run: sudo pip3 install -r requirements_bundles.txt
- run: .circleci/update_version
- run: npm run bundle
- run: .circleci/docker_build
jobs:
backend-lint:
docker:
- image: circleci/python:3.7.0
steps:
- checkout
- run: sudo pip install flake8
- run: ./bin/flake8_tests.sh
backend-unit-tests:
environment:
COMPOSE_FILE: .circleci/docker-compose.circle.yml
COMPOSE_PROJECT_NAME: redash
docker:
- image: circleci/buildpack-deps:xenial
steps:
- setup_remote_docker
- checkout
- run:
name: Build Docker Images
command: |
set -x
docker-compose build --build-arg skip_ds_deps=true --build-arg skip_frontend_build=true
docker-compose up -d
sleep 10
- run:
name: Create Test Database
command: docker-compose run --rm postgres psql -h postgres -U postgres -c "create database tests;"
- run:
name: List Enabled Query Runners
command: docker-compose run --rm redash manage ds list_types
- run:
name: Run Tests
command: docker-compose run --name tests redash tests --junitxml=junit.xml --cov-report xml --cov=redash --cov-config .coveragerc tests/
- run:
name: Copy Test Results
command: |
mkdir -p /tmp/test-results/unit-tests
docker cp tests:/app/coverage.xml ./coverage.xml
docker cp tests:/app/junit.xml /tmp/test-results/unit-tests/results.xml
when: always
- store_test_results:
path: /tmp/test-results
- store_artifacts:
path: coverage.xml
frontend-lint:
environment:
CYPRESS_INSTALL_BINARY: 0
PUPPETEER_SKIP_CHROMIUM_DOWNLOAD: 1
docker:
- image: circleci/node:12
steps:
- checkout
- run: mkdir -p /tmp/test-results/eslint
- run: npm ci
- run: npm run lint:ci
- store_test_results:
path: /tmp/test-results
frontend-unit-tests:
environment:
CYPRESS_INSTALL_BINARY: 0
PUPPETEER_SKIP_CHROMIUM_DOWNLOAD: 1
docker:
- image: circleci/node:12
steps:
- checkout
- run: sudo apt update
- run: sudo apt install python3-pip
- run: sudo pip3 install -r requirements_bundles.txt
- run: npm ci
- run: npm run bundle
- run:
name: Run App Tests
command: npm test
- run:
name: Run Visualizations Tests
command: (cd viz-lib && npm test)
- run: npm run lint
frontend-e2e-tests:
environment:
COMPOSE_FILE: .circleci/docker-compose.cypress.yml
COMPOSE_PROJECT_NAME: cypress
PERCY_TOKEN_ENCODED: ZGRiY2ZmZDQ0OTdjMzM5ZWE0ZGQzNTZiOWNkMDRjOTk4Zjg0ZjMxMWRmMDZiM2RjOTYxNDZhOGExMjI4ZDE3MA==
CYPRESS_PROJECT_ID_ENCODED: OTI0Y2th
CYPRESS_RECORD_KEY_ENCODED: YzA1OTIxMTUtYTA1Yy00NzQ2LWEyMDMtZmZjMDgwZGI2ODgx
CYPRESS_INSTALL_BINARY: 0
PUPPETEER_SKIP_CHROMIUM_DOWNLOAD: 1
docker:
- image: circleci/node:12
steps:
- setup_remote_docker
- checkout
- run:
name: Enable Code Coverage report for master branch
command: |
if [ "$CIRCLE_BRANCH" = "master" ]; then
echo 'export CODE_COVERAGE=true' >> $BASH_ENV
source $BASH_ENV
fi
- run:
name: Install npm dependencies
command: |
npm ci
- run:
name: Setup Redash server
command: |
npm run cypress build
npm run cypress start -- --skip-db-seed
docker-compose run cypress npm run cypress db-seed
- run:
name: Execute Cypress tests
command: npm run cypress run-ci
- run:
name: "Failure: output container logs to console"
command: |
docker-compose logs
when: on_fail
- run:
name: Copy Code Coverage results
command: |
docker cp cypress:/usr/src/app/coverage ./coverage || true
when: always
- store_artifacts:
path: coverage
build-docker-image: *build-docker-image-job
build-preview-docker-image: *build-docker-image-job
workflows:
version: 2
build:
jobs:
- backend-lint
- backend-unit-tests:
requires:
- backend-lint
- frontend-lint
- frontend-unit-tests:
requires:
- backend-lint
- frontend-lint
- frontend-e2e-tests:
requires:
- frontend-lint
- build-preview-docker-image:
requires:
- backend-unit-tests
- frontend-unit-tests
- frontend-e2e-tests
filters:
branches:
only:
- master
- hold:
type: approval
requires:
- backend-unit-tests
- frontend-unit-tests
- frontend-e2e-tests
filters:
branches:
only:
- /release\/.*/
- build-docker-image:
requires:
- hold

View File

@@ -12,15 +12,11 @@ services:
PYTHONUNBUFFERED: 0
REDASH_LOG_LEVEL: "INFO"
REDASH_REDIS_URL: "redis://redis:6379/0"
POSTGRES_PASSWORD: "FmTKs5vX52ufKR1rd8tn4MoSP7zvCJwb"
REDASH_DATABASE_URL: "postgresql://postgres:FmTKs5vX52ufKR1rd8tn4MoSP7zvCJwb@postgres/postgres"
REDASH_COOKIE_SECRET: "2H9gNG9obnAQ9qnR9BDTQUph6CbXKCzF"
REDASH_DATABASE_URL: "postgresql://postgres@postgres/postgres"
redis:
image: redis:7-alpine
image: redis:3.0-alpine
restart: unless-stopped
postgres:
image: pgautoupgrade/pgautoupgrade:15-alpine3.8
image: postgres:9.5.6-alpine
command: "postgres -c fsync=off -c full_page_writes=off -c synchronous_commit=OFF"
restart: unless-stopped
environment:
POSTGRES_HOST_AUTH_METHOD: "trust"

View File

@@ -3,16 +3,15 @@ x-redash-service: &redash-service
build:
context: ../
args:
install_groups: "main"
skip_dev_deps: "true"
skip_ds_deps: "true"
code_coverage: ${CODE_COVERAGE}
x-redash-environment: &redash-environment
REDASH_LOG_LEVEL: "INFO"
REDASH_REDIS_URL: "redis://redis:6379/0"
POSTGRES_PASSWORD: "FmTKs5vX52ufKR1rd8tn4MoSP7zvCJwb"
REDASH_DATABASE_URL: "postgresql://postgres:FmTKs5vX52ufKR1rd8tn4MoSP7zvCJwb@postgres/postgres"
REDASH_DATABASE_URL: "postgresql://postgres@postgres/postgres"
REDASH_RATELIMIT_ENABLED: "false"
REDASH_ENFORCE_CSRF: "true"
REDASH_COOKIE_SECRET: "2H9gNG9obnAQ9qnR9BDTQUph6CbXKCzF"
services:
server:
<<: *redash-service
@@ -44,7 +43,7 @@ services:
ipc: host
build:
context: ../
dockerfile: .ci/Dockerfile.cypress
dockerfile: .circleci/Dockerfile.cypress
depends_on:
- server
- worker
@@ -64,11 +63,9 @@ services:
CYPRESS_PROJECT_ID: ${CYPRESS_PROJECT_ID}
CYPRESS_RECORD_KEY: ${CYPRESS_RECORD_KEY}
redis:
image: redis:7-alpine
image: redis:3.0-alpine
restart: unless-stopped
postgres:
image: pgautoupgrade/pgautoupgrade:15-alpine3.8
image: postgres:9.5.6-alpine
command: "postgres -c fsync=off -c full_page_writes=off -c synchronous_commit=OFF"
restart: unless-stopped
environment:
POSTGRES_HOST_AUTH_METHOD: "trust"

17
.circleci/docker_build Executable file
View File

@@ -0,0 +1,17 @@
#!/bin/bash
VERSION=$(jq -r .version package.json)
VERSION_TAG=$VERSION.b$CIRCLE_BUILD_NUM
docker login -u $DOCKER_USER -p $DOCKER_PASS
if [ $CIRCLE_BRANCH = master ] || [ $CIRCLE_BRANCH = preview-image ]
then
docker build --build-arg skip_dev_deps=true -t redash/redash:preview -t redash/preview:$VERSION_TAG .
docker push redash/redash:preview
docker push redash/preview:$VERSION_TAG
else
docker build --build-arg skip_dev_deps=true -t redash/redash:$VERSION_TAG .
docker push redash/redash:$VERSION_TAG
fi
echo "Built: $VERSION_TAG"

6
.circleci/update_version Executable file
View File

@@ -0,0 +1,6 @@
#!/bin/bash
VERSION=$(jq -r .version package.json)
FULL_VERSION=$VERSION+b$CIRCLE_BUILD_NUM
sed -ri "s/^__version__ = '([A-Za-z0-9.-]*)'/__version__ = '$FULL_VERSION'/" redash/__init__.py
sed -i "s/dev/$CIRCLE_SHA1/" client/app/version.json

View File

@@ -7,10 +7,10 @@ about: Report reproducible software issues so we can improve
We use GitHub only for bug reports 🐛
Anything else should be a discussion: https://github.com/getredash/redash/discussions/ 👫
Anything else should be posted to https://discuss.redash.io 👫
🚨For support, help & questions use https://github.com/getredash/redash/discussions/categories/q-a
💡For feature requests & ideas use https://github.com/getredash/redash/discussions/categories/ideas
🚨For support, help & questions use https://discuss.redash.io/c/support
💡For feature requests & ideas use https://discuss.redash.io/c/feature-requests
**Found a security vulnerability?** Please email security@redash.io to report any security vulnerabilities. We will acknowledge receipt of your vulnerability and strive to send you regular updates about our progress. If you're curious about the status of your disclosure please feel free to email us again. If you want to encrypt your disclosure email, you can use this PGP key.

View File

@@ -1,17 +1,17 @@
---
name: "\U0001F4A1Anything else"
about: "For help, support, features & ideas - please use Discussions \U0001F46B "
about: "For help, support, features & ideas - please use https://discuss.redash.io \U0001F46B "
labels: "Support Question"
---
We use GitHub only for bug reports 🐛
Anything else should be a discussion: https://github.com/getredash/redash/discussions/ 👫
Anything else should be posted to https://discuss.redash.io 👫
🚨For support, help & questions use https://github.com/getredash/redash/discussions/categories/q-a
💡For feature requests & ideas use https://github.com/getredash/redash/discussions/categories/ideas
🚨For support, help & questions use https://discuss.redash.io/c/support
💡For feature requests & ideas use https://discuss.redash.io/c/feature-requests
Alternatively, check out these resources below. Thanks! 😁.
- [Discussions](https://github.com/getredash/redash/discussions/)
- [Forum](https://disucss.redash.io)
- [Knowledge Base](https://redash.io/help)

View File

@@ -1,5 +1,5 @@
## What type of PR is this?
<!-- Check all that apply, delete what doesn't apply. -->
## What type of PR is this? (check all applicable)
<!-- Please leave only what's applicable -->
- [ ] Refactor
- [ ] Feature
@@ -9,18 +9,7 @@
- [ ] Other
## Description
<!-- In case of adding / modifying a query runner, please specify which version(s) you expect are compatible. -->
## How is this tested?
- [ ] Unit tests (pytest, jest)
- [ ] E2E Tests (Cypress)
- [ ] Manually
- [ ] N/A
<!-- If Manually, please describe. -->
## Related Tickets & Documents
<!-- If applicable, please include a link to your documentation PR against getredash/website -->
## Mobile & Desktop Screenshots/Recordings (if there are UI changes)

23
.github/support.yml vendored Normal file
View File

@@ -0,0 +1,23 @@
# Configuration for Support Requests - https://github.com/dessant/support-requests
# Label used to mark issues as support requests
supportLabel: Support Question
# Comment to post on issues marked as support requests, `{issue-author}` is an
# optional placeholder. Set to `false` to disable
supportComment: >
:wave: @{issue-author}, we use the issue tracker exclusively for bug reports
and planned work. However, this issue appears to be a support request.
Please use [our forum](https://discuss.redash.io) to get help.
# Close issues marked as support requests
close: true
# Lock issues marked as support requests
lock: false
# Assign `off-topic` as the reason for locking. Set to `false` to disable
setLockReason: true
# Repository to extend settings from
# _extends: repo

View File

@@ -1,237 +0,0 @@
name: Tests
on:
push:
branches:
- master
pull_request:
env:
NODE_VERSION: 16.20.1
jobs:
backend-lint:
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 1
- uses: actions/setup-python@v4
with:
python-version: '3.8'
- run: sudo pip install black==23.1.0 ruff==0.0.287
- run: ruff check .
- run: black --check .
backend-unit-tests:
runs-on: ubuntu-22.04
needs: backend-lint
env:
COMPOSE_FILE: .ci/docker-compose.ci.yml
COMPOSE_PROJECT_NAME: redash
COMPOSE_DOCKER_CLI_BUILD: 1
DOCKER_BUILDKIT: 1
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 1
- name: Build Docker Images
run: |
set -x
docker compose build --build-arg install_groups="main,all_ds,dev" --build-arg skip_frontend_build=true
docker compose up -d
sleep 10
- name: Create Test Database
run: docker compose -p redash run --rm postgres psql -h postgres -U postgres -c "create database tests;"
- name: List Enabled Query Runners
run: docker compose -p redash run --rm redash manage ds list_types
- name: Run Tests
run: docker compose -p redash run --name tests redash tests --junitxml=junit.xml --cov-report=xml --cov=redash --cov-config=.coveragerc tests/
- name: Copy Test Results
run: |
mkdir -p /tmp/test-results/unit-tests
docker cp tests:/app/coverage.xml ./coverage.xml
docker cp tests:/app/junit.xml /tmp/test-results/unit-tests/results.xml
- name: Upload coverage reports to Codecov
uses: codecov/codecov-action@v3
- name: Store Test Results
uses: actions/upload-artifact@v3
with:
name: test-results
path: /tmp/test-results
- name: Store Coverage Results
uses: actions/upload-artifact@v3
with:
name: coverage
path: coverage.xml
frontend-lint:
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 1
- uses: actions/setup-node@v3
with:
node-version: ${{ env.NODE_VERSION }}
cache: 'yarn'
- name: Install Dependencies
run: |
npm install --global --force yarn@1.22.19
yarn cache clean && yarn --frozen-lockfile --network-concurrency 1
- name: Run Lint
run: yarn lint:ci
- name: Store Test Results
uses: actions/upload-artifact@v3
with:
name: test-results
path: /tmp/test-results
frontend-unit-tests:
runs-on: ubuntu-22.04
needs: frontend-lint
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 1
- uses: actions/setup-node@v3
with:
node-version: ${{ env.NODE_VERSION }}
cache: 'yarn'
- name: Install Dependencies
run: |
npm install --global --force yarn@1.22.19
yarn cache clean && yarn --frozen-lockfile --network-concurrency 1
- name: Run App Tests
run: yarn test
- name: Run Visualizations Tests
run: cd viz-lib && yarn test
- run: yarn lint
frontend-e2e-tests:
runs-on: ubuntu-22.04
needs: frontend-lint
env:
COMPOSE_FILE: .ci/docker-compose.cypress.yml
COMPOSE_PROJECT_NAME: cypress
PERCY_TOKEN_ENCODED: ZGRiY2ZmZDQ0OTdjMzM5ZWE0ZGQzNTZiOWNkMDRjOTk4Zjg0ZjMxMWRmMDZiM2RjOTYxNDZhOGExMjI4ZDE3MA==
CYPRESS_PROJECT_ID_ENCODED: OTI0Y2th
CYPRESS_RECORD_KEY_ENCODED: YzA1OTIxMTUtYTA1Yy00NzQ2LWEyMDMtZmZjMDgwZGI2ODgx
CYPRESS_INSTALL_BINARY: 0
PUPPETEER_SKIP_CHROMIUM_DOWNLOAD: 1
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 1
- uses: actions/setup-node@v3
with:
node-version: ${{ env.NODE_VERSION }}
cache: 'yarn'
- name: Enable Code Coverage Report For Master Branch
if: endsWith(github.ref, '/master')
run: |
echo "CODE_COVERAGE=true" >> "$GITHUB_ENV"
- name: Install Dependencies
run: |
npm install --global --force yarn@1.22.19
yarn cache clean && yarn --frozen-lockfile --network-concurrency 1
- name: Setup Redash Server
run: |
set -x
yarn cypress build
yarn cypress start -- --skip-db-seed
docker compose run cypress yarn cypress db-seed
- name: Execute Cypress Tests
run: yarn cypress run-ci
- name: "Failure: output container logs to console"
if: failure()
run: docker compose logs
- name: Copy Code Coverage Results
run: docker cp cypress:/usr/src/app/coverage ./coverage || true
- name: Store Coverage Results
uses: actions/upload-artifact@v3
with:
name: coverage
path: coverage
build-skip-check:
runs-on: ubuntu-22.04
outputs:
skip: ${{ steps.skip-check.outputs.skip }}
steps:
- name: Skip?
id: skip-check
run: |
if [[ "${{ vars.DOCKER_USER }}" == '' ]]; then
echo 'Docker user is empty. Skipping build+push'
echo skip=true >> "$GITHUB_OUTPUT"
elif [[ "${{ secrets.DOCKER_PASS }}" == '' ]]; then
echo 'Docker password is empty. Skipping build+push'
echo skip=true >> "$GITHUB_OUTPUT"
elif [[ "${{ github.ref_name }}" != 'master' ]]; then
echo 'Ref name is not `master`. Skipping build+push'
echo skip=true >> "$GITHUB_OUTPUT"
else
echo 'Docker user and password are set and branch is `master`.'
echo 'Building + pushing `preview` image.'
echo skip=false >> "$GITHUB_OUTPUT"
fi
build-docker-image:
runs-on: ubuntu-22.04
needs:
- backend-unit-tests
- frontend-unit-tests
- frontend-e2e-tests
- build-skip-check
if: needs.build-skip-check.outputs.skip == 'false'
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 1
- uses: actions/setup-node@v3
with:
node-version: ${{ env.NODE_VERSION }}
cache: 'yarn'
- name: Install Dependencies
run: |
npm install --global --force yarn@1.22.19
yarn cache clean && yarn --frozen-lockfile --network-concurrency 1
- name: Set up QEMU
timeout-minutes: 1
uses: docker/setup-qemu-action@v2.2.0
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v2
- name: Login to DockerHub
uses: docker/login-action@v2
with:
username: ${{ vars.DOCKER_USER }}
password: ${{ secrets.DOCKER_PASS }}
- name: Bump version
id: version
run: |
set -x
.ci/update_version
VERSION=$(jq -r .version package.json)
VERSION_TAG="${VERSION}.b${GITHUB_RUN_ID}.${GITHUB_RUN_NUMBER}"
echo "VERSION_TAG=$VERSION_TAG" >> "$GITHUB_OUTPUT"
- name: Build and push preview image to Docker Hub
uses: docker/build-push-action@v4
with:
push: true
tags: |
redash/redash:preview
redash/preview:${{ steps.version.outputs.VERSION_TAG }}
context: .
build-args: |
test_all_deps=true
cache-from: type=ghq
cache-to: type=gha,mode=max
env:
DOCKER_CONTENT_TRUST: true
- name: "Failure: output container logs to console"
if: failure()
run: docker compose logs

View File

@@ -1,27 +0,0 @@
name: Periodic Snapshot
# 10 minutes after midnight on the first of every month
on:
schedule:
- cron: "10 0 1 * *"
permissions:
contents: write
jobs:
bump-version-and-tag:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- run: |
date="$(date +%y.%m).0-dev"
gawk -i inplace -F: -v q=\" -v tag=$date '/^ "version": / { print $1 FS, q tag q ","; next} { print }' package.json
gawk -i inplace -F= -v q=\" -v tag=$date '/^__version__ =/ { print $1 FS, q tag q; next} { print }' redash/__init__.py
gawk -i inplace -F= -v q=\" -v tag=$date '/^version =/ { print $1 FS, q tag q; next} { print }' pyproject.toml
git config user.name github-actions
git config user.email github-actions@github.com
git add package.json redash/__init__.py pyproject.toml
git commit -m "Snapshot: ${date}"
git push origin
git tag $date
git push origin $date

1
.nvmrc
View File

@@ -1 +0,0 @@
v16.20.1

View File

@@ -1,10 +0,0 @@
repos:
- repo: https://github.com/psf/black
rev: 23.1.0
hooks:
- id: black
language_version: python3
- repo: https://github.com/charliermarsh/ruff-pre-commit
rev: "v0.0.287"
hooks:
- id: ruff

View File

@@ -57,9 +57,6 @@ restylers:
- migrations/versions
- name: prettier
image: restyled/restyler-prettier:v1.19.1-2
command:
- prettier
- --write
include:
- client/app/**/*.js
- client/app/**/*.jsx

2
.yarn/.gitignore vendored
View File

@@ -1,2 +0,0 @@
*
!.gitignore

View File

@@ -1,152 +1,5 @@
# Change Log
## V10.1.0 - 2021-11-23
This release includes patches for three security vulnerabilities:
- Insecure default configuration affects installations where REDASH_COOKIE_SECRET is not set explicitly (CVE-2021-41192)
- SSRF vulnerability affects installations that enabled URL-loading data sources (CVE-2021-43780)
- Incorrect usage of state parameter in OAuth client code affects installations where Google Login is enabled (CVE-2021-43777)
And a couple features that didn't merge in time for 10.0.0
- Big Query: Speed up schema loading (#5632)
- Add support for Firebolt data source (#5606)
- Fix: Loading schema for Sqlite DB with "Order" column name fails (#5623)
## v10.0.0 - 2021-10-01
A few changes were merged during the V10 beta period.
- New Data Source: CSV/Excel Files
- Fix: Edit Source button disappeared for users without CanEdit permissions
- We pinned our docker base image to Python3.7-slim-buster to avoid build issues
- Fix: dashboard list pagination didn't work
## v10.0.0-beta - 2021-06-16
Just over a year since our last release, the V10 beta is ready. Since we never made a non-beta release of V9, we expect many users will upgrade directly from V8 -> V10. This will bring a lot of exciting features. Please check out the V9 beta release notes below to learn more.
This V10 beta incorporates fixes for the feedback we received on the V9 beta along with a few long-requested features (horizontal bar charts!) and other changes to improve UX and reliability.
This release was made possible by contributions from 35+ people (the Github API didn't let us pull handles this time around): Alex Kovar, Alexander Rusanov, Arik Fraimovich, Ben Amor, Christopher Grant, Đặng Minh Dũng, Daniel Lang, deecay, Elad Ossadon, Gabriel Dutra, iwakiriK, Jannis Leidel, Jerry, Jesse Whitehouse, Jiajie Zhong, Jim Sparkman, Jonathan Hult, Josh Bohde, Justin Talbot, koooge, Lei Ni, Levko Kravets, Lingkai Kong, max-voronov, Mike Nason, Nolan Nichols, Omer Lachish, Patrick Yang, peterlee, Rafael Wendel, Sebastian Tramp, simonschneider-db, Tim Gates, Tobias Macey, Vipul Mathur, and Vladislav Denisov
Our special thanks to [Sohail Ahmed](https://pk.linkedin.com/in/sohail-ahmed-755776184) for reporting a vulnerability in our "forgot password" page (#5425)
### Upgrading
(This section is duplicated from the previous release - since many users will upgrade directly from V8 -> V10)
Typically, if you are running your own instance of Redash and wish to upgrade, you would simply modify the Docker tag in your `docker-compose.yml` file. Since RQ has replaced Celery in this version, there are a couple extra modifications that need to be done in your `docker-compose.yml`:
1. Under `services/scheduler/environment`, omit `QUEUES` and `WORKERS_COUNT` (and omit `environment` altogether if it is empty).
2. Under `services`, add a new service for general RQ jobs:
```yaml
worker:
<<: *redash-service
command: worker
environment:
QUEUES: "periodic emails default"
WORKERS_COUNT: 1
```
Following that, force a recreation of your containers with `docker-compose up --force-recreate --build` and you should be good to go.
### UX
- Redash now uses a vertical navbar
- Dashboard list now includes “My Dashboards” filter
- Dashboard parameters can now be re-ordered
- Queries can now be executed with Shift + Enter on all platforms.
- Added New Dashboard/Query/Alert buttons to corresponding list pages
- Dashboard text widgets now prompt to confirm before closing the text editor
- A plus sign is now shown between tags used for search
- On the queries list view “My Queries” has moved above “Archived”
- Improved behavior for filtering by tags in list views
- When a users session expires for inactivity, they are prompted to log-in with a pop-up so they dont lose their place in the app
- Numerous accessibility changes towards the a11y standard
- Hide the “Create” menu button if current user doesnt have permission to any data sources
### Visualizations
- Feature: Added support for horizontal box plots
- Feature: Added support for horizontal bar charts
- Feature: Added “Reverse” option for Chart visualization legend
- Feature: Added option to align Chart Y-axes at zero
- Feature: The table visualization header is now fixed when scrolling
- Feature: Added USA map to choropleth visualization
- Fix: Selected filters were reset when switching visualizations
- Fix: Stacked bar chart showed the wrong Y-axis range in some cases
- Fix: Bar chart with second y axis overlapped data series
- Fix: Y-axis autoscale failed when min or max was set
- Fix: Custom JS visualization was broken because of a typo
- Fix: Too large visualization caused filters block to collapse
- Fix: Sankey visualization looked inconsistent if the data source returned VARCHAR instead of numeric types
### Structural Updates
- Redash now prevents CSRF attacks
- Migration to TypeScript
- Upgrade to Antd version 4
### Data Sources
- New Data Sources: SPARQL Endpoint, Eccenca Corporate Memory, TrinoDB
- Databricks
- Custom Schema Browser that allows switching between databases
- Option added to truncate large results
- Support for multiple-statement queries
- Schema browser can now use eventlet instead of RQ
- MongoDB:
- Moved Username and Password out of the connection string so that password can be stored secretly
- Oracle:
- Fix: Annotated queries always failed. Annotation is now disabled
- Postgres/CockroachDB:
- SSL certfile/keyfile fields are now handled as secret
- Python:
- Feature: Custom built-ins are now supported
- Fix: Query runner was not compatible with Python 3
- Snowflake:
- Data source now accepts a custom host address (for use with proxies)
- TreasureData:
- API key field is now handled as secret
- Yandex:
- OAuth token field is now handled as secret
### Alerts
- Feature: Added ability to mute alerts without deleting them
- Change: Non-email alert destination details are now obfuscated to avoid leaking sensitive information (webhook URLs, tokens etc.)
- Fix: numerical comparisons failed if value from query was a string
### Parameters
- Added “Last 12 months” option for dynamic date ranges
### Bug Fixes
- Fix: Private addresses were not allowed even when enforcing was disabled
- Fix: Python query runner wasnt updated for Python 3
- Fix: Sorting queries by schedule returned the wrong order
- Fix: Counter visualization was enormous in some cases
- Fix: Dashboard URL will now change when the dashboard title changes
- Fix: URL parameters were removed when forking a query
- Fix: Create link on data sources page was broken
- Fix: Queries could be reassigned to read-only data sources
- Fix: Multi-select dropdown was very slow if there were 1k+ options
- Fix: Search Input couldnt be focused or updated while editing a dashboard
- Fix: The CLI command for “status” did not work
- Fix: The dashboard list screen displayed too few items under certain pagination configurations
### Other
- Added an environment variable to disable public sharing links for queries and dashboards
- Alert destinations are now encrypted at the database
- The base query runner now has stubs to implement result truncating for other data sources
- Static SAML configuration and assertion encryption are now supported
- Adds new component for adding extra actions to the query and dashboard pages
- Non-admins with at least view_only permission on a dashboard can now make GET requests to the data source resource
- Added a BLOCKED_DOMAINS setting to prevent sign-ups from emails at specific domains
- Added a rate limit to the “forgot password” page
- RQ workers will now shutdown gracefully for known error codes
- Scheduled execution failure counter now resets following a successful ad hoc execution
- Redash now deletes locks for cancelled queries
- Upgraded Ace Editor from v6 to v9
- Added a periodic job to remove ghost locks
- Removed content width limit on all pages
- Introduce a <Link> React component
## v9.0.0-beta - 2020-06-11
This release was long time in the making and has several major changes:

View File

@@ -4,7 +4,19 @@ Thank you for taking the time to contribute! :tada::+1:
The following is a set of guidelines for contributing to Redash. These are guidelines, not rules, please use your best judgement and feel free to propose changes to this document in a pull request.
:star: If you're already here and love the project, please make sure to press the Star button. :star:
## Quick Links:
- [Feature Requests](https://discuss.redash.io/c/feature-requests)
- [Documentation](https://redash.io/help/)
- [Blog](https://blog.redash.io/)
- [Twitter](https://twitter.com/getredash)
---
:star: If you already here and love the project, please make sure to press the Star button. :star:
---
## Table of Contents
[How can I contribute?](#how-can-i-contribute)
@@ -20,13 +32,6 @@ The following is a set of guidelines for contributing to Redash. These are guide
- [Release Method](#release-method)
- [Code of Conduct](#code-of-conduct)
## Quick Links:
- [User Forum](https://github.com/getredash/redash/discussions)
- [Documentation](https://redash.io/help/)
---
## How can I contribute?
### Reporting Bugs
@@ -34,54 +39,25 @@ The following is a set of guidelines for contributing to Redash. These are guide
When creating a new bug report, please make sure to:
- Search for existing issues first. If you find a previous report of your issue, please update the existing issue with additional information instead of creating a new one.
- If you are not sure if your issue is really a bug or just some configuration/setup problem, please start a [Q&A discussion](https://github.com/getredash/redash/discussions/new?category=q-a) first. Unless you can provide clear steps to reproduce, it's probably better to start with a discussion and later to open an issue.
- If you are not sure if your issue is really a bug or just some configuration/setup problem, please start a discussion in [the support forum](https://discuss.redash.io/c/support) first. Unless you can provide clear steps to reproduce, it's probably better to start with a thread in the forum and later to open an issue.
- If you still decide to open an issue, please review the template and guidelines and include as much details as possible.
### Suggesting Enhancements / Feature Requests
If you would like to suggest an enhancement or ask for a new feature:
- Please check [the Ideas discussions](https://github.com/getredash/redash/discussions/categories/ideas) for existing threads about what you want to suggest/ask. If there is, feel free to upvote it to signal interest or add your comments.
- Please check [the forum](https://discuss.redash.io/c/feature-requests/5) for existing threads about what you want to suggest/ask. If there is, feel free to upvote it to signal interest or add your comments.
- If there is no open thread, you're welcome to start one to have a discussion about what you want to suggest. Try to provide as much details and context as possible and include information about *the problem you want to solve* rather only *your proposed solution*.
### Pull Requests
**Code contributions are welcomed**. For big changes or significant features, it's usually better to reach out first and discuss what you want to implement and how (we recommend reading: [Pull Request First](https://medium.com/practical-blend/pull-request-first-f6bb667a9b6#.ozlqxvj36)). This is to make sure that what you want to implement is aligned with our goals for the project and that no one else is already working on it.
#### Criteria for Review / Merging
When you open your pull request, please follow this repositorys PR template carefully:
- Indicate the type of change
- If you implement multiple unrelated features, bug fixes, or refactors please split them into individual pull requests.
- Describe the change
- If fixing a bug, please describe the bug or link to an existing github issue / forum discussion
- Include UI screenshots / GIFs whenever possible
- **Code contributions are welcomed**. For big changes or significant features, it's usually better to reach out first and discuss what you want to implement and how (we recommend reading: [Pull Request First](https://medium.com/practical-blend/pull-request-first-f6bb667a9b6#.ozlqxvj36)). This to make sure that what you want to implement is aligned with our goals for the project and that no one else is already working on it.
- Include screenshots and animated GIFs in your pull request whenever possible.
- Please add [documentation](#documentation) for new features or changes in functionality along with the code.
- Please follow existing code style:
- Python: we use [Black](https://github.com/psf/black) to auto format the code.
- Javascript: we use [Prettier](https://github.com/prettier/prettier) to auto-format the code.
#### Initial Review (1 week)
During this phase, a team member will apply the “Team Review” label if a pull request meets our criteria or a “Needs More Information” label if not. If more information is required, the team member will comment which criteria have not been met.
If your pull request receives the “Needs More Information” label, please make the requested changes and then remove the label. This resets the 1 week timer for an initial review.
Stale pull requests that remain untouched in “Needs More Information” for more than 4 weeks will be closed.
If a team member closes your pull request, you may reopen it after you have made the changes requested during initial review. After you make these changes, remove the “Needs More Information” label. This again resets the timer for another initial review.
#### Full Review (2 weeks)
After the “Team Review” label is applied, a member of the core team will review the PR within 2 weeks.
Reviews will approve, request changes, or ask questions to discuss areas of uncertainty. After youve responded, a member of the team will re-review within one week.
#### Merging (1 week)
After your pull request has been approved, a member of the core team will merge the pull request within a week.
### Documentation
The project's documentation can be found at [https://redash.io/help/](https://redash.io/help/). The [documentation sources](https://github.com/getredash/website/tree/master/src/pages/kb) are hosted on GitHub. To contribute edits / new pages, you can use GitHub's interface. Click the "Edit on GitHub" link on the documentation page to quickly open the edit interface.

View File

@@ -1,6 +1,4 @@
FROM node:16.20.1 as frontend-builder
RUN npm install --global --force yarn@1.22.19
FROM node:12 as frontend-builder
# Controls whether to build the frontend assets
ARG skip_frontend_build
@@ -12,90 +10,84 @@ RUN useradd -m -d /frontend redash
USER redash
WORKDIR /frontend
COPY --chown=redash package.json yarn.lock .yarnrc /frontend/
COPY --chown=redash package.json package-lock.json /frontend/
COPY --chown=redash viz-lib /frontend/viz-lib
# Controls whether to instrument code for coverage information
ARG code_coverage
ENV BABEL_ENV=${code_coverage:+test}
RUN if [ "x$skip_frontend_build" = "x" ] ; then yarn --frozen-lockfile --network-concurrency 1; fi
RUN if [ "x$skip_frontend_build" = "x" ] ; then npm ci --unsafe-perm; fi
COPY --chown=redash client /frontend/client
COPY --chown=redash webpack.config.js /frontend/
RUN if [ "x$skip_frontend_build" = "x" ] ; then yarn build; else mkdir -p /frontend/client/dist && touch /frontend/client/dist/multi_org.html && touch /frontend/client/dist/index.html; fi
FROM python:3.8-slim-buster
RUN if [ "x$skip_frontend_build" = "x" ] ; then npm run build; else mkdir -p /frontend/client/dist && touch /frontend/client/dist/multi_org.html && touch /frontend/client/dist/index.html; fi
FROM python:3.7-slim
EXPOSE 5000
# Controls whether to install extra dependencies needed for all data sources.
ARG skip_ds_deps
# Controls whether to install dev dependencies.
ARG skip_dev_deps
RUN useradd --create-home redash
# Ubuntu packages
RUN apt-get update && \
apt-get install -y --no-install-recommends \
pkg-config \
curl \
gnupg \
build-essential \
pwgen \
libffi-dev \
sudo \
git-core \
# Kerberos, needed for MS SQL Python driver to compile on arm64
libkrb5-dev \
# Postgres client
libpq-dev \
# ODBC support:
g++ unixodbc-dev \
# for SAML
xmlsec1 \
# Additional packages required for data sources:
libssl-dev \
default-libmysqlclient-dev \
freetds-dev \
libsasl2-dev \
unzip \
libsasl2-modules-gssapi-mit && \
apt-get install -y \
curl \
gnupg \
build-essential \
pwgen \
libffi-dev \
sudo \
git-core \
wget \
# Postgres client
libpq-dev \
# ODBC support:
g++ unixodbc-dev \
# for SAML
xmlsec1 \
# Additional packages required for data sources:
libssl-dev \
default-libmysqlclient-dev \
freetds-dev \
libsasl2-dev \
unzip \
libsasl2-modules-gssapi-mit && \
# MSSQL ODBC Driver:
curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add - && \
curl https://packages.microsoft.com/config/debian/10/prod.list > /etc/apt/sources.list.d/mssql-release.list && \
apt-get update && \
ACCEPT_EULA=Y apt-get install -y msodbcsql17 && \
apt-get clean && \
rm -rf /var/lib/apt/lists/*
ARG TARGETPLATFORM
ARG databricks_odbc_driver_url=https://databricks-bi-artifacts.s3.us-east-2.amazonaws.com/simbaspark-drivers/odbc/2.6.26/SimbaSparkODBC-2.6.26.1045-Debian-64bit.zip
RUN if [ "$TARGETPLATFORM" = "linux/amd64" ]; then \
curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add - \
&& curl https://packages.microsoft.com/config/debian/10/prod.list > /etc/apt/sources.list.d/mssql-release.list \
&& apt-get update \
&& ACCEPT_EULA=Y apt-get install -y --no-install-recommends msodbcsql17 \
&& apt-get clean \
&& rm -rf /var/lib/apt/lists/* \
&& curl "$databricks_odbc_driver_url" --location --output /tmp/simba_odbc.zip \
&& chmod 600 /tmp/simba_odbc.zip \
&& unzip /tmp/simba_odbc.zip -d /tmp/simba \
&& dpkg -i /tmp/simba/*.deb \
&& printf "[Simba]\nDriver = /opt/simba/spark/lib/64/libsparkodbc_sb64.so" >> /etc/odbcinst.ini \
ARG databricks_odbc_driver_url=https://databricks.com/wp-content/uploads/2.6.10.1010-2/SimbaSparkODBC-2.6.10.1010-2-Debian-64bit.zip
ADD $databricks_odbc_driver_url /tmp/simba_odbc.zip
RUN unzip /tmp/simba_odbc.zip -d /tmp/ \
&& dpkg -i /tmp/SimbaSparkODBC-*/*.deb \
&& echo "[Simba]\nDriver = /opt/simba/spark/lib/64/libsparkodbc_sb64.so" >> /etc/odbcinst.ini \
&& rm /tmp/simba_odbc.zip \
&& rm -rf /tmp/simba; fi
&& rm -rf /tmp/SimbaSparkODBC*
WORKDIR /app
ENV POETRY_VERSION=1.6.1
ENV POETRY_HOME=/etc/poetry
ENV POETRY_VIRTUALENVS_CREATE=false
RUN curl -sSL https://install.python-poetry.org | python3 -
# Disalbe PIP Cache and Version Check
ENV PIP_DISABLE_PIP_VERSION_CHECK=1
ENV PIP_NO_CACHE_DIR=1
COPY pyproject.toml poetry.lock ./
# We first copy only the requirements file, to avoid rebuilding on every file
# change.
COPY requirements.txt requirements_bundles.txt requirements_dev.txt requirements_all_ds.txt ./
RUN if [ "x$skip_dev_deps" = "x" ] ; then pip install -r requirements.txt -r requirements_dev.txt; else pip install -r requirements.txt; fi
RUN if [ "x$skip_ds_deps" = "x" ] ; then pip install -r requirements_all_ds.txt ; else echo "Skipping pip install -r requirements_all_ds.txt" ; fi
ARG POETRY_OPTIONS="--no-root --no-interaction --no-ansi"
# for LDAP authentication, install with `ldap3` group
# disabled by default due to GPL license conflict
ARG install_groups="main,all_ds,dev"
RUN /etc/poetry/bin/poetry install --only $install_groups $POETRY_OPTIONS
COPY --chown=redash . /app
COPY --from=frontend-builder --chown=redash /frontend/client/dist /app/client/dist
RUN chown redash /app
COPY . /app
COPY --from=frontend-builder /frontend/client/dist /app/client/dist
RUN chown -R redash /app
USER redash
ENTRYPOINT ["/app/bin/docker-entrypoint"]

View File

@@ -1,3 +0,0 @@
The Bahrain map data used in Redash was downloaded from
https://cartographyvectors.com/map/857-bahrain-detailed-boundary in PR #6192.
* Free for personal and commercial purpose with attribution.

View File

@@ -1,62 +1,57 @@
.PHONY: compose_build up test_db create_database clean down tests lint backend-unit-tests frontend-unit-tests test build watch start redis-cli bash
.PHONY: compose_build up test_db create_database clean down bundle tests lint backend-unit-tests frontend-unit-tests test build watch start redis-cli bash
compose_build: .env
COMPOSE_DOCKER_CLI_BUILD=1 DOCKER_BUILDKIT=1 docker compose build
compose_build:
docker-compose build
up:
COMPOSE_DOCKER_CLI_BUILD=1 DOCKER_BUILDKIT=1 docker compose up -d --build
docker-compose up -d --build
test_db:
@for i in `seq 1 5`; do \
if (docker compose exec postgres sh -c 'psql -U postgres -c "select 1;"' 2>&1 > /dev/null) then break; \
if (docker-compose exec postgres sh -c 'psql -U postgres -c "select 1;"' 2>&1 > /dev/null) then break; \
else echo "postgres initializing..."; sleep 5; fi \
done
docker compose exec postgres sh -c 'psql -U postgres -c "drop database if exists tests;" && psql -U postgres -c "create database tests;"'
docker-compose exec postgres sh -c 'psql -U postgres -c "drop database if exists tests;" && psql -U postgres -c "create database tests;"'
create_database: .env
docker compose run server create_db
create_database:
docker-compose run server create_db
clean:
docker compose down && docker compose rm
docker-compose down && docker-compose rm
down:
docker compose down
docker-compose down
.env:
printf "REDASH_COOKIE_SECRET=`pwgen -1s 32`\nREDASH_SECRET_KEY=`pwgen -1s 32`\n" >> .env
env: .env
format:
pre-commit run --all-files
bundle:
docker-compose run server bin/bundle-extensions
tests:
docker compose run server tests
docker-compose run server tests
lint:
ruff check .
black --check . --diff
./bin/flake8_tests.sh
backend-unit-tests: up test_db
docker compose run --rm --name tests server tests
docker-compose run --rm --name tests server tests
frontend-unit-tests:
CYPRESS_INSTALL_BINARY=0 PUPPETEER_SKIP_CHROMIUM_DOWNLOAD=1 yarn --frozen-lockfile
yarn test
frontend-unit-tests: bundle
CYPRESS_INSTALL_BINARY=0 PUPPETEER_SKIP_CHROMIUM_DOWNLOAD=1 npm ci
npm run bundle
npm test
test: backend-unit-tests frontend-unit-tests lint
test: lint backend-unit-tests frontend-unit-tests
build:
yarn build
build: bundle
npm run build
watch:
yarn watch
watch: bundle
npm run watch
start:
yarn start
start: bundle
npm run start
redis-cli:
docker compose run --rm redis redis-cli -h redis
docker-compose run --rm redis redis-cli -h redis
bash:
docker compose run --rm server bash
docker-compose run --rm server bash

View File

@@ -4,7 +4,7 @@
[![Documentation](https://img.shields.io/badge/docs-redash.io/help-brightgreen.svg)](https://redash.io/help/)
[![Datree](https://s3.amazonaws.com/catalog.static.datree.io/datree-badge-20px.svg)](https://datree.io/?src=badge)
[![GitHub Build](https://github.com/getredash/redash/actions/workflows/ci.yml/badge.svg)](https://github.com/getredash/redash/actions)
[![Build Status](https://circleci.com/gh/getredash/redash.png?style=shield&circle-token=8a695aa5ec2cbfa89b48c275aea298318016f040)](https://circleci.com/gh/getredash/redash/tree/master)
Redash is designed to enable anyone, regardless of the level of technical sophistication, to harness the power of data big and small. SQL users leverage Redash to explore, query, visualize, and share data from any data sources. Their work in turn enables anybody in their organization to use the data. Every day, millions of users at thousands of organizations around the world use Redash to develop insights and make data-driven decisions.
@@ -32,51 +32,36 @@ Redash features:
Redash supports more than 35 SQL and NoSQL [data sources](https://redash.io/help/data-sources/supported-data-sources). It can also be extended to support more. Below is a list of built-in sources:
- Amazon Athena
- Amazon CloudWatch / Insights
- Amazon DynamoDB
- Amazon Redshift
- ArangoDB
- Axibase Time Series Database
- Apache Cassandra
- Cassandra
- ClickHouse
- CockroachDB
- Couchbase
- CSV
- Databricks
- Databricks (Apache Spark)
- DB2 by IBM
- Dgraph
- Apache Drill
- Apache Druid
- Eccenca Corporate Memory
- Druid
- Elasticsearch
- Exasol
- Microsoft Excel
- Firebolt
- Databend
- Google Analytics
- Google BigQuery
- Google Spreadsheets
- Graphite
- Greenplum
- Apache Hive
- Apache Impala
- Hive
- Impala
- InfluxDB
- IBM Netezza Performance Server
- JIRA (JQL)
- JIRA
- JSON
- Apache Kylin
- OmniSciDB (Formerly MapD)
- MariaDB
- MemSQL
- Microsoft Azure Data Warehouse / Synapse
- Microsoft Azure SQL Database
- Microsoft Azure Data Explorer / Kusto
- Microsoft SQL Server
- MongoDB
- MySQL
- Oracle
- Apache Phoenix
- Apache Pinot
- PostgreSQL
- Presto
- Prometheus
@@ -87,13 +72,8 @@ Redash supports more than 35 SQL and NoSQL [data sources](https://redash.io/help
- ScyllaDB
- Shell Scripts
- Snowflake
- SPARQL
- SQLite
- TiDB
- Tinybird
- TreasureData
- Trino
- Uptycs
- Vertica
- Yandex AppMetrrica
- Yandex Metrica
@@ -101,13 +81,12 @@ Redash supports more than 35 SQL and NoSQL [data sources](https://redash.io/help
## Getting Help
* Issues: https://github.com/getredash/redash/issues
* Discussion Forum: https://github.com/getredash/redash/discussions/
* Development Discussion: https://discord.gg/tN5MdmfGBp
* Discussion Forum: https://discuss.redash.io/
## Reporting Bugs and Contributing Code
* Want to report a bug or request a feature? Please open [an issue](https://github.com/getredash/redash/issues/new).
* Want to help us build **_Redash_**? Fork the project, edit in a [dev environment](https://github.com/getredash/redash/wiki/Local-development-setup) and make a pull request. We need all the help we can get!
* Want to help us build **_Redash_**? Fork the project, edit in a [dev environment](https://redash.io/help-onpremise/dev/guide.html) and make a pull request. We need all the help we can get!
## Security

115
bin/bundle-extensions Executable file
View File

@@ -0,0 +1,115 @@
#!/usr/bin/env python3
"""Copy bundle extension files to the client/app/extension directory"""
import logging
import os
from pathlib import Path
from shutil import copy
from collections import OrderedDict as odict
import importlib_metadata
import importlib_resources
# Name of the subdirectory
BUNDLE_DIRECTORY = "bundle"
logger = logging.getLogger(__name__)
# Make a directory for extensions and set it as an environment variable
# to be picked up by webpack.
extensions_relative_path = Path("client", "app", "extensions")
extensions_directory = Path(__file__).parent.parent / extensions_relative_path
if not extensions_directory.exists():
extensions_directory.mkdir()
os.environ["EXTENSIONS_DIRECTORY"] = str(extensions_relative_path)
def entry_point_module(entry_point):
"""Returns the dotted module path for the given entry point"""
return entry_point.pattern.match(entry_point.value).group("module")
def load_bundles():
""""Load bundles as defined in Redash extensions.
The bundle entry point can be defined as a dotted path to a module
or a callable, but it won't be called but just used as a means
to find the files under its file system path.
The name of the directory it looks for files in is "bundle".
So a Python package with an extension bundle could look like this::
my_extensions/
├── __init__.py
└── wide_footer
├── __init__.py
└── bundle
├── extension.js
└── styles.css
and would then need to register the bundle with an entry point
under the "redash.bundles" group, e.g. in your setup.py::
setup(
# ...
entry_points={
"redash.bundles": [
"wide_footer = my_extensions.wide_footer",
]
# ...
},
# ...
)
"""
bundles = odict()
for entry_point in importlib_metadata.entry_points().get("redash.bundles", []):
logger.info('Loading Redash bundle "%s".', entry_point.name)
module = entry_point_module(entry_point)
# Try to get a list of bundle files
try:
bundle_dir = importlib_resources.files(module).joinpath(BUNDLE_DIRECTORY)
except (ImportError, TypeError):
# Module isn't a package, so can't have a subdirectory/-package
logger.error(
'Redash bundle module "%s" could not be imported: "%s"',
entry_point.name,
module,
)
continue
if not bundle_dir.is_dir():
logger.error(
'Redash bundle directory "%s" could not be found or is not a directory: "%s"',
entry_point.name,
bundle_dir,
)
continue
bundles[entry_point.name] = list(bundle_dir.rglob("*"))
return bundles
bundles = load_bundles().items()
if bundles:
print("Number of extension bundles found: {}".format(len(bundles)))
else:
print("No extension bundles found.")
for bundle_name, paths in bundles:
# Shortcut in case not paths were found for the bundle
if not paths:
print('No paths found for bundle "{}".'.format(bundle_name))
continue
# The destination for the bundle files with the entry point name as the subdirectory
destination = Path(extensions_directory, bundle_name)
if not destination.exists():
destination.mkdir()
# Copy the bundle directory from the module to its destination.
print('Copying "{}" bundle to {}:'.format(bundle_name, destination.resolve()))
for src_path in paths:
dest_path = destination / src_path.name
print(" - {} -> {}".format(src_path, dest_path))
copy(str(src_path), str(dest_path))

View File

@@ -22,19 +22,6 @@ worker() {
exec supervisord -c worker.conf
}
workers_healthcheck() {
WORKERS_COUNT=${WORKERS_COUNT}
echo "Checking active workers count against $WORKERS_COUNT..."
ACTIVE_WORKERS_COUNT=`echo $(rq info --url $REDASH_REDIS_URL -R | grep workers | grep -oP ^[0-9]+)`
if [ "$ACTIVE_WORKERS_COUNT" -lt "$WORKERS_COUNT" ]; then
echo "$ACTIVE_WORKERS_COUNT workers are active, Exiting"
exit 1
else
echo "$ACTIVE_WORKERS_COUNT workers are active"
exit 0
fi
}
dev_worker() {
echo "Starting dev RQ worker..."
@@ -45,8 +32,7 @@ server() {
# Recycle gunicorn workers every n-th request. See http://docs.gunicorn.org/en/stable/settings.html#max-requests for more details.
MAX_REQUESTS=${MAX_REQUESTS:-1000}
MAX_REQUESTS_JITTER=${MAX_REQUESTS_JITTER:-100}
TIMEOUT=${REDASH_GUNICORN_TIMEOUT:-60}
exec /usr/local/bin/gunicorn -b 0.0.0.0:5000 --name redash -w${REDASH_WEB_WORKERS:-4} redash.wsgi:app --max-requests $MAX_REQUESTS --max-requests-jitter $MAX_REQUESTS_JITTER --timeout $TIMEOUT
exec /usr/local/bin/gunicorn -b 0.0.0.0:5000 --name redash -w${REDASH_WEB_WORKERS:-4} redash.wsgi:app --max-requests $MAX_REQUESTS --max-requests-jitter $MAX_REQUESTS_JITTER
}
create_db() {
@@ -89,10 +75,6 @@ case "$1" in
shift
worker
;;
workers_healthcheck)
shift
workers_healthcheck
;;
server)
shift
server

9
bin/flake8_tests.sh Executable file
View File

@@ -0,0 +1,9 @@
#!/bin/sh
set -o errexit # fail the build if any task fails
flake8 --version ; pip --version
# stop the build if there are Python syntax errors or undefined names
flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics
# exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide
flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics

View File

@@ -1,44 +1,35 @@
#!/bin/env python3
import sys
import re
import subprocess
import sys
def get_change_log(previous_sha):
args = [
"git",
"--no-pager",
"log",
"--merges",
"--grep",
"Merge pull request",
'--pretty=format:"%h|%s|%b|%p"',
"master...{}".format(previous_sha),
]
args = ['git', '--no-pager', 'log', '--merges', '--grep', 'Merge pull request', '--pretty=format:"%h|%s|%b|%p"', 'master...{}'.format(previous_sha)]
log = subprocess.check_output(args)
changes = []
for line in log.split("\n"):
for line in log.split('\n'):
try:
sha, subject, body, parents = line[1:-1].split("|")
sha, subject, body, parents = line[1:-1].split('|')
except ValueError:
continue
try:
pull_request = re.match(r"Merge pull request #(\d+)", subject).groups()[0]
pull_request = re.match("Merge pull request #(\d+)", subject).groups()[0]
pull_request = " #{}".format(pull_request)
except Exception:
except Exception as ex:
pull_request = ""
author = subprocess.check_output(["git", "log", "-1", '--pretty=format:"%an"', parents.split(" ")[-1]])[1:-1]
author = subprocess.check_output(['git', 'log', '-1', '--pretty=format:"%an"', parents.split(' ')[-1]])[1:-1]
changes.append("{}{}: {} ({})".format(sha, pull_request, body.strip(), author))
return changes
if __name__ == "__main__":
if __name__ == '__main__':
previous_sha = sys.argv[1]
changes = get_change_log(previous_sha)

View File

@@ -1,20 +1,17 @@
#!/usr/bin/env python3
import os
import sys
import re
import subprocess
import sys
from urllib.parse import urlparse
import requests
import simplejson
github_token = os.environ["GITHUB_TOKEN"]
auth = (github_token, "x-oauth-basic")
repo = "getredash/redash"
github_token = os.environ['GITHUB_TOKEN']
auth = (github_token, 'x-oauth-basic')
repo = 'getredash/redash'
def _github_request(method, path, params=None, headers={}):
if urlparse(path).hostname != "api.github.com":
if not path.startswith('https://api.github.com'):
url = "https://api.github.com/{}".format(path)
else:
url = path
@@ -25,18 +22,15 @@ def _github_request(method, path, params=None, headers={}):
response = requests.request(method, url, data=params, auth=auth)
return response
def exception_from_error(message, response):
return Exception("({}) {}: {}".format(response.status_code, message, response.json().get("message", "?")))
return Exception("({}) {}: {}".format(response.status_code, message, response.json().get('message', '?')))
def rc_tag_name(version):
return "v{}-rc".format(version)
def get_rc_release(version):
tag = rc_tag_name(version)
response = _github_request("get", "repos/{}/releases/tags/{}".format(repo, tag))
response = _github_request('get', 'repos/{}/releases/tags/{}'.format(repo, tag))
if response.status_code == 404:
return None
@@ -45,101 +39,84 @@ def get_rc_release(version):
raise exception_from_error("Unknown error while looking RC release: ", response)
def create_release(version, commit_sha):
tag = rc_tag_name(version)
params = {
"tag_name": tag,
"name": "{} - RC".format(version),
"target_commitish": commit_sha,
"prerelease": True,
'tag_name': tag,
'name': "{} - RC".format(version),
'target_commitish': commit_sha,
'prerelease': True
}
response = _github_request("post", "repos/{}/releases".format(repo), params)
response = _github_request('post', 'repos/{}/releases'.format(repo), params)
if response.status_code != 201:
raise exception_from_error("Failed creating new release", response)
return response.json()
def upload_asset(release, filepath):
upload_url = release["upload_url"].replace("{?name,label}", "")
filename = filepath.split("/")[-1]
upload_url = release['upload_url'].replace('{?name,label}', '')
filename = filepath.split('/')[-1]
with open(filepath) as file_content:
headers = {"Content-Type": "application/gzip"}
response = requests.post(
upload_url, file_content, params={"name": filename}, headers=headers, auth=auth, verify=False
)
headers = {'Content-Type': 'application/gzip'}
response = requests.post(upload_url, file_content, params={'name': filename}, headers=headers, auth=auth, verify=False)
if response.status_code != 201: # not 200/201/...
raise exception_from_error("Failed uploading asset", response)
raise exception_from_error('Failed uploading asset', response)
return response
def remove_previous_builds(release):
for asset in release["assets"]:
response = _github_request("delete", asset["url"])
for asset in release['assets']:
response = _github_request('delete', asset['url'])
if response.status_code != 204:
raise exception_from_error("Failed deleting asset", response)
def get_changelog(commit_sha):
latest_release = _github_request("get", "repos/{}/releases/latest".format(repo))
latest_release = _github_request('get', 'repos/{}/releases/latest'.format(repo))
if latest_release.status_code != 200:
raise exception_from_error("Failed getting latest release", latest_release)
raise exception_from_error('Failed getting latest release', latest_release)
latest_release = latest_release.json()
previous_sha = latest_release["target_commitish"]
previous_sha = latest_release['target_commitish']
args = [
"git",
"--no-pager",
"log",
"--merges",
"--grep",
"Merge pull request",
'--pretty=format:"%h|%s|%b|%p"',
"{}...{}".format(previous_sha, commit_sha),
]
args = ['git', '--no-pager', 'log', '--merges', '--grep', 'Merge pull request', '--pretty=format:"%h|%s|%b|%p"', '{}...{}'.format(previous_sha, commit_sha)]
log = subprocess.check_output(args)
changes = ["Changes since {}:".format(latest_release["name"])]
changes = ["Changes since {}:".format(latest_release['name'])]
for line in log.split("\n"):
for line in log.split('\n'):
try:
sha, subject, body, parents = line[1:-1].split("|")
sha, subject, body, parents = line[1:-1].split('|')
except ValueError:
continue
try:
pull_request = re.match(r"Merge pull request #(\d+)", subject).groups()[0]
pull_request = re.match("Merge pull request #(\d+)", subject).groups()[0]
pull_request = " #{}".format(pull_request)
except Exception:
except Exception as ex:
pull_request = ""
author = subprocess.check_output(["git", "log", "-1", '--pretty=format:"%an"', parents.split(" ")[-1]])[1:-1]
author = subprocess.check_output(['git', 'log', '-1', '--pretty=format:"%an"', parents.split(' ')[-1]])[1:-1]
changes.append("{}{}: {} ({})".format(sha, pull_request, body.strip(), author))
return "\n".join(changes)
def update_release_commit_sha(release, commit_sha):
params = {
"target_commitish": commit_sha,
'target_commitish': commit_sha,
}
response = _github_request("patch", "repos/{}/releases/{}".format(repo, release["id"]), params)
response = _github_request('patch', 'repos/{}/releases/{}'.format(repo, release['id']), params)
if response.status_code != 200:
raise exception_from_error("Failed updating commit sha for existing release", response)
return response.json()
def update_release(version, build_filepath, commit_sha):
try:
release = get_rc_release(version)
@@ -148,22 +125,21 @@ def update_release(version, build_filepath, commit_sha):
else:
release = create_release(version, commit_sha)
print("Using release id: {}".format(release["id"]))
print("Using release id: {}".format(release['id']))
remove_previous_builds(release)
response = upload_asset(release, build_filepath)
changelog = get_changelog(commit_sha)
response = _github_request("patch", release["url"], {"body": changelog})
response = _github_request('patch', release['url'], {'body': changelog})
if response.status_code != 200:
raise exception_from_error("Failed updating release description", response)
except Exception as ex:
print(ex)
if __name__ == "__main__":
if __name__ == '__main__':
commit_sha = sys.argv[1]
version = sys.argv[2]
filepath = sys.argv[3]

242
bin/upgrade Executable file
View File

@@ -0,0 +1,242 @@
#!/usr/bin/env python3
import urllib
import argparse
import os
import subprocess
import sys
from collections import namedtuple
from fnmatch import fnmatch
import requests
try:
import semver
except ImportError:
print("Missing required library: semver.")
exit(1)
REDASH_HOME = os.environ.get('REDASH_HOME', '/opt/redash')
CURRENT_VERSION_PATH = '{}/current'.format(REDASH_HOME)
def run(cmd, cwd=None):
if not cwd:
cwd = REDASH_HOME
return subprocess.check_output(cmd, cwd=cwd, shell=True, stderr=subprocess.STDOUT)
def confirm(question):
reply = str(input(question + ' (y/n): ')).lower().strip()
if reply[0] == 'y':
return True
if reply[0] == 'n':
return False
else:
return confirm("Please use 'y' or 'n'")
def version_path(version_name):
return "{}/{}".format(REDASH_HOME, version_name)
END_CODE = '\033[0m'
def colored_string(text, color):
if sys.stdout.isatty():
return "{}{}{}".format(color, text, END_CODE)
else:
return text
def h1(text):
print(colored_string(text, '\033[4m\033[1m'))
def green(text):
print(colored_string(text, '\033[92m'))
def red(text):
print(colored_string(text, '\033[91m'))
class Release(namedtuple('Release', ('version', 'download_url', 'filename', 'description'))):
def v1_or_newer(self):
return semver.compare(self.version, '1.0.0-alpha') >= 0
def is_newer(self, version):
return semver.compare(self.version, version) > 0
@property
def version_name(self):
return self.filename.replace('.tar.gz', '')
def get_latest_release_from_ci():
response = requests.get('https://circleci.com/api/v1.1/project/github/getredash/redash/latest/artifacts?branch=master')
if response.status_code != 200:
exit("Failed getting releases (status code: %s)." % response.status_code)
tarball_asset = filter(lambda asset: asset['url'].endswith('.tar.gz'), response.json())[0]
filename = urllib.unquote(tarball_asset['pretty_path'].split('/')[-1])
version = filename.replace('redash.', '').replace('.tar.gz', '')
release = Release(version, tarball_asset['url'], filename, '')
return release
def get_release(channel):
if channel == 'ci':
return get_latest_release_from_ci()
response = requests.get('https://version.redash.io/api/releases?channel={}'.format(channel))
release = response.json()[0]
filename = release['download_url'].split('/')[-1]
release = Release(release['version'], release['download_url'], filename, release['description'])
return release
def link_to_current(version_name):
green("Linking to current version...")
run('ln -nfs {} {}'.format(version_path(version_name), CURRENT_VERSION_PATH))
def restart_services():
# We're doing this instead of simple 'supervisorctl restart all' because
# otherwise it won't notice that /opt/redash/current pointing at a different
# directory.
green("Restarting...")
try:
run('sudo /etc/init.d/redash_supervisord restart')
except subprocess.CalledProcessError as e:
run('sudo service supervisor restart')
def update_requirements(version_name):
green("Installing new Python packages (if needed)...")
new_requirements_file = '{}/requirements.txt'.format(version_path(version_name))
install_requirements = False
try:
run('diff {}/requirements.txt {}'.format(CURRENT_VERSION_PATH, new_requirements_file)) != 0
except subprocess.CalledProcessError as e:
if e.returncode != 0:
install_requirements = True
if install_requirements:
run('sudo pip install -r {}'.format(new_requirements_file))
def apply_migrations(release):
green("Running migrations (if needed)...")
if not release.v1_or_newer():
return apply_migrations_pre_v1(release.version_name)
run("sudo -u redash bin/run ./manage.py db upgrade", cwd=version_path(release.version_name))
def find_migrations(version_name):
current_migrations = set([f for f in os.listdir("{}/migrations".format(CURRENT_VERSION_PATH)) if fnmatch(f, '*_*.py')])
new_migrations = sorted([f for f in os.listdir("{}/migrations".format(version_path(version_name))) if fnmatch(f, '*_*.py')])
return [m for m in new_migrations if m not in current_migrations]
def apply_migrations_pre_v1(version_name):
new_migrations = find_migrations(version_name)
if new_migrations:
green("New migrations to run: ")
print(', '.join(new_migrations))
else:
print("No new migrations in this version.")
if new_migrations and confirm("Apply new migrations? (make sure you have backup)"):
for migration in new_migrations:
print("Applying {}...".format(migration))
run("sudo sudo -u redash PYTHONPATH=. bin/run python migrations/{}".format(migration), cwd=version_path(version_name))
def download_and_unpack(release):
directory_name = release.version_name
green("Downloading release tarball...")
run('sudo wget --header="Accept: application/octet-stream" -O {} {}'.format(release.filename, release.download_url))
green("Unpacking to: {}...".format(directory_name))
run('sudo mkdir -p {}'.format(directory_name))
run('sudo tar -C {} -xvf {}'.format(directory_name, release.filename))
green("Changing ownership to redash...")
run('sudo chown redash {}'.format(directory_name))
green("Linking .env file...")
run('sudo ln -nfs {}/.env {}/.env'.format(REDASH_HOME, version_path(directory_name)))
def current_version():
real_current_path = os.path.realpath(CURRENT_VERSION_PATH).replace('.b', '+b')
return real_current_path.replace(REDASH_HOME + '/', '').replace('redash.', '')
def verify_minimum_version():
green("Current version: " + current_version())
if semver.compare(current_version(), '0.12.0') < 0:
red("You need to have Redash v0.12.0 or newer to upgrade to post v1.0.0 releases.")
green("To upgrade to v0.12.0, run the upgrade script set to the legacy channel (--channel legacy).")
exit(1)
def show_description_and_confirm(description):
if description:
print(description)
if not confirm("Continue with upgrade?"):
red("Cancelling upgrade.")
exit(1)
def verify_newer_version(release):
if not release.is_newer(current_version()):
red("The found release is not newer than your current deployed release ({}).".format(current_version()))
if not confirm("Continue with upgrade?"):
red("Cancelling upgrade.")
exit(1)
def deploy_release(channel):
h1("Starting Redash upgrade:")
release = get_release(channel)
green("Found version: {}".format(release.version))
if release.v1_or_newer():
verify_minimum_version()
verify_newer_version(release)
show_description_and_confirm(release.description)
try:
download_and_unpack(release)
update_requirements(release.version_name)
apply_migrations(release)
link_to_current(release.version_name)
restart_services()
green("Done! Enjoy.")
except subprocess.CalledProcessError as e:
red("Failed running: {}".format(e.cmd))
red("Exit status: {}\nOutput:\n{}".format(e.returncode, e.output))
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("--channel", help="The channel to get release from (default: stable).", default='stable')
args = parser.parse_args()
deploy_release(args.channel)

View File

@@ -5,11 +5,10 @@ module.exports = {
"react-app",
"plugin:compat/recommended",
"prettier",
"plugin:jsx-a11y/recommended",
// Remove any typescript-eslint rules that would conflict with prettier
"prettier/@typescript-eslint",
],
plugins: ["jest", "compat", "no-only-tests", "@typescript-eslint", "jsx-a11y"],
plugins: ["jest", "compat", "no-only-tests", "@typescript-eslint"],
settings: {
"import/resolver": "webpack",
},
@@ -20,20 +19,7 @@ module.exports = {
rules: {
// allow debugger during development
"no-debugger": process.env.NODE_ENV === "production" ? 2 : 0,
"jsx-a11y/anchor-is-valid": [
// TMP
"off",
{
components: ["Link"],
aspects: ["noHref", "invalidHref", "preferButton"],
},
],
"jsx-a11y/no-redundant-roles": "error",
"jsx-a11y/no-autofocus": "off",
"jsx-a11y/click-events-have-key-events": "off", // TMP
"jsx-a11y/no-static-element-interactions": "off", // TMP
"jsx-a11y/no-noninteractive-element-interactions": "off", // TMP
"no-console": ["warn", { allow: ["warn", "error"] }],
"jsx-a11y/anchor-is-valid": "off",
"no-restricted-imports": [
"error",
{

Binary file not shown.

Before

Width:  |  Height:  |  Size: 97 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 22 KiB

View File

@@ -225,16 +225,6 @@
}
}
&-tbody > tr&-row {
&:hover,
&:focus,
&:focus-within {
& > td {
background: @table-row-hover-bg;
}
}
}
// Custom styles
&-headerless &-tbody > tr:first-child > td {
@@ -401,18 +391,6 @@
left: 0;
}
}
&:focus,
&:focus-within {
color: @menu-highlight-color;
}
}
}
.@{dropdown-prefix-cls}-menu-item {
&:focus,
&:focus-within {
background-color: @item-hover-bg;
}
}

View File

@@ -98,10 +98,6 @@ strong {
.clickable {
cursor: pointer;
button&:disabled {
cursor: not-allowed;
}
}
.resize-vertical {

View File

@@ -1,23 +1,26 @@
.edit-in-place {
.edit-in-place span {
white-space: pre-line;
display: inline-block;
p {
margin-bottom: 0;
}
.editable {
display: inline-block;
cursor: pointer;
&:hover {
background: @redash-yellow;
border-radius: @redash-radius;
}
}
&.active input,
&.active textarea {
display: inline-block;
}
}
.edit-in-place span.editable {
display: inline-block;
cursor: pointer;
}
.edit-in-place span.editable:hover {
background: @redash-yellow;
border-radius: @redash-radius;
}
.edit-in-place.active input,
.edit-in-place.active textarea {
display: inline-block;
}
.edit-in-place {
display: inline-block;
}

View File

@@ -2,218 +2,163 @@
Generate Margin Classes (0px - 25px)
margin, margin-top, margin-bottom, margin-left, margin-right
-----------------------------------------------------------*/
.margin (@label, @size: 1, @key:1) when (@size =< 30) {
.m-@{key} {
margin: @size !important;
}
.margin (@label, @size: 1, @key:1) when (@size =< 30){
.m-@{key} {
margin: @size !important;
}
.m-t-@{key} {
margin-top: @size !important;
}
.m-t-@{key} {
margin-top: @size !important;
}
.m-b-@{key} {
margin-bottom: @size !important;
}
.m-b-@{key} {
margin-bottom: @size !important;
}
.m-l-@{key} {
margin-left: @size !important;
}
.m-l-@{key} {
margin-left: @size !important;
}
.m-r-@{key} {
margin-right: @size !important;
}
.m-r-@{key} {
margin-right: @size !important;
}
.margin(@label - 5; @size + 5; @key + 5);
.margin(@label - 5; @size + 5; @key + 5);
}
.margin(25, 0px, 0);
.m-2 {
margin: 2px;
.m-2{
margin:2px;
}
/* --------------------------------------------------------
Generate Padding Classes (0px - 25px)
padding, padding-top, padding-bottom, padding-left, padding-right
-----------------------------------------------------------*/
.padding (@label, @size: 1, @key:1) when (@size =< 30) {
.p-@{key} {
padding: @size !important;
}
.padding (@label, @size: 1, @key:1) when (@size =< 30){
.p-@{key} {
padding: @size !important;
}
.p-t-@{key} {
padding-top: @size !important;
}
.p-t-@{key} {
padding-top: @size !important;
}
.p-b-@{key} {
padding-bottom: @size !important;
}
.p-b-@{key} {
padding-bottom: @size !important;
}
.p-l-@{key} {
padding-left: @size !important;
}
.p-l-@{key} {
padding-left: @size !important;
}
.p-r-@{key} {
padding-right: @size !important;
}
.p-r-@{key} {
padding-right: @size !important;
}
.padding(@label - 5; @size + 5; @key + 5);
.padding(@label - 5; @size + 5; @key + 5);
}
.padding(25, 0px, 0);
/* --------------------------------------------------------
Generate Font-Size Classes (8px - 20px)
-----------------------------------------------------------*/
.font-size (@label, @size: 8, @key:10) when (@size =< 20) {
.f-@{key} {
font-size: @size !important;
}
.font-size (@label, @size: 8, @key:10) when (@size =< 20){
.f-@{key} {
font-size: @size !important;
}
.font-size(@label - 1; @size + 1; @key + 1);
.font-size(@label - 1; @size + 1; @key + 1);
}
.font-size(20, 8px, 8);
.f-inherit {
font-size: inherit !important;
}
.f-inherit { font-size: inherit !important; }
/* --------------------------------------------------------
Font Weight
-----------------------------------------------------------*/
.f-300 {
font-weight: 300 !important;
}
.f-400 {
font-weight: 400 !important;
}
.f-500 {
font-weight: 500 !important;
}
.f-700 {
font-weight: 700 !important;
}
.f-300 { font-weight: 300 !important; }
.f-400 { font-weight: 400 !important; }
.f-500 { font-weight: 500 !important; }
.f-700 { font-weight: 700 !important; }
/* --------------------------------------------------------
Position
-----------------------------------------------------------*/
.p-relative {
position: relative !important;
}
.p-absolute {
position: absolute !important;
}
.p-fixed {
position: fixed !important;
}
.p-static {
position: static !important;
}
.p-relative { position: relative !important; }
.p-absolute { position: absolute !important; }
.p-fixed { position: fixed !important; }
.p-static { position: static !important; }
/* --------------------------------------------------------
Overflow
-----------------------------------------------------------*/
.o-hidden {
overflow: hidden !important;
}
.o-visible {
overflow: visible !important;
}
.o-auto {
overflow: auto !important;
}
.o-hidden { overflow: hidden !important; }
.o-visible { overflow: visible !important; }
.o-auto { overflow: auto !important; }
/* --------------------------------------------------------
Display
-----------------------------------------------------------*/
.di-block {
display: inline-block !important;
}
.d-block {
display: block;
}
.di-block { display: inline-block !important; }
.d-block { display: block; }
/* --------------------------------------------------------
Background Colors and Colors
-----------------------------------------------------------*/
@array: c-white bg-white @white, c-ace bg-ace @ace, c-black bg-black @black, c-brown bg-brown @brown,
c-pink bg-pink @pink, c-red bg-red @red, c-blue bg-blue @blue, c-purple bg-purple @purple,
c-deeppurple bg-deeppurple @deeppurple, c-lightblue bg-lightblue @lightblue, c-cyan bg-cyan @cyan,
c-teal bg-teal @teal, c-green bg-green @green, c-lightgreen bg-lightgreen @lightgreen, c-lime bg-lime @lime,
c-yellow bg-yellow @yellow, c-amber bg-amber @amber, c-orange bg-orange @orange,
c-deeporange bg-deeporange @deeporange, c-gray bg-gray @gray, c-bluegray bg-bluegray @bluegray,
c-indigo bg-indigo @indigo;
@array: c-white bg-white @white, c-ace bg-ace @ace, c-black bg-black @black, c-brown bg-brown @brown, c-pink bg-pink @pink, c-red bg-red @red, c-blue bg-blue @blue, c-purple bg-purple @purple, c-deeppurple bg-deeppurple @deeppurple, c-lightblue bg-lightblue @lightblue, c-cyan bg-cyan @cyan, c-teal bg-teal @teal, c-green bg-green @green, c-lightgreen bg-lightgreen @lightgreen, c-lime bg-lime @lime, c-yellow bg-yellow @yellow, c-amber bg-amber @amber, c-orange bg-orange @orange, c-deeporange bg-deeporange @deeporange, c-gray bg-gray @gray, c-bluegray bg-bluegray @bluegray, c-indigo bg-indigo @indigo;
.for(@array);
.-each(@value) {
@name: extract(@value, 1);
@name2: extract(@value, 2);
@color: extract(@value, 3);
&.@{name2} {
background-color: @color !important;
}
.for(@array); .-each(@value) {
@name: extract(@value, 1);
@name2: extract(@value, 2);
@color: extract(@value, 3);
&.@{name2} {
background-color: @color !important;
}
&.@{name} {
color: @color !important;
}
&.@{name} {
color: @color !important;
}
}
/* --------------------------------------------------------
Background Colors
-----------------------------------------------------------*/
.bg-brand {
background-color: @brand-bg;
}
.bg-black-trp {
background-color: rgba(0, 0, 0, 0.12) !important;
}
.bg-brand { background-color: @brand-bg; }
.bg-black-trp { background-color: rgba(0,0,0,0.12) !important; }
/* --------------------------------------------------------
Borders
-----------------------------------------------------------*/
.b-0 {
border: 0 !important;
}
.b-0 { border: 0 !important; }
/* --------------------------------------------------------
Width
-----------------------------------------------------------*/
.w-100 {
width: 100% !important;
}
.w-50 {
width: 50% !important;
}
.w-25 {
width: 25% !important;
}
.w-100 { width: 100% !important; }
.w-50 { width: 50% !important; }
.w-25 { width: 25% !important; }
/* --------------------------------------------------------
Border Radius
-----------------------------------------------------------*/
.brd-2 {
border-radius: 2px;
}
.brd-2 { border-radius: 2px; }
/* --------------------------------------------------------
Alignment
-----------------------------------------------------------*/
.va-top {
vertical-align: top;
}
/* --------------------------------------------------------
Screen readers
-----------------------------------------------------------*/
.sr-only {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
white-space: nowrap;
border-width: 0;
}
.va-top { vertical-align: top; }

View File

@@ -1,107 +1,102 @@
div.table-name {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
cursor: pointer;
padding: 2px 22px 2px 10px;
border-radius: @redash-radius;
position: relative;
height: 22px;
.copy-to-editor {
display: none;
}
&:hover {
background: fade(@redash-gray, 10%);
.copy-to-editor {
display: flex;
}
}
}
.schema-container {
height: 100%;
z-index: 10;
background-color: white;
}
.schema-browser {
overflow: hidden;
border: none;
padding-top: 10px;
position: relative;
.schema-browser {
overflow: hidden;
border: none;
padding-top: 10px;
position: relative;
height: 100%;
.schema-loading-state {
display: flex;
align-items: center;
justify-content: center;
height: 100%;
}
.schema-loading-state {
display: flex;
align-items: center;
justify-content: center;
height: 100%;
}
.collapse.in {
background: transparent;
}
.collapse.in {
background: transparent;
.copy-to-editor {
color: fade(@redash-gray, 90%);
cursor: pointer;
position: absolute;
top: 0;
right: 0;
bottom: 0;
width: 20px;
display: flex;
align-items: center;
justify-content: center;
}
.table-open {
padding: 0 22px 0 26px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
position: relative;
height: 18px;
.column-type {
color: fade(@text-color, 80%);
font-size: 10px;
margin-left: 2px;
text-transform: uppercase;
}
.copy-to-editor {
visibility: hidden;
color: fade(@redash-gray, 90%);
width: 20px;
display: flex;
align-items: center;
justify-content: center;
transition: none;
display: none;
}
.schema-list-item {
display: flex;
border-radius: @redash-radius;
height: 22px;
&:hover {
background: fade(@redash-gray, 10%);
.table-name {
flex: 1;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
cursor: pointer;
padding: 2px 22px 2px 10px;
}
&:hover,
&:focus,
&:focus-within {
background: fade(@redash-gray, 10%);
.copy-to-editor {
visibility: visible;
}
}
}
.table-open {
.table-open-item {
.copy-to-editor {
display: flex;
height: 18px;
width: calc(100% - 22px);
padding-left: 22px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
transition: none;
div:first-child {
flex: 1;
}
.column-type {
color: fade(@text-color, 80%);
font-size: 10px;
margin-left: 2px;
text-transform: uppercase;
}
&:hover,
&:focus,
&:focus-within {
background: fade(@redash-gray, 10%);
.copy-to-editor {
visibility: visible;
}
}
}
}
}
.schema-control {
display: flex;
flex-wrap: nowrap;
padding: 0;
.ant-btn {
height: auto;
}
}
.parameter-label {
display: block;
}
}
.schema-control {
display: flex;
flex-wrap: nowrap;
padding: 0;
.ant-btn {
height: auto;
}
}
.parameter-label {
display: block;
}

View File

@@ -103,7 +103,7 @@
padding-top: 5px !important;
}
.btn-favorite,
.btn-favourite,
.btn-archive {
font-size: 15px;
}
@@ -114,23 +114,18 @@
line-height: 1.7 !important;
}
.btn-favorite {
.btn-favourite {
color: #d4d4d4;
transition: all 0.25s ease-in-out;
.fa-star {
color: @yellow-darker;
}
&:hover,
&:focus {
color: @yellow-darker;
cursor: pointer;
}
.fa-star {
filter: saturate(75%);
opacity: 0.75;
}
.fa-star {
color: @yellow-darker;
}
}

View File

@@ -90,23 +90,6 @@ body.fixed-layout {
.embed__vis {
display: flex;
flex-flow: column;
height: calc(~'100vh - 25px');
> .embed-heading {
flex: 0 0 auto;
}
> .query__vis {
flex: 1 1 auto;
.chart-visualization-container, .visualization-renderer-wrapper, .visualization-renderer {
height: 100%
}
}
> .tile__bottom-control {
flex: 0 0 auto;
}
width: 100%;
}
@@ -144,13 +127,11 @@ body.fixed-layout {
}
}
.label-tag {
a.label-tag {
background: fade(@redash-gray, 15%);
color: darken(@redash-gray, 15%);
&:hover,
&:focus,
&:active {
&:hover {
color: darken(@redash-gray, 15%);
background: fade(@redash-gray, 25%);
}

View File

@@ -1,11 +1,10 @@
import React, { useMemo } from "react";
import { first, includes } from "lodash";
import { first } from "lodash";
import React, { useState } from "react";
import Button from "antd/lib/button";
import Menu from "antd/lib/menu";
import Link from "@/components/Link";
import PlainButton from "@/components/PlainButton";
import HelpTrigger from "@/components/HelpTrigger";
import CreateDashboardDialog from "@/components/dashboards/CreateDashboardDialog";
import { useCurrentRoute } from "@/components/ApplicationArea/Router";
import { Auth, currentUser } from "@/services/auth";
import settingsMenu from "@/services/settingsMenu";
import logoUrl from "@/assets/images/redash_icon_small.png";
@@ -16,109 +15,83 @@ import AlertOutlinedIcon from "@ant-design/icons/AlertOutlined";
import PlusOutlinedIcon from "@ant-design/icons/PlusOutlined";
import QuestionCircleOutlinedIcon from "@ant-design/icons/QuestionCircleOutlined";
import SettingOutlinedIcon from "@ant-design/icons/SettingOutlined";
import VersionInfo from "./VersionInfo";
import MenuUnfoldOutlinedIcon from "@ant-design/icons/MenuUnfoldOutlined";
import MenuFoldOutlinedIcon from "@ant-design/icons/MenuFoldOutlined";
import VersionInfo from "./VersionInfo";
import "./DesktopNavbar.less";
function NavbarSection({ children, ...props }) {
function NavbarSection({ inlineCollapsed, children, ...props }) {
return (
<Menu selectable={false} mode="vertical" theme="dark" {...props}>
<Menu
selectable={false}
mode={inlineCollapsed ? "inline" : "vertical"}
inlineCollapsed={inlineCollapsed}
theme="dark"
{...props}>
{children}
</Menu>
);
}
function useNavbarActiveState() {
const currentRoute = useCurrentRoute();
return useMemo(
() => ({
dashboards: includes(
[
"Dashboards.List",
"Dashboards.Favorites",
"Dashboards.My",
"Dashboards.ViewOrEdit",
"Dashboards.LegacyViewOrEdit",
],
currentRoute.id
),
queries: includes(
[
"Queries.List",
"Queries.Favorites",
"Queries.Archived",
"Queries.My",
"Queries.View",
"Queries.New",
"Queries.Edit",
],
currentRoute.id
),
dataSources: includes(["DataSources.List"], currentRoute.id),
alerts: includes(["Alerts.List", "Alerts.New", "Alerts.View", "Alerts.Edit"], currentRoute.id),
}),
[currentRoute.id]
);
}
export default function DesktopNavbar() {
const firstSettingsTab = first(settingsMenu.getAvailableItems());
const [collapsed, setCollapsed] = useState(true);
const activeState = useNavbarActiveState();
const firstSettingsTab = first(settingsMenu.getAvailableItems());
const canCreateQuery = currentUser.hasPermission("create_query");
const canCreateDashboard = currentUser.hasPermission("create_dashboard");
const canCreateAlert = currentUser.hasPermission("list_alerts");
return (
<nav className="desktop-navbar">
<NavbarSection className="desktop-navbar-logo">
<div role="menuitem">
<div className="desktop-navbar">
<NavbarSection inlineCollapsed={collapsed} className="desktop-navbar-logo">
<div>
<Link href="./">
<img src={logoUrl} alt="Redash" />
</Link>
</div>
</NavbarSection>
<NavbarSection>
<NavbarSection inlineCollapsed={collapsed}>
{currentUser.hasPermission("list_dashboards") && (
<Menu.Item key="dashboards" className={activeState.dashboards ? "navbar-active-item" : null}>
<Menu.Item key="dashboards">
<Link href="dashboards">
<DesktopOutlinedIcon aria-label="Dashboard navigation button" />
<span className="desktop-navbar-label">Dashboards</span>
<DesktopOutlinedIcon />
<span>Dashboards</span>
</Link>
</Menu.Item>
)}
{currentUser.hasPermission("view_query") && (
<Menu.Item key="queries" className={activeState.queries ? "navbar-active-item" : null}>
<Menu.Item key="queries">
<Link href="queries">
<CodeOutlinedIcon aria-label="Queries navigation button" />
<span className="desktop-navbar-label">Queries</span>
<CodeOutlinedIcon />
<span>Queries</span>
</Link>
</Menu.Item>
)}
{currentUser.hasPermission("list_alerts") && (
<Menu.Item key="alerts" className={activeState.alerts ? "navbar-active-item" : null}>
<Menu.Item key="alerts">
<Link href="alerts">
<AlertOutlinedIcon aria-label="Alerts navigation button" />
<span className="desktop-navbar-label">Alerts</span>
<AlertOutlinedIcon />
<span>Alerts</span>
</Link>
</Menu.Item>
)}
</NavbarSection>
<NavbarSection className="desktop-navbar-spacer">
<NavbarSection inlineCollapsed={collapsed} className="desktop-navbar-spacer">
{(canCreateQuery || canCreateDashboard || canCreateAlert) && <Menu.Divider />}
{(canCreateQuery || canCreateDashboard || canCreateAlert) && (
<Menu.SubMenu
key="create"
popupClassName="desktop-navbar-submenu"
data-test="CreateButton"
tabIndex={0}
title={
<React.Fragment>
<PlusOutlinedIcon />
<span className="desktop-navbar-label">Create</span>
<span data-test="CreateButton">
<PlusOutlinedIcon />
<span>Create</span>
</span>
</React.Fragment>
}>
{canCreateQuery && (
@@ -130,9 +103,9 @@ export default function DesktopNavbar() {
)}
{canCreateDashboard && (
<Menu.Item key="new-dashboard">
<PlainButton data-test="CreateDashboardMenuItem" onClick={() => CreateDashboardDialog.showModal()}>
<a data-test="CreateDashboardMenuItem" onMouseUp={() => CreateDashboardDialog.showModal()}>
New Dashboard
</PlainButton>
</a>
</Menu.Item>
)}
{canCreateAlert && (
@@ -146,31 +119,32 @@ export default function DesktopNavbar() {
)}
</NavbarSection>
<NavbarSection>
<NavbarSection inlineCollapsed={collapsed}>
<Menu.Item key="help">
<HelpTrigger showTooltip={false} type="HOME" tabIndex={0}>
<HelpTrigger showTooltip={false} type="HOME">
<QuestionCircleOutlinedIcon />
<span className="desktop-navbar-label">Help</span>
<span>Help</span>
</HelpTrigger>
</Menu.Item>
{firstSettingsTab && (
<Menu.Item key="settings" className={activeState.dataSources ? "navbar-active-item" : null}>
<Menu.Item key="settings">
<Link href={firstSettingsTab.path} data-test="SettingsLink">
<SettingOutlinedIcon />
<span className="desktop-navbar-label">Settings</span>
<span>Settings</span>
</Link>
</Menu.Item>
)}
<Menu.Divider />
</NavbarSection>
<NavbarSection className="desktop-navbar-profile-menu">
<NavbarSection inlineCollapsed={collapsed} className="desktop-navbar-profile-menu">
<Menu.SubMenu
key="profile"
popupClassName="desktop-navbar-submenu"
tabIndex={0}
title={
<span data-test="ProfileDropdown" className="desktop-navbar-profile-menu-title">
<img className="profile__image_thumb" src={currentUser.profile_image_url} alt={currentUser.name} />
<span>{currentUser.name}</span>
</span>
}>
<Menu.Item key="profile">
@@ -183,16 +157,20 @@ export default function DesktopNavbar() {
)}
<Menu.Divider />
<Menu.Item key="logout">
<PlainButton data-test="LogOutButton" onClick={() => Auth.logout()}>
<a data-test="LogOutButton" onClick={() => Auth.logout()}>
Log out
</PlainButton>
</a>
</Menu.Item>
<Menu.Divider />
<Menu.Item key="version" role="presentation" disabled className="version-info">
<Menu.Item key="version" disabled className="version-info">
<VersionInfo />
</Menu.Item>
</Menu.SubMenu>
</NavbarSection>
</nav>
<Button onClick={() => setCollapsed(!collapsed)} className="desktop-navbar-collapse-button">
{collapsed ? <MenuUnfoldOutlinedIcon /> : <MenuFoldOutlinedIcon />}
</Button>
</div>
);
}

View File

@@ -1,17 +1,12 @@
@backgroundColor: #001529;
@dividerColor: rgba(255, 255, 255, 0.5);
@textColor: rgba(255, 255, 255, 0.75);
@brandColor: #ff7964; // Redash logo color
@activeItemColor: @brandColor;
@iconSize: 26px;
.desktop-navbar {
background: @backgroundColor;
display: flex;
flex-direction: column;
height: 100%;
width: 80px;
overflow: hidden;
&-spacer {
flex: 1 1 auto;
@@ -26,6 +21,12 @@
height: 40px;
transition: all 270ms;
}
&.ant-menu-inline-collapsed {
img {
height: 20px;
}
}
}
.help-trigger {
@@ -33,38 +34,33 @@
}
.ant-menu {
&:not(.ant-menu-inline-collapsed) {
width: 170px;
}
&.ant-menu-inline-collapsed > .ant-menu-submenu-title span img + span,
&.ant-menu-inline-collapsed > .ant-menu-item i + span {
display: inline-block;
max-width: 0;
opacity: 0;
}
.ant-menu-item-divider {
background: @dividerColor;
}
.ant-menu-item,
.ant-menu-submenu {
font-weight: 500;
color: @textColor;
&.navbar-active-item {
box-shadow: inset 3px 0 0 @activeItemColor;
.anticon {
color: @activeItemColor;
}
}
&.ant-menu-submenu-open,
&.ant-menu-submenu-active,
&:hover,
&:active,
&:focus,
&:focus-within {
&:active {
color: #fff;
}
.anticon {
font-size: @iconSize;
margin: 0;
}
.desktop-navbar-label {
margin-top: 4px;
font-size: 11px;
}
a,
span,
.anticon {
@@ -75,33 +71,21 @@
.ant-menu-submenu-arrow {
display: none;
}
}
.ant-menu-item,
.ant-menu-submenu {
padding: 0;
height: 60px;
display: flex;
align-items: center;
flex-direction: column;
justify-content: center;
.ant-btn.desktop-navbar-collapse-button {
background-color: @backgroundColor;
border: 0;
border-radius: 0;
color: @textColor;
&:hover,
&:active {
color: #fff;
}
.ant-menu-submenu-title {
width: 100%;
padding: 0;
}
a,
&.ant-menu-vertical > .ant-menu-submenu > .ant-menu-submenu-title,
.ant-menu-submenu-title {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
line-height: normal;
height: auto;
background: none;
color: inherit;
&:after {
animation: 0s !important;
}
}
@@ -115,8 +99,37 @@
.profile__image_thumb {
margin: 0;
vertical-align: middle;
width: @iconSize;
height: @iconSize;
}
.profile__image_thumb + span {
flex: 1 1 auto;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
margin-left: 10px;
vertical-align: middle;
display: inline-block;
// styles from Antd
opacity: 1;
transition: opacity 0.3s cubic-bezier(0.645, 0.045, 0.355, 1),
margin-left 0.3s cubic-bezier(0.645, 0.045, 0.355, 1), width 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
}
}
&.ant-menu-inline-collapsed {
.ant-menu-submenu-title {
padding-left: 16px !important;
padding-right: 16px !important;
}
.desktop-navbar-profile-menu-title {
.profile__image_thumb + span {
opacity: 0;
max-width: 0;
margin-left: 0;
}
}
}
}
@@ -133,9 +146,7 @@
color: @textColor;
&:hover,
&:active,
&:focus,
&:focus-within {
&:active {
color: #fff;
}
@@ -160,9 +171,7 @@
color: rgba(255, 255, 255, 0.8);
&:hover,
&:active,
&:focus,
&:focus-within {
&:active {
color: rgba(255, 255, 255, 1);
}
}

View File

@@ -14,8 +14,8 @@ export default function VersionInfo() {
<div className="m-t-10">
{/* eslint-disable react/jsx-no-target-blank */}
<Link href="https://version.redash.io/" className="update-available" target="_blank" rel="noopener">
Update Available <i className="fa fa-external-link m-l-5" aria-hidden="true" />
<span className="sr-only">(opens in a new tab)</span>
Update Available
<i className="fa fa-external-link m-l-5" />
</Link>
</div>
)}

View File

@@ -49,7 +49,7 @@ export default function ErrorMessage({ error, message }) {
<div className="error-message-container" data-test="ErrorMessage" role="alert">
<div className="error-state bg-white tiled">
<div className="error-state__icon">
<i className="zmdi zmdi-alert-circle-o" aria-hidden="true" />
<i className="zmdi zmdi-alert-circle-o" />
</div>
<div className="error-state__details">
<DynamicComponent

View File

@@ -17,13 +17,6 @@ export default function ApplicationArea() {
useEffect(() => {
function globalErrorHandler(event) {
event.preventDefault();
if (event.message === "Uncaught SyntaxError: Unexpected token '<'") {
// if we see a javascript error on unexpected token where the unexpected token is '<', this usually means that a fallback html file (like index.html)
// was served as content of script rather than the expected script, give a friendlier message in the console on what could be going on
console.error(
`[Uncaught SyntaxError: Unexpected token '<'] usually means that a fallback html file was returned from server rather than the expected script. Check that the server is properly serving the file ${event.filename}.`
);
}
setUnhandledError(event.error);
}

View File

@@ -1,4 +1,5 @@
import React, { useEffect, useState } from "react";
// @ts-expect-error (Must be removed after adding @redash/viz typing)
import ErrorBoundary, { ErrorBoundaryContext } from "@redash/viz/lib/components/ErrorBoundary";
import { Auth } from "@/services/auth";
import { policy } from "@/services/policy";
@@ -61,14 +62,11 @@ export function UserSessionWrapper<P>({ bodyClass, currentRoute, render }: UserS
return (
<ApplicationLayout>
<React.Fragment key={currentRoute.key}>
{/* @ts-expect-error FIXME */}
<ErrorBoundary renderError={(error: Error) => <ErrorMessage error={error} />}>
<ErrorBoundaryContext.Consumer>
{(
{
handleError,
} /* : { handleError: UserSessionWrapperRenderChildrenProps<P>["onError"] } FIXME bring back type */
) => render({ ...currentRoute.routeParams, pageTitle: currentRoute.title, onError: handleError })}
{({ handleError }: { handleError: UserSessionWrapperRenderChildrenProps<P>["onError"] }) =>
render({ ...currentRoute.routeParams, pageTitle: currentRoute.title, onError: handleError })
}
</ErrorBoundaryContext.Consumer>
</ErrorBoundary>
</React.Fragment>

View File

@@ -1,21 +1,14 @@
import React from "react";
import PropTypes from "prop-types";
import { useUniqueId } from "@/lib/hooks/useUniqueId";
import cx from "classnames";
function BigMessage({ message, icon, children, className }) {
const messageId = useUniqueId("bm-message");
return (
<div
className={"big-message p-15 text-center " + className}
role="status"
aria-live="assertive"
aria-relevant="additions removals">
<h3 className="m-t-0 m-b-0" aria-labelledby={messageId}>
<i className={cx("fa", icon)} aria-hidden="true" />
<div className={"p-15 text-center " + className}>
<h3 className="m-t-0 m-b-0">
<i className={"fa " + icon} />
</h3>
<br />
<span id={messageId}>{message}</span>
{message}
{children}
</div>
);

View File

@@ -1,7 +1,7 @@
import React from "react";
import PropTypes from "prop-types";
import Button from "antd/lib/button";
import Tooltip from "@/components/Tooltip";
import Tooltip from "antd/lib/tooltip";
import CopyOutlinedIcon from "@ant-design/icons/CopyOutlined";
import "./CodeBlock.less";

View File

@@ -1,4 +1,4 @@
@import (reference, less) "~@/assets/less/ant";
@import '~antd/lib/button/style/index';
.code-block {
background: rgba(0, 0, 0, 0.06);

View File

@@ -1,6 +1,6 @@
import React from "react";
import PropTypes from "prop-types";
import { isEmpty, toUpper, includes, get, uniqueId } from "lodash";
import { isEmpty, toUpper, includes, get } from "lodash";
import Button from "antd/lib/button";
import List from "antd/lib/list";
import Modal from "antd/lib/modal";
@@ -45,8 +45,6 @@ class CreateSourceDialog extends React.Component {
currentStep: StepEnum.SELECT_TYPE,
};
formId = uniqueId("sourceForm");
selectType = selectedType => {
this.setState({ selectedType, currentStep: StepEnum.CONFIGURE_IT });
};
@@ -84,7 +82,6 @@ class CreateSourceDialog extends React.Component {
<div className="m-t-10">
<Search
placeholder="Search..."
aria-label="Search"
onChange={e => this.setState({ searchText: e.target.value })}
autoFocus
data-test="SearchSource"
@@ -114,12 +111,11 @@ class CreateSourceDialog extends React.Component {
<div className="text-right">
{HELP_TRIGGER_TYPES[helpTriggerType] && (
<HelpTrigger className="f-13" type={helpTriggerType}>
Setup Instructions <i className="fa fa-question-circle" aria-hidden="true" />
<span className="sr-only">(help)</span>
Setup Instructions <i className="fa fa-question-circle" />
</HelpTrigger>
)}
</div>
<DynamicForm id={this.formId} fields={fields} onSubmit={this.createSource} feedbackIcons hideSubmitButton />
<DynamicForm id="sourceForm" fields={fields} onSubmit={this.createSource} feedbackIcons hideSubmitButton />
{selectedType.type === "databricks" && (
<small>
By using the Databricks Data Source you agree to the Databricks JDBC/ODBC{" "}
@@ -143,7 +139,7 @@ class CreateSourceDialog extends React.Component {
roundedImage={false}
data-test="PreviewItem"
data-test-type={item.type}>
<i className="fa fa-angle-double-right" aria-hidden="true" />
<i className="fa fa-angle-double-right" />
</PreviewCard>
</List.Item>
);
@@ -173,7 +169,7 @@ class CreateSourceDialog extends React.Component {
<Button
key="submit"
htmlType="submit"
form={this.formId}
form="sourceForm"
type="primary"
loading={savingSource}
data-test="CreateSourceSaveButton">

View File

@@ -86,7 +86,6 @@ export default class EditInPlace extends React.Component {
return (
<InputComponent
defaultValue={value}
aria-label="Editing"
onBlur={e => this.stopEditing(e.target.value)}
onKeyDown={this.handleKeyDown}
autoFocus

View File

@@ -1,5 +1,5 @@
import { includes, words, capitalize, clone, isNull } from "lodash";
import React, { useState, useEffect } from "react";
import { includes, words, capitalize, clone, isNull, map, get, find } from "lodash";
import React, { useState, useEffect, useRef, useMemo } from "react";
import PropTypes from "prop-types";
import Checkbox from "antd/lib/checkbox";
import Modal from "antd/lib/modal";
@@ -11,7 +11,8 @@ import Divider from "antd/lib/divider";
import { wrap as wrapDialog, DialogPropType } from "@/components/DialogWrapper";
import QuerySelector from "@/components/QuerySelector";
import { Query } from "@/services/query";
import { useUniqueId } from "@/lib/hooks/useUniqueId";
import { QueryBasedParameterMappingType } from "@/services/parameters/QueryBasedDropdownParameter";
import QueryBasedParameterMappingTable from "./query-based-parameter/QueryBasedParameterMappingTable";
const { Option } = Select;
const formItemProps = { labelCol: { span: 6 }, wrapperCol: { span: 16 } };
@@ -70,17 +71,27 @@ NameInput.propTypes = {
function EditParameterSettingsDialog(props) {
const [param, setParam] = useState(clone(props.parameter));
const [isNameValid, setIsNameValid] = useState(true);
const [initialQuery, setInitialQuery] = useState();
const [paramQuery, setParamQuery] = useState();
const mappingParameters = useMemo(
() =>
map(paramQuery && paramQuery.getParametersDefs(), mappingParam => ({
mappingParam,
existingMapping: get(param.parameterMapping, mappingParam.name, {
mappingType: QueryBasedParameterMappingType.UNDEFINED,
}),
})),
[param.parameterMapping, paramQuery]
);
const isNew = !props.parameter.name;
// fetch query by id
const initialQueryId = useRef(props.parameter.queryId);
useEffect(() => {
const queryId = props.parameter.queryId;
if (queryId) {
Query.get({ id: queryId }).then(setInitialQuery);
if (initialQueryId.current) {
Query.get({ id: initialQueryId.current }).then(setParamQuery);
}
}, [props.parameter.queryId]);
}, []);
function isFulfilled() {
// name
@@ -94,8 +105,14 @@ function EditParameterSettingsDialog(props) {
}
// query
if (param.type === "query" && !param.queryId) {
return false;
if (param.type === "query") {
if (!param.queryId) {
return false;
}
if (find(mappingParameters, { existingMapping: { mappingType: QueryBasedParameterMappingType.UNDEFINED } })) {
return false;
}
}
return true;
@@ -112,8 +129,6 @@ function EditParameterSettingsDialog(props) {
props.dialog.close(param);
}
const paramFormId = useUniqueId("paramForm");
return (
<Modal
{...props.dialog.props}
@@ -128,12 +143,12 @@ function EditParameterSettingsDialog(props) {
htmlType="submit"
disabled={!isFulfilled()}
type="primary"
form={paramFormId}
form="paramForm"
data-test="SaveParameterSettings">
{isNew ? "Add Parameter" : "OK"}
</Button>,
]}>
<Form layout="horizontal" onFinish={onConfirm} id={paramFormId}>
<Form layout="horizontal" onFinish={onConfirm} id="paramForm">
{isNew && (
<NameInput
name={param.name}
@@ -190,14 +205,28 @@ function EditParameterSettingsDialog(props) {
</Form.Item>
)}
{param.type === "query" && (
<Form.Item label="Query" help="Select query to load dropdown values from" {...formItemProps}>
<Form.Item label="Query" help="Select query to load dropdown values from" required {...formItemProps}>
<QuerySelector
selectedQuery={initialQuery}
onChange={q => setParam({ ...param, queryId: q && q.id })}
selectedQuery={paramQuery}
onChange={q => {
if (q) {
setParamQuery(q);
setParam({ ...param, queryId: q.id, parameterMapping: {} });
}
}}
type="select"
/>
</Form.Item>
)}
{param.type === "query" && paramQuery && paramQuery.hasParameters() && (
<Form.Item className="m-t-15 m-b-5" label="Parameters" required {...formItemProps}>
<QueryBasedParameterMappingTable
param={param}
mappingParameters={mappingParameters}
onChangeParam={setParam}
/>
</Form.Item>
)}
{(param.type === "enum" || param.type === "query") && (
<Form.Item className="m-b-0" label=" " colon={false} {...formItemProps}>
<Checkbox

View File

@@ -0,0 +1,134 @@
import React, { useState, useEffect, useRef, useReducer } from "react";
import PropTypes from "prop-types";
import { values } from "lodash";
import Button from "antd/lib/button";
import Tooltip from "antd/lib/tooltip";
import Radio from "antd/lib/radio";
import Typography from "antd/lib/typography/Typography";
import ParameterValueInput from "@/components/ParameterValueInput";
import InputPopover from "@/components/InputPopover";
import Form from "antd/lib/form";
import { QueryBasedParameterMappingType } from "@/services/parameters/QueryBasedDropdownParameter";
import QuestionCircleFilledIcon from "@ant-design/icons/QuestionCircleFilled";
import EditOutlinedIcon from "@ant-design/icons/EditOutlined";
const { Text } = Typography;
const formItemProps = { labelCol: { span: 6 }, wrapperCol: { span: 16 } };
export default function QueryBasedParameterMappingEditor({ parameter, mapping, searchAvailable, onChange }) {
const [showPopover, setShowPopover] = useState(false);
const [newMapping, setNewMapping] = useReducer((prevState, updates) => ({ ...prevState, ...updates }), mapping);
const newMappingRef = useRef(newMapping);
useEffect(() => {
if (
mapping.mappingType !== newMappingRef.current.mappingType ||
mapping.staticValue !== newMappingRef.current.staticValue
) {
setNewMapping(mapping);
}
}, [mapping]);
const parameterRef = useRef(parameter);
useEffect(() => {
parameterRef.current.setValue(mapping.staticValue);
}, [mapping.staticValue]);
const onCancel = () => {
setNewMapping(mapping);
setShowPopover(false);
};
const onOk = () => {
onChange(newMapping);
setShowPopover(false);
};
let currentState = <Text type="secondary">Pick a type</Text>;
if (mapping.mappingType === QueryBasedParameterMappingType.DROPDOWN_SEARCH) {
currentState = "Dropdown Search";
} else if (mapping.mappingType === QueryBasedParameterMappingType.STATIC) {
currentState = `Value: ${mapping.staticValue}`;
}
return (
<>
{currentState}
<InputPopover
placement="left"
trigger="click"
header="Edit Parameter Source"
okButtonProps={{
disabled: newMapping.mappingType === QueryBasedParameterMappingType.STATIC && parameter.isEmpty,
}}
onOk={onOk}
onCancel={onCancel}
content={
<Form>
<Form.Item className="m-b-15" label="Source" {...formItemProps}>
<Radio.Group
value={newMapping.mappingType}
onChange={({ target }) => setNewMapping({ mappingType: target.value })}>
<Radio
className="radio"
value={QueryBasedParameterMappingType.DROPDOWN_SEARCH}
disabled={!searchAvailable || parameter.type !== "text"}>
Dropdown Search{" "}
{(!searchAvailable || parameter.type !== "text") && (
<Tooltip
title={
parameter.type !== "text"
? "Dropdown Search is only available for Text Parameters"
: "There is already a parameter mapped with the Dropdown Search type."
}>
<QuestionCircleFilledIcon />
</Tooltip>
)}
</Radio>
<Radio className="radio" value={QueryBasedParameterMappingType.STATIC}>
Static Value
</Radio>
</Radio.Group>
</Form.Item>
{newMapping.mappingType === QueryBasedParameterMappingType.STATIC && (
<Form.Item label="Value" required {...formItemProps}>
<ParameterValueInput
type={parameter.type}
value={parameter.normalizedValue}
enumOptions={parameter.enumOptions}
queryId={parameter.queryId}
parameter={parameter}
onSelect={value => {
parameter.setValue(value);
setNewMapping({ staticValue: parameter.getExecutionValue({ joinListValues: true }) });
}}
/>
</Form.Item>
)}
</Form>
}
visible={showPopover}
onVisibleChange={setShowPopover}>
<Button className="m-l-5" size="small" type="dashed">
<EditOutlinedIcon />
</Button>
</InputPopover>
</>
);
}
QueryBasedParameterMappingEditor.propTypes = {
parameter: PropTypes.object.isRequired, // eslint-disable-line react/forbid-prop-types
mapping: PropTypes.shape({
mappingType: PropTypes.oneOf(values(QueryBasedParameterMappingType)),
staticValue: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
}),
searchAvailable: PropTypes.bool,
onChange: PropTypes.func,
};
QueryBasedParameterMappingEditor.defaultProps = {
mapping: { mappingType: QueryBasedParameterMappingType.UNDEFINED, staticValue: undefined },
searchAvailable: false,
onChange: () => {},
};

View File

@@ -0,0 +1,56 @@
import React from "react";
import { findKey } from "lodash";
import PropTypes from "prop-types";
import Table from "antd/lib/table";
import { QueryBasedParameterMappingType } from "@/services/parameters/QueryBasedDropdownParameter";
import QueryBasedParameterMappingEditor from "./QueryBasedParameterMappingEditor";
export default function QueryBasedParameterMappingTable({ param, mappingParameters, onChangeParam }) {
return (
<Table
dataSource={mappingParameters}
size="middle"
pagination={false}
rowKey={({ mappingParam }) => `param${mappingParam.name}`}>
<Table.Column title="Title" key="title" render={({ mappingParam }) => mappingParam.getTitle()} />
<Table.Column
title="Keyword"
key="keyword"
className="keyword"
render={({ mappingParam }) => <code>{`{{ ${mappingParam.name} }}`}</code>}
/>
<Table.Column
title="Value Source"
key="source"
render={({ mappingParam, existingMapping }) => (
<QueryBasedParameterMappingEditor
parameter={mappingParam.setValue(existingMapping.staticValue)}
mapping={existingMapping}
searchAvailable={
!findKey(param.parameterMapping, {
mappingType: QueryBasedParameterMappingType.DROPDOWN_SEARCH,
}) || existingMapping.mappingType === QueryBasedParameterMappingType.DROPDOWN_SEARCH
}
onChange={mapping =>
onChangeParam({
...param,
parameterMapping: { ...param.parameterMapping, [mappingParam.name]: mapping },
})
}
/>
)}
/>
</Table>
);
}
QueryBasedParameterMappingTable.propTypes = {
param: PropTypes.object.isRequired, // eslint-disable-line react/forbid-prop-types
mappingParameters: PropTypes.arrayOf(PropTypes.object), // eslint-disable-line react/forbid-prop-types
onChangeParam: PropTypes.func,
};
QueryBasedParameterMappingTable.defaultProps = {
mappingParameters: [],
onChangeParam: () => {},
};

View File

@@ -3,7 +3,6 @@ import PropTypes from "prop-types";
import Dropdown from "antd/lib/dropdown";
import Menu from "antd/lib/menu";
import Button from "antd/lib/button";
import PlainButton from "@/components/PlainButton";
import { clientConfig } from "@/services/auth";
import PlusCircleFilledIcon from "@ant-design/icons/PlusCircleFilled";
@@ -19,18 +18,16 @@ export default function QueryControlDropdown(props) {
<Menu>
{!props.query.isNew() && (!props.query.is_draft || !props.query.is_archived) && (
<Menu.Item>
<PlainButton onClick={() => props.openAddToDashboardForm(props.selectedTab)}>
<a target="_self" onClick={() => props.openAddToDashboardForm(props.selectedTab)}>
<PlusCircleFilledIcon /> Add to Dashboard
</PlainButton>
</a>
</Menu.Item>
)}
{!clientConfig.disablePublicUrls && !props.query.isNew() && (
<Menu.Item>
<PlainButton
onClick={() => props.showEmbedDialog(props.query, props.selectedTab)}
data-test="ShowEmbedDialogButton">
<a onClick={() => props.showEmbedDialog(props.query, props.selectedTab)} data-test="ShowEmbedDialogButton">
<ShareAltOutlinedIcon /> Embed Elsewhere
</PlainButton>
</a>
</Menu.Item>
)}
<Menu.Item>

View File

@@ -1,14 +1,12 @@
import React from "react";
import PropTypes from "prop-types";
import cx from "classnames";
import { clientConfig, currentUser } from "@/services/auth";
import Tooltip from "@/components/Tooltip";
import Tooltip from "antd/lib/tooltip";
import Alert from "antd/lib/alert";
import HelpTrigger from "@/components/HelpTrigger";
import { useUniqueId } from "@/lib/hooks/useUniqueId";
export default function EmailSettingsWarning({ featureName, className, mode, adminOnly }) {
const messageDescriptionId = useUniqueId("sr-mail-description");
if (!clientConfig.mailSettingsMissing) {
return null;
}
@@ -18,7 +16,7 @@ export default function EmailSettingsWarning({ featureName, className, mode, adm
}
const message = (
<span id={messageDescriptionId}>
<span>
Your mail server isn&apos;t configured correctly, and is needed for {featureName} to work.{" "}
<HelpTrigger type="MAIL_CONFIG" className="f-inherit" />
</span>
@@ -26,11 +24,8 @@ export default function EmailSettingsWarning({ featureName, className, mode, adm
if (mode === "icon") {
return (
<Tooltip title={message} placement="topRight" arrowPointAtCenter>
{/* eslint-disable-next-line jsx-a11y/no-noninteractive-tabindex */}
<span className={className} aria-label="Mail alert" aria-describedby={messageDescriptionId} tabIndex={0}>
<i className={"fa fa-exclamation-triangle"} aria-hidden="true" />
</span>
<Tooltip title={message}>
<i className={cx("fa fa-exclamation-triangle", className)} />
</Tooltip>
);
}

View File

@@ -1,6 +1,5 @@
import React from "react";
import PropTypes from "prop-types";
import PlainButton from "@/components/PlainButton";
export default class FavoritesControl extends React.Component {
static propTypes = {
@@ -30,13 +29,12 @@ export default class FavoritesControl extends React.Component {
const icon = item.is_favorite ? "fa fa-star" : "fa fa-star-o";
const title = item.is_favorite ? "Remove from favorites" : "Add to favorites";
return (
<PlainButton
<a
title={title}
aria-label={title}
className="favorites-control btn-favorite"
className="favorites-control btn-favourite"
onClick={event => this.toggleItem(event, item, onChange)}>
<i className={icon} aria-hidden="true" />
</PlainButton>
</a>
);
}
}

View File

@@ -112,11 +112,11 @@ function Filters({ filters, onChange }) {
{!filter.multiple && options}
{filter.multiple && [
<Select.Option key={NONE_VALUES} data-test="ClearOption">
<i className="fa fa-square-o m-r-5" aria-hidden="true" />
<i className="fa fa-square-o m-r-5" />
Clear
</Select.Option>,
<Select.Option key={ALL_VALUES} data-test="SelectAllOption">
<i className="fa fa-check-square-o m-r-5" aria-hidden="true" />
<i className="fa fa-check-square-o m-r-5" />
Select All
</Select.Option>,
<Select.OptGroup key="Values" title="Values">

View File

@@ -2,10 +2,9 @@ import { startsWith, get, some, mapValues } from "lodash";
import React from "react";
import PropTypes from "prop-types";
import cx from "classnames";
import Tooltip from "@/components/Tooltip";
import Tooltip from "antd/lib/tooltip";
import Drawer from "antd/lib/drawer";
import Link from "@/components/Link";
import PlainButton from "@/components/PlainButton";
import CloseOutlinedIcon from "@ant-design/icons/CloseOutlined";
import BigMessage from "@/components/BigMessage";
import DynamicComponent, { registerComponent } from "@/components/DynamicComponent";
@@ -46,7 +45,7 @@ export const TYPES = mapValues(
NUMBER_FORMAT_SPECS: ["/user-guide/visualizations/formatting-numbers", "Formatting Numbers"],
GETTING_STARTED: ["/user-guide/getting-started", "Guide: Getting Started"],
DASHBOARDS: ["/user-guide/dashboards", "Guide: Dashboards"],
QUERIES: ["/user-guide/querying", "Guide: Queries"],
QUERIES: ["/help/user-guide/querying", "Guide: Queries"],
ALERTS: ["/user-guide/alerts", "Guide: Alerts"],
},
([url, title]) => [DOMAIN + HELP_PATH + url, title]
@@ -69,7 +68,7 @@ const HelpTriggerDefaultProps = {
className: null,
showTooltip: true,
renderAsLink: false,
children: <i className="fa fa-question-circle" aria-hidden="true" />,
children: <i className="fa fa-question-circle" />,
};
export function helpTriggerWithTypes(types, allowedDomains = [], drawerClassName = null) {
@@ -171,13 +170,7 @@ export function helpTriggerWithTypes(types, allowedDomains = [], drawerClassName
this.props.showTooltip ? (
<>
{tooltip}
{shouldRenderAsLink && (
<>
{" "}
<i className="fa fa-external-link" style={{ marginLeft: 5 }} aria-hidden="true" />
<span className="sr-only">(opens in a new tab)</span>
</>
)}
{shouldRenderAsLink && <i className="fa fa-external-link" style={{ marginLeft: 5 }} />}
</>
) : null
}>
@@ -204,15 +197,14 @@ export function helpTriggerWithTypes(types, allowedDomains = [], drawerClassName
<Tooltip title="Open page in a new window" placement="left">
{/* eslint-disable-next-line react/jsx-no-target-blank */}
<Link href={url} target="_blank">
<i className="fa fa-external-link" aria-hidden="true" />
<span className="sr-only">(opens in a new tab)</span>
<i className="fa fa-external-link" />
</Link>
</Tooltip>
)}
<Tooltip title="Close" placement="bottom">
<PlainButton onClick={this.closeDrawer}>
<a onClick={this.closeDrawer}>
<CloseOutlinedIcon />
</PlainButton>
</a>
</Tooltip>
</div>

View File

@@ -1,4 +1,4 @@
@import (reference, less) "~@/assets/less/ant";
@import "~antd/lib/drawer/style/drawer";
@help-doc-bg: #f7f7f7; // according to https://github.com/getredash/website/blob/13daff2d8b570956565f482236f6245042e8477f/src/scss/_components/_variables.scss#L15
@@ -38,8 +38,7 @@
border: 2px solid @help-doc-bg;
display: flex;
a,
.plain-button {
a {
height: 26px;
width: 26px;
display: flex;

View File

@@ -0,0 +1,57 @@
import React from "react";
import PropTypes from "prop-types";
import Button from "antd/lib/button";
import Popover from "antd/lib/popover";
import "./index.less";
export default function InputPopover({
header,
content,
children,
okButtonProps,
cancelButtonProps,
onCancel,
onOk,
...props
}) {
return (
<Popover
{...props}
content={
<div className="input-popover-content" data-test="InputPopoverContent">
{header && <header>{header}</header>}
{content}
<footer>
<Button onClick={onCancel} {...cancelButtonProps}>
Cancel
</Button>
<Button onClick={onOk} type="primary" {...okButtonProps}>
OK
</Button>
</footer>
</div>
}>
{children}
</Popover>
);
}
InputPopover.propTypes = {
header: PropTypes.node,
content: PropTypes.node,
children: PropTypes.node,
okButtonProps: PropTypes.object,
cancelButtonProps: PropTypes.object,
onOk: PropTypes.func,
onCancel: PropTypes.func,
};
InputPopover.defaultProps = {
header: null,
children: null,
okButtonProps: null,
cancelButtonProps: null,
onOk: () => {},
onCancel: () => {},
};

View File

@@ -0,0 +1,37 @@
@import "~antd/lib/modal/style/index"; // for ant @vars
.input-popover-content {
width: 390px;
.radio {
display: block;
height: 30px;
line-height: 30px;
}
.form-item {
margin-bottom: 10px;
}
header {
padding: 0 16px 10px;
margin: 0 -16px 20px;
border-bottom: @border-width-base @border-style-base @border-color-split;
font-size: @font-size-lg;
font-weight: 500;
color: @heading-color;
display: flex;
justify-content: space-between;
}
footer {
border-top: @border-width-base @border-style-base @border-color-split;
padding: 10px 16px 0;
margin: 0 -16px;
text-align: right;
button {
margin-left: 8px;
}
}
}

View File

@@ -1,8 +1,7 @@
import React from "react";
import Input from "antd/lib/input";
import CopyOutlinedIcon from "@ant-design/icons/CopyOutlined";
import Tooltip from "@/components/Tooltip";
import PlainButton from "./PlainButton";
import Tooltip from "antd/lib/tooltip";
export default class InputWithCopy extends React.Component {
constructor(props) {
@@ -43,10 +42,7 @@ export default class InputWithCopy extends React.Component {
render() {
const copyButton = (
<Tooltip title={this.state.copied || "Copy"}>
<PlainButton onClick={this.copy}>
{/* TODO: lacks visual feedback */}
<CopyOutlinedIcon />
</PlainButton>
<CopyOutlinedIcon style={{ cursor: "pointer" }} onClick={this.copy} />
</Tooltip>
);

View File

@@ -0,0 +1,26 @@
import React from "react";
import Button from "antd/lib/button";
function DefaultLinkComponent(props) {
return <a {...props} />; // eslint-disable-line jsx-a11y/anchor-has-content
}
function Link(props) {
return <Link.Component {...props} />;
}
Link.Component = DefaultLinkComponent;
function DefaultButtonLinkComponent(props) {
return <Button role="button" {...props} />;
}
function ButtonLink(props) {
return <ButtonLink.Component {...props} />;
}
ButtonLink.Component = DefaultButtonLinkComponent;
Link.Button = ButtonLink;
export default Link;

View File

@@ -1,61 +0,0 @@
import React from "react";
import Button, { ButtonProps as AntdButtonProps } from "antd/lib/button";
function DefaultLinkComponent({ children, ...props }: React.AnchorHTMLAttributes<HTMLAnchorElement>) {
return <a {...props}>{children}</a>;
}
Link.Component = DefaultLinkComponent;
interface LinkProps extends Omit<React.AnchorHTMLAttributes<HTMLAnchorElement>, "role" | "type" | "target"> {
href: string;
}
function Link({ children, ...props }: LinkProps) {
return <Link.Component {...props}>{children}</Link.Component>;
}
interface LinkWithIconProps extends LinkProps {
children: string;
icon: JSX.Element;
alt: string;
target?: "_self" | "_blank" | "_parent" | "_top";
}
function LinkWithIcon({ icon, alt, children, ...props }: LinkWithIconProps) {
return (
<Link.Component {...props}>
{children} {icon} <span className="sr-only">{alt}</span>
</Link.Component>
);
}
Link.WithIcon = LinkWithIcon;
function ExternalLink({
icon = <i className="fa fa-external-link" aria-hidden="true" />,
alt = "(opens in a new tab)",
...props
}: Omit<LinkWithIconProps, "target">) {
return <Link.WithIcon target="_blank" rel="noopener noreferrer" icon={icon} alt={alt} {...props} />;
}
Link.External = ExternalLink;
// Ant Button will render an <a> if href is present.
function DefaultButtonLinkComponent(props: ButtonProps) {
return <Button {...props} />;
}
ButtonLink.Component = DefaultButtonLinkComponent;
interface ButtonProps extends AntdButtonProps {
href: string;
}
function ButtonLink(props: ButtonProps) {
return <ButtonLink.Component {...props} />;
}
Link.Button = ButtonLink;
export default Link;

View File

@@ -2,26 +2,21 @@ import React from "react";
import PropTypes from "prop-types";
import Button from "antd/lib/button";
import Badge from "antd/lib/badge";
import Tooltip from "@/components/Tooltip";
import Tooltip from "antd/lib/tooltip";
import KeyboardShortcuts from "@/services/KeyboardShortcuts";
function ParameterApplyButton({ paramCount, onClick }) {
// show spinner when count is empty so the fade out is consistent
const icon = !paramCount ? (
<span role="status" aria-live="polite" aria-relevant="additions removals">
<i className="fa fa-spinner fa-pulse" aria-hidden="true" />
<span className="sr-only">Loading...</span>
</span>
) : (
<i className="fa fa-check" aria-hidden="true" />
);
const icon = !paramCount ? "spinner fa-pulse" : "check";
return (
<div className="parameter-apply-button" data-show={!!paramCount} data-test="ParameterApplyButton">
<Badge count={paramCount}>
<Tooltip title={paramCount ? `${KeyboardShortcuts.modKey} + Enter` : null}>
<span>
<Button onClick={onClick}>{icon} Apply Changes</Button>
<Button onClick={onClick}>
<i className={`fa fa-${icon}`} /> Apply Changes
</Button>
</span>
</Tooltip>
</Badge>

View File

@@ -12,11 +12,12 @@ import Tag from "antd/lib/tag";
import Input from "antd/lib/input";
import Radio from "antd/lib/radio";
import Form from "antd/lib/form";
import Tooltip from "@/components/Tooltip";
import Tooltip from "antd/lib/tooltip";
import ParameterValueInput from "@/components/ParameterValueInput";
import { ParameterMappingType } from "@/services/widget";
import { Parameter, cloneParameter } from "@/services/parameters";
import HelpTrigger from "@/components/HelpTrigger";
import InputPopover from "@/components/InputPopover";
import QuestionCircleFilledIcon from "@ant-design/icons/QuestionCircleFilled";
import EditOutlinedIcon from "@ant-design/icons/EditOutlined";
@@ -201,13 +202,7 @@ export class ParameterMappingInput extends React.Component {
const {
mapping: { mapTo },
} = this.props;
return (
<Input
value={mapTo}
aria-label="Parameter name (key)"
onChange={e => this.updateParamMapping({ mapTo: e.target.value })}
/>
);
return <Input value={mapTo} onChange={e => this.updateParamMapping({ mapTo: e.target.value })} />;
}
renderDashboardMapToExisting() {
@@ -319,43 +314,34 @@ class MappingEditor extends React.Component {
this.setState({ visible: false });
};
renderContent() {
const { mapping, inputError } = this.state;
return (
<div className="parameter-mapping-editor" data-test="EditParamMappingPopover">
<header>
Edit Source and Value <HelpTrigger type="VALUE_SOURCE_OPTIONS" />
</header>
<ParameterMappingInput
mapping={mapping}
existingParamNames={this.props.existingParamNames}
onChange={this.onChange}
inputError={inputError}
/>
<footer>
<Button onClick={this.hide}>Cancel</Button>
<Button onClick={this.save} disabled={!!inputError} type="primary">
OK
</Button>
</footer>
</div>
);
}
render() {
const { visible, mapping } = this.state;
const { visible, mapping, inputError } = this.state;
return (
<Popover
<InputPopover
placement="left"
trigger="click"
content={this.renderContent()}
header={
<>
Edit Source and Value <HelpTrigger type="VALUE_SOURCE_OPTIONS" />
</>
}
content={
<ParameterMappingInput
mapping={mapping}
existingParamNames={this.props.existingParamNames}
onChange={this.onChange}
inputError={inputError}
/>
}
onOk={this.save}
onCancel={this.hide}
okButtonProps={{ disabled: !!inputError }}
visible={visible}
onVisibleChange={this.onVisibleChange}>
<Button size="small" type="dashed" data-test={`EditParamMappingButton-${mapping.param.name}`}>
<EditOutlinedIcon />
</Button>
</Popover>
</InputPopover>
);
}
}
@@ -426,7 +412,6 @@ class TitleEditor extends React.Component {
size="small"
value={this.state.title}
placeholder={paramTitle}
aria-label="Edit parameter title"
onChange={this.onEditingTitleChange}
onPressEnter={this.save}
maxLength={100}
@@ -447,10 +432,7 @@ class TitleEditor extends React.Component {
if (mapping.type === MappingType.StaticValue) {
return (
<Tooltip placement="right" title="Titles for static values don't appear in widgets">
{/* eslint-disable-next-line jsx-a11y/no-noninteractive-tabindex */}
<span tabIndex={0}>
<i className="fa fa-eye-slash" aria-hidden="true" />
</span>
<i className="fa fa-eye-slash" />
</Tooltip>
);
}

View File

@@ -1,4 +1,4 @@
@import (reference, less) "~@/assets/less/ant"; // for ant @vars
@import "~antd/lib/modal/style/index"; // for ant @vars
.parameters-mapping-list {
.keyword {
@@ -22,42 +22,6 @@
}
}
.parameter-mapping-editor {
width: 390px;
.radio {
display: block;
height: 30px;
line-height: 30px;
}
.form-item {
margin-bottom: 10px;
}
header {
padding: 0 16px 10px;
margin: 0 -16px 20px;
border-bottom: @border-width-base @border-style-base @border-color-split;
font-size: @font-size-lg;
font-weight: 500;
color: @heading-color;
display: flex;
justify-content: space-between;
}
footer {
border-top: @border-width-base @border-style-base @border-color-split;
padding: 10px 16px 0;
margin: 0 -16px;
text-align: right;
button {
margin-left: 8px;
}
}
}
.parameter-mapping-title {
.text {
margin-right: 3px;

View File

@@ -101,6 +101,7 @@ class ParameterValueInput extends React.Component {
<SelectWithVirtualScroll
className={this.props.className}
mode={parameter.multiValuesOptions ? "multiple" : "default"}
optionFilterProp="children"
value={normalize(value)}
onChange={this.onSelect}
options={map(enumOptionsArray, opt => ({ label: String(opt), value: opt }))}
@@ -119,6 +120,7 @@ class ParameterValueInput extends React.Component {
<QueryBasedParameterInput
className={this.props.className}
mode={parameter.multiValuesOptions ? "multiple" : "default"}
optionFilterProp="children"
parameter={parameter}
value={value}
queryId={queryId}
@@ -136,12 +138,7 @@ class ParameterValueInput extends React.Component {
const normalize = val => (isNaN(val) ? undefined : val);
return (
<InputNumber
className={className}
value={normalize(value)}
aria-label="Parameter number value"
onChange={val => this.onSelect(normalize(val))}
/>
<InputNumber className={className} value={normalize(value)} onChange={val => this.onSelect(normalize(val))} />
);
}
@@ -153,7 +150,6 @@ class ParameterValueInput extends React.Component {
<Input
className={className}
value={value}
aria-label="Parameter text value"
data-test="TextParamInput"
onChange={e => this.onSelect(e.target.value)}
/>

View File

@@ -1,4 +1,4 @@
@import (reference, less) "~@/assets/less/ant"; // for ant @vars
@import "~antd/lib/input-number/style/index"; // for ant @vars
@input-dirty: #fffce1;
@@ -21,7 +21,7 @@
.@{ant-prefix}-input-number,
.@{ant-prefix}-select-selector,
.@{ant-prefix}-picker {
background-color: @input-dirty;
background-color: @input-dirty !important;
}
}
}

View File

@@ -1,4 +1,4 @@
import { size, filter, forEach, extend, isEmpty } from "lodash";
import { size, filter, forEach, extend } from "lodash";
import React from "react";
import PropTypes from "prop-types";
import { SortableContainer, SortableElement, DragHandle } from "@redash/viz/lib/components/sortable";
@@ -6,9 +6,7 @@ import location from "@/services/location";
import { Parameter, createParameter } from "@/services/parameters";
import ParameterApplyButton from "@/components/ParameterApplyButton";
import ParameterValueInput from "@/components/ParameterValueInput";
import PlainButton from "@/components/PlainButton";
import EditParameterSettingsDialog from "./EditParameterSettingsDialog";
import { toHuman } from "@/lib/utils";
import "./Parameters.less";
@@ -24,42 +22,28 @@ export default class Parameters extends React.Component {
static propTypes = {
parameters: PropTypes.arrayOf(PropTypes.instanceOf(Parameter)),
editable: PropTypes.bool,
sortable: PropTypes.bool,
disableUrlUpdate: PropTypes.bool,
onValuesChange: PropTypes.func,
onPendingValuesChange: PropTypes.func,
onParametersEdit: PropTypes.func,
appendSortableToParent: PropTypes.bool,
};
static defaultProps = {
parameters: [],
editable: false,
sortable: false,
disableUrlUpdate: false,
onValuesChange: () => {},
onPendingValuesChange: () => {},
onParametersEdit: () => {},
appendSortableToParent: true,
};
toCamelCase = str => {
if (isEmpty(str)) {
return "";
}
return str.replace(/\s+/g, "").toLowerCase();
};
constructor(props) {
super(props);
const { parameters, disableUrlUpdate } = props;
const { parameters } = props;
this.state = { parameters };
if (!disableUrlUpdate) {
if (!props.disableUrlUpdate) {
updateUrl(parameters);
}
const hideRegex = /hide_filter=([^&]+)/g;
const matches = window.location.search.matchAll(hideRegex);
this.hideValues = Array.from(matches, match => match[1]);
}
componentDidUpdate = prevProps => {
@@ -100,7 +84,7 @@ export default class Parameters extends React.Component {
if (oldIndex !== newIndex) {
this.setState(({ parameters }) => {
parameters.splice(newIndex, 0, parameters.splice(oldIndex, 1)[0]);
onParametersEdit(parameters);
onParametersEdit();
return { parameters };
});
}
@@ -125,36 +109,28 @@ export default class Parameters extends React.Component {
this.setState(({ parameters }) => {
const updatedParameter = extend(parameter, updated);
parameters[index] = createParameter(updatedParameter, updatedParameter.parentQueryId);
onParametersEdit(parameters);
onParametersEdit();
return { parameters };
});
});
};
renderParameter(param, index) {
if (this.hideValues.some(value => this.toCamelCase(value) === this.toCamelCase(param.name))) {
return null;
}
const { editable } = this.props;
if (param.hidden) {
return null;
}
return (
<div key={param.name} className="di-block" data-test={`ParameterName-${param.name}`}>
<div className="parameter-heading">
<label>{param.title || toHuman(param.name)}</label>
<label>{param.getTitle()}</label>
{editable && (
<PlainButton
<button
className="btn btn-default btn-xs m-l-5"
aria-label="Edit"
onClick={() => this.showParameterSettings(param, index)}
data-test={`ParameterSettings-${param.name}`}
type="button">
<i className="fa fa-cog" aria-hidden="true" />
</PlainButton>
<i className="fa fa-cog" />
</button>
)}
</div>
<ParameterValueInput
type={param.type}
value={param.normalizedValue}
@@ -169,34 +145,29 @@ export default class Parameters extends React.Component {
render() {
const { parameters } = this.state;
const { sortable, appendSortableToParent } = this.props;
const { editable } = this.props;
const dirtyParamCount = size(filter(parameters, "hasPendingValue"));
return (
<SortableContainer
disabled={!sortable}
disabled={!editable}
axis="xy"
useDragHandle
lockToContainerEdges
helperClass="parameter-dragged"
helperContainer={containerEl => (appendSortableToParent ? containerEl : document.body)}
updateBeforeSortStart={this.onBeforeSortStart}
onSortEnd={this.moveParameter}
containerProps={{
className: "parameter-container",
onKeyDown: dirtyParamCount ? this.handleKeyDown : null,
}}>
{parameters &&
parameters.map((param, index) => (
<SortableElement key={param.name} index={index}>
<div
className="parameter-block"
data-editable={sortable || null}
data-test={`ParameterBlock-${param.name}`}>
{sortable && <DragHandle data-test={`DragHandle-${param.name}`} />}
{this.renderParameter(param, index)}
</div>
</SortableElement>
))}
{parameters.map((param, index) => (
<SortableElement key={param.name} index={index}>
<div className="parameter-block" data-editable={editable || null}>
{editable && <DragHandle data-test={`DragHandle-${param.name}`} />}
{this.renderParameter(param, index)}
</div>
</SortableElement>
))}
<ParameterApplyButton onClick={this.applyChanges} paramCount={dirtyParamCount} />
</SortableContainer>
);

View File

@@ -1,4 +1,4 @@
@import (reference, less) "~@/assets/less/ant";
@import "../assets/less/ant";
.parameter-block {
display: inline-block;
@@ -21,8 +21,6 @@
&.parameter-dragged {
z-index: 2;
margin: 4px 0 0 4px;
padding: 3px 6px 6px;
box-shadow: 0 4px 9px -3px rgba(102, 136, 153, 0.15);
}
}

View File

@@ -7,12 +7,11 @@ import List from "antd/lib/list";
import Modal from "antd/lib/modal";
import Select from "antd/lib/select";
import Tag from "antd/lib/tag";
import Tooltip from "@/components/Tooltip";
import Tooltip from "antd/lib/tooltip";
import { wrap as wrapDialog, DialogPropType } from "@/components/DialogWrapper";
import { toHuman } from "@/lib/utils";
import HelpTrigger from "@/components/HelpTrigger";
import { UserPreviewCard } from "@/components/PreviewCard";
import PlainButton from "@/components/PlainButton";
import notification from "@/services/notification";
import User from "@/services/user";
@@ -103,16 +102,7 @@ function UserSelect({ onSelect, shouldShowUser }) {
placeholder="Add users..."
showSearch
onSearch={setSearchTerm}
suffixIcon={
loadingUsers ? (
<span role="status" aria-live="polite" aria-relevant="additions removals">
<i className="fa fa-spinner fa-pulse" aria-hidden="true" />
<span className="sr-only">Loading...</span>
</span>
) : (
<i className="fa fa-search" aria-hidden="true" />
)
}
suffixIcon={loadingUsers ? <i className="fa fa-spinner fa-pulse" /> : <i className="fa fa-search" />}
filterOption={false}
notFoundContent={null}
value={undefined}
@@ -166,12 +156,7 @@ function PermissionsEditorDialog({ dialog, author, context, aclUrl }) {
/>
<div className="d-flex align-items-center m-t-5">
<h5 className="flex-fill">Users with permissions</h5>
{loadingGrantees && (
<span role="status" aria-live="polite" aria-relevant="additions removals">
<i className="fa fa-spinner fa-pulse" aria-hidden="true" />
<span className="sr-only">Loading...</span>
</span>
)}
{loadingGrantees && <i className="fa fa-spinner fa-pulse" />}
</div>
<div className="scrollbox p-5" style={{ maxHeight: "40vh" }}>
<List
@@ -184,11 +169,10 @@ function PermissionsEditorDialog({ dialog, author, context, aclUrl }) {
<Tag className="m-0">Author</Tag>
) : (
<Tooltip title="Remove user permissions">
<PlainButton
aria-label="Remove permissions"
onClick={() => removePermission(user.id).then(loadUsersWithPermissions)}>
<i className="fa fa-remove clickable" aria-hidden="true" />
</PlainButton>
<i
className="fa fa-remove clickable"
onClick={() => removePermission(user.id).then(loadUsersWithPermissions)}
/>
</Tooltip>
)}
</UserPreviewCard>

View File

@@ -1,22 +0,0 @@
@import (reference, less) "~@/assets/less/ant";
.plain-button {
all: unset;
transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
.@{dropdown-prefix-cls}-menu-item > & {
width: 100%;
margin: -5px -12px;
padding: 5px 12px;
}
.@{menu-prefix-cls}-item > & {
width: 100%;
margin: 0 -16px;
padding: 0 16px;
}
}
.plain-button-link {
.btn-link();
}

View File

@@ -1,20 +0,0 @@
import classNames from "classnames";
import React from "react";
import "./PlainButton.less";
export interface PlainButtonProps extends Omit<React.ButtonHTMLAttributes<HTMLButtonElement>, "type"> {
type?: "link" | "button";
}
function PlainButton({ className, type, ...rest }: PlainButtonProps) {
return (
<button
className={classNames("plain-button", "clickable", { "plain-button-link": type === "link" }, className)}
type="button"
{...rest}
/>
);
}
export default PlainButton;

View File

@@ -1,8 +1,19 @@
import { find, isArray, get, first, map, intersection, isEqual, isEmpty } from "lodash";
import { find, isArray, get, first, map, intersection, isEqual, isEmpty, trim, debounce, isNil } from "lodash";
import React from "react";
import PropTypes from "prop-types";
import SelectWithVirtualScroll from "@/components/SelectWithVirtualScroll";
const SEARCH_DEBOUNCE_TIME = 300;
function filterValuesThatAreNotInOptions(value, options) {
if (isArray(value)) {
const optionValues = map(options, option => option.value);
return intersection(value, optionValues);
}
const found = find(options, option => option.value === value) !== undefined;
return found ? value : get(first(options), "value");
}
export default class QueryBasedParameterInput extends React.Component {
static propTypes = {
parameter: PropTypes.any, // eslint-disable-line react/forbid-prop-types
@@ -28,6 +39,7 @@ export default class QueryBasedParameterInput extends React.Component {
options: [],
value: null,
loading: false,
currentSearchTerm: null,
};
}
@@ -36,9 +48,10 @@ export default class QueryBasedParameterInput extends React.Component {
}
componentDidUpdate(prevProps) {
if (this.props.queryId !== prevProps.queryId) {
if (this.props.queryId !== prevProps.queryId || this.props.parameter !== prevProps.parameter) {
this._loadOptions(this.props.queryId);
}
if (this.props.value !== prevProps.value) {
this.setValue(this.props.value);
}
@@ -46,53 +59,85 @@ export default class QueryBasedParameterInput extends React.Component {
setValue(value) {
const { options } = this.state;
if (this.props.mode === "multiple") {
const { mode, parameter } = this.props;
if (mode === "multiple") {
if (isNil(value)) {
value = [];
}
value = isArray(value) ? value : [value];
const optionValues = map(options, option => option.value);
const validValues = intersection(value, optionValues);
this.setState({ value: validValues });
return validValues;
}
const found = find(options, option => option.value === this.props.value) !== undefined;
value = found ? value : get(first(options), "value");
// parameters with search don't have options available, so we trust what we get
if (!parameter.searchFunction) {
value = filterValuesThatAreNotInOptions(value, options);
}
this.setState({ value });
return value;
}
updateOptions(options) {
this.setState({ options, loading: false }, () => {
const updatedValue = this.setValue(this.props.value);
if (!isEqual(updatedValue, this.props.value)) {
this.props.onSelect(updatedValue);
}
});
}
async _loadOptions(queryId) {
if (queryId && queryId !== this.state.queryId) {
this.setState({ loading: true });
const options = await this.props.parameter.loadDropdownValues();
const options = await this.props.parameter.loadDropdownValues(this.state.currentSearchTerm);
// stale queryId check
if (this.props.queryId === queryId) {
this.setState({ options, loading: false }, () => {
const updatedValue = this.setValue(this.props.value);
if (!isEqual(updatedValue, this.props.value)) {
this.props.onSelect(updatedValue);
}
});
this.updateOptions(options);
}
}
}
searchFunction = debounce(searchTerm => {
const { parameter } = this.props;
if (parameter.searchFunction && trim(searchTerm)) {
this.setState({ loading: true, currentSearchTerm: searchTerm });
parameter.searchFunction(searchTerm).then(options => {
if (this.state.currentSearchTerm === searchTerm) {
this.updateOptions(options);
}
});
}
}, SEARCH_DEBOUNCE_TIME);
render() {
const { className, mode, onSelect, queryId, value, ...otherProps } = this.props;
const { parameter, className, mode, onSelect, queryId, value, ...otherProps } = this.props;
const { loading, options } = this.state;
const selectProps = { ...otherProps };
if (parameter.searchColumn) {
selectProps.filterOption = false;
selectProps.onSearch = this.searchFunction;
selectProps.onChange = value => onSelect(parameter.normalizeValue(value));
selectProps.notFoundContent = null;
selectProps.labelInValue = true;
}
return (
<span>
<SelectWithVirtualScroll
className={className}
disabled={loading}
disabled={!parameter.searchFunction && loading}
loading={loading}
mode={mode}
value={this.state.value}
value={this.state.value || undefined}
onChange={onSelect}
options={map(options, ({ value, name }) => ({ label: String(name), value }))}
options={options}
optionFilterProp="children"
showSearch
showArrow
notFoundContent={isEmpty(options) ? "No options available" : null}
{...otherProps}
{...selectProps}
/>
</span>
);

View File

@@ -21,12 +21,10 @@ function QueryLink({ query, visualization, readOnly }) {
return query.getUrl(false, hash);
};
const QueryLinkWrapper = props => (readOnly ? <span {...props} /> : <Link href={getUrl()} {...props} />);
return (
<QueryLinkWrapper className="query-link">
<Link href={readOnly ? null : getUrl()} className="query-link">
<VisualizationName visualization={visualization} /> <span>{query.name}</span>
</QueryLinkWrapper>
</Link>
);
}

Some files were not shown because too many files have changed in this diff Show More