Compare commits
165 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8a9f4b3c0a | ||
|
|
77468d34ae | ||
|
|
a0577ec0ce | ||
|
|
e7d1398546 | ||
|
|
aa52048d51 | ||
|
|
33913f8f5c | ||
|
|
51eb7a543c | ||
|
|
a3fb38b23c | ||
|
|
3bb40b4eb7 | ||
|
|
6864bf84f8 | ||
|
|
9f1b3823f6 | ||
|
|
7574f529c3 | ||
|
|
653f8eff7b | ||
|
|
9b3dda6cff | ||
|
|
d94604ebfb | ||
|
|
16868ef430 | ||
|
|
b162c7043e | ||
|
|
8e856063b8 | ||
|
|
8684b4cef9 | ||
|
|
bcaebd4840 | ||
|
|
4619461af8 | ||
|
|
9fff1d699a | ||
|
|
5ab19c3fae | ||
|
|
cc483f4720 | ||
|
|
a07f2d3d99 | ||
|
|
b9844b8696 | ||
|
|
464bff3db8 | ||
|
|
00e434e142 | ||
|
|
5d6280abec | ||
|
|
7a39e905b9 | ||
|
|
297ea2c18a | ||
|
|
1f2327a724 | ||
|
|
6d512422cf | ||
|
|
8ce9a01372 | ||
|
|
acd56a85cb | ||
|
|
a45e218e3f | ||
|
|
a2bc495259 | ||
|
|
7f4b167dc2 | ||
|
|
5ded99e89f | ||
|
|
a991b02a20 | ||
|
|
9b6aa3d6c7 | ||
|
|
92022f9083 | ||
|
|
15636fed5f | ||
|
|
9ed53e0d25 | ||
|
|
35baaf2722 | ||
|
|
453098b410 | ||
|
|
a469de3674 | ||
|
|
24411ac18f | ||
|
|
a7ef152140 | ||
|
|
97c0c6191b | ||
|
|
9a91dd19bf | ||
|
|
472794e203 | ||
|
|
58d4a7bacd | ||
|
|
d0c624a3cc | ||
|
|
9e29a12ebb | ||
|
|
fdbac941d5 | ||
|
|
628e9cee62 | ||
|
|
803622f18f | ||
|
|
edd45b317a | ||
|
|
6ce5d2b201 | ||
|
|
5c9a5560b7 | ||
|
|
13a8b33815 | ||
|
|
5ba371e339 | ||
|
|
5db8376f95 | ||
|
|
be56079e4e | ||
|
|
a7c8c29624 | ||
|
|
9ce1c27cf5 | ||
|
|
b2d21cc859 | ||
|
|
1945467dc7 | ||
|
|
73c0936927 | ||
|
|
8867092601 | ||
|
|
c7039e144a | ||
|
|
b30eeb6788 | ||
|
|
c2864b4308 | ||
|
|
ba75685a23 | ||
|
|
9314e27d0e | ||
|
|
d4d68bb682 | ||
|
|
05b642bc86 | ||
|
|
62386d3fc0 | ||
|
|
2acfc75da2 | ||
|
|
98cc09741c | ||
|
|
abc852624a | ||
|
|
7791f477cb | ||
|
|
eb950c1b9c | ||
|
|
e60a28ca23 | ||
|
|
4b67fb268b | ||
|
|
8f445ba570 | ||
|
|
0bf5300c9d | ||
|
|
a8e12d64a0 | ||
|
|
aa63aa94ee | ||
|
|
8decda51a4 | ||
|
|
d52f822c15 | ||
|
|
507e978386 | ||
|
|
a457f967c0 | ||
|
|
854d2adfca | ||
|
|
6118a12672 | ||
|
|
7bd8388fd6 | ||
|
|
664c43bce1 | ||
|
|
95d6d6131e | ||
|
|
46757bd5ef | ||
|
|
43cfc8d815 | ||
|
|
6cb0d2d95d | ||
|
|
8e5e2787c7 | ||
|
|
4014aa5730 | ||
|
|
869da1da74 | ||
|
|
3b34f81d56 | ||
|
|
720f23745f | ||
|
|
797430e9f8 | ||
|
|
f6559c1015 | ||
|
|
2974bc6d34 | ||
|
|
f3beeb9f1c | ||
|
|
36f0809546 | ||
|
|
896b8af1a2 | ||
|
|
7e26446573 | ||
|
|
9a7dca3482 | ||
|
|
f6c7c9283e | ||
|
|
840f4fa450 | ||
|
|
d68616b543 | ||
|
|
9e41dab43e | ||
|
|
5006f6935a | ||
|
|
9d38f2a047 | ||
|
|
a787d9afb2 | ||
|
|
82592ed69d | ||
|
|
3bcf0b9ea6 | ||
|
|
cd866fcf50 | ||
|
|
8eb33633e2 | ||
|
|
5c17638a90 | ||
|
|
7550c1e8bd | ||
|
|
82b80e4760 | ||
|
|
6cf22cef09 | ||
|
|
a8f49d9187 | ||
|
|
d45212733d | ||
|
|
f640727d96 | ||
|
|
242b65c446 | ||
|
|
e041e58e7f | ||
|
|
083386383e | ||
|
|
3aa9c144e3 | ||
|
|
ba44a6dfc6 | ||
|
|
8652edc139 | ||
|
|
6886b7903f | ||
|
|
1be139d327 | ||
|
|
86825475f0 | ||
|
|
eb1f71608d | ||
|
|
58401edc35 | ||
|
|
6dede6ee4d | ||
|
|
42199f6ebc | ||
|
|
badcefc4f7 | ||
|
|
b55dec55ee | ||
|
|
8e73e526ec | ||
|
|
fd6d7b8b3a | ||
|
|
6612f4444b | ||
|
|
3168c77c17 | ||
|
|
33a9b261bf | ||
|
|
11721590c1 | ||
|
|
78e803b95d | ||
|
|
8d083a93c4 | ||
|
|
9035cae19f | ||
|
|
e98fa8793b | ||
|
|
ef461be3e5 | ||
|
|
4c2da33d01 | ||
|
|
c3ae115546 | ||
|
|
bbcb553fdc | ||
|
|
08e4f5333d | ||
|
|
dc3979584c | ||
|
|
34764a6e33 |
@@ -12,13 +12,14 @@ module.exports = {
|
||||
},
|
||||
rules: {
|
||||
'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
|
||||
'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off'
|
||||
'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
|
||||
'no-case-declarations': 'off'
|
||||
},
|
||||
overrides: [
|
||||
{
|
||||
files: [
|
||||
'**/__tests__/*.{j,t}s?(x)',
|
||||
'**/tests/unit/**/*.spec.{j,t}s?(x)'
|
||||
'**/tests/**/*.spec.{j,t}s?(x)'
|
||||
],
|
||||
env: {
|
||||
mocha: true
|
||||
|
||||
17
.github/workflows/config.grenrc.js
vendored
Normal file
@@ -0,0 +1,17 @@
|
||||
module.exports = {
|
||||
dataSource: 'milestones',
|
||||
ignoreIssuesWith: [
|
||||
'wontfix',
|
||||
'duplicate'
|
||||
],
|
||||
milestoneMatch: 'v{{tag_name}}',
|
||||
template: {
|
||||
issue: '- {{name}} [{{text}}]({{url}})',
|
||||
changelogTitle: "## Release notes\n\n",
|
||||
release: "{{body}}",
|
||||
},
|
||||
groupBy: {
|
||||
'Enhancements:': ["enhancement", "internal"],
|
||||
'Bug fixes:': ["bug"]
|
||||
}
|
||||
}
|
||||
20
.github/workflows/main.yml
vendored
@@ -25,16 +25,26 @@ jobs:
|
||||
cd dist
|
||||
zip -9 -r dist.zip . -x "js/*.map"
|
||||
|
||||
- name: Create Release Notes
|
||||
run: |
|
||||
npm install github-release-notes@0.16.0 -g
|
||||
gren changelog --generate --config="/.github/workflows/config.grenrc.js"
|
||||
env:
|
||||
GREN_GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Create release
|
||||
uses: ncipollo/release-action@v1
|
||||
with:
|
||||
artifacts: "dist/dist.zip"
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
bodyFile: "CHANGELOG.md"
|
||||
|
||||
- name: Deploy 🚀
|
||||
uses: JamesIves/github-pages-deploy-action@3.6.2
|
||||
uses: JamesIves/github-pages-deploy-action@4.1.1
|
||||
with:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
BRANCH: build # The branch the action should deploy to.
|
||||
FOLDER: dist/ # The folder the action should deploy.
|
||||
CLEAN: false # Automatically remove deleted files from the deploy branch
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
branch: build # The branch the action should deploy to.
|
||||
folder: dist/ # The folder the action should deploy.
|
||||
clean: true # Automatically remove deleted files from the deploy branch
|
||||
clean-exclude: .nojekyll
|
||||
|
||||
|
||||
31
.github/workflows/test.yml
vendored
Normal file
@@ -0,0 +1,31 @@
|
||||
name: Run tests
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches:
|
||||
- 'master'
|
||||
|
||||
jobs:
|
||||
test:
|
||||
name: Run tests
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- name: Use Node.js
|
||||
uses: actions/setup-node@v1
|
||||
with:
|
||||
node-version: 10.x
|
||||
- name: Install browsers
|
||||
run: |
|
||||
export DEBIAN_FRONTEND=noninteractive
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y chromium-browser firefox
|
||||
|
||||
- name: Install the project
|
||||
run: npm install
|
||||
|
||||
- name: Run lint
|
||||
run: npm run lint
|
||||
|
||||
- name: Run karma tests
|
||||
run: npm run test
|
||||
36
README.md
@@ -4,22 +4,38 @@
|
||||
|
||||
# sqliteviz
|
||||
|
||||
**Note: This is a work-in-progress project.**
|
||||
Sqliteviz is a single-page offline-first PWA for fully client-side visualisation of SQLite databases or CSV files.
|
||||
|
||||
Sqliteviz is a single-page application for fully client-side visualisation of SQLite databases.
|
||||
With sqliteviz you can:
|
||||
- run SQL queries against a SQLite database and create [Plotly][11] charts based on the result sets
|
||||
- import a CSV file into a SQLite database and visualize imported data
|
||||
- manage queries and chart settings and run them against different databases
|
||||
- import/export queries and chart settings to/from a JSON file
|
||||
- export a modified SQLite database
|
||||
- use it offline from your OS application menu like any other desktop app
|
||||
|
||||
https://user-images.githubusercontent.com/24638357/117355518-fa332680-aeb2-11eb-8a69-fbcea4f7aeb0.mp4
|
||||
|
||||
## Quickstart
|
||||
The latest release of sqliteviz is deployed on GitHub Pages at [lana-k.github.io/sqliteviz][6].
|
||||
|
||||
## Wiki
|
||||
For user documentation, check out sqliteviz [Wiki][7].
|
||||
|
||||
## Motivation
|
||||
It's a kind of middleground between [Plotly Falcon][1] and [Redash][2].
|
||||
It is built on top of [react-chart-editor][3] and [sql.js][4] in [Vue.js][5].
|
||||
|
||||
## Features
|
||||
|
||||
1. Ad-hoc and prepared visualisation of a SQLite database using flexibility
|
||||
of SQL and richness of Plotly's `react-chart-editor`
|
||||
2. Visualisation pallete, SQL and chart definitions, kept in local
|
||||
storage with import/export
|
||||
3. Integration-side provided pallete
|
||||
## Components
|
||||
It is built on top of [react-chart-editor][3], [sql.js][4] and [Vue-Codemirror][8] in [Vue.js][5]. CSV parsing is performed with [Papa Parse][9].
|
||||
|
||||
[1]: https://github.com/plotly/falcon
|
||||
[2]: https://github.com/getredash/redash
|
||||
[3]: https://github.com/plotly/react-chart-editor
|
||||
[4]: https://github.com/sql-js/sql.js
|
||||
[5]: https://github.com/vuejs/vue
|
||||
[6]: https://lana-k.github.io/sqliteviz/
|
||||
[7]: https://github.com/lana-k/sqliteviz/wiki
|
||||
[8]: https://github.com/surmon-china/vue-codemirror#readme
|
||||
[9]: https://www.papaparse.com/
|
||||
[10]: https://github.com/lana-k/sqliteviz/wiki/Predefined-queries
|
||||
[11]: https://github.com/plotly/plotly.js
|
||||
|
||||
119
karma.conf.js
@@ -1,31 +1,26 @@
|
||||
// Karma configuration
|
||||
"use strict";
|
||||
const path = require("path");
|
||||
const VueLoaderPlugin = require("vue-loader/lib/plugin");
|
||||
'use strict'
|
||||
const path = require('path')
|
||||
const VueLoaderPlugin = require('vue-loader/lib/plugin')
|
||||
|
||||
function resolve(dir) {
|
||||
return path.join(__dirname, dir);
|
||||
function resolve (dir) {
|
||||
return path.join(__dirname, dir)
|
||||
}
|
||||
|
||||
module.exports = function(config) {
|
||||
module.exports = function (config) {
|
||||
config.set({
|
||||
// base path that will be used to resolve all patterns (eg. files, exclude)
|
||||
basePath: "",
|
||||
basePath: '',
|
||||
|
||||
// frameworks to use
|
||||
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
|
||||
frameworks: ["mocha", "sinon-chai"],
|
||||
frameworks: ['mocha', 'sinon-chai'],
|
||||
|
||||
// list of files / patterns to load in the browser
|
||||
files: [
|
||||
"tests/unit/*.spec.js",
|
||||
{ pattern: 'node_modules/sql.js/dist/sql-wasm.wasm',
|
||||
watched: false,
|
||||
included: false,
|
||||
served: true,
|
||||
nocache: false
|
||||
},
|
||||
{ pattern: 'node_modules/sql.js/dist/worker.sql-wasm.js',
|
||||
'./karma.files.js',
|
||||
{
|
||||
pattern: 'node_modules/sql.js/dist/sql-wasm.wasm',
|
||||
watched: false,
|
||||
included: false,
|
||||
served: true,
|
||||
@@ -39,29 +34,29 @@ module.exports = function(config) {
|
||||
// preprocess matching files before serving them to the browser
|
||||
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
|
||||
preprocessors: {
|
||||
"tests/unit/*.spec.js": ["webpack"]
|
||||
'./karma.files.js': ['webpack']
|
||||
},
|
||||
|
||||
// test results reporter to use
|
||||
// possible values: 'dots', 'progress'
|
||||
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
|
||||
reporters: ["spec", "coverage"],
|
||||
reporters: ['spec', 'coverage'],
|
||||
|
||||
coverageReporter: {
|
||||
dir: "coverage",
|
||||
reporters: [{ type: "lcov", subdir: "." }, { type: "text-summary" }]
|
||||
dir: 'coverage',
|
||||
reporters: [{ type: 'lcov', subdir: '.' }, { type: 'text-summary' }]
|
||||
},
|
||||
|
||||
// !!DONOT delete this reporter, or vue-cli-addon-ui-karma doesnot work
|
||||
jsonResultReporter: {
|
||||
outputFile: "report/karma-result.json",
|
||||
outputFile: 'report/karma-result.json',
|
||||
isSynchronous: true
|
||||
},
|
||||
|
||||
junitReporter: {
|
||||
outputDir: "report", // results will be saved as $outputDir/$browserName.xml
|
||||
outputDir: 'report', // results will be saved as $outputDir/$browserName.xml
|
||||
outputFile: undefined, // if included, results will be saved as $outputDir/$browserName/$outputFile
|
||||
suite: "", // suite will become the package name attribute in xml testsuite element
|
||||
suite: '', // suite will become the package name attribute in xml testsuite element
|
||||
useBrowserName: true, // add browser name to report and classes names
|
||||
nameFormatter: undefined, // function (browser, result) to customize the name attribute in xml testcase element
|
||||
classNameFormatter: undefined, // function (browser, result) to customize the classname attribute in xml testcase element
|
||||
@@ -79,11 +74,19 @@ module.exports = function(config) {
|
||||
logLevel: config.LOG_INFO,
|
||||
|
||||
// enable / disable watching file and executing tests whenever any file changes
|
||||
autoWatch: true,
|
||||
autoWatch: false,
|
||||
|
||||
customLaunchers: {
|
||||
FirefoxHeadlessTouch: {
|
||||
base: 'FirefoxHeadless',
|
||||
prefs: {
|
||||
'dom.w3c_touch_events.enabled': 1
|
||||
}
|
||||
}
|
||||
},
|
||||
// start these browsers
|
||||
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
|
||||
browsers: ["ChromiumHeadless"],
|
||||
browsers: ['ChromiumHeadless', 'FirefoxHeadlessTouch'],
|
||||
|
||||
// Continuous Integration mode
|
||||
// if true, Karma captures browsers, runs the tests and exits
|
||||
@@ -91,23 +94,26 @@ module.exports = function(config) {
|
||||
|
||||
// Concurrency level
|
||||
// how many browser should be started simultaneous
|
||||
concurrency: Infinity,
|
||||
concurrency: 2,
|
||||
|
||||
client: {
|
||||
captureConsole: true
|
||||
captureConsole: true,
|
||||
mocha: {
|
||||
timeout: 7000
|
||||
}
|
||||
},
|
||||
browserConsoleLogOptions: {
|
||||
terminal: true,
|
||||
level: ""
|
||||
level: ''
|
||||
},
|
||||
webpack: {
|
||||
mode: "development",
|
||||
entry: "./src/main.js",
|
||||
mode: 'development',
|
||||
entry: './src/main.js',
|
||||
resolve: {
|
||||
extensions: [".js", ".vue", ".json"],
|
||||
extensions: ['.js', '.vue', '.json'],
|
||||
alias: {
|
||||
vue$: "vue/dist/vue.esm.js",
|
||||
"@": resolve("src")
|
||||
vue$: 'vue/dist/vue.esm.js',
|
||||
'@': resolve('src')
|
||||
}
|
||||
},
|
||||
module: {
|
||||
@@ -117,46 +123,57 @@ module.exports = function(config) {
|
||||
exclude: /(node_modules|bower_components)/,
|
||||
use: [
|
||||
{
|
||||
loader: "babel-loader"
|
||||
loader: 'babel-loader'
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
loader: "istanbul-instrumenter-loader",
|
||||
test: /\.js$/,
|
||||
include: /src/,
|
||||
exclude: /(node_modules|bower_components|\.spec\.js$)/,
|
||||
use: [
|
||||
{
|
||||
loader: 'istanbul-instrumenter-loader',
|
||||
options: {
|
||||
esModules: true
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
test: /worker\.js$/,
|
||||
loader: 'worker-loader'
|
||||
},
|
||||
{
|
||||
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
|
||||
loader: "url-loader"
|
||||
loader: 'url-loader'
|
||||
},
|
||||
{
|
||||
test: /\.vue$/,
|
||||
loader: "vue-loader",
|
||||
loader: 'vue-loader',
|
||||
options: {
|
||||
loaders: {
|
||||
js: "babel-loader"
|
||||
js: 'babel-loader'
|
||||
},
|
||||
postLoaders: {
|
||||
js: "istanbul-instrumenter-loader?esModules=true"
|
||||
js: 'istanbul-instrumenter-loader?esModules=true'
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
test: /\.css$/,
|
||||
use: ["vue-style-loader", "css-loader"]
|
||||
use: ['vue-style-loader', 'css-loader']
|
||||
},
|
||||
{
|
||||
test: /\.scss$/,
|
||||
use: ["vue-style-loader", "css-loader", "sass-loader"]
|
||||
use: ['vue-style-loader', 'css-loader', 'sass-loader']
|
||||
},
|
||||
{
|
||||
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
|
||||
loader: "url-loader",
|
||||
loader: 'url-loader',
|
||||
options: {
|
||||
limit: 10000,
|
||||
name: resolve("fonts/[name].[hash:7].[ext]")
|
||||
name: resolve('fonts/[name].[hash:7].[ext]')
|
||||
}
|
||||
}
|
||||
]
|
||||
@@ -166,8 +183,16 @@ module.exports = function(config) {
|
||||
fs: 'empty'
|
||||
}
|
||||
},
|
||||
proxies: {
|
||||
"/js/": "/base/node_modules/sql.js/dist/"
|
||||
webpackMiddleware: {
|
||||
watchOptions: {
|
||||
ignored: /node_modules/
|
||||
}
|
||||
});
|
||||
};
|
||||
},
|
||||
proxies: {
|
||||
'/_karma_webpack_/sql-wasm.wasm': '/base/node_modules/sql.js/dist/sql-wasm.wasm',
|
||||
'/base/sql-wasm.wasm': '/base/node_modules/sql.js/dist/sql-wasm.wasm'
|
||||
}
|
||||
})
|
||||
// Fix the timezone
|
||||
process.env.TZ = 'Europe/Amsterdam'
|
||||
}
|
||||
|
||||
21
karma.files.js
Normal file
@@ -0,0 +1,21 @@
|
||||
import Vue from 'vue'
|
||||
import { VuePlugin } from 'vuera'
|
||||
import VModal from 'vue-js-modal'
|
||||
|
||||
Vue.use(VuePlugin)
|
||||
Vue.use(VModal)
|
||||
Vue.config.productionTip = false
|
||||
|
||||
// require all test files (files that ends with .spec.js)
|
||||
const testsContext = require.context('./tests', true, /\.spec.js$/)
|
||||
|
||||
// Read more about why we need to call testContext:
|
||||
// https://www.npmjs.com/package/require-context#context-api
|
||||
testsContext.keys().forEach(testsContext)
|
||||
|
||||
// require all src files except main.js and router/index.js for coverage.
|
||||
// you can also change this to match only the subset of files that
|
||||
// you want coverage for.
|
||||
// We don't include router/index.js to avoid installing VueRouter globally in tests
|
||||
const srcContext = require.context('./src', true, /^\.\/(?!(main|(router(\/)?(index)?))(\.js)?$)/)
|
||||
srcContext.keys().forEach(srcContext)
|
||||
4273
package-lock.json
generated
18
package.json
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "sqliteviz",
|
||||
"version": "0.8.0",
|
||||
"version": "0.11.0",
|
||||
"license": "Apache-2.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"serve": "vue-cli-service serve",
|
||||
"build": "NODE_OPTIONS=--max_old_space_size=4096 vue-cli-service build",
|
||||
"test:unit": "vue-cli-service test:unit",
|
||||
"test": "vue-cli-service karma",
|
||||
"lint": "vue-cli-service lint"
|
||||
},
|
||||
"dependencies": {
|
||||
@@ -14,11 +14,13 @@
|
||||
"core-js": "^3.6.5",
|
||||
"debounce": "^1.2.0",
|
||||
"nanoid": "^3.1.12",
|
||||
"plotly.js": "^1.57.1",
|
||||
"papaparse": "^5.3.0",
|
||||
"plotly.js": "^1.58.4",
|
||||
"promise-worker": "^2.0.1",
|
||||
"react": "^16.13.1",
|
||||
"react-chart-editor": "^0.42.0",
|
||||
"react-dom": "^16.13.1",
|
||||
"sql.js": "^1.3.0",
|
||||
"sql.js": "^1.5.0",
|
||||
"sqlite-parser": "^1.0.1",
|
||||
"vue": "^2.6.11",
|
||||
"vue-codemirror": "^4.0.6",
|
||||
@@ -35,9 +37,10 @@
|
||||
"@vue/cli-plugin-vuex": "^4.4.0",
|
||||
"@vue/cli-service": "^4.4.0",
|
||||
"@vue/eslint-config-standard": "^5.1.2",
|
||||
"@vue/test-utils": "^1.0.3",
|
||||
"@vue/test-utils": "^1.1.2",
|
||||
"babel-eslint": "^10.1.0",
|
||||
"chai": "^4.1.2",
|
||||
"chai-as-promised": "^7.1.1",
|
||||
"eslint": "^6.7.2",
|
||||
"eslint-plugin-import": "^2.20.2",
|
||||
"eslint-plugin-node": "^11.1.0",
|
||||
@@ -45,8 +48,11 @@
|
||||
"eslint-plugin-standard": "^4.0.0",
|
||||
"eslint-plugin-vue": "^6.2.2",
|
||||
"karma": "^3.1.4",
|
||||
"karma-firefox-launcher": "^2.1.0",
|
||||
"karma-webpack": "^4.0.2",
|
||||
"vue-cli-plugin-ui-karma": "^0.2.5",
|
||||
"vue-template-compiler": "^2.6.11"
|
||||
"vue-template-compiler": "^2.6.11",
|
||||
"workbox-webpack-plugin": "^6.1.5",
|
||||
"worker-loader": "^3.0.8"
|
||||
}
|
||||
}
|
||||
|
||||
BIN
public/Logo192x192.png
Normal file
|
After Width: | Height: | Size: 11 KiB |
BIN
public/Logo48x48.png
Normal file
|
After Width: | Height: | Size: 1.1 KiB |
BIN
public/Logo512x512.png
Normal file
|
After Width: | Height: | Size: 68 KiB |
|
Before Width: | Height: | Size: 798 B After Width: | Height: | Size: 774 B |
@@ -5,13 +5,94 @@
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=edge">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1.0">
|
||||
<link rel="icon" href="<%= BASE_URL %>favicon.png">
|
||||
<link rel="manifest" href="<%= BASE_URL %>manifest.webmanifest">
|
||||
<title><%= htmlWebpackPlugin.options.title %></title>
|
||||
<style>
|
||||
#sqliteviz-loading-wrapper {
|
||||
position: fixed;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
left: 0;
|
||||
top: 0;
|
||||
background-color: white;
|
||||
}
|
||||
|
||||
#sqliteviz-loading-text {
|
||||
display: block;
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
left: 50%;
|
||||
transform: translate(-50%, -50%);
|
||||
color: #506784;
|
||||
font-family: sans-serif;
|
||||
font-size: 20px;
|
||||
}
|
||||
|
||||
#sqliteviz-loading-wrapper svg {
|
||||
display: block;
|
||||
position: absolute;
|
||||
left: 50%;
|
||||
top: 50%;
|
||||
transform: translate(-50%, -50%);
|
||||
}
|
||||
|
||||
#sqliteviz-loading-wrapper circle {
|
||||
position: absolute;
|
||||
left: 0; right: 0; top: 0; bottom: 0;
|
||||
fill: none;
|
||||
stroke-width: 5px;
|
||||
stroke-linecap: round;
|
||||
stroke: #119DFF;
|
||||
}
|
||||
|
||||
#sqliteviz-loading-wrapper circle.bg {
|
||||
stroke: #C8D4E3;
|
||||
}
|
||||
|
||||
#sqliteviz-loading-wrapper circle.front {
|
||||
stroke-dasharray: 402px;
|
||||
animation: sqliteviz-loading 2s linear 0s infinite;
|
||||
}
|
||||
|
||||
@keyframes sqliteviz-loading {
|
||||
0% {
|
||||
stroke-dasharray: 100px 402px;
|
||||
stroke-dashoffset: 0;
|
||||
}
|
||||
50% {
|
||||
stroke-dasharray: 251px;
|
||||
stroke-dashoffset: -251px;
|
||||
}
|
||||
100% {
|
||||
stroke-dasharray: 100px 402px;
|
||||
stroke-dashoffset: -502px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<noscript>
|
||||
<strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
|
||||
</noscript>
|
||||
<div id="app"></div>
|
||||
<div id="app">
|
||||
<div id="sqliteviz-loading-wrapper">
|
||||
<div id="sqliteviz-loading-text">LOADING</div>
|
||||
<svg height="170" width="170" viewBox="0 0 170 170">
|
||||
<circle
|
||||
class="bg"
|
||||
cx="85"
|
||||
cy="85"
|
||||
r="80"
|
||||
/>
|
||||
<circle
|
||||
class="front"
|
||||
cx="85"
|
||||
cy="85"
|
||||
r="80"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
<!-- built files will be auto injected -->
|
||||
</body>
|
||||
</html>
|
||||
|
||||
30
public/manifest.webmanifest
Normal file
@@ -0,0 +1,30 @@
|
||||
{
|
||||
"background_color": "white",
|
||||
"description": "Sqliteviz is a single-page application for fully client-side visualisation of SQLite databases or CSV.",
|
||||
"display": "fullscreen",
|
||||
"icons": [
|
||||
{
|
||||
"src": "favicon.png",
|
||||
"sizes": "32x32",
|
||||
"type": "image/png"
|
||||
},
|
||||
{
|
||||
"src": "Logo48x48.png",
|
||||
"sizes": "48x48",
|
||||
"type": "image/png"
|
||||
},
|
||||
{
|
||||
"src": "Logo192x192.png",
|
||||
"sizes": "192x192",
|
||||
"type": "image/png"
|
||||
},
|
||||
{
|
||||
"src": "Logo512x512.png",
|
||||
"sizes": "512x512",
|
||||
"type": "image/png"
|
||||
}
|
||||
],
|
||||
"name": "sqliteviz",
|
||||
"short_name": "sqliteviz",
|
||||
"start_url": "index.html"
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
[]
|
||||
@@ -60,4 +60,7 @@ button,
|
||||
body {
|
||||
margin: 0;
|
||||
}
|
||||
.CodeMirror-hints {
|
||||
z-index: 999 !important;
|
||||
}
|
||||
</style>
|
||||
|
||||
BIN
src/assets/images/Screenshot_editor.png
Normal file
|
After Width: | Height: | Size: 83 KiB |
17
src/assets/images/checkbox_checked_disabled.svg
Normal file
@@ -0,0 +1,17 @@
|
||||
<svg width="18" height="18" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<rect x="0.5" y="0.5" width="17" height="17" rx="2.5" fill="#DFE8F3" stroke="#C8D4E3"/>
|
||||
<g filter="url(#filter0_d)">
|
||||
<path d="M15.75 5.25L6.75 14.25L2.625 10.125L3.6825 9.0675L6.75 12.1275L14.6925 4.1925L15.75 5.25Z" fill="#A2B1C6"/>
|
||||
</g>
|
||||
<defs>
|
||||
<filter id="filter0_d" x="0.625" y="3.1925" width="17.125" height="14.0575" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">
|
||||
<feFlood flood-opacity="0" result="BackgroundImageFix"/>
|
||||
<feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"/>
|
||||
<feOffset dy="1"/>
|
||||
<feGaussianBlur stdDeviation="1"/>
|
||||
<feColorMatrix type="matrix" values="0 0 0 0 0.164706 0 0 0 0 0.247059 0 0 0 0 0.372549 0 0 0 0.2 0"/>
|
||||
<feBlend mode="normal" in2="BackgroundImageFix" result="effect1_dropShadow"/>
|
||||
<feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow" result="shape"/>
|
||||
</filter>
|
||||
</defs>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 983 B |
5
src/assets/images/error.svg
Normal file
@@ -0,0 +1,5 @@
|
||||
<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M9.99984 16.6667C6.32484 16.6667 3.33317 13.675 3.33317 10C3.33317 6.32502 6.32484 3.33335 9.99984 3.33335C13.6748 3.33335 16.6665 6.32502 16.6665 10C16.6665 13.675 13.6748 16.6667 9.99984 16.6667ZM9.99984 1.66669C8.90549 1.66669 7.82186 1.88224 6.81081 2.30102C5.79976 2.71981 4.8811 3.33364 4.10728 4.10746C2.54448 5.67027 1.6665 7.78988 1.6665 10C1.6665 12.2102 2.54448 14.3298 4.10728 15.8926C4.8811 16.6664 5.79976 17.2802 6.81081 17.699C7.82186 18.1178 8.90549 18.3334 9.99984 18.3334C12.21 18.3334 14.3296 17.4554 15.8924 15.8926C17.4552 14.3298 18.3332 12.2102 18.3332 10C18.3332 8.90567 18.1176 7.82204 17.6988 6.81099C17.28 5.79995 16.6662 4.88129 15.8924 4.10746C15.1186 3.33364 14.1999 2.71981 13.1889 2.30102C12.1778 1.88224 11.0942 1.66669 9.99984 1.66669Z" fill="#EF553B"/>
|
||||
<rect x="6.36768" y="7.54855" width="1.67" height="8.60363" transform="rotate(-45 6.36768 7.54855)" fill="#EF553B"/>
|
||||
<rect x="12.4517" y="6.36771" width="1.67" height="8.60363" transform="rotate(45 12.4517 6.36771)" fill="#EF553B"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.1 KiB |
5
src/assets/images/success.svg
Normal file
@@ -0,0 +1,5 @@
|
||||
<svg width="21" height="20" viewBox="0 0 21 20" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M10.4998 16.6667C6.82484 16.6667 3.83317 13.675 3.83317 10C3.83317 6.32502 6.82484 3.33335 10.4998 3.33335C14.1748 3.33335 17.1665 6.32502 17.1665 10C17.1665 13.675 14.1748 16.6667 10.4998 16.6667ZM10.4998 1.66669C9.40549 1.66669 8.32186 1.88224 7.31081 2.30102C6.29976 2.71981 5.3811 3.33364 4.60728 4.10746C3.04448 5.67027 2.1665 7.78988 2.1665 10C2.1665 12.2102 3.04448 14.3298 4.60728 15.8926C5.3811 16.6664 6.29976 17.2802 7.31081 17.699C8.32186 18.1178 9.40549 18.3334 10.4998 18.3334C12.71 18.3334 14.8296 17.4554 16.3924 15.8926C17.9552 14.3298 18.8332 12.2102 18.8332 10C18.8332 8.90567 18.6176 7.82204 18.1988 6.81099C17.78 5.79995 17.1662 4.88129 16.3924 4.10746C15.6186 3.33364 14.6999 2.71981 13.6889 2.30102C12.6778 1.88224 11.5942 1.66669 10.4998 1.66669Z" fill="#00CC96"/>
|
||||
<rect x="6.09717" y="10.2771" width="1.67" height="4.345" transform="rotate(-45 6.09717 10.2771)" fill="#00CC96"/>
|
||||
<rect x="13.752" y="6.97589" width="1.67" height="7.74359" transform="rotate(45 13.752 6.97589)" fill="#00CC96"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.1 KiB |
@@ -27,14 +27,6 @@ button.primary:hover {
|
||||
text-shadow: var(--shadow);
|
||||
}
|
||||
|
||||
button.primary:disabled {
|
||||
background: var(--color-bg-light-2);
|
||||
border: 1px solid var(--color-border);
|
||||
color: var(--color-text-light-2);
|
||||
text-shadow: none;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
button.secondary {
|
||||
background: white;
|
||||
border: 1px solid var(--color-border);
|
||||
@@ -59,5 +51,13 @@ button.toolbar:hover {
|
||||
color: var(--color-accent);
|
||||
}
|
||||
|
||||
button.primary:disabled,
|
||||
button.secondary:disabled {
|
||||
background: var(--color-bg-light-2);
|
||||
border: 1px solid var(--color-border);
|
||||
color: var(--color-text-light-2);
|
||||
text-shadow: none;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -1,13 +1,11 @@
|
||||
.icon-tooltip {
|
||||
visibility: hidden;
|
||||
background-color: rgba(80, 103, 132, 0.85);
|
||||
color: #fff;
|
||||
text-align: center;
|
||||
font-size: 11px;
|
||||
font-size: 12px;
|
||||
padding: 0 6px;
|
||||
line-height: 19px;;
|
||||
position: fixed;
|
||||
z-index: 5;
|
||||
height: 19px;
|
||||
border-radius: var(--border-radius-medium);
|
||||
white-space: nowrap;
|
||||
|
||||
@@ -20,6 +20,7 @@
|
||||
--color-bg-light-3: var(--color-gray-light-5);
|
||||
--color-bg-dark: var(--color-gray-dark);
|
||||
--color-bg-warning: var(--color-yellow);
|
||||
--color-danger: var(--color-red);
|
||||
--color-accent: var(--color-blue-medium);
|
||||
--color-accent-shade: var(--color-blue-dark);
|
||||
--color-border-light: var(--color-gray-light-2);
|
||||
|
||||
@@ -1,20 +1,26 @@
|
||||
<template>
|
||||
<div class="checkbox-container" @click.stop="onClick">
|
||||
<div
|
||||
:class="['checkbox-container', { 'checked': checked }, {'disabled': disabled}]"
|
||||
@click.stop="onClick"
|
||||
>
|
||||
<div v-show="!checked" class="unchecked" />
|
||||
<img
|
||||
v-show="checked && theme === 'accent'"
|
||||
:src="require('@/assets/images/checkbox_checked.svg')"
|
||||
v-show="checked && !disabled"
|
||||
:src="theme === 'light'
|
||||
? require('@/assets/images/checkbox_checked_light.svg')
|
||||
: require('@/assets/images/checkbox_checked.svg')"
|
||||
/>
|
||||
<img
|
||||
v-show="checked && theme === 'light'"
|
||||
:src="require('@/assets/images/checkbox_checked_light.svg')"
|
||||
v-show="checked && disabled"
|
||||
:src="require('@/assets/images/checkbox_checked_disabled.svg')"
|
||||
/>
|
||||
<span v-if="label" class="label">{{ label }}</span>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
export default {
|
||||
name: 'checkBox',
|
||||
name: 'CheckBox',
|
||||
props: {
|
||||
theme: {
|
||||
type: String,
|
||||
@@ -28,6 +34,16 @@ export default {
|
||||
type: Boolean,
|
||||
required: false,
|
||||
default: false
|
||||
},
|
||||
label: {
|
||||
type: String,
|
||||
required: false,
|
||||
default: ''
|
||||
},
|
||||
disabled: {
|
||||
type: Boolean,
|
||||
required: false,
|
||||
default: false
|
||||
}
|
||||
},
|
||||
data () {
|
||||
@@ -37,16 +53,18 @@ export default {
|
||||
},
|
||||
methods: {
|
||||
onClick () {
|
||||
if (!this.disabled) {
|
||||
this.checked = !this.checked
|
||||
this.$emit('click', this.checked)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.checkbox-container {
|
||||
display: inline-block;
|
||||
display: inline-flex;
|
||||
cursor: pointer;
|
||||
}
|
||||
.unchecked {
|
||||
@@ -64,4 +82,24 @@ export default {
|
||||
img {
|
||||
display: block;
|
||||
}
|
||||
.label {
|
||||
margin-left: 6px;
|
||||
color: var(--color-text-base);
|
||||
}
|
||||
.checked .label {
|
||||
color: var(--color-text-active);
|
||||
}
|
||||
|
||||
.disabled.checkbox-container {
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.disabled .label {
|
||||
color: var(--color-text-light-2);
|
||||
}
|
||||
|
||||
.disabled .unchecked,
|
||||
.disabled .unchecked:hover {
|
||||
background-color: var(--color-bg-light-2);
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,200 +0,0 @@
|
||||
<template>
|
||||
<div class="db-upload-container">
|
||||
<label for="assetsFieldHandle">
|
||||
<div
|
||||
class="drop-area"
|
||||
@dragover.prevent="state = 'dragover'"
|
||||
@dragleave.prevent="state=''"
|
||||
@drop.prevent="drop"
|
||||
>
|
||||
<input
|
||||
type="file"
|
||||
id="assetsFieldHandle"
|
||||
@change="loadDb"
|
||||
ref="file"
|
||||
accept=".db,.sqlite,.sqlite3"
|
||||
/>
|
||||
<div class="text">
|
||||
Drop the database file here or click to choose a file from your computer.
|
||||
</div>
|
||||
</div>
|
||||
</label>
|
||||
<div v-if="illustrated" id="img-container">
|
||||
<img id="drop-file-top-img" :src="require('@/assets/images/top.svg')" />
|
||||
<img
|
||||
id="left-arm-img"
|
||||
:class="{'swing': state === 'dragover'}"
|
||||
:src="require('@/assets/images/leftArm.svg')"
|
||||
/>
|
||||
<img
|
||||
id="file-img"
|
||||
ref="fileImg"
|
||||
:class="{
|
||||
'swing': state === 'dragover',
|
||||
'fly': state === 'drop'
|
||||
}"
|
||||
:src="require('@/assets/images/file.png')"
|
||||
/>
|
||||
<img id="drop-file-bottom-img" :src="require('@/assets/images/bottom.svg')" />
|
||||
<img id="body-img" :src="require('@/assets/images/body.svg')" />
|
||||
<img
|
||||
id="right-arm-img"
|
||||
:class="{'swing': state === 'dragover'}"
|
||||
:src="require('@/assets/images/rightArm.svg')"
|
||||
/>
|
||||
</div>
|
||||
<div id="error" class="error"></div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
export default {
|
||||
name: 'DbUpload',
|
||||
props: {
|
||||
illustrated: {
|
||||
type: Boolean,
|
||||
required: false,
|
||||
default: false
|
||||
}
|
||||
},
|
||||
data () {
|
||||
return {
|
||||
state: '',
|
||||
animationPromise: Promise.resolve()
|
||||
}
|
||||
},
|
||||
mounted () {
|
||||
if (this.illustrated) {
|
||||
this.animationPromise = new Promise((resolve) => {
|
||||
this.$refs.fileImg.addEventListener('animationend', event => {
|
||||
if (event.animationName.startsWith('fly')) {
|
||||
resolve()
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
loadDb () {
|
||||
this.state = 'drop'
|
||||
return Promise.all([this.$db.loadDb(this.$refs.file.files[0]), this.animationPromise])
|
||||
.then(([schema]) => {
|
||||
this.$store.commit('saveSchema', schema)
|
||||
if (this.$route.path !== '/editor') {
|
||||
this.$router.push('/editor')
|
||||
}
|
||||
})
|
||||
},
|
||||
drop (event) {
|
||||
this.$refs.file.files = event.dataTransfer.files
|
||||
this.loadDb()
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
label {
|
||||
display: inline-block;
|
||||
border: 1px dashed var(--color-border);
|
||||
padding: 8px;
|
||||
border-radius: var(--border-radius-big);
|
||||
height: 100%;
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.drop-area {
|
||||
background-color: var(--color-bg-light-3);
|
||||
border-radius: var(--border-radius-big);
|
||||
color: var(--color-text-base);
|
||||
font-size: 13px;
|
||||
text-align: center;
|
||||
box-sizing: border-box;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
input {
|
||||
display: none;
|
||||
}
|
||||
|
||||
#img-container {
|
||||
position: absolute;
|
||||
top: calc(50% - 120px);
|
||||
left: 50%;
|
||||
transform: translate(-50%, -50%);
|
||||
width: 450px;
|
||||
height: 338px;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
#drop-file-top-img {
|
||||
width: 450px;
|
||||
height: 175px;
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
}
|
||||
#drop-file-bottom-img {
|
||||
width: 450px;
|
||||
height: 167px;
|
||||
position: absolute;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
}
|
||||
#body-img {
|
||||
width: 74px;
|
||||
position: absolute;
|
||||
top: 94.05px;
|
||||
left: 46px;
|
||||
}
|
||||
#right-arm-img {
|
||||
width: 106px;
|
||||
position: absolute;
|
||||
top: 110.05px;
|
||||
left: 78px;
|
||||
}
|
||||
#left-arm-img {
|
||||
width: 114px;
|
||||
position: absolute;
|
||||
top: 69.05px;
|
||||
left: 69px;
|
||||
}
|
||||
#file-img {
|
||||
width: 125px;
|
||||
position: absolute;
|
||||
top: 15.66px;
|
||||
left: 152px;
|
||||
}
|
||||
|
||||
.swing {
|
||||
animation: swing ease-in-out 0.6s infinite alternate;
|
||||
}
|
||||
#left-arm-img.swing {
|
||||
transform-origin: 9px 83px;
|
||||
}
|
||||
#right-arm-img.swing {
|
||||
transform-origin: 0 56px;
|
||||
}
|
||||
#file-img.swing {
|
||||
transform-origin: -74px 139px;
|
||||
}
|
||||
@keyframes swing {
|
||||
0% { transform: rotate(0deg); }
|
||||
100% { transform: rotate(-7deg); }
|
||||
}
|
||||
|
||||
#file-img.fly {
|
||||
animation: fly ease-in-out 1s 1 normal;
|
||||
transform-origin: center center;
|
||||
top: 183px;
|
||||
left: 225px;
|
||||
transition: top 1s ease-in-out, left 1s ease-in-out;
|
||||
}
|
||||
@keyframes fly {
|
||||
100% { transform: rotate(360deg) scale(0.5); }
|
||||
}
|
||||
</style>
|
||||
130
src/components/DbUploader/DelimiterSelector/ascii.js
Normal file
@@ -0,0 +1,130 @@
|
||||
export default {
|
||||
0: { name: 'null character' },
|
||||
1: { name: 'start of header' },
|
||||
2: { name: 'start of text' },
|
||||
3: { name: 'end of text' },
|
||||
4: { name: 'end of transmission' },
|
||||
5: { name: 'enquiry' },
|
||||
6: { name: 'acknowledge' },
|
||||
7: { name: 'bell (ring)' },
|
||||
8: { name: 'backspace' },
|
||||
9: { name: 'horizontal tab' },
|
||||
10: { name: 'line feed' },
|
||||
11: { name: 'vertical tab' },
|
||||
12: { name: 'form feed' },
|
||||
13: { name: 'carriage return' },
|
||||
14: { name: 'shift out' },
|
||||
15: { name: 'shift in' },
|
||||
16: { name: 'data link escape' },
|
||||
17: { name: 'device control 1' },
|
||||
18: { name: 'device control 2' },
|
||||
19: { name: 'device control 3' },
|
||||
20: { name: 'device control 4' },
|
||||
21: { name: 'negative acknowledge' },
|
||||
22: { name: 'synchronize' },
|
||||
23: { name: 'end transmission block' },
|
||||
24: { name: 'cancel' },
|
||||
25: { name: 'end of medium' },
|
||||
26: { name: 'substitute' },
|
||||
27: { name: 'escape' },
|
||||
28: { name: 'file separator' },
|
||||
29: { name: 'group separator' },
|
||||
30: { name: 'record separator' },
|
||||
31: { name: 'unit separator' },
|
||||
32: { name: 'space' },
|
||||
33: { name: 'exclamation mark' },
|
||||
34: { name: 'quotation mark' },
|
||||
35: { name: 'number sign' },
|
||||
36: { name: 'dollar sign' },
|
||||
37: { name: 'percent sign' },
|
||||
38: { name: 'ampersand' },
|
||||
39: { name: 'apostrophe' },
|
||||
40: { name: 'left parenthesis' },
|
||||
41: { name: 'right parenthesis' },
|
||||
42: { name: 'asterisk' },
|
||||
43: { name: 'plus sign' },
|
||||
44: { name: 'comma' },
|
||||
45: { name: 'hyphen' },
|
||||
46: { name: 'period' },
|
||||
47: { name: 'slash' },
|
||||
48: { name: 'digit 0' },
|
||||
49: { name: 'digit 1' },
|
||||
50: { name: 'digit 2' },
|
||||
51: { name: 'digit 3' },
|
||||
52: { name: 'digit 4' },
|
||||
53: { name: 'digit 5' },
|
||||
54: { name: 'digit 6' },
|
||||
55: { name: 'digit 7' },
|
||||
56: { name: 'digit 8' },
|
||||
57: { name: 'digit 9' },
|
||||
58: { name: 'colon' },
|
||||
59: { name: 'semicolon' },
|
||||
60: { name: 'less-than' },
|
||||
61: { name: 'equals-to' },
|
||||
62: { name: 'greater-than' },
|
||||
63: { name: 'question mark' },
|
||||
64: { name: 'at sign' },
|
||||
65: { name: 'uppercase A' },
|
||||
66: { name: 'uppercase B' },
|
||||
67: { name: 'uppercase C' },
|
||||
68: { name: 'uppercase D' },
|
||||
69: { name: 'uppercase E' },
|
||||
70: { name: 'uppercase F' },
|
||||
71: { name: 'uppercase G' },
|
||||
72: { name: 'uppercase H' },
|
||||
73: { name: 'uppercase I' },
|
||||
74: { name: 'uppercase J' },
|
||||
75: { name: 'uppercase K' },
|
||||
76: { name: 'uppercase L' },
|
||||
77: { name: 'uppercase M' },
|
||||
78: { name: 'uppercase N' },
|
||||
79: { name: 'uppercase O' },
|
||||
80: { name: 'uppercase P' },
|
||||
81: { name: 'uppercase Q' },
|
||||
82: { name: 'uppercase R' },
|
||||
83: { name: 'uppercase S' },
|
||||
84: { name: 'uppercase T' },
|
||||
85: { name: 'uppercase U' },
|
||||
86: { name: 'uppercase V' },
|
||||
87: { name: 'uppercase W' },
|
||||
88: { name: 'uppercase X' },
|
||||
89: { name: 'uppercase Y' },
|
||||
90: { name: 'uppercase Z' },
|
||||
91: { name: 'left square bracket' },
|
||||
92: { name: 'backslash' },
|
||||
93: { name: 'right square bracket' },
|
||||
94: { name: 'caret' },
|
||||
95: { name: 'underscore' },
|
||||
96: { name: 'grave accent' },
|
||||
97: { name: 'lowercase a' },
|
||||
98: { name: 'lowercase b' },
|
||||
99: { name: 'lowercase c' },
|
||||
100: { name: 'lowercase d' },
|
||||
101: { name: 'lowercase e' },
|
||||
102: { name: 'lowercase f' },
|
||||
103: { name: 'lowercase g' },
|
||||
104: { name: 'lowercase h' },
|
||||
105: { name: 'lowercase i' },
|
||||
106: { name: 'lowercase j' },
|
||||
107: { name: 'lowercase k' },
|
||||
108: { name: 'lowercase l' },
|
||||
109: { name: 'lowercase m' },
|
||||
110: { name: 'lowercase n' },
|
||||
111: { name: 'lowercase o' },
|
||||
112: { name: 'lowercase p' },
|
||||
113: { name: 'lowercase q' },
|
||||
114: { name: 'lowercase r' },
|
||||
115: { name: 'lowercase s' },
|
||||
116: { name: 'lowercase t' },
|
||||
117: { name: 'lowercase u' },
|
||||
118: { name: 'lowercase v' },
|
||||
119: { name: 'lowercase w' },
|
||||
120: { name: 'lowercase x' },
|
||||
121: { name: 'lowercase y' },
|
||||
122: { name: 'lowercase z' },
|
||||
123: { name: 'left curly brace' },
|
||||
124: { name: 'vertical bar' },
|
||||
125: { name: 'right curly brace' },
|
||||
126: { name: 'tilde' },
|
||||
127: { name: 'delete (rubout)' }
|
||||
}
|
||||
204
src/components/DbUploader/DelimiterSelector/index.vue
Normal file
@@ -0,0 +1,204 @@
|
||||
<template>
|
||||
<div :class="{ 'disabled': disabled }">
|
||||
<div class="text-field-label">Delimiter</div>
|
||||
<div
|
||||
class="delimiter-selector-container"
|
||||
:style="{ width: width }"
|
||||
@click="onContainerClick"
|
||||
>
|
||||
<div class="value">
|
||||
<input
|
||||
:class="{ 'filled': filled }"
|
||||
ref="delimiterInput"
|
||||
type="text"
|
||||
maxlength="1"
|
||||
v-model="inputValue"
|
||||
@click.stop
|
||||
:disabled="disabled"
|
||||
/>
|
||||
<div class="name">{{ getSymbolName(value) }}</div>
|
||||
</div>
|
||||
<div class="controls" @click.stop>
|
||||
<clear-icon @click.native="clear" :disabled="disabled"/>
|
||||
<drop-down-chevron
|
||||
:disabled="disabled"
|
||||
@click.native="!disabled && (showOptions = !showOptions)"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div v-show="showOptions" class="options" :style="{ width: width }">
|
||||
<div
|
||||
v-for="(option, index) in options"
|
||||
:key="index"
|
||||
@click="chooseOption(option)"
|
||||
class="option"
|
||||
>
|
||||
<pre>{{option}}</pre><div>{{ getSymbolName(option) }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import ascii from './ascii'
|
||||
import DropDownChevron from '@/components/svg/dropDownChevron'
|
||||
import ClearIcon from '@/components/svg/clear'
|
||||
|
||||
export default {
|
||||
name: 'DelimiterSelector',
|
||||
props: ['value', 'width', 'disabled'],
|
||||
components: { DropDownChevron, ClearIcon },
|
||||
data () {
|
||||
return {
|
||||
showOptions: false,
|
||||
options: [',', '\t', ' ', '|', ';', '\u001F', '\u001E'],
|
||||
filled: false,
|
||||
inputValue: ''
|
||||
}
|
||||
},
|
||||
watch: {
|
||||
inputValue () {
|
||||
if (this.inputValue) {
|
||||
this.filled = true
|
||||
if (this.inputValue !== this.value) {
|
||||
this.$emit('input', this.inputValue)
|
||||
}
|
||||
} else {
|
||||
this.filled = false
|
||||
}
|
||||
}
|
||||
},
|
||||
created () {
|
||||
this.inputValue = this.value
|
||||
},
|
||||
methods: {
|
||||
getSymbolName (str) {
|
||||
if (!str) {
|
||||
return ''
|
||||
}
|
||||
return ascii[str.charCodeAt(0).toString()].name
|
||||
},
|
||||
chooseOption (option) {
|
||||
this.inputValue = option
|
||||
this.showOptions = false
|
||||
},
|
||||
onContainerClick (event) {
|
||||
this.$refs.delimiterInput.focus()
|
||||
},
|
||||
|
||||
clear () {
|
||||
if (!this.disabled) {
|
||||
this.inputValue = ''
|
||||
this.$refs.delimiterInput.focus()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.delimiter-selector-container {
|
||||
background: var(--color-white);
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: var(--border-radius-medium-2);
|
||||
height: 36px;
|
||||
padding: 0 8px;
|
||||
font-size: 12px;
|
||||
box-sizing: border-box;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.value {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.value .name {
|
||||
color: var(--color-text-light-2);
|
||||
cursor: default;
|
||||
margin-left: 4px;
|
||||
}
|
||||
|
||||
.controls {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.options {
|
||||
background: var(--color-white);
|
||||
border: 1px solid var(--color-border);
|
||||
border-width: 0 1px 1px 1px;
|
||||
color: var(--color-text-base);
|
||||
border-radius: var(--border-radius-medium-2);
|
||||
font-size: 12px;
|
||||
box-sizing: border-box;
|
||||
position: absolute;
|
||||
z-index: 2;
|
||||
}
|
||||
|
||||
.option {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
height: 24px;
|
||||
padding: 0 6px;
|
||||
}
|
||||
|
||||
.option:hover {
|
||||
background-color: var(--color-bg-light);
|
||||
color: var(--color-text-active);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.option pre {
|
||||
background-color: var(--color-bg-warning);
|
||||
line-height: 20px;
|
||||
margin-right: 6px;
|
||||
tab-size: 1;
|
||||
font-family: monospace;
|
||||
width: 16px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
input {
|
||||
background: var(--color-white);
|
||||
border: none;
|
||||
color: var(--color-text-base);
|
||||
height: 20px;
|
||||
font-family: monospace;
|
||||
font-size: 12px;
|
||||
box-sizing: border-box;
|
||||
width: 16px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
input.filled {
|
||||
background: var(--color-bg-warning);
|
||||
}
|
||||
|
||||
input:focus {
|
||||
outline: none;
|
||||
}
|
||||
|
||||
input:disabled {
|
||||
background: var(--color-bg-light);
|
||||
color: var(--color-text-light-2);
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.text-field-label {
|
||||
font-size: 12px;
|
||||
color: var(--color-text-base);
|
||||
padding-left: 8px;
|
||||
margin-bottom: 2px;
|
||||
}
|
||||
|
||||
.disabled .text-field-label {
|
||||
color: var(--color-text-light-2);
|
||||
}
|
||||
|
||||
.disabled .delimiter-selector-container {
|
||||
background: var(--color-bg-light);
|
||||
}
|
||||
</style>
|
||||
78
src/components/DbUploader/csv.js
Normal file
@@ -0,0 +1,78 @@
|
||||
import Papa from 'papaparse'
|
||||
|
||||
const hintsByCode = {
|
||||
MissingQuotes: 'Edit your CSV so that the field has a closing quote char.',
|
||||
TooFewFields: 'Add fields or try another delimiter.',
|
||||
TooManyFields: 'Edit your CSV or try another delimiter.'
|
||||
}
|
||||
|
||||
export default {
|
||||
getResult (source) {
|
||||
const result = {}
|
||||
if (source.meta.fields) {
|
||||
result.columns = source.meta.fields.map(col => col.trim())
|
||||
result.values = source.data.map(row => {
|
||||
const resultRow = []
|
||||
result.columns.forEach(col => { resultRow.push(row[col]) })
|
||||
return resultRow
|
||||
})
|
||||
} else {
|
||||
result.values = source.data
|
||||
result.columns = []
|
||||
for (let i = 1; i <= source.data[0].length; i++) {
|
||||
result.columns.push(`col${i}`)
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
},
|
||||
|
||||
parse (file, config = {}) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const defaultConfig = {
|
||||
delimiter: '', // auto-detect
|
||||
newline: '', // auto-detect
|
||||
quoteChar: '"',
|
||||
escapeChar: '"',
|
||||
header: false,
|
||||
transformHeader: undefined,
|
||||
dynamicTyping: true,
|
||||
preview: 0,
|
||||
encoding: 'UTF-8',
|
||||
worker: true,
|
||||
comments: false,
|
||||
step: undefined,
|
||||
complete: results => {
|
||||
const res = {
|
||||
data: this.getResult(results),
|
||||
delimiter: results.meta.delimiter,
|
||||
hasErrors: false
|
||||
}
|
||||
res.messages = results.errors.map(msg => {
|
||||
msg.type = msg.code === 'UndetectableDelimiter' ? 'info' : 'error'
|
||||
if (msg.type === 'error') res.hasErrors = true
|
||||
msg.hint = hintsByCode[msg.code]
|
||||
return msg
|
||||
})
|
||||
resolve(res)
|
||||
},
|
||||
error: (error, file) => {
|
||||
reject(error)
|
||||
},
|
||||
download: false,
|
||||
downloadRequestHeaders: undefined,
|
||||
downloadRequestBody: undefined,
|
||||
skipEmptyLines: 'greedy',
|
||||
chunk: undefined,
|
||||
chunkSize: undefined,
|
||||
fastMode: undefined,
|
||||
beforeFirstChunk: undefined,
|
||||
withCredentials: undefined,
|
||||
transform: undefined,
|
||||
delimitersToGuess: [',', '\t', '|', ';', Papa.RECORD_SEP, Papa.UNIT_SEP]
|
||||
}
|
||||
|
||||
Papa.parse(file, { ...defaultConfig, ...config })
|
||||
})
|
||||
}
|
||||
}
|
||||
551
src/components/DbUploader/index.vue
Normal file
@@ -0,0 +1,551 @@
|
||||
<template>
|
||||
<div class="db-uploader-container" :style="{ width }">
|
||||
<change-db-icon v-if="type === 'small'" @click.native="browse"/>
|
||||
<div v-if="type === 'illustrated'" class="drop-area-container">
|
||||
<div
|
||||
class="drop-area"
|
||||
@dragover.prevent="state = 'dragover'"
|
||||
@dragleave.prevent="state=''"
|
||||
@drop.prevent="drop"
|
||||
@click="browse"
|
||||
>
|
||||
<div class="text">
|
||||
Drop the database or CSV file here or click to choose a file from your computer.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="type === 'illustrated'" id="img-container">
|
||||
<img id="drop-file-top-img" :src="require('@/assets/images/top.svg')" />
|
||||
<img
|
||||
id="left-arm-img"
|
||||
:class="{'swing': state === 'dragover'}"
|
||||
:src="require('@/assets/images/leftArm.svg')"
|
||||
/>
|
||||
<img
|
||||
id="file-img"
|
||||
ref="fileImg"
|
||||
:class="{
|
||||
'swing': state === 'dragover',
|
||||
'fly': state === 'dropping',
|
||||
'hidden': state === 'dropped'
|
||||
}"
|
||||
:src="require('@/assets/images/file.png')"
|
||||
/>
|
||||
<img id="drop-file-bottom-img" :src="require('@/assets/images/bottom.svg')" />
|
||||
<img id="body-img" :src="require('@/assets/images/body.svg')" />
|
||||
<img
|
||||
id="right-arm-img"
|
||||
:class="{'swing': state === 'dragover'}"
|
||||
:src="require('@/assets/images/rightArm.svg')"
|
||||
/>
|
||||
</div>
|
||||
<div id="error" class="error"></div>
|
||||
|
||||
<!--Parse csv dialog -->
|
||||
<modal name="parse" classes="dialog" height="auto" width="60%" :clickToClose="false">
|
||||
<div class="dialog-header">
|
||||
Import CSV
|
||||
<close-icon @click="cancelCsvImport" :disabled="disableDialog"/>
|
||||
</div>
|
||||
<div class="dialog-body">
|
||||
<div class="chars">
|
||||
<delimiter-selector
|
||||
v-model="delimiter"
|
||||
width="210px"
|
||||
class="char-input"
|
||||
@input="previewCSV"
|
||||
:disabled="disableDialog"
|
||||
/>
|
||||
<text-field
|
||||
label="Quote char"
|
||||
hint="The character used to quote fields."
|
||||
v-model="quoteChar"
|
||||
width="93px"
|
||||
:disabled="disableDialog"
|
||||
class="char-input"
|
||||
id="quote-char"
|
||||
/>
|
||||
<text-field
|
||||
label="Escape char"
|
||||
hint='The character used to escape the quote character within a field (e.g. "column with ""quotes"" in text").'
|
||||
max-hint-width="242px"
|
||||
v-model="escapeChar"
|
||||
width="93px"
|
||||
:disabled="disableDialog"
|
||||
class="char-input"
|
||||
id="escape-char"
|
||||
/>
|
||||
</div>
|
||||
<check-box
|
||||
@click="header = $event"
|
||||
:init="true"
|
||||
label="Use first row as column headers"
|
||||
:disabled="disableDialog"
|
||||
/>
|
||||
<sql-table
|
||||
v-if="previewData"
|
||||
:data-set="previewData"
|
||||
height="160"
|
||||
class="preview-table"
|
||||
:preview="true"
|
||||
/>
|
||||
<div v-if="!previewData" class="no-data">No data</div>
|
||||
<logs
|
||||
class="import-csv-errors"
|
||||
:messages="importCsvMessages"
|
||||
/>
|
||||
</div>
|
||||
<div class="dialog-buttons-container">
|
||||
<button
|
||||
class="secondary"
|
||||
:disabled="disableDialog"
|
||||
@click="cancelCsvImport"
|
||||
id="csv-cancel"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
v-show="!importCsvCompleted"
|
||||
class="primary"
|
||||
:disabled="disableDialog"
|
||||
@click="loadFromCsv(file)"
|
||||
id="csv-import"
|
||||
>
|
||||
Import
|
||||
</button>
|
||||
<button
|
||||
v-show="importCsvCompleted"
|
||||
class="primary"
|
||||
:disabled="disableDialog"
|
||||
@click="finish"
|
||||
id="csv-finish"
|
||||
>
|
||||
Finish
|
||||
</button>
|
||||
</div>
|
||||
</modal>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import fIo from '@/lib/utils/fileIo'
|
||||
import csv from './csv'
|
||||
import CloseIcon from '@/components/svg/close'
|
||||
import TextField from '@/components/TextField'
|
||||
import DelimiterSelector from './DelimiterSelector'
|
||||
import CheckBox from '@/components/CheckBox'
|
||||
import SqlTable from '@/components/SqlTable'
|
||||
import Logs from '@/components/Logs'
|
||||
import ChangeDbIcon from '@/components/svg/changeDb'
|
||||
import time from '@/lib/utils/time'
|
||||
import database from '@/lib/database'
|
||||
|
||||
export default {
|
||||
name: 'DbUploader',
|
||||
props: {
|
||||
type: {
|
||||
type: String,
|
||||
required: false,
|
||||
default: 'small',
|
||||
validator: (value) => {
|
||||
return ['illustrated', 'small'].includes(value)
|
||||
}
|
||||
},
|
||||
width: {
|
||||
type: String,
|
||||
required: false,
|
||||
default: 'unset'
|
||||
}
|
||||
},
|
||||
components: {
|
||||
ChangeDbIcon,
|
||||
TextField,
|
||||
DelimiterSelector,
|
||||
CloseIcon,
|
||||
CheckBox,
|
||||
SqlTable,
|
||||
Logs
|
||||
},
|
||||
data () {
|
||||
return {
|
||||
state: '',
|
||||
animationPromise: Promise.resolve(),
|
||||
file: null,
|
||||
schema: null,
|
||||
delimiter: '',
|
||||
quoteChar: '"',
|
||||
escapeChar: '"',
|
||||
header: true,
|
||||
previewData: null,
|
||||
importCsvMessages: [],
|
||||
disableDialog: false,
|
||||
importCsvCompleted: false,
|
||||
newDb: null
|
||||
}
|
||||
},
|
||||
mounted () {
|
||||
if (this.type === 'illustrated') {
|
||||
this.animationPromise = new Promise((resolve) => {
|
||||
this.$refs.fileImg.addEventListener('animationend', event => {
|
||||
if (event.animationName.startsWith('fly')) {
|
||||
this.state = 'dropped'
|
||||
resolve()
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
},
|
||||
watch: {
|
||||
quoteChar () {
|
||||
this.previewCSV()
|
||||
},
|
||||
|
||||
escapeChar () {
|
||||
this.previewCSV()
|
||||
},
|
||||
|
||||
header () {
|
||||
this.previewCSV()
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
cancelCsvImport () {
|
||||
if (!this.disableDialog) {
|
||||
this.$modal.hide('parse')
|
||||
if (this.newDb) {
|
||||
this.newDb.shutDown()
|
||||
this.newDb = null
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
async finish () {
|
||||
this.$store.commit('setDb', this.newDb)
|
||||
this.$store.commit('saveSchema', this.schema)
|
||||
if (this.importCsvCompleted) {
|
||||
this.$modal.hide('parse')
|
||||
const stmt = [
|
||||
'/*',
|
||||
' * Your CSV file has been imported into csv_import table.',
|
||||
' * You can run this SQL query to make all CSV records available for charting.',
|
||||
' */',
|
||||
'SELECT * FROM csv_import'
|
||||
].join('\n')
|
||||
const tabId = await this.$store.dispatch('addTab', { query: stmt })
|
||||
this.$store.commit('setCurrentTabId', tabId)
|
||||
this.importCsvCompleted = false
|
||||
}
|
||||
if (this.$route.path !== '/editor') {
|
||||
this.$router.push('/editor')
|
||||
}
|
||||
},
|
||||
|
||||
async previewCSV () {
|
||||
this.importCsvCompleted = false
|
||||
const config = {
|
||||
preview: 3,
|
||||
quoteChar: this.quoteChar || '"',
|
||||
escapeChar: this.escapeChar,
|
||||
header: this.header,
|
||||
delimiter: this.delimiter
|
||||
}
|
||||
try {
|
||||
const start = new Date()
|
||||
const parseResult = await csv.parse(this.file, config)
|
||||
const end = new Date()
|
||||
this.previewData = parseResult.data
|
||||
this.delimiter = parseResult.delimiter
|
||||
|
||||
// In parseResult.messages we can get parse errors
|
||||
this.importCsvMessages = parseResult.messages || []
|
||||
|
||||
if (!parseResult.hasErrors) {
|
||||
this.importCsvMessages.push({
|
||||
message: `Preview parsing is completed in ${time.getPeriod(start, end)}.`,
|
||||
type: 'success'
|
||||
})
|
||||
}
|
||||
} catch (err) {
|
||||
this.importCsvMessages = [{
|
||||
message: err,
|
||||
type: 'error'
|
||||
}]
|
||||
}
|
||||
},
|
||||
|
||||
loadDb (file) {
|
||||
this.newDb = database.getNewDatabase()
|
||||
return Promise.all([this.newDb.loadDb(file), this.animationPromise])
|
||||
.then(([schema]) => {
|
||||
this.schema = schema
|
||||
this.finish()
|
||||
})
|
||||
},
|
||||
|
||||
async loadFromCsv (file) {
|
||||
this.disableDialog = true
|
||||
const config = {
|
||||
quoteChar: this.quoteChar || '"',
|
||||
escapeChar: this.escapeChar,
|
||||
header: this.header,
|
||||
delimiter: this.delimiter
|
||||
}
|
||||
const parseCsvMsg = {
|
||||
message: 'Parsing CSV...',
|
||||
type: 'info'
|
||||
}
|
||||
this.importCsvMessages.push(parseCsvMsg)
|
||||
const parseCsvLoadingIndicator = setTimeout(() => { parseCsvMsg.type = 'loading' }, 1000)
|
||||
|
||||
const importMsg = {
|
||||
message: 'Importing CSV into a SQLite database...',
|
||||
type: 'info'
|
||||
}
|
||||
let importLoadingIndicator = null
|
||||
|
||||
const updateProgress = progress => {
|
||||
this.$set(importMsg, 'progress', progress)
|
||||
}
|
||||
this.newDb = database.getNewDatabase()
|
||||
const progressCounterId = this.newDb.createProgressCounter(updateProgress)
|
||||
|
||||
try {
|
||||
let start = new Date()
|
||||
const parseResult = await csv.parse(this.file, config)
|
||||
let end = new Date()
|
||||
|
||||
if (!parseResult.hasErrors) {
|
||||
const rowCount = parseResult.data.values.length
|
||||
let period = time.getPeriod(start, end)
|
||||
parseCsvMsg.type = 'success'
|
||||
|
||||
if (parseResult.messages.length > 0) {
|
||||
this.importCsvMessages = this.importCsvMessages.concat(parseResult.messages)
|
||||
parseCsvMsg.message = `${rowCount} rows are parsed in ${period}.`
|
||||
} else {
|
||||
// Inform about csv parsing success
|
||||
parseCsvMsg.message = `${rowCount} rows are parsed successfully in ${period}.`
|
||||
}
|
||||
|
||||
// Loading indicator for csv parsing is not needed anymore
|
||||
clearTimeout(parseCsvLoadingIndicator)
|
||||
|
||||
// Add info about import start
|
||||
this.importCsvMessages.push(importMsg)
|
||||
|
||||
// Show import progress after 1 second
|
||||
importLoadingIndicator = setTimeout(() => {
|
||||
importMsg.type = 'loading'
|
||||
}, 1000)
|
||||
|
||||
// Create db with csv table and get schema
|
||||
const name = file.name.replace(/\.[^.]+$/, '')
|
||||
start = new Date()
|
||||
this.schema = await this.newDb.importDb(name, parseResult.data, progressCounterId)
|
||||
end = new Date()
|
||||
|
||||
// Inform about import success
|
||||
period = time.getPeriod(start, end)
|
||||
importMsg.message = `Importing CSV into a SQLite database is completed in ${period}.`
|
||||
importMsg.type = 'success'
|
||||
|
||||
// Loading indicator for import is not needed anymore
|
||||
clearTimeout(importLoadingIndicator)
|
||||
|
||||
this.importCsvCompleted = true
|
||||
} else {
|
||||
parseCsvMsg.message = 'Parsing ended with errors.'
|
||||
parseCsvMsg.type = 'info'
|
||||
this.importCsvMessages = this.importCsvMessages.concat(parseResult.messages)
|
||||
}
|
||||
} catch (err) {
|
||||
if (parseCsvMsg.type === 'loading') {
|
||||
parseCsvMsg.type = 'info'
|
||||
}
|
||||
|
||||
if (importMsg.type === 'loading') {
|
||||
importMsg.type = 'info'
|
||||
}
|
||||
|
||||
this.importCsvMessages.push({
|
||||
message: err,
|
||||
type: 'error'
|
||||
})
|
||||
}
|
||||
|
||||
clearTimeout(parseCsvLoadingIndicator)
|
||||
clearTimeout(importLoadingIndicator)
|
||||
this.newDb.deleteProgressCounter(progressCounterId)
|
||||
this.disableDialog = false
|
||||
},
|
||||
|
||||
async checkFile (file) {
|
||||
this.state = 'dropping'
|
||||
if (fIo.isDatabase(file)) {
|
||||
this.loadDb(file)
|
||||
} else {
|
||||
this.file = file
|
||||
this.header = true
|
||||
this.quoteChar = '"'
|
||||
this.escapeChar = '"'
|
||||
this.delimiter = ''
|
||||
return Promise.all([this.previewCSV(), this.animationPromise])
|
||||
.then(() => {
|
||||
this.$modal.show('parse')
|
||||
})
|
||||
}
|
||||
},
|
||||
browse () {
|
||||
fIo.getFileFromUser('.db,.sqlite,.sqlite3,.csv')
|
||||
.then(this.checkFile)
|
||||
},
|
||||
|
||||
drop (event) {
|
||||
this.checkFile(event.dataTransfer.files[0])
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.db-uploader-container {
|
||||
position: relative;
|
||||
}
|
||||
.drop-area-container {
|
||||
display: inline-block;
|
||||
border: 1px dashed var(--color-border);
|
||||
padding: 8px;
|
||||
border-radius: var(--border-radius-big);
|
||||
height: 100%;
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.drop-area {
|
||||
background-color: var(--color-bg-light-3);
|
||||
border-radius: var(--border-radius-big);
|
||||
color: var(--color-text-base);
|
||||
font-size: 13px;
|
||||
text-align: center;
|
||||
box-sizing: border-box;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 100%;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
#img-container {
|
||||
position: absolute;
|
||||
top: 54px;
|
||||
left: 50%;
|
||||
transform: translate(-50%, 0);
|
||||
width: 450px;
|
||||
height: 338px;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
#drop-file-top-img {
|
||||
width: 450px;
|
||||
height: 175px;
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
}
|
||||
#drop-file-bottom-img {
|
||||
width: 450px;
|
||||
height: 167px;
|
||||
position: absolute;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
}
|
||||
#body-img {
|
||||
width: 74px;
|
||||
position: absolute;
|
||||
top: 94.05px;
|
||||
left: 46px;
|
||||
}
|
||||
#right-arm-img {
|
||||
width: 106px;
|
||||
position: absolute;
|
||||
top: 110.05px;
|
||||
left: 78px;
|
||||
}
|
||||
#left-arm-img {
|
||||
width: 114px;
|
||||
position: absolute;
|
||||
top: 69.05px;
|
||||
left: 69px;
|
||||
}
|
||||
#file-img {
|
||||
width: 125px;
|
||||
position: absolute;
|
||||
top: 15.66px;
|
||||
left: 152px;
|
||||
}
|
||||
|
||||
.swing {
|
||||
animation: swing ease-in-out 0.6s infinite alternate;
|
||||
}
|
||||
#left-arm-img.swing {
|
||||
transform-origin: 9px 83px;
|
||||
}
|
||||
#right-arm-img.swing {
|
||||
transform-origin: 0 56px;
|
||||
}
|
||||
#file-img.swing {
|
||||
transform-origin: -74px 139px;
|
||||
}
|
||||
@keyframes swing {
|
||||
0% { transform: rotate(0deg); }
|
||||
100% { transform: rotate(-7deg); }
|
||||
}
|
||||
|
||||
#file-img.fly {
|
||||
animation: fly ease-in-out 1s 1 normal;
|
||||
transform-origin: center center;
|
||||
}
|
||||
@keyframes fly {
|
||||
100% {
|
||||
transform: rotate(360deg) scale(0.5);
|
||||
top: 183px;
|
||||
left: 225px;
|
||||
}
|
||||
}
|
||||
|
||||
#file-img.hidden {
|
||||
display: none;
|
||||
}
|
||||
|
||||
/* Parse CSV dialog */
|
||||
.chars {
|
||||
display: flex;
|
||||
align-items: flex-end;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
.char-input {
|
||||
margin-right: 44px;
|
||||
}
|
||||
.preview-table {
|
||||
margin-top: 32px;
|
||||
}
|
||||
|
||||
.import-csv-errors {
|
||||
height: 160px;
|
||||
margin-top: 32px;
|
||||
}
|
||||
.no-data {
|
||||
margin-top: 32px;
|
||||
background-color: white;
|
||||
border-radius: 5px;
|
||||
position: relative;
|
||||
border: 1px solid var(--color-border-light);
|
||||
box-sizing: border-box;
|
||||
height: 160px;
|
||||
font-size: 13px;
|
||||
color: var(--color-text-base);
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
}
|
||||
</style>
|
||||
115
src/components/LoadingIndicator.vue
Normal file
@@ -0,0 +1,115 @@
|
||||
<template>
|
||||
<svg :class="animationClass" :height="size" :width="size" :viewBox="`0 0 ${size} ${size}`">
|
||||
<circle
|
||||
class="loader-svg bg"
|
||||
:style="{ strokeWidth }"
|
||||
:cx="size / 2"
|
||||
:cy="size / 2"
|
||||
:r="radius"
|
||||
/>
|
||||
<circle
|
||||
class="loader-svg front"
|
||||
:style="{ strokeDasharray: circleProgress, strokeDashoffset: offset, strokeWidth }"
|
||||
:cx="size / 2"
|
||||
:cy="size / 2"
|
||||
:r="radius"
|
||||
/>
|
||||
</svg>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
export default {
|
||||
name: 'LoadingIndicator',
|
||||
props: {
|
||||
progress: {
|
||||
type: Number,
|
||||
required: false
|
||||
},
|
||||
size: {
|
||||
type: Number,
|
||||
required: false,
|
||||
default: 20
|
||||
}
|
||||
},
|
||||
computed: {
|
||||
circleProgress () {
|
||||
const circle = this.radius * 3.14 * 2
|
||||
const dash = this.progress ? (circle * this.progress) / 100 : circle * 1 / 3
|
||||
const space = circle - dash
|
||||
return `${dash}px, ${space}px`
|
||||
},
|
||||
animationClass () {
|
||||
return this.progress === undefined ? 'loading' : 'progress'
|
||||
},
|
||||
radius () {
|
||||
return this.size / 2 - this.strokeWidth
|
||||
},
|
||||
offset () {
|
||||
return this.radius * 3.14 / 2
|
||||
},
|
||||
strokeWidth () {
|
||||
return this.size / 10
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.loader-svg {
|
||||
position: absolute;
|
||||
left: 0; right: 0; top: 0; bottom: 0;
|
||||
fill: none;
|
||||
stroke-linecap: round;
|
||||
stroke: var(--color-accent);
|
||||
}
|
||||
|
||||
.loader-svg.bg {
|
||||
stroke: var(--color-gray-light-3);
|
||||
}
|
||||
|
||||
.loading .loader-svg.front {
|
||||
will-change: transform;
|
||||
animation: fill-animation-loading 1s cubic-bezier(1,1,1,1) 0s infinite;
|
||||
transform-origin: center;
|
||||
}
|
||||
|
||||
/*
|
||||
We can't change anything in loading animation except transform, opacity and filter. Because in
|
||||
our case the Main Thread can be busy and animation will be frozen (e. g. getting a result set
|
||||
from the web-worker after query execution).
|
||||
But transform, opacity and filter trigger changes only in the Composite Layer stage in rendering
|
||||
waterfall. Hence they can be processed only with Compositor Thread while the Main Thread
|
||||
processes something else.
|
||||
https://www.viget.com/articles/animation-performance-101-browser-under-the-hood/
|
||||
*/
|
||||
@keyframes fill-animation-loading {
|
||||
0% {
|
||||
transform: rotate(0deg);
|
||||
}
|
||||
100% {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
|
||||
.progress .loader-svg.front {
|
||||
transition: stroke-dasharray 0.2s;
|
||||
}
|
||||
|
||||
.progress .loader-svg.bg {
|
||||
animation: bg-animation 1.5s cubic-bezier(1,1,1,1) 0s infinite;
|
||||
}
|
||||
|
||||
@keyframes bg-animation{
|
||||
0% {
|
||||
r: 8;
|
||||
}
|
||||
50% {
|
||||
stroke: var(--color-gray-light-2);
|
||||
r: 9;
|
||||
}
|
||||
100% {
|
||||
r: 8;
|
||||
}
|
||||
}
|
||||
|
||||
</style>
|
||||
85
src/components/Logs.vue
Normal file
@@ -0,0 +1,85 @@
|
||||
<template>
|
||||
<div class="logs-container" ref="logsContainer">
|
||||
<div v-for="(msg, index) in messages" :key="index" class="msg">
|
||||
<img v-if="msg.type === 'error'" :src="require('@/assets/images/error.svg')">
|
||||
<img v-if="msg.type === 'info'" :src="require('@/assets/images/info.svg')" width="20px">
|
||||
<img v-if="msg.type === 'success'" :src="require('@/assets/images/success.svg')">
|
||||
<loading-indicator v-if="msg.type === 'loading'" :progress="msg.progress" />
|
||||
<span class="msg-text">{{ serializeMessage(msg) }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import LoadingIndicator from '@/components/LoadingIndicator'
|
||||
|
||||
export default {
|
||||
name: 'logs',
|
||||
props: ['messages'],
|
||||
components: { LoadingIndicator },
|
||||
watch: {
|
||||
'messages.length': 'scrollToBottom'
|
||||
},
|
||||
mounted () {
|
||||
this.scrollToBottom()
|
||||
},
|
||||
methods: {
|
||||
async scrollToBottom () {
|
||||
const container = this.$refs.logsContainer
|
||||
if (container) {
|
||||
await this.$nextTick()
|
||||
container.scrollTop = container.scrollHeight
|
||||
}
|
||||
},
|
||||
|
||||
serializeMessage (msg) {
|
||||
let result = ''
|
||||
if (msg.row !== null && msg.row !== undefined) {
|
||||
if (msg.type === 'error') {
|
||||
result += `Error in row ${msg.row}. `
|
||||
} else {
|
||||
result += `Information about row ${msg.row}. `
|
||||
}
|
||||
}
|
||||
|
||||
result += msg.message
|
||||
if (!(/(\.|!|\?)$/.test(result))) {
|
||||
result += '.'
|
||||
}
|
||||
|
||||
if (msg.hint) {
|
||||
result += ` ${msg.hint}`
|
||||
}
|
||||
return result
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.logs-container {
|
||||
background-color: var(--color-white);
|
||||
padding: 0 5px;
|
||||
border-radius: 5px;
|
||||
border: 1px solid var(--color-border-light);
|
||||
box-sizing: border-box;
|
||||
overflow-y: scroll;
|
||||
color: var(--color-text-base);
|
||||
}
|
||||
.msg {
|
||||
padding: 16px 7px;
|
||||
border-bottom: 1px solid var(--color-border-light);
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
font-family: monospace;
|
||||
}
|
||||
|
||||
.msg:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
.msg-text {
|
||||
margin-left: 6px;
|
||||
margin-top: 2px;
|
||||
}
|
||||
</style>
|
||||
@@ -3,13 +3,13 @@
|
||||
ref="container"
|
||||
:class="[
|
||||
'splitpanes',
|
||||
`splitpanes--${horizontal ? 'horizontal' : 'vertical'}`,
|
||||
{ 'splitpanes--dragging': touch.dragging }
|
||||
`splitpanes-${horizontal ? 'horizontal' : 'vertical'}`,
|
||||
{ 'splitpanes-dragging': dragging }
|
||||
]"
|
||||
>
|
||||
<div class="movable-splitter" ref="movableSplitter" :style="movableSplitterStyle" />
|
||||
<div
|
||||
class="splitpanes__pane"
|
||||
class="splitpanes-pane"
|
||||
ref="left"
|
||||
:size="paneBefore.size"
|
||||
max-size="30"
|
||||
@@ -19,20 +19,20 @@
|
||||
</div>
|
||||
<!-- Splitter start-->
|
||||
<div
|
||||
class="splitpanes__splitter"
|
||||
@mousedown="onMouseDown"
|
||||
@touchstart="onMouseDown"
|
||||
class="splitpanes-splitter"
|
||||
@mousedown="bindEvents"
|
||||
@touchstart="bindEvents"
|
||||
>
|
||||
<div
|
||||
:class="[
|
||||
'toggle-btns',
|
||||
{'both': after.max === 100 && before.max === 100 && after.size > 0 && before.size > 0}
|
||||
{'both': after.max === 100 && before.max === 100 && paneAfter.size > 0 && paneBefore.size > 0}
|
||||
]"
|
||||
>
|
||||
<div
|
||||
v-if="after.max === 100 && after.size > 0"
|
||||
v-if="after.max === 100 && paneAfter.size > 0"
|
||||
class="toggle-btn"
|
||||
@click="togglePane('before')"
|
||||
@click="togglePane(paneBefore)"
|
||||
>
|
||||
<img
|
||||
class="direction-icon"
|
||||
@@ -41,9 +41,9 @@
|
||||
>
|
||||
</div>
|
||||
<div
|
||||
v-if="before.max === 100 && before.size > 0"
|
||||
v-if="before.max === 100 && paneBefore.size > 0"
|
||||
class="toggle-btn"
|
||||
@click="togglePane('after')"
|
||||
@click="togglePane(paneAfter)"
|
||||
>
|
||||
<img
|
||||
class="direction-icon"
|
||||
@@ -55,7 +55,7 @@
|
||||
</div>
|
||||
<!-- splitter end -->
|
||||
<div
|
||||
class="splitpanes__pane"
|
||||
class="splitpanes-pane"
|
||||
ref="right"
|
||||
:style="styles.after"
|
||||
>
|
||||
@@ -65,6 +65,7 @@
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import splitter from './splitter'
|
||||
|
||||
export default {
|
||||
name: 'Splitpanes',
|
||||
@@ -82,10 +83,7 @@ export default {
|
||||
before: this.before.size,
|
||||
after: this.after.size
|
||||
},
|
||||
touch: {
|
||||
mouseDown: false,
|
||||
dragging: false
|
||||
},
|
||||
dragging: false,
|
||||
movableSplitter: {
|
||||
top: 0,
|
||||
left: 0,
|
||||
@@ -108,38 +106,42 @@ export default {
|
||||
},
|
||||
directionBeforeIconStyle () {
|
||||
const expanded = this.paneBefore.size !== 0
|
||||
const translation = 'translate(-50%, -50%)'
|
||||
const translation = 'translate(-50%, -50%) '
|
||||
let rotation = ''
|
||||
|
||||
if (this.horizontal) {
|
||||
return {
|
||||
transform: `${translation} ${expanded ? 'rotate(90deg)' : 'rotate(-90deg)'}`
|
||||
}
|
||||
rotation = expanded ? 'rotate(90deg)' : 'rotate(-90deg)'
|
||||
} else {
|
||||
return {
|
||||
transform: `${translation} ${expanded ? 'rotate(0deg)' : 'rotate(180deg)'}`
|
||||
rotation = expanded ? 'rotate(0deg)' : 'rotate(180deg)'
|
||||
}
|
||||
|
||||
return {
|
||||
transform: translation + rotation
|
||||
}
|
||||
},
|
||||
directionAfterIconStyle () {
|
||||
const expanded = this.paneAfter.size !== 0
|
||||
const translation = 'translate(-50%, -50%)'
|
||||
let rotation = ''
|
||||
|
||||
if (this.horizontal) {
|
||||
return {
|
||||
transform: `${translation} ${expanded ? 'rotate(-90deg)' : 'rotate(90deg)'}`
|
||||
}
|
||||
rotation = expanded ? 'rotate(-90deg)' : 'rotate(90deg)'
|
||||
} else {
|
||||
return {
|
||||
transform: `${translation} ${expanded ? 'rotate(180deg)' : 'rotate(0deg)'}`
|
||||
rotation = expanded ? 'rotate(180deg)' : 'rotate(0deg)'
|
||||
}
|
||||
|
||||
return {
|
||||
transform: translation + rotation
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
methods: {
|
||||
bindEvents () {
|
||||
// Passive: false to prevent scrolling while touch dragging.
|
||||
document.addEventListener('mousemove', this.onMouseMove, { passive: false })
|
||||
document.addEventListener('mouseup', this.onMouseUp)
|
||||
|
||||
// Passive: false to prevent scrolling while touch dragging.
|
||||
if ('ontouchstart' in window) {
|
||||
document.addEventListener('touchmove', this.onMouseMove, { passive: false })
|
||||
document.addEventListener('touchend', this.onMouseUp)
|
||||
@@ -156,24 +158,15 @@ export default {
|
||||
}
|
||||
},
|
||||
|
||||
onMouseDown () {
|
||||
this.bindEvents()
|
||||
this.touch.mouseDown = true
|
||||
},
|
||||
|
||||
onMouseMove (event) {
|
||||
if (this.touch.mouseDown) {
|
||||
// Prevent scrolling while touch dragging (only works with an active event, eg. passive: false).
|
||||
event.preventDefault()
|
||||
this.touch.dragging = true
|
||||
this.$set(this.movableSplitter, 'visibility', 'visible')
|
||||
this.dragging = true
|
||||
this.movableSplitter.visibility = 'visible'
|
||||
this.moveSplitter(event)
|
||||
}
|
||||
},
|
||||
|
||||
onMouseUp () {
|
||||
this.touch.mouseDown = false
|
||||
if (this.touch.dragging) {
|
||||
if (this.dragging) {
|
||||
const dragPercentage = this.horizontal
|
||||
? this.movableSplitter.top
|
||||
: this.movableSplitter.left
|
||||
@@ -186,65 +179,31 @@ export default {
|
||||
left: 0,
|
||||
visibility: 'hidden'
|
||||
}
|
||||
|
||||
this.dragging = false
|
||||
}
|
||||
|
||||
// Keep dragging flag until click event is finished (click happens immediately after mouseup)
|
||||
// in order to prevent emitting `splitter-click` event if splitter was dragged.
|
||||
setTimeout(() => {
|
||||
this.touch.dragging = false
|
||||
this.unbindEvents()
|
||||
}, 100)
|
||||
},
|
||||
|
||||
// Get the cursor position relative to the splitpane container.
|
||||
getCurrentMouseDrag (event) {
|
||||
const rect = this.container.getBoundingClientRect()
|
||||
const { clientX, clientY } = ('ontouchstart' in window && event.touches)
|
||||
? event.touches[0]
|
||||
: event
|
||||
return {
|
||||
x: clientX - rect.left,
|
||||
y: clientY - rect.top
|
||||
}
|
||||
},
|
||||
|
||||
// Returns the drag percentage of the splitter relative to the 2 panes it's inbetween.
|
||||
// if the sum of size of the 2 cells is 60%, the dragPercentage range will be 0 to 100% of this 60%.
|
||||
getCurrentDragPercentage (drag) {
|
||||
drag = drag[this.horizontal ? 'y' : 'x']
|
||||
// In the code bellow 'size' refers to 'width' for vertical and 'height' for horizontal layout.
|
||||
const containerSize = this.container[this.horizontal ? 'clientHeight' : 'clientWidth']
|
||||
return drag * 100 / containerSize
|
||||
},
|
||||
|
||||
moveSplitter (event) {
|
||||
const dragPercentage = this.getCurrentDragPercentage(this.getCurrentMouseDrag(event))
|
||||
const paneBefore = this.paneBefore
|
||||
const paneAfter = this.paneAfter
|
||||
|
||||
const paneBeforeMaxReached = paneBefore.max < 100 && (dragPercentage >= paneBefore.max)
|
||||
const paneAfterMaxReached = paneAfter.max < 100 && (dragPercentage <= 100 - paneAfter.max)
|
||||
|
||||
const splitterInfo = {
|
||||
container: this.container,
|
||||
paneBeforeMax: this.paneBefore.max,
|
||||
paneAfterMax: this.paneAfter.max,
|
||||
isHorisontal: this.horizontal
|
||||
}
|
||||
const offset = splitter.calculateOffset(event, splitterInfo)
|
||||
const dir = this.horizontal ? 'top' : 'left'
|
||||
|
||||
// Prevent dragging beyond pane max.
|
||||
if (paneBeforeMaxReached || paneAfterMaxReached) {
|
||||
if (paneBeforeMaxReached) {
|
||||
this.$set(this.movableSplitter, dir, paneBefore.max)
|
||||
} else {
|
||||
this.$set(this.movableSplitter, dir, Math.max(100 - paneAfter.max, 0))
|
||||
}
|
||||
} else {
|
||||
this.$set(this.movableSplitter, dir, Math.min(Math.max(dragPercentage, 0), paneBefore.max))
|
||||
}
|
||||
this.movableSplitter[dir] = offset
|
||||
},
|
||||
togglePane (toggledPane) {
|
||||
const pane = toggledPane === 'before' ? this.paneBefore : this.paneAfter
|
||||
|
||||
togglePane (pane) {
|
||||
if (pane.size > 0) {
|
||||
this.beforeMinimising.before = this.paneBefore.size
|
||||
this.beforeMinimising.after = this.paneAfter.size
|
||||
pane.size = 0
|
||||
const otherPane = toggledPane === 'before' ? this.paneAfter : this.paneBefore
|
||||
const otherPane = pane === this.paneBefore ? this.paneAfter : this.paneBefore
|
||||
otherPane.size = 100 - pane.size
|
||||
} else {
|
||||
this.paneBefore.size = this.beforeMinimising.before
|
||||
@@ -265,11 +224,11 @@ export default {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.splitpanes--vertical {flex-direction: row;}
|
||||
.splitpanes--horizontal {flex-direction: column;}
|
||||
.splitpanes--dragging * {user-select: none;}
|
||||
.splitpanes-vertical {flex-direction: row;}
|
||||
.splitpanes-horizontal {flex-direction: column;}
|
||||
.splitpanes-dragging * {user-select: none;}
|
||||
|
||||
.splitpanes__pane {
|
||||
.splitpanes-pane {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
overflow: auto;
|
||||
@@ -277,16 +236,16 @@ export default {
|
||||
|
||||
/* Splitter */
|
||||
|
||||
.splitpanes--vertical > .splitpanes__splitter,
|
||||
.splitpanes--vertical.splitpanes--dragging {
|
||||
.splitpanes-vertical > .splitpanes-splitter,
|
||||
.splitpanes-vertical.splitpanes-dragging {
|
||||
cursor: col-resize;
|
||||
}
|
||||
.splitpanes--horizontal > .splitpanes__splitter,
|
||||
.splitpanes--horizontal.splitpanes--dragging {
|
||||
.splitpanes-horizontal > .splitpanes-splitter,
|
||||
.splitpanes-horizontal.splitpanes-dragging {
|
||||
cursor: row-resize;
|
||||
}
|
||||
|
||||
.splitpanes__splitter {
|
||||
.splitpanes-splitter {
|
||||
touch-action: none;
|
||||
background-color: var(--color-bg-light);
|
||||
box-sizing: border-box;
|
||||
@@ -295,12 +254,12 @@ export default {
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
.splitpanes--horizontal > .splitpanes__splitter {
|
||||
.splitpanes-horizontal > .splitpanes-splitter {
|
||||
border-top: 1px solid var(--color-border-light);
|
||||
border-bottom: 1px solid var(--color-border-light);
|
||||
}
|
||||
|
||||
.splitpanes--vertical > .splitpanes__splitter {
|
||||
.splitpanes-vertical > .splitpanes-splitter {
|
||||
border-left: 1px solid var(--color-border-light);
|
||||
border-right: 1px solid var(--color-border-light);
|
||||
}
|
||||
@@ -310,15 +269,15 @@ export default {
|
||||
background-color:rgba(162, 177, 198, 0.5);
|
||||
}
|
||||
|
||||
.splitpanes--vertical > .splitpanes__splitter,
|
||||
.splitpanes--vertical > .movable-splitter {
|
||||
.splitpanes-vertical > .splitpanes-splitter,
|
||||
.splitpanes-vertical > .movable-splitter {
|
||||
width: 8px;
|
||||
z-index: 5;
|
||||
height: 100%
|
||||
}
|
||||
|
||||
.splitpanes--horizontal > .splitpanes__splitter,
|
||||
.splitpanes--horizontal > .movable-splitter {
|
||||
.splitpanes-horizontal > .splitpanes-splitter,
|
||||
.splitpanes-horizontal > .movable-splitter {
|
||||
height: 8px;
|
||||
width: 100%;
|
||||
z-index: 5;
|
||||
@@ -332,11 +291,11 @@ export default {
|
||||
display: flex;
|
||||
}
|
||||
|
||||
.splitpanes--vertical > .splitpanes__splitter .toggle-btns {
|
||||
.splitpanes-vertical > .splitpanes-splitter .toggle-btns {
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.splitpanes--horizontal > .splitpanes__splitter .toggle-btns {
|
||||
.splitpanes-horizontal > .splitpanes-splitter .toggle-btns {
|
||||
flex-direction: row;
|
||||
}
|
||||
|
||||
@@ -349,12 +308,12 @@ export default {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.splitpanes--vertical > .splitpanes__splitter .toggle-btn {
|
||||
.splitpanes-vertical > .splitpanes-splitter .toggle-btn {
|
||||
height: 49px;
|
||||
width: 8px;
|
||||
}
|
||||
|
||||
.splitpanes--horizontal > .splitpanes__splitter .toggle-btn {
|
||||
.splitpanes-horizontal > .splitpanes-splitter .toggle-btn {
|
||||
width: 49px;
|
||||
height: 8px;
|
||||
}
|
||||
@@ -365,20 +324,20 @@ export default {
|
||||
left: 50%;
|
||||
}
|
||||
|
||||
.splitpanes--horizontal > .splitpanes__splitter .toggle-btns.both .toggle-btn:first-child {
|
||||
.splitpanes-horizontal > .splitpanes-splitter .toggle-btns.both .toggle-btn:first-child {
|
||||
border-radius: var(--border-radius-small) 0 0 var(--border-radius-small);
|
||||
}
|
||||
|
||||
.splitpanes--horizontal > .splitpanes__splitter .toggle-btns.both .toggle-btn:last-child {
|
||||
.splitpanes-horizontal > .splitpanes-splitter .toggle-btns.both .toggle-btn:last-child {
|
||||
border-radius: 0 var(--border-radius-small) var(--border-radius-small) 0;
|
||||
margin-left: -1px;
|
||||
}
|
||||
|
||||
.splitpanes--vertical > .splitpanes__splitter .toggle-btns.both .toggle-btn:first-child {
|
||||
.splitpanes-vertical > .splitpanes-splitter .toggle-btns.both .toggle-btn:first-child {
|
||||
border-radius: var(--border-radius-small) var(--border-radius-small) 0 0;
|
||||
}
|
||||
|
||||
.splitpanes--vertical > .splitpanes__splitter .toggle-btns.both .toggle-btn:last-child {
|
||||
.splitpanes-vertical > .splitpanes-splitter .toggle-btns.both .toggle-btn:last-child {
|
||||
border-radius: 0 0 var(--border-radius-small) var(--border-radius-small);
|
||||
margin-top: -1px;
|
||||
}
|
||||
36
src/components/Splitpanes/splitter.js
Normal file
@@ -0,0 +1,36 @@
|
||||
export default {
|
||||
// Get the cursor position relative to the splitpane container.
|
||||
getCurrentMouseDrag (event, container) {
|
||||
const rect = container.getBoundingClientRect()
|
||||
const { clientX, clientY } = ('ontouchstart' in window && event.touches)
|
||||
? event.touches[0]
|
||||
: event
|
||||
return {
|
||||
x: clientX - rect.left,
|
||||
y: clientY - rect.top
|
||||
}
|
||||
},
|
||||
|
||||
// Returns the drag percentage of the splitter relative to the 2 panes it's inbetween.
|
||||
getCurrentDragPercentage (event, container, isHorisontal) {
|
||||
let drag = this.getCurrentMouseDrag(event, container)
|
||||
drag = drag[isHorisontal ? 'y' : 'x']
|
||||
const containerSize = container[isHorisontal ? 'clientHeight' : 'clientWidth']
|
||||
return drag * 100 / containerSize
|
||||
},
|
||||
|
||||
// Returns the new position in percents.
|
||||
calculateOffset (event, { container, isHorisontal, paneBeforeMax, paneAfterMax }) {
|
||||
const dragPercentage = this.getCurrentDragPercentage(event, container, isHorisontal)
|
||||
|
||||
const paneBeforeMaxReached = paneBeforeMax < 100 && (dragPercentage >= paneBeforeMax)
|
||||
const paneAfterMaxReached = paneAfterMax < 100 && (dragPercentage <= 100 - paneAfterMax)
|
||||
|
||||
// Prevent dragging beyond pane max.
|
||||
if (paneBeforeMaxReached || paneAfterMaxReached) {
|
||||
return paneBeforeMaxReached ? paneBeforeMax : Math.max(100 - paneAfterMax, 0)
|
||||
} else {
|
||||
return Math.min(Math.max(dragPercentage, 0), paneBeforeMax)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,105 +0,0 @@
|
||||
<template>
|
||||
<div class="codemirror-container">
|
||||
<codemirror v-model="query" :options="cmOptions" @changes="onCmChange" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import CM from 'codemirror'
|
||||
import { codemirror } from 'vue-codemirror'
|
||||
import 'codemirror/lib/codemirror.css'
|
||||
import 'codemirror/mode/sql/sql.js'
|
||||
import 'codemirror/theme/neo.css'
|
||||
import 'codemirror/addon/hint/show-hint.js'
|
||||
import 'codemirror/addon/hint/show-hint.css'
|
||||
import 'codemirror/addon/hint/sql-hint.js'
|
||||
import { debounce } from 'debounce'
|
||||
|
||||
const sqlHint = CM.hint.sql
|
||||
CM.hint.sql = (cm, options) => {
|
||||
const token = cm.getTokenAt(cm.getCursor()).string.toUpperCase()
|
||||
const result = sqlHint(cm, options)
|
||||
// Don't show the hint if there is only one option
|
||||
// and the token is already completed with this option
|
||||
if (result.list.length === 1 && result.list[0].text.toUpperCase() === token) {
|
||||
result.list = []
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
export default {
|
||||
name: 'SqlEditor',
|
||||
props: ['value'],
|
||||
components: {
|
||||
codemirror
|
||||
},
|
||||
data () {
|
||||
return {
|
||||
query: this.value,
|
||||
cmOptions: {
|
||||
// codemirror options
|
||||
tabSize: 4,
|
||||
mode: 'text/x-mysql',
|
||||
theme: 'neo',
|
||||
lineNumbers: true,
|
||||
line: true
|
||||
}
|
||||
}
|
||||
},
|
||||
computed: {
|
||||
tables () {
|
||||
const tables = {}
|
||||
if (this.$store.state.schema) {
|
||||
this.$store.state.schema.forEach(table => {
|
||||
tables[table.name] = table.columns.map(column => column.name)
|
||||
})
|
||||
}
|
||||
return tables
|
||||
}
|
||||
},
|
||||
watch: {
|
||||
query () {
|
||||
this.$emit('input', this.query)
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
onCmChange: debounce(function (editor) {
|
||||
// Don't show autocomplete after a space or semicolon or in string literals
|
||||
const ch = editor.getTokenAt(editor.getCursor()).string.slice(-1)
|
||||
const tokenType = editor.getTokenAt(editor.getCursor()).type
|
||||
if (tokenType === 'string' || !ch || ch === ' ' || ch === ';') {
|
||||
return
|
||||
}
|
||||
|
||||
const hintOptions = {
|
||||
tables: this.tables,
|
||||
completeSingle: false,
|
||||
completeOnSingleClick: true,
|
||||
alignWithWord: false
|
||||
}
|
||||
|
||||
CM.showHint(editor, CM.hint.sql, hintOptions)
|
||||
}, 400)
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.codemirror-container {
|
||||
flex-grow: 1;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
>>> .vue-codemirror {
|
||||
height: 100%;
|
||||
max-height: 100%;
|
||||
}
|
||||
>>> .CodeMirror {
|
||||
height: 100%;
|
||||
max-height: 100%;
|
||||
}
|
||||
>>> .CodeMirror-cursor {
|
||||
width: 1px;
|
||||
background: var(--color-text-base);
|
||||
}
|
||||
</style>
|
||||
@@ -40,6 +40,8 @@
|
||||
<div class="table-footer">
|
||||
<div class="table-footer-count">
|
||||
{{ dataSet.values.length}} {{dataSet.values.length === 1 ? 'row' : 'rows'}} retrieved
|
||||
<span v-if="preview">for preview</span>
|
||||
<span v-if="time">in {{ time }}</span>
|
||||
</div>
|
||||
<pager v-show="pageCount > 1" :page-count="pageCount" v-model="currentPage" />
|
||||
</div>
|
||||
@@ -47,12 +49,12 @@
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import Pager from '@/components/Pager'
|
||||
import Pager from './Pager'
|
||||
|
||||
export default {
|
||||
name: 'SqlTable',
|
||||
components: { Pager },
|
||||
props: ['dataSet', 'height'],
|
||||
props: ['dataSet', 'time', 'height', 'preview'],
|
||||
data () {
|
||||
return {
|
||||
header: null,
|
||||
@@ -89,9 +91,6 @@ export default {
|
||||
},
|
||||
onScrollTable () {
|
||||
this.$refs['header-container'].scrollLeft = this.$refs['table-container'].scrollLeft
|
||||
},
|
||||
functionName () {
|
||||
|
||||
}
|
||||
},
|
||||
mounted () {
|
||||
@@ -1,22 +1,28 @@
|
||||
<template>
|
||||
<div>
|
||||
<div :class="['text-field-label', { error: errorMsg }]">{{ label }}</div>
|
||||
<div v-if="label" :class="['text-field-label', { error: errorMsg }, {'disabled': disabled}]">
|
||||
{{ label }}
|
||||
<hint-icon class="hint" v-if="hint" :hint="hint" :max-width="maxHintWidth || '149px'"/>
|
||||
</div>
|
||||
<input
|
||||
type="text"
|
||||
:placeholder="placeholder"
|
||||
:class="{ error: errorMsg }"
|
||||
:style="{ width: width }"
|
||||
:value="value"
|
||||
:disabled="disabled"
|
||||
@input="$emit('input', $event.target.value)"
|
||||
/>
|
||||
<div class="text-field-error">{{ errorMsg }}</div>
|
||||
<div v-show="errorMsg" class="text-field-error">{{ errorMsg }}</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import HintIcon from '@/components/svg/hint'
|
||||
export default {
|
||||
name: 'textField',
|
||||
props: ['placeholder', 'label', 'errorMsg', 'value', 'width']
|
||||
props: ['placeholder', 'label', 'errorMsg', 'value', 'width', 'hint', 'maxHintWidth', 'disabled'],
|
||||
components: { HintIcon }
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -30,6 +36,7 @@ input {
|
||||
padding: 0 8px;
|
||||
font-size: 13px;
|
||||
box-sizing: border-box;
|
||||
display: block;
|
||||
}
|
||||
|
||||
input::placeholder {
|
||||
@@ -40,24 +47,44 @@ input:focus {
|
||||
outline: none;
|
||||
}
|
||||
|
||||
input:disabled {
|
||||
background: var(--color-bg-light);
|
||||
color: var(--color-text-light-2);
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
input.error {
|
||||
border-color: var(--color-text-error);
|
||||
}
|
||||
|
||||
.text-field-label {
|
||||
font-size: 12px;
|
||||
color: var(--color-text-base);
|
||||
padding-left: 8px;
|
||||
margin-bottom: 2px;
|
||||
display: inline-block;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.text-field-label .hint{
|
||||
position: absolute;
|
||||
top: -2px;
|
||||
right: -22px;
|
||||
}
|
||||
|
||||
.text-field-label.error {
|
||||
color: var(--color-text-error);
|
||||
}
|
||||
|
||||
.text-field-label.disabled {
|
||||
color: var(--color-text-light-2);
|
||||
}
|
||||
|
||||
.text-field-error {
|
||||
color: var(--color-text-error);
|
||||
font-size: 12px;
|
||||
padding-left: 8px;
|
||||
margin-top: 2px;
|
||||
position: absolute;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
fill="none"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
@mouseover="showTooltip"
|
||||
@mouseout="$set(tooltipStyle, 'visibility', 'hidden')"
|
||||
@mouseout="hideTooltip"
|
||||
>
|
||||
<path
|
||||
d="M3 10.5V12.75C3 14.25 5.2875 15.54 8.25 15.75V13.5825L8.3475 13.5C5.34 13.32 3 12.045 3 10.5ZM9 9.75C5.685 9.75 3 8.4075 3 6.75V9C3 10.6575 5.685 12 9 12C9.2925 12 9.5775 12 9.87 12L12.75 9.09C11.55 9.54 10.2825 9.75 9 9.75ZM9 2.25C5.685 2.25 3 3.5925 3 5.25C3 6.9075 5.685 8.25 9 8.25C12.315 8.25 15 6.9075 15 5.25C15 3.5925 12.315 2.25 9 2.25ZM15.75 8.3475C15.6375 8.3475 15.5325 8.3925 15.4575 8.475L14.7075 9.225L16.245 10.725L16.995 9.975C17.1525 9.825 17.16 9.57 16.995 9.3975L16.065 8.475C15.99 8.3925 15.885 8.3475 15.78 8.3475H15.75ZM14.28 9.66L9.75 14.205V15.75H11.295L15.84 11.1975L14.28 9.66Z"
|
||||
@@ -16,13 +16,13 @@
|
||||
/>
|
||||
</svg>
|
||||
<span class="icon-tooltip" :style="tooltipStyle">
|
||||
Change database
|
||||
Load another database or CSV
|
||||
</span>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import tooltipMixin from '@/mixins/tooltips'
|
||||
import tooltipMixin from '@/tooltipMixin'
|
||||
|
||||
export default {
|
||||
name: 'changeDbIcon',
|
||||
|
||||
41
src/components/svg/clear.vue
Normal file
@@ -0,0 +1,41 @@
|
||||
<template>
|
||||
<svg
|
||||
:class="['clear-icon', {'disabled': disabled}]"
|
||||
width="20"
|
||||
height="20"
|
||||
viewBox="0 0 20 20"
|
||||
fill="none"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<path
|
||||
d="M14.3481 14.849C13.8791 15.318 13.1191 15.318 12.6511 14.849L10.0001 11.819L7.34907 14.848C6.88007 15.317 6.12007 15.317 5.65207 14.848C5.18307 14.379 5.18307 13.619 5.65207 13.151L8.41007 10.001L5.65107 6.84898C5.18207 6.37998 5.18207 5.62098 5.65107 5.15198C6.12007 4.68298 6.87907 4.68298 7.34807 5.15198L10.0001 8.18298L12.6511 5.15198C13.1201 4.68298 13.8791 4.68298 14.3481 5.15198C14.8171 5.62098 14.8171 6.38098 14.3481 6.84898L11.5901 10.001L14.3481 13.151C14.8171 13.62 14.8171 14.38 14.3481 14.849V14.849Z"
|
||||
fill="#C8D4E3"
|
||||
/>
|
||||
</svg>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
|
||||
export default {
|
||||
name: 'ClearIcon',
|
||||
props: ['disabled']
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.clear-icon {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.clear-icon:hover path {
|
||||
fill: var(--color-danger);
|
||||
}
|
||||
|
||||
.disabled.clear-icon {
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.disabled.clear-icon:hover path {
|
||||
fill: #C8D4E3;
|
||||
}
|
||||
</style>
|
||||
@@ -1,7 +1,7 @@
|
||||
<template>
|
||||
<svg
|
||||
@click.stop="$emit('click')"
|
||||
class="icon"
|
||||
:class="['icon', {'disabled': disabled }]"
|
||||
:width="size"
|
||||
:height="size"
|
||||
viewBox="0 0 14 14"
|
||||
@@ -23,6 +23,11 @@ export default {
|
||||
type: Number,
|
||||
required: false,
|
||||
default: 14
|
||||
},
|
||||
disabled: {
|
||||
type: Boolean,
|
||||
required: false,
|
||||
default: false
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -32,6 +37,9 @@ export default {
|
||||
.icon {
|
||||
cursor: pointer;
|
||||
}
|
||||
.disabled {
|
||||
pointer-events: none;
|
||||
}
|
||||
.icon:hover path {
|
||||
fill: var(--color-text-base);
|
||||
}
|
||||
|
||||
38
src/components/svg/dropDownChevron.vue
Normal file
@@ -0,0 +1,38 @@
|
||||
<template>
|
||||
<svg
|
||||
:class="['chevron-icon', {'disabled': disabled}]"
|
||||
width="20"
|
||||
height="20"
|
||||
viewBox="0 0 20 20"
|
||||
fill="none"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<path d="M6.175 7.15002L10 10.975L13.825 7.15002L15 8.33336L10 13.3334L5 8.33336L6.175 7.15002Z" fill="#C8D4E3"/>
|
||||
</svg>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
|
||||
export default {
|
||||
name: 'DropDownChevron',
|
||||
props: ['disabled']
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.chevron-icon {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.chevron-icon:hover path {
|
||||
fill: var(--color-accent);
|
||||
}
|
||||
|
||||
.disabled.chevron-icon {
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.disabled.chevron-icon:hover path {
|
||||
fill: #C8D4E3;
|
||||
}
|
||||
</style>
|
||||
@@ -9,7 +9,7 @@
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
@click.stop="$emit('click')"
|
||||
@mouseover="showTooltip"
|
||||
@mouseout="$set(tooltipStyle, 'visibility', 'hidden')"
|
||||
@mouseout="hideTooltip"
|
||||
>
|
||||
<path
|
||||
d="M10.5 1.5H4.5C3.675 1.5 3 2.175 3 3V15C3 15.825 3.675 16.5 4.5 16.5H13.5C14.325 16.5 15 15.825 15 15V6L10.5 1.5ZM13.5 15H4.5V3H9.75V6.75H13.5V15ZM12 8.25V13.575L10.425 12L8.325 14.1L6.225 12L8.325 9.9L6.675 8.25H12Z"
|
||||
@@ -17,24 +17,26 @@
|
||||
/>
|
||||
</svg>
|
||||
<span class="icon-tooltip" :style="tooltipStyle">
|
||||
Export query to file
|
||||
{{ tooltip }}
|
||||
</span>
|
||||
</span>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import tooltipMixin from '@/mixins/tooltips'
|
||||
import tooltipMixin from '@/tooltipMixin'
|
||||
|
||||
export default {
|
||||
name: 'ExportIcon',
|
||||
mixins: [tooltipMixin]
|
||||
mixins: [tooltipMixin],
|
||||
props: ['tooltip']
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.icon {
|
||||
vertical-align: middle;
|
||||
display: block;
|
||||
margin: 0 12px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.icon:hover path {
|
||||
|
||||
48
src/components/svg/hint.vue
Normal file
@@ -0,0 +1,48 @@
|
||||
<template>
|
||||
<div>
|
||||
<svg
|
||||
class="hint-icon"
|
||||
width="20"
|
||||
height="20"
|
||||
viewBox="0 0 20 20"
|
||||
fill="none"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
@mouseover="showTooltip"
|
||||
@mouseout="hideTooltip"
|
||||
>
|
||||
<path d="M8.75 14.1666H10.4167V12.5H8.75V14.1666ZM9.58333 16.25C5.90833 16.25 2.91667 13.2583 2.91667 9.58333C2.91667 5.90833 5.90833 2.91667 9.58333 2.91667C13.2583 2.91667 16.25 5.90833 16.25 9.58333C16.25 13.2583 13.2583 16.25 9.58333 16.25ZM9.58333 1.25C8.48898 1.25 7.40535 1.46555 6.3943 1.88434C5.38326 2.30313 4.4646 2.91696 3.69078 3.69078C2.12797 5.25358 1.25 7.3732 1.25 9.58333C1.25 11.7935 2.12797 13.9131 3.69078 15.4759C4.4646 16.2497 5.38326 16.8635 6.3943 17.2823C7.40535 17.7011 8.48898 17.9167 9.58333 17.9167C11.7935 17.9167 13.9131 17.0387 15.4759 15.4759C17.0387 13.9131 17.9167 11.7935 17.9167 9.58333C17.9167 8.48898 17.7011 7.40535 17.2823 6.3943C16.8635 5.38326 16.2497 4.4646 15.4759 3.69078C14.7021 2.91696 13.7834 2.30313 12.7724 1.88434C11.7613 1.46555 10.6777 1.25 9.58333 1.25Z" fill="#A2B1C6"/>
|
||||
<path d="M9.91601 4.51787C8.98167 4.42606 8.05144 4.69097 7.36309 5.24472C6.68735 5.78828 6.2998 6.56661 6.2998 7.38012H7.92488C7.92488 6.97463 8.11059 6.60187 8.44779 6.33061C8.79784 6.049 9.25647 5.92005 9.73896 5.96755C10.4832 6.04076 11.0828 6.57277 11.1647 7.23265C11.2306 7.764 10.9661 8.28194 10.4744 8.58426C9.38676 9.25303 8.73742 10.343 8.73742 11.5H10.3625C10.3625 10.8243 10.7477 10.184 11.3929 9.78733C12.3808 9.17985 12.9122 8.13913 12.7798 7.07124C12.6144 5.73863 11.41 4.66476 9.91601 4.51787Z" fill="#A2B1C6"/>
|
||||
</svg>
|
||||
<span class="icon-tooltip" :style="{...tooltipStyle, maxWidth: maxWidth }">
|
||||
{{ hint }}
|
||||
</span>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import tooltipMixin from '@/tooltipMixin'
|
||||
|
||||
export default {
|
||||
name: 'HintIcon',
|
||||
props: ['hint', 'maxWidth'],
|
||||
mixins: [tooltipMixin]
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.hint-icon {
|
||||
display: block;
|
||||
cursor: pointer;
|
||||
}
|
||||
.hint-icon:hover path {
|
||||
fill: var(--color-text-base);
|
||||
}
|
||||
.icon-tooltip {
|
||||
display: block;
|
||||
white-space: normal;
|
||||
height: auto;
|
||||
line-height: normal;
|
||||
padding: 6px;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
</style>
|
||||
@@ -1,47 +0,0 @@
|
||||
import store from '@/store'
|
||||
const worker = new Worker('js/worker.sql-wasm.js')
|
||||
|
||||
export default {
|
||||
loadDb (file) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const dbName = file.name
|
||||
store.commit('saveDbName', dbName)
|
||||
const f = file
|
||||
const r = new FileReader()
|
||||
r.onload = () => {
|
||||
// on 'action: open' completed
|
||||
worker.onmessage = () => {
|
||||
const getSchemaSql = `
|
||||
SELECT name, sql
|
||||
FROM sqlite_master
|
||||
WHERE type='table' AND name NOT LIKE 'sqlite_%';`
|
||||
|
||||
// on 'action: exec' completed
|
||||
worker.onmessage = event => {
|
||||
resolve(event.data.results[0].values)
|
||||
}
|
||||
worker.postMessage({ action: 'exec', sql: getSchemaSql })
|
||||
}
|
||||
|
||||
try {
|
||||
worker.postMessage({ action: 'open', buffer: r.result }, [r.result])
|
||||
} catch (exception) {
|
||||
worker.postMessage({ action: 'open', buffer: r.result })
|
||||
}
|
||||
}
|
||||
r.readAsArrayBuffer(f)
|
||||
})
|
||||
},
|
||||
execute (commands) {
|
||||
return new Promise((resolve, reject) => {
|
||||
worker.onmessage = (event) => {
|
||||
if (event.data.error) {
|
||||
reject(event.data.error)
|
||||
}
|
||||
// if it was more than one select - take only the first one
|
||||
resolve(event.data.results[0])
|
||||
}
|
||||
worker.postMessage({ action: 'exec', sql: commands })
|
||||
})
|
||||
}
|
||||
}
|
||||
79
src/lib/database/_sql.js
Normal file
@@ -0,0 +1,79 @@
|
||||
import initSqlJs from 'sql.js/dist/sql-wasm.js'
|
||||
import dbUtils from './_statements'
|
||||
|
||||
let SQL = null
|
||||
const sqlModuleReady = initSqlJs().then(sqlModule => { SQL = sqlModule })
|
||||
|
||||
export default class Sql {
|
||||
constructor () {
|
||||
this.db = null
|
||||
}
|
||||
|
||||
static build () {
|
||||
return sqlModuleReady
|
||||
.then(() => {
|
||||
return new Sql()
|
||||
})
|
||||
}
|
||||
|
||||
createDb (buffer) {
|
||||
if (this.db != null) this.db.close()
|
||||
this.db = new SQL.Database(buffer)
|
||||
return this.db
|
||||
}
|
||||
|
||||
open (buffer) {
|
||||
this.createDb(buffer && new Uint8Array(buffer))
|
||||
return {
|
||||
ready: true
|
||||
}
|
||||
}
|
||||
|
||||
exec (sql, params) {
|
||||
if (this.db === null) {
|
||||
this.createDb()
|
||||
}
|
||||
if (!sql) {
|
||||
throw new Error('exec: Missing query string')
|
||||
}
|
||||
return this.db.exec(sql, params)
|
||||
}
|
||||
|
||||
import (columns, values, progressCounterId, progressCallback, chunkSize = 1500) {
|
||||
this.createDb()
|
||||
this.db.exec(dbUtils.getCreateStatement(columns, values))
|
||||
const chunks = dbUtils.generateChunks(values, chunkSize)
|
||||
const chunksAmount = Math.ceil(values.length / chunkSize)
|
||||
let count = 0
|
||||
const insertStr = dbUtils.getInsertStmt(columns)
|
||||
const insertStmt = this.db.prepare(insertStr)
|
||||
|
||||
progressCallback({ progress: 0, id: progressCounterId })
|
||||
for (const chunk of chunks) {
|
||||
this.db.exec('BEGIN')
|
||||
for (const row of chunk) {
|
||||
insertStmt.run(row)
|
||||
}
|
||||
this.db.exec('COMMIT')
|
||||
count++
|
||||
progressCallback({ progress: 100 * (count / chunksAmount), id: progressCounterId })
|
||||
}
|
||||
|
||||
return {
|
||||
finish: true
|
||||
}
|
||||
}
|
||||
|
||||
export () {
|
||||
return this.db.export()
|
||||
}
|
||||
|
||||
close () {
|
||||
if (this.db) {
|
||||
this.db.close()
|
||||
}
|
||||
return {
|
||||
finished: true
|
||||
}
|
||||
}
|
||||
}
|
||||
44
src/lib/database/_statements.js
Normal file
@@ -0,0 +1,44 @@
|
||||
export default {
|
||||
* generateChunks (arr, size) {
|
||||
const count = Math.ceil(arr.length / size)
|
||||
|
||||
for (let i = 0; i <= count - 1; i++) {
|
||||
const start = size * i
|
||||
const end = start + size
|
||||
yield arr.slice(start, end)
|
||||
}
|
||||
},
|
||||
|
||||
getInsertStmt (columns) {
|
||||
const colList = `"${columns.join('", "')}"`
|
||||
const params = columns.map(() => '?').join(', ')
|
||||
return `INSERT INTO csv_import (${colList}) VALUES (${params});`
|
||||
},
|
||||
|
||||
getCreateStatement (columns, values) {
|
||||
let result = 'CREATE table csv_import('
|
||||
columns.forEach((col, index) => {
|
||||
// Get the first row of values to determine types
|
||||
const value = values[0][index]
|
||||
let type = ''
|
||||
switch (typeof value) {
|
||||
case 'number': {
|
||||
type = 'REAL'
|
||||
break
|
||||
}
|
||||
case 'boolean': {
|
||||
type = 'INTEGER'
|
||||
break
|
||||
}
|
||||
case 'string': {
|
||||
type = 'TEXT'
|
||||
break
|
||||
}
|
||||
default: type = 'TEXT'
|
||||
}
|
||||
result += `"${col}" ${type}, `
|
||||
})
|
||||
result = result.replace(/,\s$/, ');')
|
||||
return result
|
||||
}
|
||||
}
|
||||
34
src/lib/database/_worker.js
Normal file
@@ -0,0 +1,34 @@
|
||||
import registerPromiseWorker from 'promise-worker/register'
|
||||
import Sql from './_sql'
|
||||
|
||||
const sqlReady = Sql.build()
|
||||
|
||||
function processMsg (sql) {
|
||||
const data = this
|
||||
switch (data && data.action) {
|
||||
case 'open':
|
||||
return sql.open(data.buffer)
|
||||
case 'exec':
|
||||
return sql.exec(data.sql, data.params)
|
||||
case 'import':
|
||||
return sql.import(data.columns, data.values, data.progressCounterId, postMessage)
|
||||
case 'export':
|
||||
return sql.export()
|
||||
case 'close':
|
||||
return sql.close()
|
||||
default:
|
||||
throw new Error('Invalid action : ' + (data && data.action))
|
||||
}
|
||||
}
|
||||
|
||||
function onError (error) {
|
||||
return {
|
||||
error: error.message
|
||||
}
|
||||
}
|
||||
|
||||
registerPromiseWorker(data => {
|
||||
return sqlReady
|
||||
.then(processMsg.bind(data))
|
||||
.catch(onError)
|
||||
})
|
||||
167
src/lib/database/index.js
Normal file
@@ -0,0 +1,167 @@
|
||||
import sqliteParser from 'sqlite-parser'
|
||||
import fu from '@/lib/utils/fileIo'
|
||||
// We can import workers like so because of worker-loader:
|
||||
// https://webpack.js.org/loaders/worker-loader/
|
||||
import Worker from './_worker.js'
|
||||
|
||||
// Use promise-worker in order to turn worker into the promise based one:
|
||||
// https://github.com/nolanlawson/promise-worker
|
||||
import PromiseWorker from 'promise-worker'
|
||||
|
||||
function getNewDatabase () {
|
||||
const worker = new Worker()
|
||||
return new Database(worker)
|
||||
}
|
||||
|
||||
export default {
|
||||
getNewDatabase
|
||||
}
|
||||
|
||||
let progressCounterIds = 0
|
||||
class Database {
|
||||
constructor (worker) {
|
||||
this.worker = worker
|
||||
this.pw = new PromiseWorker(worker)
|
||||
|
||||
this.importProgresses = {}
|
||||
worker.addEventListener('message', e => {
|
||||
const progress = e.data.progress
|
||||
if (progress !== undefined) {
|
||||
const id = e.data.id
|
||||
this.importProgresses[id].dispatchEvent(new CustomEvent('progress', {
|
||||
detail: progress
|
||||
}))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
shutDown () {
|
||||
this.worker.terminate()
|
||||
}
|
||||
|
||||
createProgressCounter (callback) {
|
||||
const id = progressCounterIds++
|
||||
this.importProgresses[id] = new EventTarget()
|
||||
this.importProgresses[id].addEventListener('progress', e => { callback(e.detail) })
|
||||
return id
|
||||
}
|
||||
|
||||
deleteProgressCounter (id) {
|
||||
delete this.importProgresses[id]
|
||||
}
|
||||
|
||||
async importDb (name, data, progressCounterId) {
|
||||
const result = await this.pw.postMessage({
|
||||
action: 'import',
|
||||
columns: data.columns,
|
||||
values: data.values,
|
||||
progressCounterId
|
||||
})
|
||||
|
||||
if (result.error) {
|
||||
throw new Error(result.error)
|
||||
}
|
||||
|
||||
return await this.getSchema(name)
|
||||
}
|
||||
|
||||
async loadDb (file) {
|
||||
const fileContent = file ? await fu.readAsArrayBuffer(file) : null
|
||||
const res = await this.pw.postMessage({ action: 'open', buffer: fileContent })
|
||||
|
||||
if (res.error) {
|
||||
throw new Error(res.error)
|
||||
}
|
||||
|
||||
const dbName = file ? file.name.replace(/\.[^.]+$/, '') : 'database'
|
||||
return this.getSchema(dbName)
|
||||
}
|
||||
|
||||
async getSchema (name) {
|
||||
const getSchemaSql = `
|
||||
SELECT name, sql
|
||||
FROM sqlite_master
|
||||
WHERE type='table' AND name NOT LIKE 'sqlite_%';
|
||||
`
|
||||
const result = await this.execute(getSchemaSql)
|
||||
// Parse DDL statements to get column names and types
|
||||
const parsedSchema = []
|
||||
if (result && result.values) {
|
||||
result.values.forEach(item => {
|
||||
parsedSchema.push({
|
||||
name: item[0],
|
||||
columns: getColumns(item[1])
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// Return db name and schema
|
||||
return {
|
||||
dbName: name,
|
||||
schema: parsedSchema
|
||||
}
|
||||
}
|
||||
|
||||
async execute (commands) {
|
||||
const results = await this.pw.postMessage({ action: 'exec', sql: commands })
|
||||
|
||||
if (results.error) {
|
||||
throw new Error(results.error)
|
||||
}
|
||||
// if it was more than one select - take only the last one
|
||||
return results[results.length - 1]
|
||||
}
|
||||
|
||||
async export (fileName) {
|
||||
const data = await this.pw.postMessage({ action: 'export' })
|
||||
|
||||
if (data.error) {
|
||||
throw new Error(data.error)
|
||||
}
|
||||
fu.exportToFile(data, fileName)
|
||||
}
|
||||
}
|
||||
|
||||
function getAst (sql) {
|
||||
// There is a bug is sqlite-parser
|
||||
// It throws an error if tokenizer has an arguments:
|
||||
// https://github.com/codeschool/sqlite-parser/issues/59
|
||||
const fixedSql = sql
|
||||
.replace(/(tokenize=[^,]+)"tokenchars=.+?"/, '$1')
|
||||
.replace(/(tokenize=[^,]+)"remove_diacritics=.+?"/, '$1')
|
||||
.replace(/(tokenize=[^,]+)"separators=.+?"/, '$1')
|
||||
.replace(/tokenize=.+?(,|\))/, 'tokenize=unicode61$1')
|
||||
|
||||
return sqliteParser(fixedSql)
|
||||
}
|
||||
|
||||
/*
|
||||
* Return an array of columns with name and type. E.g.:
|
||||
* [
|
||||
* { name: 'id', type: 'INTEGER' },
|
||||
* { name: 'title', type: 'NVARCHAR(30)' },
|
||||
* ]
|
||||
*/
|
||||
function getColumns (sql) {
|
||||
const columns = []
|
||||
const ast = getAst(sql)
|
||||
|
||||
const columnDefinition = ast.statement[0].format === 'table'
|
||||
? ast.statement[0].definition
|
||||
: ast.statement[0].result.args.expression // virtual table
|
||||
|
||||
columnDefinition.forEach(item => {
|
||||
if (item.variant === 'column' && ['identifier', 'definition'].includes(item.type)) {
|
||||
let type = item.datatype ? item.datatype.variant : 'N/A'
|
||||
if (item.datatype && item.datatype.args) {
|
||||
type = type + '(' + item.datatype.args.expression[0].value
|
||||
if (item.datatype.args.expression.length === 2) {
|
||||
type = type + ', ' + item.datatype.args.expression[1].value
|
||||
}
|
||||
type = type + ')'
|
||||
}
|
||||
columns.push({ name: item.name, type: type })
|
||||
}
|
||||
})
|
||||
return columns
|
||||
}
|
||||
96
src/lib/storedQueries.js
Normal file
@@ -0,0 +1,96 @@
|
||||
import { nanoid } from 'nanoid'
|
||||
import fu from '@/lib/utils/fileIo'
|
||||
|
||||
export default {
|
||||
getStoredQueries () {
|
||||
return JSON.parse(localStorage.getItem('myQueries')) || []
|
||||
},
|
||||
|
||||
duplicateQuery (baseQuery) {
|
||||
const newQuery = JSON.parse(JSON.stringify(baseQuery))
|
||||
newQuery.name = newQuery.name + ' Copy'
|
||||
newQuery.id = nanoid()
|
||||
newQuery.createdAt = new Date()
|
||||
delete newQuery.isPredefined
|
||||
|
||||
return newQuery
|
||||
},
|
||||
|
||||
isTabNeedName (queryTab) {
|
||||
const isFromScratch = !queryTab.initName
|
||||
return queryTab.isPredefined || isFromScratch
|
||||
},
|
||||
|
||||
save (queryTab, newName) {
|
||||
const value = {
|
||||
id: queryTab.isPredefined ? nanoid() : queryTab.id,
|
||||
query: queryTab.query,
|
||||
chart: queryTab.$refs.chart.getChartStateForSave(),
|
||||
name: newName || queryTab.initName
|
||||
}
|
||||
|
||||
// Get queries from local storage
|
||||
const myQueries = this.getStoredQueries()
|
||||
|
||||
// Set createdAt
|
||||
if (newName) {
|
||||
value.createdAt = new Date()
|
||||
} else {
|
||||
var queryIndex = myQueries.findIndex(oldQuery => oldQuery.id === queryTab.id)
|
||||
value.createdAt = myQueries[queryIndex].createdAt
|
||||
}
|
||||
|
||||
// Insert in queries list
|
||||
if (newName) {
|
||||
myQueries.push(value)
|
||||
} else {
|
||||
myQueries[queryIndex] = value
|
||||
}
|
||||
|
||||
// Save to local storage
|
||||
this.updateStorage(myQueries)
|
||||
return value
|
||||
},
|
||||
|
||||
updateStorage (value) {
|
||||
localStorage.setItem('myQueries', JSON.stringify(value))
|
||||
},
|
||||
|
||||
serialiseQueries (queryList) {
|
||||
const preparedData = JSON.parse(JSON.stringify(queryList))
|
||||
preparedData.forEach(query => delete query.isPredefined)
|
||||
return JSON.stringify(preparedData, null, 4)
|
||||
},
|
||||
|
||||
deserialiseQueries (str) {
|
||||
let queryList = JSON.parse(str)
|
||||
// Turn data into array if they are not
|
||||
if (!Array.isArray(queryList)) {
|
||||
queryList = [queryList]
|
||||
}
|
||||
|
||||
// Generate new ids if they are the same as existing queries
|
||||
queryList.forEach(query => {
|
||||
const allQueriesIds = this.getStoredQueries().map(query => query.id)
|
||||
if (allQueriesIds.includes(query.id)) {
|
||||
query.id = nanoid()
|
||||
}
|
||||
})
|
||||
|
||||
return queryList
|
||||
},
|
||||
|
||||
importQueries () {
|
||||
return fu.importFile()
|
||||
.then(data => {
|
||||
return this.deserialiseQueries(data)
|
||||
})
|
||||
},
|
||||
|
||||
readPredefinedQueries () {
|
||||
return fu.readFile('./queries.json')
|
||||
.then(resp => {
|
||||
return resp.json()
|
||||
})
|
||||
}
|
||||
}
|
||||
78
src/lib/utils/fileIo.js
Normal file
@@ -0,0 +1,78 @@
|
||||
export default {
|
||||
isDatabase (file) {
|
||||
const dbTypes = ['application/vnd.sqlite3', 'application/x-sqlite3']
|
||||
return file.type
|
||||
? dbTypes.includes(file.type)
|
||||
: /\.(db|sqlite(3)?)+$/.test(file.name)
|
||||
},
|
||||
|
||||
exportToFile (str, fileName, type = 'octet/stream') {
|
||||
// Create downloader
|
||||
const downloader = document.createElement('a')
|
||||
const blob = new Blob([str], { type })
|
||||
const url = URL.createObjectURL(blob)
|
||||
downloader.href = url
|
||||
downloader.download = fileName
|
||||
|
||||
// Trigger click
|
||||
downloader.click()
|
||||
|
||||
// Clean up
|
||||
URL.revokeObjectURL(url)
|
||||
},
|
||||
|
||||
/**
|
||||
* Note: if user press Cancel in file choosing dialog
|
||||
* it will be an unsettled promise. But it's grabbed by
|
||||
* the garbage collector (tested with FinalizationRegistry).
|
||||
*/
|
||||
getFileFromUser (type) {
|
||||
return new Promise(resolve => {
|
||||
const uploader = document.createElement('input')
|
||||
|
||||
uploader.type = 'file'
|
||||
uploader.accept = type
|
||||
|
||||
uploader.addEventListener('change', () => {
|
||||
const file = uploader.files[0]
|
||||
resolve(file)
|
||||
})
|
||||
|
||||
uploader.click()
|
||||
})
|
||||
},
|
||||
|
||||
importFile () {
|
||||
const reader = new FileReader()
|
||||
|
||||
return this.getFileFromUser('.json')
|
||||
.then(file => {
|
||||
return new Promise((resolve, reject) => {
|
||||
reader.onload = e => {
|
||||
resolve(e.target.result)
|
||||
}
|
||||
reader.readAsText(file)
|
||||
})
|
||||
})
|
||||
},
|
||||
|
||||
readFile (path) {
|
||||
return fetch(path)
|
||||
},
|
||||
|
||||
readAsArrayBuffer (file) {
|
||||
const fileReader = new FileReader()
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
fileReader.onerror = () => {
|
||||
fileReader.abort()
|
||||
reject(new Error('Problem parsing input file.'))
|
||||
}
|
||||
|
||||
fileReader.onload = () => {
|
||||
resolve(fileReader.result)
|
||||
}
|
||||
fileReader.readAsArrayBuffer(file)
|
||||
})
|
||||
}
|
||||
}
|
||||
7
src/lib/utils/time.js
Normal file
@@ -0,0 +1,7 @@
|
||||
export default {
|
||||
getPeriod (start, end) {
|
||||
const diff = end.getTime() - start.getTime()
|
||||
const seconds = diff / 1000
|
||||
return seconds.toFixed(3) + 's'
|
||||
}
|
||||
}
|
||||
12
src/main.js
@@ -1,10 +1,9 @@
|
||||
import Vue from 'vue'
|
||||
import App from './App.vue'
|
||||
import router from './router'
|
||||
import store from './store'
|
||||
import App from '@/App.vue'
|
||||
import router from '@/router'
|
||||
import store from '@/store'
|
||||
import { VuePlugin } from 'vuera'
|
||||
import VModal from 'vue-js-modal'
|
||||
import db from '@/dataBase'
|
||||
|
||||
import '@/assets/styles/variables.css'
|
||||
import '@/assets/styles/buttons.css'
|
||||
@@ -13,11 +12,14 @@ import '@/assets/styles/dialogs.css'
|
||||
import '@/assets/styles/tooltips.css'
|
||||
import '@/assets/styles/messages.css'
|
||||
|
||||
if (!['localhost', '127.0.0.1'].includes(location.hostname)) {
|
||||
import('./registerServiceWorker') // eslint-disable-line no-unused-expressions
|
||||
}
|
||||
|
||||
Vue.use(VuePlugin)
|
||||
Vue.use(VModal)
|
||||
|
||||
Vue.config.productionTip = false
|
||||
Vue.prototype.$db = db
|
||||
|
||||
new Vue({
|
||||
router,
|
||||
|
||||
@@ -1,17 +0,0 @@
|
||||
export default {
|
||||
data () {
|
||||
return {
|
||||
tooltipStyle: {}
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
showTooltip (e) {
|
||||
this.tooltipStyle = {
|
||||
visibility: 'visible',
|
||||
position: 'fixed',
|
||||
top: e.clientY - 12 + 'px',
|
||||
left: e.clientX + 12 + 'px'
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
44
src/registerServiceWorker.js
Normal file
@@ -0,0 +1,44 @@
|
||||
let refresh = false
|
||||
|
||||
function invokeServiceWorkerUpdateFlow (registration) {
|
||||
const agree = confirm('New version of the app is available. Refresh now?')
|
||||
if (agree) {
|
||||
if (registration.waiting) {
|
||||
// let waiting Service Worker know it should became active
|
||||
refresh = true
|
||||
registration.waiting.postMessage({ type: 'SKIP_WAITING' })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ('serviceWorker' in navigator) {
|
||||
window.addEventListener('load', async () => {
|
||||
const registration = await navigator.serviceWorker.register('service-worker.js')
|
||||
// ensure the case when the updatefound event was missed is also handled
|
||||
// by re-invoking the prompt when there's a waiting Service Worker
|
||||
if (registration.waiting) {
|
||||
invokeServiceWorkerUpdateFlow(registration)
|
||||
}
|
||||
|
||||
// detect Service Worker update available and wait for it to become installed
|
||||
registration.addEventListener('updatefound', () => {
|
||||
const newRegestration = registration.installing
|
||||
if (newRegestration) {
|
||||
// wait until the new Service worker is actually installed (ready to take over)
|
||||
newRegestration.addEventListener('statechange', () => {
|
||||
if (registration.waiting && navigator.serviceWorker.controller) {
|
||||
invokeServiceWorkerUpdateFlow(registration)
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
// detect controller change and refresh the page
|
||||
navigator.serviceWorker.addEventListener('controllerchange', () => {
|
||||
if (refresh) {
|
||||
window.location.reload()
|
||||
refresh = false
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
import Vue from 'vue'
|
||||
import VueRouter from 'vue-router'
|
||||
import Editor from '../views/Editor'
|
||||
import MyQueries from '../views/MyQueries'
|
||||
import Home from '../views/Home'
|
||||
import MainView from '../views/MainView'
|
||||
import Editor from '@/views/Main/Editor'
|
||||
import MyQueries from '@/views/Main/MyQueries'
|
||||
import Welcome from '@/views/Welcome'
|
||||
import Main from '@/views/Main'
|
||||
|
||||
Vue.use(VueRouter)
|
||||
|
||||
@@ -11,12 +11,12 @@ const routes = [
|
||||
{
|
||||
path: '/',
|
||||
name: 'Welcome',
|
||||
component: Home
|
||||
component: Welcome
|
||||
},
|
||||
{
|
||||
path: '/',
|
||||
name: 'MainView',
|
||||
component: MainView,
|
||||
name: 'Main',
|
||||
component: Main,
|
||||
children: [
|
||||
{
|
||||
path: '/editor',
|
||||
30
src/store/actions.js
Normal file
@@ -0,0 +1,30 @@
|
||||
import { nanoid } from 'nanoid'
|
||||
|
||||
export default {
|
||||
async addTab ({ state }, data) {
|
||||
const tab = data ? JSON.parse(JSON.stringify(data)) : {}
|
||||
// If no data then create a new blank one...
|
||||
// No data.id means to create new tab, but not blank,
|
||||
// e.g. with 'select * from csv_import' query after csv import
|
||||
if (!data || !data.id) {
|
||||
tab.id = nanoid()
|
||||
tab.name = null
|
||||
tab.tempName = state.untitledLastIndex
|
||||
? `Untitled ${state.untitledLastIndex}`
|
||||
: 'Untitled'
|
||||
tab.isUnsaved = true
|
||||
} else {
|
||||
tab.isUnsaved = false
|
||||
}
|
||||
|
||||
// add new tab only if was not already opened
|
||||
if (!state.tabs.some(openedTab => openedTab.id === tab.id)) {
|
||||
state.tabs.push(tab)
|
||||
if (!tab.name) {
|
||||
state.untitledLastIndex += 1
|
||||
}
|
||||
}
|
||||
|
||||
return tab.id
|
||||
}
|
||||
}
|
||||
@@ -1,132 +1,13 @@
|
||||
import Vue from 'vue'
|
||||
import Vuex from 'vuex'
|
||||
import sqliteParser from 'sqlite-parser'
|
||||
import state from '@/store/state'
|
||||
import mutations from '@/store/mutations'
|
||||
import actions from '@/store/actions'
|
||||
|
||||
Vue.use(Vuex)
|
||||
|
||||
function getAst (sql) {
|
||||
// There is a bug is sqlite-parser
|
||||
// It throws an error if tokenizer has an arguments:
|
||||
// https://github.com/codeschool/sqlite-parser/issues/59
|
||||
const fixedSql = sql
|
||||
.replace(/(?<=tokenize=.+)"tokenchars=.+"/, '')
|
||||
.replace(/(?<=tokenize=.+)"remove_diacritics=.+"/, '')
|
||||
.replace(/(?<=tokenize=.+)"separators=.+"/, '')
|
||||
.replace(/tokenize=.+(?=(,|\)))/, 'tokenize=unicode61')
|
||||
|
||||
return sqliteParser(fixedSql)
|
||||
}
|
||||
|
||||
function getColumns (sql) {
|
||||
const columns = []
|
||||
const ast = getAst(sql)
|
||||
|
||||
const columnDefinition = ast.statement[0].format === 'table'
|
||||
? ast.statement[0].definition
|
||||
: ast.statement[0].result.args.expression // virtual table
|
||||
|
||||
columnDefinition.forEach(item => {
|
||||
if (item.variant === 'column' && ['identifier', 'definition'].includes(item.type)) {
|
||||
let type = item.datatype ? item.datatype.variant : 'N/A'
|
||||
if (item.datatype && item.datatype.args) {
|
||||
type = type + '(' + item.datatype.args.expression[0].value
|
||||
if (item.datatype.args.expression.length === 2) {
|
||||
type = type + ', ' + item.datatype.args.expression[1].value
|
||||
}
|
||||
type = type + ')'
|
||||
}
|
||||
columns.push({ name: item.name, type: type })
|
||||
}
|
||||
})
|
||||
return columns
|
||||
}
|
||||
|
||||
export default new Vuex.Store({
|
||||
state: {
|
||||
schema: null,
|
||||
dbFile: null,
|
||||
dbName: null,
|
||||
tabs: [],
|
||||
currentTab: null,
|
||||
currentTabId: null,
|
||||
untitledLastIndex: 0,
|
||||
predefinedQueries: []
|
||||
},
|
||||
mutations: {
|
||||
saveSchema (state, schema) {
|
||||
const parsedSchema = []
|
||||
schema.forEach(item => {
|
||||
parsedSchema.push({
|
||||
name: item[0],
|
||||
columns: getColumns(item[1])
|
||||
})
|
||||
})
|
||||
state.schema = parsedSchema
|
||||
},
|
||||
saveDbFile (state, file) {
|
||||
state.dbFile = file
|
||||
},
|
||||
saveDbName (state, name) {
|
||||
state.dbName = name
|
||||
},
|
||||
addTab (state, tab) {
|
||||
// add new tab only if was not already opened
|
||||
if (!state.tabs.some(openedTab => openedTab.id === tab.id)) {
|
||||
state.tabs.push(tab)
|
||||
if (!tab.name) {
|
||||
state.untitledLastIndex += 1
|
||||
}
|
||||
}
|
||||
},
|
||||
updateTab (state, { index, name, id, query, chart, isUnsaved }) {
|
||||
const tab = state.tabs[index]
|
||||
const oldId = tab.id
|
||||
|
||||
if (state.currentTabId === oldId) {
|
||||
state.currentTabId = id
|
||||
}
|
||||
|
||||
tab.id = id
|
||||
if (name) { tab.name = name }
|
||||
if (query) { tab.query = query }
|
||||
if (chart) { tab.chart = chart }
|
||||
if (isUnsaved !== undefined) { tab.isUnsaved = isUnsaved }
|
||||
delete tab.isPredefined
|
||||
|
||||
Vue.set(state.tabs, index, tab)
|
||||
},
|
||||
updateTabState (state, { index, isUnsaved }) {
|
||||
const tab = state.tabs[index]
|
||||
tab.isUnsaved = isUnsaved
|
||||
Vue.set(state.tabs, index, tab)
|
||||
},
|
||||
deleteTab (state, index) {
|
||||
if (state.tabs[index].id !== state.currentTabId) {
|
||||
} else if (index < state.tabs.length - 1) {
|
||||
state.currentTabId = state.tabs[index + 1].id
|
||||
} else if (index > 0) {
|
||||
state.currentTabId = state.tabs[index - 1].id
|
||||
} else {
|
||||
state.currentTabId = null
|
||||
state.currentTab = null
|
||||
state.untitledLastIndex = 0
|
||||
}
|
||||
state.tabs.splice(index, 1)
|
||||
},
|
||||
setCurrentTabId (state, id) {
|
||||
state.currentTabId = id
|
||||
},
|
||||
setCurrentTab (state, tab) {
|
||||
state.currentTab = tab
|
||||
},
|
||||
updatePredefinedQueries (state, queries) {
|
||||
if (Array.isArray(queries)) {
|
||||
state.predefinedQueries = queries
|
||||
} else {
|
||||
state.predefinedQueries = [queries]
|
||||
}
|
||||
}
|
||||
},
|
||||
actions: {
|
||||
}
|
||||
state,
|
||||
mutations,
|
||||
actions
|
||||
})
|
||||
|
||||
63
src/store/mutations.js
Normal file
@@ -0,0 +1,63 @@
|
||||
import Vue from 'vue'
|
||||
|
||||
export default {
|
||||
setDb (state, db) {
|
||||
if (state.db) {
|
||||
state.db.shutDown()
|
||||
}
|
||||
state.db = db
|
||||
},
|
||||
saveSchema (state, { dbName, schema }) {
|
||||
state.dbName = dbName
|
||||
state.schema = schema
|
||||
},
|
||||
|
||||
updateTab (state, { index, name, id, query, chart, isUnsaved }) {
|
||||
const tab = state.tabs[index]
|
||||
const oldId = tab.id
|
||||
|
||||
if (id && state.currentTabId === oldId) {
|
||||
state.currentTabId = id
|
||||
}
|
||||
|
||||
if (id) { tab.id = id }
|
||||
if (name) { tab.name = name }
|
||||
if (query) { tab.query = query }
|
||||
if (chart) { tab.chart = chart }
|
||||
if (isUnsaved !== undefined) { tab.isUnsaved = isUnsaved }
|
||||
if (!isUnsaved) {
|
||||
// Saved query is not predefined
|
||||
delete tab.isPredefined
|
||||
}
|
||||
|
||||
Vue.set(state.tabs, index, tab)
|
||||
},
|
||||
deleteTab (state, index) {
|
||||
// If closing tab is the current opened
|
||||
if (state.tabs[index].id === state.currentTabId) {
|
||||
if (index < state.tabs.length - 1) {
|
||||
state.currentTabId = state.tabs[index + 1].id
|
||||
} else if (index > 0) {
|
||||
state.currentTabId = state.tabs[index - 1].id
|
||||
} else {
|
||||
state.currentTabId = null
|
||||
state.currentTab = null
|
||||
state.untitledLastIndex = 0
|
||||
}
|
||||
}
|
||||
state.tabs.splice(index, 1)
|
||||
},
|
||||
setCurrentTabId (state, id) {
|
||||
state.currentTabId = id
|
||||
},
|
||||
setCurrentTab (state, tab) {
|
||||
state.currentTab = tab
|
||||
},
|
||||
updatePredefinedQueries (state, queries) {
|
||||
if (Array.isArray(queries)) {
|
||||
state.predefinedQueries = queries
|
||||
} else {
|
||||
state.predefinedQueries = [queries]
|
||||
}
|
||||
}
|
||||
}
|
||||
11
src/store/state.js
Normal file
@@ -0,0 +1,11 @@
|
||||
export default {
|
||||
schema: null,
|
||||
dbFile: null,
|
||||
dbName: null,
|
||||
tabs: [],
|
||||
currentTab: null,
|
||||
currentTabId: null,
|
||||
untitledLastIndex: 0,
|
||||
predefinedQueries: [],
|
||||
db: null
|
||||
}
|
||||
19
src/tooltipMixin.js
Normal file
@@ -0,0 +1,19 @@
|
||||
export default {
|
||||
data () {
|
||||
return {
|
||||
tooltipStyle: {
|
||||
visibility: 'hidden'
|
||||
}
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
showTooltip (e) {
|
||||
this.tooltipStyle.top = e.clientY - 12 + 'px'
|
||||
this.tooltipStyle.left = e.clientX + 12 + 'px'
|
||||
this.tooltipStyle.visibility = 'visible'
|
||||
},
|
||||
hideTooltip () {
|
||||
this.tooltipStyle.visibility = 'hidden'
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,78 +0,0 @@
|
||||
<template>
|
||||
<div>
|
||||
<splitpanes
|
||||
class="schema-tabs-splitter"
|
||||
:before="{ size: 20, max: 30 }"
|
||||
:after="{ size: 80, max: 100 }"
|
||||
>
|
||||
<template #left-pane>
|
||||
<schema v-if="$store.state.schema"/>
|
||||
<div v-else id="empty-schema-container">
|
||||
<div class="warning">
|
||||
Database is not loaded. Queries can’t be run without database.
|
||||
</div>
|
||||
<db-upload id="db-uploader"/>
|
||||
</div>
|
||||
</template>
|
||||
<template #right-pane>
|
||||
<tabs />
|
||||
</template>
|
||||
</splitpanes>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import Splitpanes from '@/components/Splitpanes'
|
||||
import Schema from '@/components/Schema'
|
||||
import Tabs from '@/components/Tabs'
|
||||
import dbUpload from '@/components/DbUpload'
|
||||
|
||||
export default {
|
||||
name: 'Editor',
|
||||
components: {
|
||||
Schema,
|
||||
Splitpanes,
|
||||
Tabs,
|
||||
dbUpload
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.schema-tabs-splitter {
|
||||
height: 100%;
|
||||
background-color: var(--color-white);
|
||||
}
|
||||
#empty-schema-container {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
min-width: 200px;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
#db-uploader {
|
||||
flex-grow: 1;
|
||||
padding: 24px;
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.warning {
|
||||
padding: 12px 24px;
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
>>> .db-upload-container {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
>>>.drop-area {
|
||||
padding: 0 15px;
|
||||
}
|
||||
|
||||
>>>.drop-area .text {
|
||||
max-width: 200px;
|
||||
}
|
||||
</style>
|
||||
@@ -5,17 +5,13 @@
|
||||
</div>
|
||||
<div id="db">
|
||||
<div @click="schemaVisible = !schemaVisible" class="db-name">
|
||||
<tree-chevron :expanded="schemaVisible"/>
|
||||
<tree-chevron v-show="schema.length > 0" :expanded="schemaVisible"/>
|
||||
{{ dbName }}
|
||||
</div>
|
||||
<div class="db-edit">
|
||||
<input type="file" id="actual-btn" ref="dbfile" hidden @change="changeDb"/>
|
||||
<label for="actual-btn">
|
||||
<change-db-icon />
|
||||
</label>
|
||||
<db-uploader id="db-edit" type="small" />
|
||||
<export-icon tooltip="Export database" @click="exportToFile"/>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="schemaVisible" class="schema">
|
||||
<div v-show="schemaVisible" class="schema">
|
||||
<table-description
|
||||
v-for="table in schema"
|
||||
:key="table.name"
|
||||
@@ -27,18 +23,20 @@
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import TableDescription from '@/components/TableDescription'
|
||||
import TableDescription from './TableDescription'
|
||||
import TextField from '@/components/TextField'
|
||||
import ChangeDbIcon from '@/components/svg/changeDb'
|
||||
import TreeChevron from '@/components/svg/treeChevron'
|
||||
import DbUploader from '@/components/DbUploader'
|
||||
import ExportIcon from '@/components/svg/export'
|
||||
|
||||
export default {
|
||||
name: 'Schema',
|
||||
components: {
|
||||
TableDescription,
|
||||
TextField,
|
||||
ChangeDbIcon,
|
||||
TreeChevron
|
||||
TreeChevron,
|
||||
DbUploader,
|
||||
ExportIcon
|
||||
},
|
||||
data () {
|
||||
return {
|
||||
@@ -63,11 +61,8 @@ export default {
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
changeDb () {
|
||||
this.$db.loadDb(this.$refs.dbfile.files[0])
|
||||
.then((schema) => {
|
||||
this.$store.commit('saveSchema', schema)
|
||||
})
|
||||
exportToFile () {
|
||||
this.$store.state.db.export(`${this.dbName}.sqlite`)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -91,7 +86,7 @@ export default {
|
||||
width: 100%;
|
||||
height: 100px;
|
||||
box-sizing: border-box;
|
||||
background-image: linear-gradient(white 73%, transparent);;
|
||||
background-image: linear-gradient(white 73%, rgba(255, 255, 255, 0));
|
||||
z-index: 2;
|
||||
}
|
||||
.schema, .db-name {
|
||||
@@ -108,6 +103,11 @@ export default {
|
||||
|
||||
.db-name {
|
||||
cursor: pointer;
|
||||
margin-right: 6px;
|
||||
max-width: 150px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.db-name:hover .chevron-icon path,
|
||||
40
src/views/Main/Editor/Tabs/Tab/Chart/chartHelper.js
Normal file
@@ -0,0 +1,40 @@
|
||||
import dereference from 'react-chart-editor/lib/lib/dereference'
|
||||
|
||||
export function getDataSourcesFromSqlResult (sqlResult) {
|
||||
if (!sqlResult) {
|
||||
return {}
|
||||
}
|
||||
const dataSorces = {}
|
||||
const matrix = sqlResult.values
|
||||
const [row] = matrix
|
||||
const transposedMatrix = row.map((value, column) => matrix.map(row => row[column]))
|
||||
sqlResult.columns.forEach((column, index) => {
|
||||
dataSorces[column] = transposedMatrix[index]
|
||||
})
|
||||
return dataSorces
|
||||
}
|
||||
|
||||
export function getOptionsFromDataSources (dataSources) {
|
||||
return Object.keys(dataSources).map(name => ({
|
||||
value: name,
|
||||
label: name
|
||||
}))
|
||||
}
|
||||
|
||||
export function getChartStateForSave (state, dataSources) {
|
||||
// we don't need to save the data, only settings
|
||||
// so we modify state.data using dereference
|
||||
const stateCopy = JSON.parse(JSON.stringify(state))
|
||||
const emptySources = {}
|
||||
for (const key in dataSources) {
|
||||
emptySources[key] = []
|
||||
}
|
||||
dereference(stateCopy.data, emptySources)
|
||||
return stateCopy
|
||||
}
|
||||
|
||||
export default {
|
||||
getDataSourcesFromSqlResult,
|
||||
getOptionsFromDataSources,
|
||||
getChartStateForSave
|
||||
}
|
||||
@@ -12,10 +12,12 @@
|
||||
:dataSourceOptions="dataSourceOptions"
|
||||
:plotly="plotly"
|
||||
@onUpdate="update"
|
||||
@onRender="go"
|
||||
:useResizeHandler="true"
|
||||
:debug="true"
|
||||
:advancedTraceTypeSelector="true"
|
||||
class="chart"
|
||||
ref="plotlyEditor"
|
||||
:style="{ height: !sqlResult ? 'calc(100% - 40px)' : '100%' }"
|
||||
/>
|
||||
</div>
|
||||
@@ -26,6 +28,7 @@ import plotly from 'plotly.js/dist/plotly'
|
||||
import 'react-chart-editor/lib/react-chart-editor.min.css'
|
||||
|
||||
import PlotlyEditor from 'react-chart-editor'
|
||||
import chartHelper from './chartHelper'
|
||||
import dereference from 'react-chart-editor/lib/lib/dereference'
|
||||
|
||||
export default {
|
||||
@@ -46,23 +49,10 @@ export default {
|
||||
},
|
||||
computed: {
|
||||
dataSources () {
|
||||
if (!this.sqlResult) {
|
||||
return {}
|
||||
}
|
||||
const dataSorces = {}
|
||||
const matrix = this.sqlResult.values
|
||||
const [row] = matrix
|
||||
const transposedMatrix = row.map((value, column) => matrix.map(row => row[column]))
|
||||
this.sqlResult.columns.forEach((column, index) => {
|
||||
dataSorces[column] = transposedMatrix[index]
|
||||
})
|
||||
return dataSorces
|
||||
return chartHelper.getDataSourcesFromSqlResult(this.sqlResult)
|
||||
},
|
||||
dataSourceOptions () {
|
||||
return Object.keys(this.dataSources).map(name => ({
|
||||
value: name,
|
||||
label: name
|
||||
}))
|
||||
return chartHelper.getOptionsFromDataSources(this.dataSources)
|
||||
}
|
||||
},
|
||||
watch: {
|
||||
@@ -73,20 +63,15 @@ export default {
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
go (data, layout, frames) {
|
||||
// TODO: check changes and enable Save button if needed
|
||||
},
|
||||
update (data, layout, frames) {
|
||||
this.state = { data, layout, frames }
|
||||
this.$emit('update')
|
||||
},
|
||||
getChartSatateForSave () {
|
||||
// we don't need to save the data, only settings
|
||||
// so we modify state.data using dereference
|
||||
const stateCopy = JSON.parse(JSON.stringify(this.state))
|
||||
const emptySources = {}
|
||||
for (const key in this.dataSources) {
|
||||
emptySources[key] = []
|
||||
}
|
||||
dereference(stateCopy.data, emptySources)
|
||||
return stateCopy
|
||||
getChartStateForSave () {
|
||||
return chartHelper.getChartStateForSave(this.state, this.dataSources)
|
||||
}
|
||||
}
|
||||
}
|
||||
50
src/views/Main/Editor/Tabs/Tab/SqlEditor/hint.js
Normal file
@@ -0,0 +1,50 @@
|
||||
import CM from 'codemirror'
|
||||
import 'codemirror/addon/hint/show-hint.js'
|
||||
import 'codemirror/addon/hint/sql-hint.js'
|
||||
import store from '@/store'
|
||||
|
||||
export function getHints (cm, options) {
|
||||
const token = cm.getTokenAt(cm.getCursor()).string.toUpperCase()
|
||||
const result = CM.hint.sql(cm, options)
|
||||
// Don't show the hint if there is only one option
|
||||
// and the token is already completed with this option
|
||||
if (result.list.length === 1 && result.list[0].text.toUpperCase() === token) {
|
||||
result.list = []
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
const hintOptions = {
|
||||
get tables () {
|
||||
const tables = {}
|
||||
if (store.state.schema) {
|
||||
store.state.schema.forEach(table => {
|
||||
tables[table.name] = table.columns.map(column => column.name)
|
||||
})
|
||||
}
|
||||
return tables
|
||||
},
|
||||
get defaultTable () {
|
||||
const schema = store.state.schema
|
||||
return schema && schema.length === 1 ? schema[0].name : null
|
||||
},
|
||||
completeSingle: false,
|
||||
completeOnSingleClick: true,
|
||||
alignWithWord: false
|
||||
}
|
||||
|
||||
export function showHintOnDemand (editor) {
|
||||
CM.showHint(editor, getHints, hintOptions)
|
||||
}
|
||||
|
||||
export default function showHint (editor) {
|
||||
// Don't show autocomplete after a space or semicolon or in string literals
|
||||
const token = editor.getTokenAt(editor.getCursor())
|
||||
const ch = token.string.slice(-1)
|
||||
const tokenType = token.type
|
||||
if (tokenType === 'string' || !ch || ch === ' ' || ch === ';') {
|
||||
return
|
||||
}
|
||||
|
||||
CM.showHint(editor, getHints, hintOptions)
|
||||
}
|
||||
66
src/views/Main/Editor/Tabs/Tab/SqlEditor/index.vue
Normal file
@@ -0,0 +1,66 @@
|
||||
<template>
|
||||
<div class="codemirror-container">
|
||||
<codemirror v-model="query" :options="cmOptions" @changes="onChange" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import showHint, { showHintOnDemand } from './hint'
|
||||
import { debounce } from 'debounce'
|
||||
import { codemirror } from 'vue-codemirror'
|
||||
import 'codemirror/lib/codemirror.css'
|
||||
import 'codemirror/mode/sql/sql.js'
|
||||
import 'codemirror/theme/neo.css'
|
||||
import 'codemirror/addon/hint/show-hint.css'
|
||||
import 'codemirror/addon/display/autorefresh.js'
|
||||
|
||||
export default {
|
||||
name: 'SqlEditor',
|
||||
props: ['value'],
|
||||
components: { codemirror },
|
||||
data () {
|
||||
return {
|
||||
query: this.value,
|
||||
cmOptions: {
|
||||
// codemirror options
|
||||
tabSize: 4,
|
||||
mode: 'text/x-mysql',
|
||||
theme: 'neo',
|
||||
lineNumbers: true,
|
||||
line: true,
|
||||
autofocus: true,
|
||||
autoRefresh: true,
|
||||
extraKeys: { 'Ctrl-Space': showHintOnDemand }
|
||||
}
|
||||
}
|
||||
},
|
||||
watch: {
|
||||
query () {
|
||||
this.$emit('input', this.query)
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
onChange: debounce(showHint, 400)
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.codemirror-container {
|
||||
flex-grow: 1;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
>>> .vue-codemirror {
|
||||
height: 100%;
|
||||
max-height: 100%;
|
||||
}
|
||||
>>> .CodeMirror {
|
||||
height: 100%;
|
||||
max-height: 100%;
|
||||
}
|
||||
>>> .CodeMirror-cursor {
|
||||
width: 1px;
|
||||
background: var(--color-text-base);
|
||||
}
|
||||
</style>
|
||||
@@ -15,26 +15,31 @@
|
||||
<div id="bottomPane" ref="bottomPane">
|
||||
<view-switcher :view.sync="view" />
|
||||
<div v-show="view === 'table'" class="table-view">
|
||||
<div v-show="result === null && !isGettingResults && !error" class="table-preview">
|
||||
<div
|
||||
v-show="result === null && !isGettingResults && !error"
|
||||
class="table-preview result-before"
|
||||
>
|
||||
Run your query and get results here
|
||||
</div>
|
||||
<div v-show="isGettingResults" class="table-preview">
|
||||
<div v-if="isGettingResults" class="table-preview result-in-progress">
|
||||
<loading-indicator :size="30"/>
|
||||
Fetching results...
|
||||
</div>
|
||||
<div v-show="result === undefined && !isGettingResults && !error" class="table-preview">
|
||||
<div
|
||||
v-show="result === undefined && !isGettingResults && !error"
|
||||
class="table-preview result-empty"
|
||||
>
|
||||
No rows retrieved according to your query
|
||||
</div>
|
||||
<div v-show="error" class="table-preview error">
|
||||
{{ error }}
|
||||
</div>
|
||||
<sql-table v-if="result" :data-set="result" :height="tableViewHeight" />
|
||||
<logs v-if="error" :messages="[error]"/>
|
||||
<sql-table v-if="result" :data-set="result" :time="time" :height="tableViewHeight" />
|
||||
</div>
|
||||
<chart
|
||||
:visible="view === 'chart'"
|
||||
:sql-result="result"
|
||||
:init-chart="initChart"
|
||||
ref="chart"
|
||||
@update="$store.commit('updateTabState', { index: tabIndex, isUnsaved: true })"
|
||||
@update="$store.commit('updateTab', { index: tabIndex, isUnsaved: true })"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
@@ -44,10 +49,13 @@
|
||||
|
||||
<script>
|
||||
import SqlTable from '@/components/SqlTable'
|
||||
import SqlEditor from '@/components/SqlEditor'
|
||||
import Splitpanes from '@/components/Splitpanes'
|
||||
import ViewSwitcher from '@/components/ViewSwitcher'
|
||||
import Chart from '@/components/Chart'
|
||||
import LoadingIndicator from '@/components/LoadingIndicator'
|
||||
import SqlEditor from './SqlEditor'
|
||||
import ViewSwitcher from './ViewSwitcher'
|
||||
import Chart from './Chart'
|
||||
import Logs from '@/components/Logs'
|
||||
import time from '@/lib/utils/time'
|
||||
|
||||
export default {
|
||||
name: 'Tab',
|
||||
@@ -57,7 +65,9 @@ export default {
|
||||
SqlTable,
|
||||
Splitpanes,
|
||||
ViewSwitcher,
|
||||
Chart
|
||||
Chart,
|
||||
LoadingIndicator,
|
||||
Logs
|
||||
},
|
||||
data () {
|
||||
return {
|
||||
@@ -67,7 +77,8 @@ export default {
|
||||
tableViewHeight: 0,
|
||||
isGettingResults: false,
|
||||
error: null,
|
||||
resizeObserver: null
|
||||
resizeObserver: null,
|
||||
time: 0
|
||||
}
|
||||
},
|
||||
computed: {
|
||||
@@ -93,26 +104,29 @@ export default {
|
||||
}
|
||||
},
|
||||
query () {
|
||||
this.$store.commit('updateTabState', { index: this.tabIndex, isUnsaved: true })
|
||||
this.$store.commit('updateTab', { index: this.tabIndex, isUnsaved: true })
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
// Run a command in the database
|
||||
execute () {
|
||||
// this.$refs.output.textContent = 'Fetching results...' */
|
||||
async execute () {
|
||||
this.isGettingResults = true
|
||||
this.result = null
|
||||
this.error = null
|
||||
this.$db.execute(this.query + ';')
|
||||
.then(result => {
|
||||
this.result = result
|
||||
})
|
||||
.catch(err => {
|
||||
this.error = err
|
||||
})
|
||||
.finally(() => {
|
||||
const state = this.$store.state
|
||||
try {
|
||||
const start = new Date()
|
||||
this.result = await state.db.execute(this.query + ';')
|
||||
this.time = time.getPeriod(start, new Date())
|
||||
const schema = await state.db.getSchema(state.dbName)
|
||||
this.$store.commit('saveSchema', schema)
|
||||
} catch (err) {
|
||||
this.error = {
|
||||
type: 'error',
|
||||
message: err
|
||||
}
|
||||
}
|
||||
this.isGettingResults = false
|
||||
})
|
||||
},
|
||||
handleResize () {
|
||||
if (this.view === 'chart') {
|
||||
@@ -133,9 +147,6 @@ export default {
|
||||
// 40 - height of table header
|
||||
const freeSpace = bottomPane.offsetHeight - 88 - 42 - 30 - 5 - 40
|
||||
this.tableViewHeight = freeSpace - (freeSpace % 40)
|
||||
},
|
||||
getChartSatateForSave () {
|
||||
return this.$refs.chart.getChartSatateForSave()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -182,11 +193,32 @@ export default {
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.table-preview.error {
|
||||
color: var(--color-text-error);
|
||||
.result-in-progress {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
will-change: opacity;
|
||||
/*
|
||||
We need to show loader in 1 sec after starting query execution. We can't do that with
|
||||
setTimeout because the main thread can be busy by getting a result set from the web worker.
|
||||
But we can use CSS animation for opacity. Opacity triggers changes only in the Composite Layer
|
||||
stage in rendering waterfall. Hence it can be processed only with Compositor Thread while
|
||||
the Main Thread processes a result set.
|
||||
https://www.viget.com/articles/animation-performance-101-browser-under-the-hood/
|
||||
*/
|
||||
animation: show-loader 1s linear 0s 1;
|
||||
}
|
||||
|
||||
.table-preview.error::first-letter {
|
||||
text-transform: capitalize;
|
||||
@keyframes show-loader {
|
||||
0% {
|
||||
opacity: 0;
|
||||
}
|
||||
99% {
|
||||
opacity: 0;
|
||||
}
|
||||
100% {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -1,14 +1,14 @@
|
||||
<template>
|
||||
<div id="tabs-container">
|
||||
<div id="tabs__header" v-if="tabs.length > 0">
|
||||
<div id="tabs">
|
||||
<div id="tabs-header" v-if="tabs.length > 0">
|
||||
<div
|
||||
v-for="(tab, index) in tabs"
|
||||
:key="index"
|
||||
@click="selectTab(tab.id)"
|
||||
:class="[{'tab__selected': (tab.id === selectedIndex)}, 'tab']"
|
||||
:class="[{'tab-selected': (tab.id === selectedIndex)}, 'tab']"
|
||||
>
|
||||
<div class="tab-name">
|
||||
<span v-show="tab.isUnsaved">*</span>
|
||||
<span v-show="tab.isUnsaved" class="star">*</span>
|
||||
<span v-if="tab.name">{{ tab.name }}</span>
|
||||
<span v-else class="tab-untitled">{{ tab.tempName }}</span>
|
||||
</div>
|
||||
@@ -27,7 +27,7 @@
|
||||
:is-predefined="tab.isPredefined"
|
||||
:tab-index="index"
|
||||
/>
|
||||
<div v-if="tabs.length === 0" id="start-guide">
|
||||
<div v-show="tabs.length === 0" id="start-guide">
|
||||
<span class="link" @click="$root.$emit('createNewQuery')">Create</span>
|
||||
a new query from scratch or open the one from
|
||||
<router-link class="link" to="/my-queries">My queries</router-link>
|
||||
@@ -62,7 +62,7 @@
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import Tab from '@/components/Tab'
|
||||
import Tab from './Tab'
|
||||
import CloseIcon from '@/components/svg/close'
|
||||
|
||||
export default {
|
||||
@@ -86,9 +86,6 @@ export default {
|
||||
created () {
|
||||
window.addEventListener('beforeunload', this.leavingSqliteviz)
|
||||
},
|
||||
unmounted () {
|
||||
window.removeEventListener('beforeunload', this.leavingSqliteviz)
|
||||
},
|
||||
methods: {
|
||||
leavingSqliteviz (event) {
|
||||
if (this.tabs.some(tab => tab.isUnsaved)) {
|
||||
@@ -128,18 +125,18 @@ export default {
|
||||
</script>
|
||||
|
||||
<style>
|
||||
#tabs-container {
|
||||
#tabs {
|
||||
position: relative;
|
||||
height: 100%;
|
||||
background-color: var(--color-bg-light);
|
||||
}
|
||||
#tabs__header {
|
||||
#tabs-header {
|
||||
display: flex;
|
||||
margin: 0;
|
||||
max-width: 100%;
|
||||
overflow: hidden;
|
||||
}
|
||||
#tabs__header .tab {
|
||||
#tabs-header .tab {
|
||||
height: 36px;
|
||||
background-color: var(--color-bg-light);
|
||||
border-right: 1px solid var(--color-border-light);
|
||||
@@ -155,24 +152,24 @@ export default {
|
||||
flex-shrink: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
#tabs__header .tab-name {
|
||||
#tabs-header .tab-name {
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
flex-shrink: 1;
|
||||
}
|
||||
|
||||
#tabs__header div:hover {
|
||||
#tabs-header div:hover {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
#tabs__header .tab__selected {
|
||||
#tabs-header .tab-selected {
|
||||
color: var(--color-text-active);
|
||||
font-weight: 600;
|
||||
border-bottom: none;
|
||||
background-color: var(--color-white);
|
||||
}
|
||||
#tabs__header .tab__selected:hover {
|
||||
#tabs-header .tab-selected:hover {
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
68
src/views/Main/Editor/index.vue
Normal file
@@ -0,0 +1,68 @@
|
||||
<template>
|
||||
<div>
|
||||
<splitpanes
|
||||
class="schema-tabs-splitter"
|
||||
:before="{ size: 20, max: 30 }"
|
||||
:after="{ size: 80, max: 100 }"
|
||||
>
|
||||
<template #left-pane>
|
||||
<schema/>
|
||||
</template>
|
||||
<template #right-pane>
|
||||
<tabs />
|
||||
</template>
|
||||
</splitpanes>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import Splitpanes from '@/components/Splitpanes'
|
||||
import Schema from './Schema'
|
||||
import Tabs from './Tabs'
|
||||
import database from '@/lib/database'
|
||||
import store from '@/store'
|
||||
|
||||
export default {
|
||||
name: 'Editor',
|
||||
components: {
|
||||
Schema,
|
||||
Splitpanes,
|
||||
Tabs
|
||||
},
|
||||
async beforeRouteEnter (to, from, next) {
|
||||
if (!store.state.schema) {
|
||||
const newDb = database.getNewDatabase()
|
||||
const newSchema = await newDb.loadDb()
|
||||
store.commit('setDb', newDb)
|
||||
store.commit('saveSchema', newSchema)
|
||||
const stmt = [
|
||||
'/*',
|
||||
' * Your database is empty. In order to start building charts',
|
||||
' * you should create a table and insert data into it.',
|
||||
' */',
|
||||
'CREATE TABLE house',
|
||||
'(',
|
||||
' name TEXT,',
|
||||
' points INTEGER',
|
||||
');',
|
||||
'INSERT INTO house VALUES',
|
||||
"('Gryffindor', 100),",
|
||||
"('Hufflepuff', 90),",
|
||||
"('Ravenclaw', 95),",
|
||||
"('Slytherin', 80);"
|
||||
].join('\n')
|
||||
|
||||
const tabId = await store.dispatch('addTab', { query: stmt })
|
||||
store.commit('setCurrentTabId', tabId)
|
||||
}
|
||||
next()
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.schema-tabs-splitter {
|
||||
height: 100%;
|
||||
background-color: var(--color-white);
|
||||
}
|
||||
</style>
|
||||
@@ -3,9 +3,11 @@
|
||||
<div>
|
||||
<router-link to="/editor">Editor</router-link>
|
||||
<router-link to="/my-queries">My queries</router-link>
|
||||
<a href="https://github.com/lana-k/sqliteviz/wiki" target="_blank">Help</a>
|
||||
</div>
|
||||
<div>
|
||||
<button
|
||||
id="run-btn"
|
||||
v-if="currentQuery && $route.path === '/editor'"
|
||||
class="primary"
|
||||
:disabled="runDisabled"
|
||||
@@ -14,6 +16,7 @@
|
||||
Run
|
||||
</button>
|
||||
<button
|
||||
id="save-btn"
|
||||
v-show="currentQuery && $route.path === '/editor'"
|
||||
class="primary"
|
||||
:disabled="!isUnsaved"
|
||||
@@ -21,7 +24,13 @@
|
||||
>
|
||||
Save
|
||||
</button>
|
||||
<button class="primary" @click="createNewQuery">Create</button>
|
||||
<button
|
||||
id="create-btn"
|
||||
class="primary"
|
||||
@click="createNewQuery"
|
||||
>
|
||||
Create
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!--Save Query dialog -->
|
||||
@@ -52,9 +61,9 @@
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import { nanoid } from 'nanoid'
|
||||
import TextField from '@/components/TextField'
|
||||
import CloseIcon from '@/components/svg/close'
|
||||
import storedQueries from '@/lib/storedQueries'
|
||||
|
||||
export default {
|
||||
name: 'MainMenu',
|
||||
@@ -77,7 +86,8 @@ export default {
|
||||
return false
|
||||
}
|
||||
const tabIndex = this.currentQuery.tabIndex
|
||||
return this.$store.state.tabs[tabIndex].isUnsaved
|
||||
const tab = this.$store.state.tabs[tabIndex]
|
||||
return tab && tab.isUnsaved
|
||||
},
|
||||
isPredefined () {
|
||||
if (this.currentQuery) {
|
||||
@@ -100,16 +110,12 @@ export default {
|
||||
},
|
||||
methods: {
|
||||
createNewQuery () {
|
||||
const tab = {
|
||||
id: nanoid(),
|
||||
name: null,
|
||||
tempName: this.$store.state.untitledLastIndex
|
||||
? `Untitled ${this.$store.state.untitledLastIndex}`
|
||||
: 'Untitled',
|
||||
isUnsaved: true
|
||||
this.$store.dispatch('addTab').then(id => {
|
||||
this.$store.commit('setCurrentTabId', id)
|
||||
if (this.$route.path !== '/editor') {
|
||||
this.$router.push('/editor')
|
||||
}
|
||||
this.$store.commit('addTab', tab)
|
||||
this.$store.commit('setCurrentTabId', tab.id)
|
||||
})
|
||||
},
|
||||
cancelSave () {
|
||||
this.$modal.hide('save')
|
||||
@@ -117,46 +123,27 @@ export default {
|
||||
},
|
||||
checkQueryBeforeSave () {
|
||||
this.errorMsg = null
|
||||
const isFromScratch = !this.currentQuery.initName
|
||||
|
||||
if (isFromScratch || this.isPredefined) {
|
||||
this.name = ''
|
||||
|
||||
if (storedQueries.isTabNeedName(this.currentQuery)) {
|
||||
this.$modal.show('save')
|
||||
} else {
|
||||
this.saveQuery()
|
||||
}
|
||||
},
|
||||
saveQuery () {
|
||||
const isFromScratch = !this.currentQuery.initName
|
||||
if ((isFromScratch || this.isPredefined) && !this.name) {
|
||||
const isNeedName = storedQueries.isTabNeedName(this.currentQuery)
|
||||
if (isNeedName && !this.name) {
|
||||
this.errorMsg = 'Query name can\'t be empty'
|
||||
return
|
||||
}
|
||||
const dataSet = this.currentQuery.result
|
||||
const tabView = this.currentQuery.view
|
||||
// Prepare query
|
||||
const value = {
|
||||
id: this.isPredefined ? nanoid() : this.currentQuery.id,
|
||||
query: this.currentQuery.query,
|
||||
chart: this.currentQuery.getChartSatateForSave(),
|
||||
name: (!this.isPredefined && this.currentQuery.initName) || this.name,
|
||||
createdAt: new Date()
|
||||
}
|
||||
|
||||
// Save query
|
||||
let myQueries = JSON.parse(localStorage.getItem('myQueries'))
|
||||
if (!myQueries) {
|
||||
myQueries = [value]
|
||||
} else if (isFromScratch || this.isPredefined) {
|
||||
myQueries.push(value)
|
||||
} else {
|
||||
const queryIndex = myQueries.findIndex(query => query.id === this.currentQuery.id)
|
||||
value.createdAt = myQueries[queryIndex].createdAt
|
||||
myQueries[queryIndex] = value
|
||||
}
|
||||
localStorage.setItem('myQueries', JSON.stringify(myQueries))
|
||||
const value = storedQueries.save(this.currentQuery, this.name)
|
||||
|
||||
// Update tab
|
||||
// Update tab in store
|
||||
this.$store.commit('updateTab', {
|
||||
index: this.currentQuery.tabIndex,
|
||||
name: value.name,
|
||||
@@ -184,12 +171,13 @@ export default {
|
||||
},
|
||||
_keyListener (e) {
|
||||
if (this.$route.path === '/editor') {
|
||||
// Run query Ctrl+R
|
||||
if (e.key === 'r' && (e.ctrlKey || e.metaKey)) {
|
||||
// Run query Ctrl+R or Ctrl+Enter
|
||||
if ((e.key === 'r' || e.key === 'Enter') && (e.ctrlKey || e.metaKey)) {
|
||||
e.preventDefault()
|
||||
if (!this.runDisabled) {
|
||||
this.currentQuery.execute()
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Save query Ctrl+S
|
||||
@@ -198,8 +186,9 @@ export default {
|
||||
if (this.isUnsaved) {
|
||||
this.checkQueryBeforeSave()
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// New (blank) query Ctrl+B
|
||||
if (e.key === 'b' && (e.ctrlKey || e.metaKey)) {
|
||||
e.preventDefault()
|
||||
@@ -207,7 +196,6 @@ export default {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -2,33 +2,26 @@
|
||||
<div>
|
||||
<div id="start-guide" v-if="showedQueries.length === 0">
|
||||
You don't have saved queries so far.
|
||||
<span class="link" @click="create">Create</span>
|
||||
<span class="link" @click="$root.$emit('createNewQuery')">Create</span>
|
||||
the one from scratch or
|
||||
<label for="import-file" class="link">import</label> from a file.
|
||||
<span @click="importQueries" class="link">import</span> from a file.
|
||||
</div>
|
||||
<div id="my-queries-content" ref="my-queries-content" v-show="showedQueries.length > 0">
|
||||
<div id="my-queries-toolbar">
|
||||
<div id="toolbar-buttons">
|
||||
<input
|
||||
ref="importFile"
|
||||
type="file"
|
||||
accept=".json"
|
||||
id="import-file"
|
||||
@change="importQueries"
|
||||
/>
|
||||
<button class="toolbar">
|
||||
<label for="import-file">
|
||||
<button id="toolbar-btns-import" class="toolbar" @click="importQueries">
|
||||
Import
|
||||
</label>
|
||||
</button>
|
||||
<button
|
||||
id="toolbar-btns-export"
|
||||
class="toolbar"
|
||||
v-show="selectedQueriesCount > 0"
|
||||
@click="exportQuery(selectedQueriesIds)"
|
||||
@click="exportSelectedQueries()"
|
||||
>
|
||||
Export
|
||||
</button>
|
||||
<button
|
||||
id="toolbar-btns-delete"
|
||||
class="toolbar"
|
||||
v-show="selectedNotPredefinedCount > 0"
|
||||
@click="showDeleteDialog(selectedQueriesIds)"
|
||||
@@ -52,15 +45,12 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
class="table-container" :style="{ 'max-height': `${maxTableHeight}px` }"
|
||||
>
|
||||
<div class="table-container" :style="{ 'max-height': `${maxTableHeight}px` }">
|
||||
<table ref="table">
|
||||
<tbody>
|
||||
<tr
|
||||
v-for="(query, index) in showedQueries"
|
||||
:key="query.id"
|
||||
:class="{ 'predefined': query.isPredefined }"
|
||||
@click="openQuery(index)"
|
||||
>
|
||||
<td ref="name-td">
|
||||
@@ -72,9 +62,10 @@
|
||||
/>
|
||||
<div class="name">{{ query.name }}</div>
|
||||
<div
|
||||
v-if="query.isPredefined"
|
||||
class="badge"
|
||||
@mouseover="showTooltip"
|
||||
@mouseout="$set(tooltipStyle, 'visibility', 'hidden')"
|
||||
@mouseout="hideTooltip"
|
||||
>
|
||||
Predefined
|
||||
<span class="icon-tooltip" :style="tooltipStyle">
|
||||
@@ -90,8 +81,14 @@
|
||||
<div class="icons-container">
|
||||
<rename-icon v-if="!query.isPredefined" @click="showRenameDialog(query.id)" />
|
||||
<copy-icon @click="duplicateQuery(index)"/>
|
||||
<export-icon @click="exportQuery(index)"/>
|
||||
<delete-icon v-if="!query.isPredefined" @click="showDeleteDialog(query.id)"/>
|
||||
<export-icon
|
||||
@click="exportToFile([query], `${query.name}.json`)"
|
||||
tooltip="Export query to file"
|
||||
/>
|
||||
<delete-icon
|
||||
v-if="!query.isPredefined"
|
||||
@click="showDeleteDialog((new Set()).add(query.id))"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
@@ -128,21 +125,8 @@
|
||||
Delete {{ deleteGroup ? 'queries' : 'query' }}
|
||||
<close-icon @click="$modal.hide('delete')"/>
|
||||
</div>
|
||||
<div
|
||||
v-if="
|
||||
deleteGroup || (
|
||||
currentQueryIndex !== null
|
||||
&& currentQueryIndex >= 0
|
||||
&& currentQueryIndex < queries.length
|
||||
)
|
||||
"
|
||||
class="dialog-body"
|
||||
>
|
||||
Are you sure you want to delete
|
||||
{{ deleteGroup
|
||||
? `${selectedNotPredefinedCount} ${selectedNotPredefinedCount > 1 ? 'queries' : 'query'}`
|
||||
: `"${queries[currentQueryIndex].name}"`
|
||||
}}?
|
||||
<div class="dialog-body">
|
||||
{{ deleteDialogMsg }}
|
||||
<div v-show="selectedQueriesCount > selectedNotPredefinedCount" id="note">
|
||||
<img :src="require('@/assets/images/info.svg')">
|
||||
Note: Predefined queries you've selected won't be deleted
|
||||
@@ -153,20 +137,20 @@
|
||||
<button class="primary" @click="deleteQuery">Delete</button>
|
||||
</div>
|
||||
</modal>
|
||||
<a ref="downloader" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import RenameIcon from '@/components/svg/rename'
|
||||
import CopyIcon from '@/components/svg/copy'
|
||||
import RenameIcon from './svg/rename'
|
||||
import CopyIcon from './svg/copy'
|
||||
import ExportIcon from '@/components/svg/export'
|
||||
import DeleteIcon from '@/components/svg/delete'
|
||||
import DeleteIcon from './svg/delete'
|
||||
import CloseIcon from '@/components/svg/close'
|
||||
import TextField from '@/components/TextField'
|
||||
import CheckBox from '@/components/CheckBox'
|
||||
import tooltipMixin from '@/mixins/tooltips'
|
||||
import { nanoid } from 'nanoid'
|
||||
import tooltipMixin from '@/tooltipMixin'
|
||||
import storedQueries from '@/lib/storedQueries'
|
||||
import fu from '@/lib/utils/fileIo'
|
||||
|
||||
export default {
|
||||
name: 'MyQueries',
|
||||
@@ -185,7 +169,7 @@ export default {
|
||||
queries: [],
|
||||
filter: null,
|
||||
newName: null,
|
||||
currentQueryId: null,
|
||||
processedQueryId: null,
|
||||
errorMsg: null,
|
||||
selectedQueriesIds: new Set(),
|
||||
selectedQueriesCount: 0,
|
||||
@@ -218,12 +202,36 @@ export default {
|
||||
allQueries () {
|
||||
return this.predefinedQueries.concat(this.queries)
|
||||
},
|
||||
currentQueryIndex () {
|
||||
return this.queries.findIndex(query => query.id === this.currentQueryId)
|
||||
processedQueryIndex () {
|
||||
return this.queries.findIndex(query => query.id === this.processedQueryId)
|
||||
},
|
||||
deleteDialogMsg () {
|
||||
if (!this.deleteGroup && (
|
||||
this.processedQueryIndex === null ||
|
||||
this.processedQueryIndex < 0 ||
|
||||
this.processedQueryIndex > this.queries.length
|
||||
)) {
|
||||
return ''
|
||||
}
|
||||
|
||||
const deleteItem = this.deleteGroup
|
||||
? `${this.selectedNotPredefinedCount} ${this.selectedNotPredefinedCount > 1
|
||||
? 'queries'
|
||||
: 'query'}`
|
||||
: `"${this.queries[this.processedQueryIndex].name}"`
|
||||
|
||||
return `Are you sure you want to delete ${deleteItem}?`
|
||||
}
|
||||
},
|
||||
created () {
|
||||
this.queries = JSON.parse(localStorage.getItem('myQueries')) || []
|
||||
storedQueries.readPredefinedQueries()
|
||||
.then(queries => {
|
||||
this.$store.commit('updatePredefinedQueries', queries)
|
||||
})
|
||||
.catch(console.error)
|
||||
.finally(() => {
|
||||
this.queries = storedQueries.getStoredQueries()
|
||||
})
|
||||
},
|
||||
mounted () {
|
||||
this.resizeObserver = new ResizeObserver(this.calcMaxTableHeight)
|
||||
@@ -264,21 +272,17 @@ export default {
|
||||
const freeSpace = this.$refs['my-queries-content'].offsetHeight - 200
|
||||
this.maxTableHeight = freeSpace - (freeSpace % 40) + 1
|
||||
},
|
||||
create () {
|
||||
this.$root.$emit('createNewQuery')
|
||||
this.$router.push('/editor')
|
||||
},
|
||||
openQuery (index) {
|
||||
const tab = JSON.parse(JSON.stringify(this.showedQueries[index]))
|
||||
tab.isUnsaved = false
|
||||
this.$store.commit('addTab', tab)
|
||||
this.$store.commit('setCurrentTabId', tab.id)
|
||||
const tab = this.showedQueries[index]
|
||||
this.$store.dispatch('addTab', tab).then(id => {
|
||||
this.$store.commit('setCurrentTabId', id)
|
||||
this.$router.push('/editor')
|
||||
})
|
||||
},
|
||||
showRenameDialog (id) {
|
||||
this.errorMsg = null
|
||||
this.currentQueryId = id
|
||||
this.newName = this.queries[this.currentQueryIndex].name
|
||||
this.processedQueryId = id
|
||||
this.newName = this.queries[this.processedQueryIndex].name
|
||||
this.$modal.show('rename')
|
||||
},
|
||||
renameQuery () {
|
||||
@@ -286,119 +290,92 @@ export default {
|
||||
this.errorMsg = 'Query name can\'t be empty'
|
||||
return
|
||||
}
|
||||
const currentQuery = this.queries[this.currentQueryIndex]
|
||||
currentQuery.name = this.newName
|
||||
this.$set(this.queries, this.currentQueryIndex, currentQuery)
|
||||
const processedQuery = this.queries[this.processedQueryIndex]
|
||||
processedQuery.name = this.newName
|
||||
this.$set(this.queries, this.processedQueryIndex, processedQuery)
|
||||
|
||||
// update queries in local storage
|
||||
this.saveQueriesInLocalStorage()
|
||||
storedQueries.updateStorage(this.queries)
|
||||
|
||||
// update tab, if renamed query is opened
|
||||
const tabIndex = this.findTabIndex(currentQuery.id)
|
||||
const tabIndex = this.findTabIndex(processedQuery.id)
|
||||
if (tabIndex >= 0) {
|
||||
this.$store.commit('updateTab', {
|
||||
index: tabIndex,
|
||||
name: this.newName,
|
||||
id: currentQuery.id
|
||||
id: processedQuery.id
|
||||
})
|
||||
}
|
||||
// hide dialog
|
||||
this.$modal.hide('rename')
|
||||
},
|
||||
duplicateQuery (index) {
|
||||
const newQuery = JSON.parse(JSON.stringify(this.showedQueries[index]))
|
||||
newQuery.name = newQuery.name + ' Copy'
|
||||
newQuery.id = nanoid()
|
||||
newQuery.createdAt = new Date()
|
||||
delete newQuery.isPredefined
|
||||
const newQuery = storedQueries.duplicateQuery(this.showedQueries[index])
|
||||
if (this.selectAll) {
|
||||
this.selectedQueriesIds.add(newQuery.id)
|
||||
this.selectedQueriesCount = this.selectedQueriesIds.size
|
||||
}
|
||||
this.queries.push(newQuery)
|
||||
this.saveQueriesInLocalStorage()
|
||||
storedQueries.updateStorage(this.queries)
|
||||
},
|
||||
showDeleteDialog (id) {
|
||||
this.deleteGroup = typeof id !== 'string'
|
||||
showDeleteDialog (idsSet) {
|
||||
this.deleteGroup = idsSet.size > 1
|
||||
if (!this.deleteGroup) {
|
||||
this.currentQueryId = id
|
||||
this.processedQueryId = idsSet.values().next().value
|
||||
}
|
||||
this.$modal.show('delete')
|
||||
},
|
||||
deleteQuery () {
|
||||
this.$modal.hide('delete')
|
||||
if (!this.deleteGroup) {
|
||||
this.queries.splice(this.currentQueryIndex, 1)
|
||||
const tabIndex = this.findTabIndex(this.currentQueryId)
|
||||
this.queries.splice(this.processedQueryIndex, 1)
|
||||
|
||||
// Close deleted query tab if it was opened
|
||||
const tabIndex = this.findTabIndex(this.processedQueryId)
|
||||
if (tabIndex >= 0) {
|
||||
this.$store.commit('deleteTab', tabIndex)
|
||||
}
|
||||
if (this.selectedQueriesIds.has(this.currentQueryId)) {
|
||||
this.selectedQueriesIds.delete(this.currentQueryId)
|
||||
|
||||
// Clear checkboxes
|
||||
if (this.selectedQueriesIds.has(this.processedQueryId)) {
|
||||
this.selectedQueriesIds.delete(this.processedQueryId)
|
||||
}
|
||||
} else {
|
||||
this.queries = this.selectAll
|
||||
? []
|
||||
: this.queries.filter(query => !this.selectedQueriesIds.has(query.id))
|
||||
|
||||
// Close deleted queries if it was opened
|
||||
const tabs = this.$store.state.tabs
|
||||
for (let i = tabs.length - 1; i >= 0; i--) {
|
||||
if (this.selectedQueriesIds.has(tabs[i].id)) {
|
||||
this.$store.commit('deleteTab', i)
|
||||
}
|
||||
}
|
||||
|
||||
// Clear checkboxes
|
||||
this.selectedQueriesIds.clear()
|
||||
}
|
||||
this.selectedQueriesCount = this.selectedQueriesIds.size
|
||||
this.saveQueriesInLocalStorage()
|
||||
storedQueries.updateStorage(this.queries)
|
||||
},
|
||||
findTabIndex (id) {
|
||||
return this.$store.state.tabs.findIndex(tab => tab.id === id)
|
||||
},
|
||||
exportQuery (index) {
|
||||
let data
|
||||
let name
|
||||
|
||||
// single operation
|
||||
if (typeof index === 'number') {
|
||||
data = JSON.parse(JSON.stringify(this.showedQueries[index]))
|
||||
name = data.name
|
||||
delete data.isPredefined
|
||||
} else {
|
||||
// group operation
|
||||
data = this.selectAll
|
||||
? JSON.parse(JSON.stringify(this.allQueries))
|
||||
exportToFile (queryList, fileName) {
|
||||
const jsonStr = storedQueries.serialiseQueries(queryList)
|
||||
fu.exportToFile(jsonStr, fileName)
|
||||
},
|
||||
exportSelectedQueries () {
|
||||
const queryList = this.selectAll
|
||||
? this.allQueries
|
||||
: this.allQueries.filter(query => this.selectedQueriesIds.has(query.id))
|
||||
name = 'My sqliteviz queries'
|
||||
data.forEach(query => delete query.isPredefined)
|
||||
}
|
||||
|
||||
// export data to file
|
||||
const downloader = this.$refs.downloader
|
||||
const json = JSON.stringify(data, null, 4)
|
||||
const blob = new Blob([json], { type: 'octet/stream' })
|
||||
const url = window.URL.createObjectURL(blob)
|
||||
downloader.href = url
|
||||
downloader.download = `${name}.json`
|
||||
downloader.click()
|
||||
window.URL.revokeObjectURL(url)
|
||||
this.exportToFile(queryList, 'My sqliteviz queries.json')
|
||||
},
|
||||
importQueries () {
|
||||
const file = this.$refs.importFile.files[0]
|
||||
const reader = new FileReader()
|
||||
reader.onload = (e) => {
|
||||
let importedQueries = JSON.parse(e.target.result)
|
||||
|
||||
if (!Array.isArray(importedQueries)) {
|
||||
importedQueries = [importedQueries]
|
||||
}
|
||||
|
||||
importedQueries.forEach(query => {
|
||||
const allQueriesIds = this.allQueries.map(query => query.id)
|
||||
if (new Set(allQueriesIds).has(query.id)) {
|
||||
query.id = nanoid()
|
||||
}
|
||||
})
|
||||
|
||||
storedQueries.importQueries()
|
||||
.then(importedQueries => {
|
||||
if (this.selectAll) {
|
||||
importedQueries.forEach(query => {
|
||||
this.selectedQueriesIds.add(query.id)
|
||||
@@ -407,13 +384,8 @@ export default {
|
||||
}
|
||||
|
||||
this.queries = this.queries.concat(importedQueries)
|
||||
this.saveQueriesInLocalStorage()
|
||||
this.$refs.importFile.value = null
|
||||
}
|
||||
reader.readAsText(file)
|
||||
},
|
||||
saveQueriesInLocalStorage () {
|
||||
localStorage.setItem('myQueries', JSON.stringify(this.queries))
|
||||
storedQueries.updateStorage(this.queries)
|
||||
})
|
||||
},
|
||||
toggleSelectAll (checked) {
|
||||
this.selectAll = checked
|
||||
@@ -551,27 +523,16 @@ tbody tr:hover td {
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
tbody tr:hover .icons-container {
|
||||
display: block;
|
||||
display: flex;
|
||||
}
|
||||
.dialog input {
|
||||
width: 100%;
|
||||
}
|
||||
a, #import-file {
|
||||
display: none;
|
||||
}
|
||||
|
||||
button.toolbar {
|
||||
margin-right: 16px;
|
||||
}
|
||||
|
||||
button label {
|
||||
display: block;
|
||||
line-height: 36px;
|
||||
}
|
||||
|
||||
button label:hover {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.badge {
|
||||
display: none;
|
||||
background-color: var(--color-gray-light-4);
|
||||
@@ -583,7 +544,7 @@ button label:hover {
|
||||
margin-left: 12px;
|
||||
}
|
||||
|
||||
tbody tr.predefined:hover .badge {
|
||||
tbody tr:hover .badge {
|
||||
display: block;
|
||||
}
|
||||
#note {
|
||||
@@ -9,7 +9,7 @@
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
@click.stop="$emit('click')"
|
||||
@mouseover="showTooltip"
|
||||
@mouseout="$set(tooltipStyle, 'visibility', 'hidden')"
|
||||
@mouseout="hideTooltip"
|
||||
>
|
||||
<path
|
||||
d="M14.25 15.75H6V5.25H14.25V15.75ZM14.25 3.75H6C5.60218 3.75 5.22064 3.90804 4.93934 4.18934C4.65804 4.47064 4.5 4.85218 4.5 5.25V15.75C4.5 16.1478 4.65804 16.5294 4.93934 16.8107C5.22064 17.092 5.60218 17.25 6 17.25H14.25C14.6478 17.25 15.0294 17.092 15.3107 16.8107C15.592 16.5294 15.75 16.1478 15.75 15.75V5.25C15.75 4.85218 15.592 4.47064 15.3107 4.18934C15.0294 3.90804 14.6478 3.75 14.25 3.75ZM12 0.75H3C2.60218 0.75 2.22064 0.908035 1.93934 1.18934C1.65804 1.47064 1.5 1.85218 1.5 2.25V12.75H3V2.25H12V0.75Z"
|
||||
@@ -23,7 +23,7 @@
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import tooltipMixin from '@/mixins/tooltips'
|
||||
import tooltipMixin from '@/tooltipMixin'
|
||||
|
||||
export default {
|
||||
name: 'CopyIcon',
|
||||
@@ -33,7 +33,7 @@ export default {
|
||||
|
||||
<style scoped>
|
||||
.icon {
|
||||
vertical-align: middle;
|
||||
display: block;
|
||||
margin: 0 12px;
|
||||
}
|
||||
.icon:hover path {
|
||||
@@ -9,7 +9,7 @@
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
@click.stop="$emit('click')"
|
||||
@mouseover="showTooltip"
|
||||
@mouseout="$set(tooltipStyle, 'visibility', 'hidden')"
|
||||
@mouseout="hideTooltip"
|
||||
>
|
||||
<path
|
||||
d="M6.75 2.25V3H3V4.5H3.75V14.25C3.75 14.6478 3.90804 15.0294 4.18934 15.3107C4.47064 15.592 4.85218 15.75 5.25 15.75H12.75C13.1478 15.75 13.5294 15.592 13.8107 15.3107C14.092 15.0294 14.25 14.6478 14.25 14.25V4.5H15V3H11.25V2.25H6.75ZM5.25 4.5H12.75V14.25H5.25V4.5ZM6.75 6V12.75H8.25V6H6.75ZM9.75 6V12.75H11.25V6H9.75Z"
|
||||
@@ -23,7 +23,7 @@
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import tooltipMixin from '@/mixins/tooltips'
|
||||
import tooltipMixin from '@/tooltipMixin'
|
||||
|
||||
export default {
|
||||
name: 'DeleteIcon',
|
||||
@@ -33,7 +33,7 @@ export default {
|
||||
|
||||
<style scoped>
|
||||
.icon {
|
||||
vertical-align: middle;
|
||||
display: block;
|
||||
margin: 0 12px;
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
@click.stop="$emit('click')"
|
||||
@mouseover="showTooltip"
|
||||
@mouseout="$set(tooltipStyle, 'visibility', 'hidden')"
|
||||
@mouseout="hideTooltip"
|
||||
>
|
||||
<path
|
||||
d="M10.545 6.75L11.25 7.455L4.44 14.25H3.75V13.56L10.545 6.75ZM13.245 2.25C13.0575 2.25 12.8625 2.325 12.72 2.4675L11.3475 3.84L14.16 6.6525L15.5325 5.28C15.825 4.9875 15.825 4.5 15.5325 4.2225L13.7775 2.4675C13.6275 2.3175 13.44 2.25 13.245 2.25ZM10.545 4.6425L2.25 12.9375V15.75H5.0625L13.3575 7.455L10.545 4.6425Z"
|
||||
@@ -23,7 +23,7 @@
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import tooltipMixin from '@/mixins/tooltips'
|
||||
import tooltipMixin from '@/tooltipMixin'
|
||||
|
||||
export default {
|
||||
name: 'RenameIcon',
|
||||
@@ -33,7 +33,7 @@ export default {
|
||||
|
||||
<style scoped>
|
||||
.icon {
|
||||
vertical-align: middle;
|
||||
display: block;
|
||||
margin: 0 12px;
|
||||
}
|
||||
|
||||
25
src/views/Main/index.vue
Normal file
@@ -0,0 +1,25 @@
|
||||
<template>
|
||||
<div>
|
||||
<main-menu />
|
||||
<keep-alive include="Editor">
|
||||
<router-view id="main-view" />
|
||||
</keep-alive>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import MainMenu from './MainMenu'
|
||||
import '@/assets/styles/scrollbars.css'
|
||||
|
||||
export default {
|
||||
name: 'Main',
|
||||
components: { MainMenu }
|
||||
}
|
||||
</script>
|
||||
<style scoped>
|
||||
#main-view {
|
||||
margin-top: 68px;
|
||||
height: calc(100vh - 68px);
|
||||
overflow-y: auto;
|
||||
}
|
||||
</style>
|
||||
@@ -1,53 +0,0 @@
|
||||
<template>
|
||||
<div>
|
||||
<main-menu />
|
||||
<keep-alive include="Editor">
|
||||
<router-view id="main-view" />
|
||||
</keep-alive>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import MainMenu from '@/components/MainMenu'
|
||||
import '@/assets/styles/scrollbars.css'
|
||||
|
||||
export default {
|
||||
name: 'MainView',
|
||||
components: { MainMenu },
|
||||
created () {
|
||||
this.readPredefinedQueries()
|
||||
.then(queries => {
|
||||
this.$store.commit('updatePredefinedQueries', queries)
|
||||
})
|
||||
.catch(console.error)
|
||||
},
|
||||
methods: {
|
||||
readPredefinedQueries () {
|
||||
return new Promise((resolve, reject) => {
|
||||
const xhr = new XMLHttpRequest()
|
||||
xhr.open('GET', './queries.json')
|
||||
xhr.onload = () => {
|
||||
if (xhr.readyState === 4) {
|
||||
if (xhr.status === 200) {
|
||||
resolve(JSON.parse(xhr.responseText || '[]'))
|
||||
} else {
|
||||
reject(xhr.statusText)
|
||||
}
|
||||
}
|
||||
}
|
||||
xhr.onerror = () => {
|
||||
reject(xhr.statusText)
|
||||
}
|
||||
xhr.send()
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
||||
<style scoped>
|
||||
#main-view {
|
||||
margin-top: 68px;
|
||||
height: calc(100vh - 68px);
|
||||
overflow-y: auto;
|
||||
}
|
||||
</style>
|
||||
@@ -1,21 +1,21 @@
|
||||
<template>
|
||||
<div id="dbloader-container">
|
||||
<db-upload illustrated />
|
||||
<db-uploader type="illustrated" />
|
||||
<div id="note">
|
||||
Sqliteviz is fully client-side. Your database never leaves your computer.
|
||||
</div>
|
||||
<button id ="skip" class="secondary" @click="$router.push('/editor')">
|
||||
Skip database loading
|
||||
<button id="skip" class="secondary" @click="$router.push('/editor')">
|
||||
Create empty database
|
||||
</button>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import dbUpload from '@/components/DbUpload'
|
||||
import DbUploader from '@/components/DbUploader'
|
||||
|
||||
export default {
|
||||
name: 'Home',
|
||||
components: { dbUpload }
|
||||
name: 'Welcome',
|
||||
components: { DbUploader }
|
||||
}
|
||||
</script>
|
||||
|
||||
50
tests/components/CheckBox.spec.js
Normal file
@@ -0,0 +1,50 @@
|
||||
import { expect } from 'chai'
|
||||
import { shallowMount } from '@vue/test-utils'
|
||||
import CheckBox from '@/components/CheckBox'
|
||||
|
||||
describe('CheckBox', () => {
|
||||
it('unchecked by default', () => {
|
||||
const wrapper = shallowMount(CheckBox, {
|
||||
propsData: { init: false }
|
||||
})
|
||||
expect(wrapper.find('img').isVisible()).to.equal(false)
|
||||
})
|
||||
|
||||
it('gets init state according to passed props', () => {
|
||||
const wrapperChecked = shallowMount(CheckBox, {
|
||||
propsData: { init: true }
|
||||
})
|
||||
expect(wrapperChecked.find('img').isVisible()).to.equal(true)
|
||||
const wrapperUnchecked = shallowMount(CheckBox, {
|
||||
propsData: { init: false }
|
||||
})
|
||||
expect(wrapperUnchecked.find('img').isVisible()).to.equal(false)
|
||||
})
|
||||
|
||||
it('checked on click', async () => {
|
||||
const wrapper = shallowMount(CheckBox)
|
||||
await wrapper.trigger('click')
|
||||
expect(wrapper.find('img').isVisible()).to.equal(true)
|
||||
})
|
||||
|
||||
it('emits event on click', async () => {
|
||||
const wrapper = shallowMount(CheckBox)
|
||||
await wrapper.trigger('click')
|
||||
expect(wrapper.emitted().click).to.have.lengthOf(1)
|
||||
expect(wrapper.emitted().click[0]).to.eql([true])
|
||||
await wrapper.trigger('click')
|
||||
expect(wrapper.emitted().click).to.have.lengthOf(2)
|
||||
expect(wrapper.emitted().click[1]).to.eql([false])
|
||||
})
|
||||
|
||||
it('disabled', async () => {
|
||||
const wrapper = shallowMount(CheckBox, {
|
||||
propsData: { disabled: true }
|
||||
})
|
||||
expect(wrapper.find('.checkbox-container').classes()).to.include('disabled')
|
||||
expect(wrapper.find('.checkbox-container').classes()).to.not.include('checked')
|
||||
await wrapper.trigger('click')
|
||||
expect(wrapper.emitted().click).to.equal(undefined)
|
||||
expect(wrapper.find('.checkbox-container').classes()).to.not.include('checked')
|
||||
})
|
||||
})
|
||||
906
tests/components/DbUploader/DbUploader.spec.js
Normal file
@@ -0,0 +1,906 @@
|
||||
import { expect } from 'chai'
|
||||
import sinon from 'sinon'
|
||||
import Vuex from 'vuex'
|
||||
import { shallowMount, mount } from '@vue/test-utils'
|
||||
import DbUploader from '@/components/DbUploader'
|
||||
import fu from '@/lib/utils/fileIo'
|
||||
import database from '@/lib/database'
|
||||
import csv from '@/components/DbUploader/csv'
|
||||
|
||||
describe('DbUploader.vue', () => {
|
||||
let state = {}
|
||||
let mutations = {}
|
||||
let store = {}
|
||||
let place
|
||||
|
||||
beforeEach(() => {
|
||||
// mock store state and mutations
|
||||
state = {}
|
||||
mutations = {
|
||||
saveSchema: sinon.stub(),
|
||||
setDb: sinon.stub()
|
||||
}
|
||||
store = new Vuex.Store({ state, mutations })
|
||||
|
||||
place = document.createElement('div')
|
||||
document.body.appendChild(place)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
sinon.restore()
|
||||
place.remove()
|
||||
})
|
||||
|
||||
it('loads db on click and redirects to /editor', async () => {
|
||||
// mock getting a file from user
|
||||
const file = { name: 'test.db' }
|
||||
sinon.stub(fu, 'getFileFromUser').resolves(file)
|
||||
|
||||
// mock db loading
|
||||
const schema = {}
|
||||
const db = {
|
||||
loadDb: sinon.stub().resolves(schema)
|
||||
}
|
||||
sinon.stub(database, 'getNewDatabase').returns(db)
|
||||
|
||||
// mock router
|
||||
const $router = { push: sinon.stub() }
|
||||
const $route = { path: '/' }
|
||||
|
||||
// mount the component
|
||||
const wrapper = shallowMount(DbUploader, {
|
||||
attachTo: place,
|
||||
store,
|
||||
mocks: { $router, $route },
|
||||
propsData: {
|
||||
type: 'illustrated'
|
||||
}
|
||||
})
|
||||
|
||||
await wrapper.find('.drop-area').trigger('click')
|
||||
expect(db.loadDb.calledOnceWith(file)).to.equal(true)
|
||||
await db.loadDb.returnValues[0]
|
||||
await wrapper.vm.animationPromise
|
||||
await wrapper.vm.$nextTick()
|
||||
expect(mutations.saveSchema.calledOnceWith(state, schema)).to.equal(true)
|
||||
expect($router.push.calledOnceWith('/editor')).to.equal(true)
|
||||
wrapper.destroy()
|
||||
})
|
||||
|
||||
it('loads db on drop and redirects to /editor', async () => {
|
||||
// mock db loading
|
||||
const schema = {}
|
||||
const db = {
|
||||
loadDb: sinon.stub().resolves(schema)
|
||||
}
|
||||
sinon.stub(database, 'getNewDatabase').returns(db)
|
||||
|
||||
// mock router
|
||||
const $router = { push: sinon.stub() }
|
||||
const $route = { path: '/' }
|
||||
|
||||
// mount the component
|
||||
const wrapper = shallowMount(DbUploader, {
|
||||
attachTo: place,
|
||||
store,
|
||||
mocks: { $router, $route },
|
||||
propsData: {
|
||||
type: 'illustrated'
|
||||
}
|
||||
})
|
||||
|
||||
// mock a file dropped by a user
|
||||
const file = { name: 'test.db' }
|
||||
const dropData = { dataTransfer: new DataTransfer() }
|
||||
Object.defineProperty(dropData.dataTransfer, 'files', {
|
||||
value: [file],
|
||||
writable: false
|
||||
})
|
||||
|
||||
await wrapper.find('.drop-area').trigger('drop', dropData)
|
||||
expect(db.loadDb.calledOnceWith(file)).to.equal(true)
|
||||
await db.loadDb.returnValues[0]
|
||||
await wrapper.vm.animationPromise
|
||||
await wrapper.vm.$nextTick()
|
||||
expect(mutations.saveSchema.calledOnceWith(state, schema)).to.equal(true)
|
||||
expect($router.push.calledOnceWith('/editor')).to.equal(true)
|
||||
wrapper.destroy()
|
||||
})
|
||||
|
||||
it("doesn't redirect if already on /editor", async () => {
|
||||
// mock getting a file from user
|
||||
const file = { name: 'test.db' }
|
||||
sinon.stub(fu, 'getFileFromUser').resolves(file)
|
||||
|
||||
// mock db loading
|
||||
const schema = {}
|
||||
const db = {
|
||||
loadDb: sinon.stub().resolves(schema)
|
||||
}
|
||||
sinon.stub(database, 'getNewDatabase').returns(db)
|
||||
|
||||
// mock router
|
||||
const $router = { push: sinon.stub() }
|
||||
const $route = { path: '/editor' }
|
||||
|
||||
// mount the component
|
||||
const wrapper = shallowMount(DbUploader, {
|
||||
attachTo: place,
|
||||
store,
|
||||
mocks: { $router, $route },
|
||||
propsData: {
|
||||
type: 'illustrated'
|
||||
}
|
||||
})
|
||||
|
||||
await wrapper.find('.drop-area').trigger('click')
|
||||
await db.loadDb.returnValues[0]
|
||||
await wrapper.vm.animationPromise
|
||||
await wrapper.vm.$nextTick()
|
||||
expect($router.push.called).to.equal(false)
|
||||
wrapper.destroy()
|
||||
})
|
||||
})
|
||||
|
||||
describe('DbUploader.vue import CSV', () => {
|
||||
let state = {}
|
||||
let mutations = {}
|
||||
let actions = {}
|
||||
const newTabId = 1
|
||||
let store = {}
|
||||
let place
|
||||
|
||||
// mock router
|
||||
const $router = { }
|
||||
const $route = { path: '/' }
|
||||
|
||||
let clock
|
||||
let wrapper
|
||||
|
||||
beforeEach(() => {
|
||||
// mock getting a file from user
|
||||
sinon.stub(fu, 'getFileFromUser').resolves({ type: 'text/csv', name: 'foo.csv' })
|
||||
|
||||
clock = sinon.useFakeTimers()
|
||||
|
||||
// mock store state and mutations
|
||||
state = {}
|
||||
mutations = {
|
||||
saveSchema: sinon.stub(),
|
||||
setDb: sinon.stub(),
|
||||
setCurrentTabId: sinon.stub()
|
||||
}
|
||||
actions = {
|
||||
addTab: sinon.stub().resolves(newTabId)
|
||||
}
|
||||
store = new Vuex.Store({ state, mutations, actions })
|
||||
|
||||
$router.push = sinon.stub()
|
||||
|
||||
place = document.createElement('div')
|
||||
document.body.appendChild(place)
|
||||
|
||||
// mount the component
|
||||
wrapper = mount(DbUploader, {
|
||||
attachTo: place,
|
||||
store,
|
||||
mocks: { $router, $route },
|
||||
propsData: {
|
||||
type: 'illustrated'
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
sinon.restore()
|
||||
wrapper.destroy()
|
||||
place.remove()
|
||||
})
|
||||
|
||||
it('shows parse dialog if gets csv file', async () => {
|
||||
sinon.stub(csv, 'parse').resolves({
|
||||
delimiter: '|',
|
||||
data: {
|
||||
columns: ['col1', 'col2'],
|
||||
values: [
|
||||
[1, 'foo'],
|
||||
[2, 'bar']
|
||||
]
|
||||
},
|
||||
messages: [{
|
||||
code: 'UndetectableDelimiter',
|
||||
message: 'Comma was used as a standart delimiter',
|
||||
row: 0,
|
||||
type: 'info',
|
||||
hint: undefined
|
||||
}]
|
||||
})
|
||||
|
||||
await wrapper.find('.drop-area').trigger('click')
|
||||
await csv.parse.returnValues[0]
|
||||
await wrapper.vm.animationPromise
|
||||
await wrapper.vm.$nextTick()
|
||||
await wrapper.vm.$nextTick()
|
||||
expect(wrapper.find('[data-modal="parse"]').exists()).to.equal(true)
|
||||
expect(wrapper.findComponent({ name: 'delimiter-selector' }).vm.value).to.equal('|')
|
||||
expect(wrapper.find('#quote-char input').element.value).to.equal('"')
|
||||
expect(wrapper.find('#escape-char input').element.value).to.equal('"')
|
||||
expect(wrapper.findComponent({ name: 'check-box' }).vm.checked).to.equal(true)
|
||||
const rows = wrapper.findAll('tbody tr')
|
||||
expect(rows).to.have.lengthOf(2)
|
||||
expect(rows.at(0).findAll('td').at(0).text()).to.equal('1')
|
||||
expect(rows.at(0).findAll('td').at(1).text()).to.equal('foo')
|
||||
expect(rows.at(1).findAll('td').at(0).text()).to.equal('2')
|
||||
expect(rows.at(1).findAll('td').at(1).text()).to.equal('bar')
|
||||
expect(wrapper.findComponent({ name: 'logs' }).text())
|
||||
.to.include('Information about row 0. Comma was used as a standart delimiter.')
|
||||
expect(wrapper.findComponent({ name: 'logs' }).text())
|
||||
.to.include('Preview parsing is completed in')
|
||||
expect(wrapper.find('#csv-finish').isVisible()).to.equal(false)
|
||||
expect(wrapper.find('#csv-import').isVisible()).to.equal(true)
|
||||
})
|
||||
|
||||
it('reparses when parameters changes', async () => {
|
||||
const parse = sinon.stub(csv, 'parse')
|
||||
parse.onCall(0).resolves({
|
||||
delimiter: '|',
|
||||
data: {
|
||||
columns: ['col1', 'col2'],
|
||||
values: [
|
||||
[1, 'foo']
|
||||
]
|
||||
}
|
||||
})
|
||||
|
||||
await wrapper.find('.drop-area').trigger('click')
|
||||
await csv.parse.returnValues[0]
|
||||
await wrapper.vm.animationPromise
|
||||
await wrapper.vm.$nextTick()
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
parse.onCall(1).resolves({
|
||||
delimiter: ',',
|
||||
data: {
|
||||
columns: ['col1', 'col2'],
|
||||
values: [
|
||||
[2, 'bar']
|
||||
]
|
||||
},
|
||||
hasErrors: false
|
||||
})
|
||||
await wrapper.find('.delimiter-selector-container input').setValue(',')
|
||||
expect(parse.callCount).to.equal(2)
|
||||
await csv.parse.returnValues[1]
|
||||
|
||||
let rows = wrapper.findAll('tbody tr')
|
||||
expect(rows).to.have.lengthOf(1)
|
||||
expect(rows.at(0).findAll('td').at(0).text()).to.equal('2')
|
||||
expect(rows.at(0).findAll('td').at(1).text()).to.equal('bar')
|
||||
expect(wrapper.findComponent({ name: 'logs' }).text())
|
||||
.to.include('Preview parsing is completed in')
|
||||
|
||||
parse.onCall(2).resolves({
|
||||
delimiter: ',',
|
||||
data: {
|
||||
columns: ['col1', 'col2'],
|
||||
values: [
|
||||
[3, 'baz']
|
||||
]
|
||||
},
|
||||
hasErrors: true,
|
||||
messages: [{
|
||||
code: 'MissingQuotes',
|
||||
message: 'Quote is missed',
|
||||
row: 0,
|
||||
type: 'error',
|
||||
hint: 'Edit your CSV so that the field has a closing quote char.'
|
||||
}]
|
||||
})
|
||||
|
||||
await wrapper.find('#quote-char input').setValue("'")
|
||||
expect(parse.callCount).to.equal(3)
|
||||
await csv.parse.returnValues[2]
|
||||
rows = wrapper.findAll('tbody tr')
|
||||
expect(rows).to.have.lengthOf(1)
|
||||
expect(rows.at(0).findAll('td').at(0).text()).to.equal('3')
|
||||
expect(rows.at(0).findAll('td').at(1).text()).to.equal('baz')
|
||||
expect(wrapper.findComponent({ name: 'logs' }).text())
|
||||
.to.contain('Error in row 0. Quote is missed. Edit your CSV so that the field has a closing quote char.')
|
||||
expect(wrapper.findComponent({ name: 'logs' }).text())
|
||||
.to.not.contain('Preview parsing is completed in')
|
||||
|
||||
parse.onCall(3).resolves({
|
||||
delimiter: ',',
|
||||
data: {
|
||||
columns: ['col1', 'col2'],
|
||||
values: [
|
||||
[4, 'qux']
|
||||
]
|
||||
},
|
||||
hasErrors: false
|
||||
})
|
||||
await wrapper.find('#escape-char input').setValue("'")
|
||||
expect(parse.callCount).to.equal(4)
|
||||
await csv.parse.returnValues[3]
|
||||
rows = wrapper.findAll('tbody tr')
|
||||
expect(rows).to.have.lengthOf(1)
|
||||
expect(rows.at(0).findAll('td').at(0).text()).to.equal('4')
|
||||
expect(rows.at(0).findAll('td').at(1).text()).to.equal('qux')
|
||||
expect(wrapper.findComponent({ name: 'logs' }).text())
|
||||
.to.contain('Preview parsing is completed in')
|
||||
|
||||
parse.onCall(4).resolves({
|
||||
delimiter: ',',
|
||||
data: {
|
||||
columns: ['col1', 'col2'],
|
||||
values: [
|
||||
[5, 'corge']
|
||||
]
|
||||
},
|
||||
hasErrors: false
|
||||
})
|
||||
await wrapper.findComponent({ name: 'check-box' }).trigger('click')
|
||||
expect(parse.callCount).to.equal(5)
|
||||
await csv.parse.returnValues[4]
|
||||
rows = wrapper.findAll('tbody tr')
|
||||
expect(rows).to.have.lengthOf(1)
|
||||
expect(rows.at(0).findAll('td').at(0).text()).to.equal('5')
|
||||
expect(rows.at(0).findAll('td').at(1).text()).to.equal('corge')
|
||||
expect(wrapper.findComponent({ name: 'logs' }).text())
|
||||
.to.include('Preview parsing is completed in')
|
||||
})
|
||||
|
||||
it('has proper state before parsing is complete', async () => {
|
||||
const parse = sinon.stub(csv, 'parse')
|
||||
parse.onCall(0).resolves({
|
||||
delimiter: '|',
|
||||
data: {
|
||||
columns: ['col1', 'col2'],
|
||||
values: [
|
||||
[1, 'foo']
|
||||
]
|
||||
}
|
||||
})
|
||||
|
||||
await wrapper.find('.drop-area').trigger('click')
|
||||
await csv.parse.returnValues[0]
|
||||
await wrapper.vm.animationPromise
|
||||
await wrapper.vm.$nextTick()
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
let resolveParsing
|
||||
parse.onCall(1).returns(new Promise(resolve => {
|
||||
resolveParsing = resolve
|
||||
}))
|
||||
await wrapper.find('#csv-import').trigger('click')
|
||||
|
||||
// "Parsing CSV..." in the logs
|
||||
expect(wrapper.findComponent({ name: 'logs' }).findAll('.msg').at(1).text())
|
||||
.to.equal('Parsing CSV...')
|
||||
|
||||
// After 1 second - loading indicator is shown
|
||||
await clock.tick(1000)
|
||||
expect(
|
||||
wrapper.findComponent({ name: 'logs' }).findComponent({ name: 'LoadingIndicator' }).exists()
|
||||
).to.equal(true)
|
||||
|
||||
// All the dialog controls are disabled
|
||||
expect(wrapper.findComponent({ name: 'delimiter-selector' }).vm.disabled).to.equal(true)
|
||||
expect(wrapper.find('#quote-char input').element.disabled).to.equal(true)
|
||||
expect(wrapper.find('#escape-char input').element.disabled).to.equal(true)
|
||||
expect(wrapper.findComponent({ name: 'check-box' }).vm.disabled).to.equal(true)
|
||||
expect(wrapper.find('#csv-cancel').element.disabled).to.equal(true)
|
||||
expect(wrapper.find('#csv-finish').element.disabled).to.equal(true)
|
||||
expect(wrapper.findComponent({ name: 'close-icon' }).vm.disabled).to.equal(true)
|
||||
expect(wrapper.find('#csv-finish').isVisible()).to.equal(false)
|
||||
expect(wrapper.find('#csv-import').isVisible()).to.equal(true)
|
||||
await resolveParsing()
|
||||
await parse.returnValues[1]
|
||||
|
||||
// Loading indicator is not shown when parsing is compete
|
||||
expect(
|
||||
wrapper.findComponent({ name: 'logs' }).findComponent({ name: 'LoadingIndicator' }).exists()
|
||||
).to.equal(false)
|
||||
})
|
||||
|
||||
it('parsing is completed successfully', async () => {
|
||||
const parse = sinon.stub(csv, 'parse')
|
||||
parse.onCall(0).resolves({
|
||||
delimiter: '|',
|
||||
data: {
|
||||
columns: ['col1', 'col2'],
|
||||
values: [
|
||||
[1, 'foo']
|
||||
]
|
||||
},
|
||||
hasErrors: false,
|
||||
messages: []
|
||||
})
|
||||
|
||||
parse.onCall(1).resolves({
|
||||
delimiter: '|',
|
||||
data: {
|
||||
columns: ['col1', 'col2'],
|
||||
values: [
|
||||
[1, 'foo'],
|
||||
[2, 'bar']
|
||||
]
|
||||
},
|
||||
hasErrors: false,
|
||||
messages: []
|
||||
})
|
||||
|
||||
await wrapper.find('.drop-area').trigger('click')
|
||||
await csv.parse.returnValues[0]
|
||||
await wrapper.vm.animationPromise
|
||||
await wrapper.vm.$nextTick()
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
await wrapper.find('#csv-import').trigger('click')
|
||||
await csv.parse.returnValues[1]
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
// Parsing success in the logs
|
||||
expect(wrapper.findComponent({ name: 'logs' }).findAll('.msg').at(1).text())
|
||||
.to.include('2 rows are parsed successfully in')
|
||||
|
||||
// All the dialog controls are disabled
|
||||
expect(wrapper.findComponent({ name: 'delimiter-selector' }).vm.disabled).to.equal(true)
|
||||
expect(wrapper.find('#quote-char input').element.disabled).to.equal(true)
|
||||
expect(wrapper.find('#escape-char input').element.disabled).to.equal(true)
|
||||
expect(wrapper.findComponent({ name: 'check-box' }).vm.disabled).to.equal(true)
|
||||
expect(wrapper.find('#csv-cancel').element.disabled).to.equal(true)
|
||||
expect(wrapper.find('#csv-finish').element.disabled).to.equal(true)
|
||||
expect(wrapper.findComponent({ name: 'close-icon' }).vm.disabled).to.equal(true)
|
||||
expect(wrapper.find('#csv-finish').isVisible()).to.equal(false)
|
||||
expect(wrapper.find('#csv-import').isVisible()).to.equal(true)
|
||||
})
|
||||
|
||||
it('parsing is completed with notes', async () => {
|
||||
const parse = sinon.stub(csv, 'parse')
|
||||
parse.onCall(0).resolves({
|
||||
delimiter: '|',
|
||||
data: {
|
||||
columns: ['col1', 'col2'],
|
||||
values: [
|
||||
[1, 'foo']
|
||||
]
|
||||
},
|
||||
hasErrors: false,
|
||||
messages: []
|
||||
})
|
||||
|
||||
parse.onCall(1).resolves({
|
||||
delimiter: '|',
|
||||
data: {
|
||||
columns: ['col1', 'col2'],
|
||||
values: [
|
||||
[1, 'foo'],
|
||||
[2, 'bar']
|
||||
]
|
||||
},
|
||||
hasErrors: false,
|
||||
messages: [{
|
||||
code: 'UndetectableDelimiter',
|
||||
message: 'Comma was used as a standart delimiter',
|
||||
type: 'info',
|
||||
hint: undefined
|
||||
}]
|
||||
})
|
||||
|
||||
await wrapper.find('.drop-area').trigger('click')
|
||||
await csv.parse.returnValues[0]
|
||||
await wrapper.vm.animationPromise
|
||||
await wrapper.vm.$nextTick()
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
await wrapper.find('#csv-import').trigger('click')
|
||||
await csv.parse.returnValues[1]
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
// Parsing success in the logs
|
||||
const logs = wrapper.findComponent({ name: 'logs' }).findAll('.msg')
|
||||
expect(logs).to.have.lengthOf(4)
|
||||
expect(logs.at(1).text()).to.include('2 rows are parsed in')
|
||||
expect(logs.at(2).text()).to.equals('Comma was used as a standart delimiter.')
|
||||
|
||||
// All the dialog controls are disabled
|
||||
expect(wrapper.findComponent({ name: 'delimiter-selector' }).vm.disabled).to.equal(true)
|
||||
expect(wrapper.find('#quote-char input').element.disabled).to.equal(true)
|
||||
expect(wrapper.find('#escape-char input').element.disabled).to.equal(true)
|
||||
expect(wrapper.findComponent({ name: 'check-box' }).vm.disabled).to.equal(true)
|
||||
expect(wrapper.find('#csv-cancel').element.disabled).to.equal(true)
|
||||
expect(wrapper.find('#csv-finish').element.disabled).to.equal(true)
|
||||
expect(wrapper.findComponent({ name: 'close-icon' }).vm.disabled).to.equal(true)
|
||||
expect(wrapper.find('#csv-finish').isVisible()).to.equal(false)
|
||||
expect(wrapper.find('#csv-import').isVisible()).to.equal(true)
|
||||
})
|
||||
|
||||
it('parsing is completed with errors', async () => {
|
||||
const parse = sinon.stub(csv, 'parse')
|
||||
parse.onCall(0).resolves({
|
||||
delimiter: '|',
|
||||
data: {
|
||||
columns: ['col1', 'col2'],
|
||||
values: [
|
||||
[1, 'foo']
|
||||
]
|
||||
},
|
||||
hasErrors: false,
|
||||
messages: []
|
||||
})
|
||||
|
||||
parse.onCall(1).resolves({
|
||||
delimiter: '|',
|
||||
data: {
|
||||
columns: ['col1', 'col2'],
|
||||
values: [
|
||||
[1, 'foo'],
|
||||
[2, 'bar']
|
||||
]
|
||||
},
|
||||
hasErrors: true,
|
||||
messages: [{
|
||||
code: 'Error',
|
||||
message: 'Something is wrong',
|
||||
type: 'error',
|
||||
hint: undefined
|
||||
}]
|
||||
})
|
||||
|
||||
await wrapper.find('.drop-area').trigger('click')
|
||||
await csv.parse.returnValues[0]
|
||||
await wrapper.vm.animationPromise
|
||||
await wrapper.vm.$nextTick()
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
await wrapper.find('#csv-import').trigger('click')
|
||||
await csv.parse.returnValues[1]
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
// Parsing success in the logs
|
||||
const logs = wrapper.findComponent({ name: 'logs' }).findAll('.msg')
|
||||
expect(logs).to.have.lengthOf(3)
|
||||
expect(logs.at(1).text()).to.include('Parsing ended with errors.')
|
||||
expect(logs.at(2).text()).to.equals('Something is wrong.')
|
||||
|
||||
// All the dialog controls are enabled
|
||||
expect(wrapper.findComponent({ name: 'delimiter-selector' }).vm.disabled).to.equal(false)
|
||||
expect(wrapper.find('#quote-char input').element.disabled).to.equal(false)
|
||||
expect(wrapper.find('#escape-char input').element.disabled).to.equal(false)
|
||||
expect(wrapper.findComponent({ name: 'check-box' }).vm.disabled).to.equal(false)
|
||||
expect(wrapper.find('#csv-cancel').element.disabled).to.equal(false)
|
||||
expect(wrapper.find('#csv-finish').element.disabled).to.equal(false)
|
||||
expect(wrapper.findComponent({ name: 'close-icon' }).vm.disabled).to.equal(false)
|
||||
expect(wrapper.find('#csv-finish').isVisible()).to.equal(false)
|
||||
expect(wrapper.find('#csv-import').isVisible()).to.equal(true)
|
||||
})
|
||||
|
||||
it('has proper state before import is completed', async () => {
|
||||
const parse = sinon.stub(csv, 'parse')
|
||||
parse.onCall(0).resolves({
|
||||
delimiter: '|',
|
||||
data: {
|
||||
columns: ['col1', 'col2'],
|
||||
values: [
|
||||
[1, 'foo']
|
||||
]
|
||||
},
|
||||
hasErrors: false,
|
||||
messages: []
|
||||
})
|
||||
|
||||
parse.onCall(1).resolves({
|
||||
delimiter: '|',
|
||||
data: {
|
||||
columns: ['col1', 'col2'],
|
||||
values: [
|
||||
[1, 'foo'],
|
||||
[2, 'bar']
|
||||
]
|
||||
},
|
||||
hasErrors: false,
|
||||
messages: []
|
||||
})
|
||||
|
||||
let resolveImport = sinon.stub()
|
||||
const newDb = {
|
||||
importDb: sinon.stub().resolves(new Promise(resolve => { resolveImport = resolve })),
|
||||
createProgressCounter: sinon.stub().returns(1),
|
||||
deleteProgressCounter: sinon.stub()
|
||||
}
|
||||
sinon.stub(database, 'getNewDatabase').returns(newDb)
|
||||
|
||||
await wrapper.find('.drop-area').trigger('click')
|
||||
await csv.parse.returnValues[0]
|
||||
await wrapper.vm.animationPromise
|
||||
await wrapper.vm.$nextTick()
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
await wrapper.find('#csv-import').trigger('click')
|
||||
await csv.parse.returnValues[1]
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
// Parsing success in the logs
|
||||
expect(wrapper.findComponent({ name: 'logs' }).findAll('.msg').at(2).text())
|
||||
.to.equal('Importing CSV into a SQLite database...')
|
||||
|
||||
// After 1 second - loading indicator is shown
|
||||
await clock.tick(1000)
|
||||
expect(
|
||||
wrapper.findComponent({ name: 'logs' }).findComponent({ name: 'LoadingIndicator' }).exists()
|
||||
).to.equal(true)
|
||||
|
||||
// All the dialog controls are disabled
|
||||
expect(wrapper.findComponent({ name: 'delimiter-selector' }).vm.disabled).to.equal(true)
|
||||
expect(wrapper.find('#quote-char input').element.disabled).to.equal(true)
|
||||
expect(wrapper.find('#escape-char input').element.disabled).to.equal(true)
|
||||
expect(wrapper.findComponent({ name: 'check-box' }).vm.disabled).to.equal(true)
|
||||
expect(wrapper.find('#csv-cancel').element.disabled).to.equal(true)
|
||||
expect(wrapper.find('#csv-finish').element.disabled).to.equal(true)
|
||||
expect(wrapper.findComponent({ name: 'close-icon' }).vm.disabled).to.equal(true)
|
||||
expect(wrapper.find('#csv-finish').isVisible()).to.equal(false)
|
||||
expect(wrapper.find('#csv-import').isVisible()).to.equal(true)
|
||||
expect(newDb.importDb.getCall(0).args[0]).to.equal('foo') // file name
|
||||
|
||||
// After resolving - loading indicator is not shown
|
||||
await resolveImport()
|
||||
await newDb.importDb.returnValues[0]
|
||||
expect(
|
||||
wrapper.findComponent({ name: 'logs' }).findComponent({ name: 'LoadingIndicator' }).exists()
|
||||
).to.equal(false)
|
||||
})
|
||||
|
||||
it('import success', async () => {
|
||||
const parse = sinon.stub(csv, 'parse')
|
||||
parse.onCall(0).resolves({
|
||||
delimiter: '|',
|
||||
data: {
|
||||
columns: ['col1', 'col2'],
|
||||
values: [
|
||||
[1, 'foo']
|
||||
]
|
||||
},
|
||||
hasErrors: false,
|
||||
messages: []
|
||||
})
|
||||
// we need to separate calles because messages will mutate
|
||||
parse.onCall(1).resolves({
|
||||
delimiter: '|',
|
||||
data: {
|
||||
columns: ['col1', 'col2'],
|
||||
values: [
|
||||
[1, 'foo'],
|
||||
[2, 'bar']
|
||||
]
|
||||
},
|
||||
hasErrors: false,
|
||||
messages: []
|
||||
})
|
||||
|
||||
const schema = {}
|
||||
const newDb = {
|
||||
importDb: sinon.stub().resolves(schema),
|
||||
createProgressCounter: sinon.stub().returns(1),
|
||||
deleteProgressCounter: sinon.stub()
|
||||
}
|
||||
sinon.stub(database, 'getNewDatabase').returns(newDb)
|
||||
|
||||
await wrapper.find('.drop-area').trigger('click')
|
||||
await csv.parse.returnValues[0]
|
||||
await wrapper.vm.animationPromise
|
||||
await wrapper.vm.$nextTick()
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
await wrapper.find('#csv-import').trigger('click')
|
||||
await csv.parse.returnValues[1]
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
// Import success in the logs
|
||||
const logs = wrapper.findComponent({ name: 'logs' }).findAll('.msg')
|
||||
expect(logs).to.have.lengthOf(3)
|
||||
expect(logs.at(2).text()).to.contain('Importing CSV into a SQLite database is completed in')
|
||||
|
||||
// All the dialog controls are enabled
|
||||
expect(wrapper.findComponent({ name: 'delimiter-selector' }).vm.disabled).to.equal(false)
|
||||
expect(wrapper.find('#quote-char input').element.disabled).to.equal(false)
|
||||
expect(wrapper.find('#escape-char input').element.disabled).to.equal(false)
|
||||
expect(wrapper.findComponent({ name: 'check-box' }).vm.disabled).to.equal(false)
|
||||
expect(wrapper.find('#csv-cancel').element.disabled).to.equal(false)
|
||||
expect(wrapper.find('#csv-finish').element.disabled).to.equal(false)
|
||||
expect(wrapper.findComponent({ name: 'close-icon' }).vm.disabled).to.equal(false)
|
||||
expect(wrapper.find('#csv-finish').isVisible()).to.equal(true)
|
||||
})
|
||||
|
||||
it('import fails', async () => {
|
||||
const parse = sinon.stub(csv, 'parse')
|
||||
parse.onCall(0).resolves({
|
||||
delimiter: '|',
|
||||
data: {
|
||||
columns: ['col1', 'col2'],
|
||||
values: [
|
||||
[1, 'foo']
|
||||
]
|
||||
},
|
||||
hasErrors: false,
|
||||
messages: []
|
||||
})
|
||||
// we need to separate calles because messages will mutate
|
||||
parse.onCall(1).resolves({
|
||||
delimiter: '|',
|
||||
data: {
|
||||
columns: ['col1', 'col2'],
|
||||
values: [
|
||||
[1, 'foo'],
|
||||
[2, 'bar']
|
||||
]
|
||||
},
|
||||
hasErrors: false,
|
||||
messages: []
|
||||
})
|
||||
|
||||
const newDb = {
|
||||
importDb: sinon.stub().rejects(new Error('fail')),
|
||||
createProgressCounter: sinon.stub().returns(1),
|
||||
deleteProgressCounter: sinon.stub()
|
||||
}
|
||||
sinon.stub(database, 'getNewDatabase').returns(newDb)
|
||||
|
||||
await wrapper.find('.drop-area').trigger('click')
|
||||
await csv.parse.returnValues[0]
|
||||
await wrapper.vm.animationPromise
|
||||
await wrapper.vm.$nextTick()
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
await wrapper.find('#csv-import').trigger('click')
|
||||
await csv.parse.returnValues[1]
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
// Import success in the logs
|
||||
const logs = wrapper.findComponent({ name: 'logs' }).findAll('.msg')
|
||||
expect(logs).to.have.lengthOf(4)
|
||||
expect(logs.at(2).text()).to.contain('Importing CSV into a SQLite database...')
|
||||
expect(logs.at(3).text()).to.equal('Error: fail.')
|
||||
|
||||
// All the dialog controls are enabled
|
||||
expect(wrapper.findComponent({ name: 'delimiter-selector' }).vm.disabled).to.equal(false)
|
||||
expect(wrapper.find('#quote-char input').element.disabled).to.equal(false)
|
||||
expect(wrapper.find('#escape-char input').element.disabled).to.equal(false)
|
||||
expect(wrapper.findComponent({ name: 'check-box' }).vm.disabled).to.equal(false)
|
||||
expect(wrapper.find('#csv-cancel').element.disabled).to.equal(false)
|
||||
expect(wrapper.find('#csv-finish').element.disabled).to.equal(false)
|
||||
expect(wrapper.findComponent({ name: 'close-icon' }).vm.disabled).to.equal(false)
|
||||
expect(wrapper.find('#csv-finish').isVisible()).to.equal(false)
|
||||
})
|
||||
|
||||
it('import final', async () => {
|
||||
sinon.stub(csv, 'parse').resolves({
|
||||
delimiter: '|',
|
||||
data: {
|
||||
columns: ['col1', 'col2'],
|
||||
values: [
|
||||
[1, 'foo']
|
||||
]
|
||||
},
|
||||
hasErrors: false,
|
||||
messages: []
|
||||
})
|
||||
|
||||
const schema = {}
|
||||
const newDb = {
|
||||
importDb: sinon.stub().resolves(schema),
|
||||
createProgressCounter: sinon.stub().returns(1),
|
||||
deleteProgressCounter: sinon.stub()
|
||||
}
|
||||
sinon.stub(database, 'getNewDatabase').returns(newDb)
|
||||
|
||||
await wrapper.find('.drop-area').trigger('click')
|
||||
await csv.parse.returnValues[0]
|
||||
await wrapper.vm.animationPromise
|
||||
await wrapper.vm.$nextTick()
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
await wrapper.find('#csv-import').trigger('click')
|
||||
await csv.parse.returnValues[1]
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
await wrapper.find('#csv-finish').trigger('click')
|
||||
|
||||
expect(mutations.setDb.calledOnceWith(state, newDb)).to.equal(true)
|
||||
expect(mutations.saveSchema.calledOnceWith(state, schema)).to.equal(true)
|
||||
expect(actions.addTab.calledOnce).to.equal(true)
|
||||
await actions.addTab.returnValues[0]
|
||||
expect(mutations.setCurrentTabId.calledOnceWith(state, newTabId)).to.equal(true)
|
||||
expect($router.push.calledOnceWith('/editor')).to.equal(true)
|
||||
expect(wrapper.find('[data-modal="parse"]').exists()).to.equal(false)
|
||||
})
|
||||
|
||||
it('import cancel', async () => {
|
||||
sinon.stub(csv, 'parse').resolves({
|
||||
delimiter: '|',
|
||||
data: {
|
||||
columns: ['col1', 'col2'],
|
||||
values: [
|
||||
[1, 'foo']
|
||||
]
|
||||
},
|
||||
hasErrors: false,
|
||||
messages: []
|
||||
})
|
||||
|
||||
const schema = {}
|
||||
const newDb = {
|
||||
importDb: sinon.stub().resolves(schema),
|
||||
createProgressCounter: sinon.stub().returns(1),
|
||||
deleteProgressCounter: sinon.stub(),
|
||||
shutDown: sinon.stub()
|
||||
}
|
||||
sinon.stub(database, 'getNewDatabase').returns(newDb)
|
||||
|
||||
await wrapper.find('.drop-area').trigger('click')
|
||||
await csv.parse.returnValues[0]
|
||||
await wrapper.vm.animationPromise
|
||||
await wrapper.vm.$nextTick()
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
await wrapper.find('#csv-import').trigger('click')
|
||||
await csv.parse.returnValues[1]
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
await wrapper.find('#csv-cancel').trigger('click')
|
||||
|
||||
expect(mutations.setDb.called).to.equal(false)
|
||||
expect(mutations.saveSchema.called).to.equal(false)
|
||||
expect(actions.addTab.called).to.equal(false)
|
||||
expect(mutations.setCurrentTabId.called).to.equal(false)
|
||||
expect($router.push.called).to.equal(false)
|
||||
expect(newDb.shutDown.calledOnce).to.equal(true)
|
||||
expect(wrapper.find('[data-modal="parse"]').exists()).to.equal(false)
|
||||
})
|
||||
|
||||
it("doesn't open new tab when load db after importing CSV", async () => {
|
||||
fu.getFileFromUser.onCall(0).resolves({ type: 'text/csv', name: 'foo.csv' })
|
||||
fu.getFileFromUser.onCall(1).resolves({ type: 'application/x-sqlite3', name: 'bar.sqlite3' })
|
||||
sinon.stub(csv, 'parse').resolves({
|
||||
delimiter: '|',
|
||||
data: {
|
||||
columns: ['col1', 'col2'],
|
||||
values: [
|
||||
[1, 'foo']
|
||||
]
|
||||
},
|
||||
hasErrors: false,
|
||||
messages: []
|
||||
})
|
||||
|
||||
const schema = {}
|
||||
const newDb = {
|
||||
importDb: sinon.stub().resolves(schema),
|
||||
createProgressCounter: sinon.stub().returns(1),
|
||||
deleteProgressCounter: sinon.stub(),
|
||||
loadDb: sinon.stub().resolves()
|
||||
}
|
||||
sinon.stub(database, 'getNewDatabase').returns(newDb)
|
||||
|
||||
await wrapper.find('.drop-area').trigger('click')
|
||||
await csv.parse.returnValues[0]
|
||||
await wrapper.vm.animationPromise
|
||||
await wrapper.vm.$nextTick()
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
await wrapper.find('#csv-import').trigger('click')
|
||||
await csv.parse.returnValues[1]
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
await wrapper.find('#csv-finish').trigger('click')
|
||||
|
||||
expect(actions.addTab.calledOnce).to.equal(true)
|
||||
await actions.addTab.returnValues[0]
|
||||
expect(mutations.setCurrentTabId.calledOnceWith(state, newTabId)).to.equal(true)
|
||||
|
||||
await wrapper.find('.drop-area').trigger('click')
|
||||
await newDb.loadDb.returnValues[0]
|
||||
expect(actions.addTab.calledOnce).to.equal(true)
|
||||
expect(mutations.setCurrentTabId.calledOnce).to.equal(true)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,109 @@
|
||||
import { expect } from 'chai'
|
||||
import { mount, shallowMount } from '@vue/test-utils'
|
||||
import DelimiterSelector from '@/components/DbUploader/DelimiterSelector'
|
||||
|
||||
describe('DelimiterSelector', async () => {
|
||||
it('shows the name of value', async () => {
|
||||
let wrapper = shallowMount(DelimiterSelector, {
|
||||
propsData: { value: ',' }
|
||||
})
|
||||
expect(wrapper.find('input').element.value).to.equal(',')
|
||||
expect(wrapper.find('.name').text()).to.equal('comma')
|
||||
|
||||
wrapper = shallowMount(DelimiterSelector, {
|
||||
propsData: { value: '\t' }
|
||||
})
|
||||
expect(wrapper.find('input').element.value).to.equal('\t')
|
||||
expect(wrapper.find('.name').text()).to.equal('horizontal tab')
|
||||
|
||||
wrapper = shallowMount(DelimiterSelector, {
|
||||
propsData: { value: '' }
|
||||
})
|
||||
expect(wrapper.find('input').element.value).to.equal('')
|
||||
expect(wrapper.find('.name').text()).to.equal('')
|
||||
})
|
||||
|
||||
it('clears the field', async () => {
|
||||
const wrapper = mount(DelimiterSelector, {
|
||||
propsData: { value: ',' }
|
||||
})
|
||||
|
||||
await wrapper.findComponent({ name: 'clear-icon' }).trigger('click')
|
||||
|
||||
expect(wrapper.find('input').element.value).to.equal('')
|
||||
expect(wrapper.emitted().input).to.equal(undefined)
|
||||
})
|
||||
|
||||
it('changes value by typing', async () => {
|
||||
const wrapper = shallowMount(DelimiterSelector, {
|
||||
propsData: { value: ',' }
|
||||
})
|
||||
|
||||
await wrapper.find('input').setValue(';')
|
||||
expect(wrapper.emitted().input).to.have.lengthOf(1)
|
||||
expect(wrapper.emitted().input[0]).to.eql([';'])
|
||||
})
|
||||
|
||||
it('changes value by selection from the list', async () => {
|
||||
const wrapper = mount(DelimiterSelector, {
|
||||
propsData: { value: '|' }
|
||||
})
|
||||
|
||||
await wrapper.findComponent({ name: 'drop-down-chevron' }).trigger('click')
|
||||
expect(wrapper.find('.options').isVisible()).to.equal(true)
|
||||
await wrapper.find('.option').trigger('click')
|
||||
expect(wrapper.find('.options').isVisible()).to.equal(false)
|
||||
expect(wrapper.emitted().input).to.have.lengthOf(1)
|
||||
expect(wrapper.emitted().input[0]).to.eql([','])
|
||||
})
|
||||
|
||||
it("doesn't change value when becomes empty", async () => {
|
||||
const wrapper = mount(DelimiterSelector, {
|
||||
propsData: { value: '|' }
|
||||
})
|
||||
|
||||
await wrapper.find('input').setValue('')
|
||||
expect(wrapper.emitted().input).to.equal(undefined)
|
||||
})
|
||||
|
||||
it('set focus in input when click on character name', async () => {
|
||||
const place = document.createElement('div')
|
||||
document.body.appendChild(place)
|
||||
|
||||
const wrapper = mount(DelimiterSelector, {
|
||||
attachTo: place,
|
||||
propsData: { value: '|' }
|
||||
})
|
||||
|
||||
await wrapper.find('.name').trigger('click')
|
||||
expect(wrapper.find('input').element).to.equal(document.activeElement)
|
||||
place.remove()
|
||||
wrapper.destroy()
|
||||
})
|
||||
|
||||
it('disabled', async () => {
|
||||
const wrapper = mount(DelimiterSelector, {
|
||||
propsData: { value: '|', disabled: true }
|
||||
})
|
||||
|
||||
await wrapper.findComponent({ name: 'clear-icon' }).trigger('click')
|
||||
|
||||
expect(wrapper.find('input').element.value).to.equal('|')
|
||||
expect(wrapper.emitted().input).to.equal(undefined)
|
||||
|
||||
await wrapper.findComponent({ name: 'drop-down-chevron' }).trigger('click')
|
||||
expect(wrapper.find('.options').isVisible()).to.equal(false)
|
||||
})
|
||||
|
||||
it('has filled class when input is not empty', async () => {
|
||||
const wrapper = shallowMount(DelimiterSelector, {
|
||||
propsData: { value: ',' }
|
||||
})
|
||||
await wrapper.vm.$nextTick()
|
||||
expect(wrapper.find('input').classes()).to.include('filled')
|
||||
await wrapper.find('input').setValue('')
|
||||
expect(wrapper.find('input').classes()).to.not.include('filled')
|
||||
await wrapper.find('input').setValue(';')
|
||||
expect(wrapper.find('input').classes()).to.include('filled')
|
||||
})
|
||||
})
|
||||
115
tests/components/DbUploader/csv.spec.js
Normal file
@@ -0,0 +1,115 @@
|
||||
import { expect } from 'chai'
|
||||
import sinon from 'sinon'
|
||||
import csv from '@/components/DbUploader/csv'
|
||||
import Papa from 'papaparse'
|
||||
|
||||
describe('csv.js', () => {
|
||||
afterEach(() => {
|
||||
sinon.restore()
|
||||
})
|
||||
|
||||
it('getResult with fields', () => {
|
||||
const source = {
|
||||
data: [
|
||||
{ id: 1, name: 'foo' },
|
||||
{ id: 2, name: 'bar' }
|
||||
],
|
||||
meta: {
|
||||
fields: ['id', 'name ']
|
||||
}
|
||||
}
|
||||
expect(csv.getResult(source)).to.eql({
|
||||
columns: ['id', 'name'],
|
||||
values: [
|
||||
[1, 'foo'],
|
||||
[2, 'bar']
|
||||
]
|
||||
})
|
||||
})
|
||||
|
||||
it('getResult without fields', () => {
|
||||
const source = {
|
||||
data: [
|
||||
[1, 'foo'],
|
||||
[2, 'bar']
|
||||
],
|
||||
meta: {}
|
||||
}
|
||||
expect(csv.getResult(source)).to.eql({
|
||||
columns: ['col1', 'col2'],
|
||||
values: [
|
||||
[1, 'foo'],
|
||||
[2, 'bar']
|
||||
]
|
||||
})
|
||||
})
|
||||
|
||||
it('parse resolves', async () => {
|
||||
sinon.stub(Papa, 'parse').callsFake((file, config) => {
|
||||
config.complete({
|
||||
data: [
|
||||
[1, 'foo'],
|
||||
[2, 'bar']
|
||||
],
|
||||
errors: [
|
||||
{
|
||||
type: 'Quotes',
|
||||
code: 'MissingQuotes',
|
||||
message: 'Quote is missed',
|
||||
row: 0
|
||||
},
|
||||
{
|
||||
type: 'Delimiter',
|
||||
code: 'UndetectableDelimiter',
|
||||
message: 'Comma was used as a standart delimiter',
|
||||
row: 0
|
||||
}
|
||||
],
|
||||
meta: {
|
||||
delimiter: ',',
|
||||
linebreak: '\n',
|
||||
aborted: false,
|
||||
truncated: true
|
||||
}
|
||||
})
|
||||
})
|
||||
const file = {}
|
||||
const result = await csv.parse(file)
|
||||
expect(result).to.eql({
|
||||
data: {
|
||||
columns: ['col1', 'col2'],
|
||||
values: [
|
||||
[1, 'foo'],
|
||||
[2, 'bar']
|
||||
]
|
||||
},
|
||||
delimiter: ',',
|
||||
hasErrors: true,
|
||||
messages: [
|
||||
{
|
||||
code: 'MissingQuotes',
|
||||
message: 'Quote is missed',
|
||||
row: 0,
|
||||
type: 'error',
|
||||
hint: 'Edit your CSV so that the field has a closing quote char.'
|
||||
},
|
||||
{
|
||||
code: 'UndetectableDelimiter',
|
||||
message: 'Comma was used as a standart delimiter',
|
||||
row: 0,
|
||||
type: 'info',
|
||||
hint: undefined
|
||||
}
|
||||
]
|
||||
})
|
||||
})
|
||||
|
||||
it('parse rejects', async () => {
|
||||
const err = new Error('something went wrong')
|
||||
sinon.stub(Papa, 'parse').callsFake((file, config) => {
|
||||
config.error(err)
|
||||
})
|
||||
const file = {}
|
||||
await expect(csv.parse(file)).to.be.rejectedWith(err)
|
||||
})
|
||||
})
|
||||
24
tests/components/LoadingIndicator.spec.js
Normal file
@@ -0,0 +1,24 @@
|
||||
import { expect } from 'chai'
|
||||
import { shallowMount } from '@vue/test-utils'
|
||||
import LoadingIndicator from '@/components/LoadingIndicator'
|
||||
|
||||
describe('LoadingIndicator.vue', () => {
|
||||
it('Calculates animation class', async () => {
|
||||
const wrapper = shallowMount(LoadingIndicator, {
|
||||
propsData: { progress: 0 }
|
||||
})
|
||||
expect(wrapper.find('svg').classes()).to.contain('progress')
|
||||
await wrapper.setProps({ progress: undefined })
|
||||
expect(wrapper.find('svg').classes()).to.not.contain('progress')
|
||||
expect(wrapper.find('svg').classes()).to.contain('loading')
|
||||
})
|
||||
|
||||
it('Calculates arc', async () => {
|
||||
const wrapper = shallowMount(LoadingIndicator, {
|
||||
propsData: { progress: 50 }
|
||||
})
|
||||
// The lendth of circle in the component is 50.24. If progress is 50% then resulting arc
|
||||
// should be 25.12
|
||||
expect(wrapper.find('.loader-svg.front').element.style.strokeDasharray).to.equal('25.12px, 25.12px')
|
||||
})
|
||||
})
|
||||
82
tests/components/Logs.spec.js
Normal file
@@ -0,0 +1,82 @@
|
||||
import { expect } from 'chai'
|
||||
import { shallowMount } from '@vue/test-utils'
|
||||
import Logs from '@/components/Logs'
|
||||
|
||||
let place
|
||||
describe('Logs.vue', () => {
|
||||
beforeEach(() => {
|
||||
place = document.createElement('div')
|
||||
document.body.appendChild(place)
|
||||
})
|
||||
afterEach(() => {
|
||||
place.remove()
|
||||
})
|
||||
|
||||
it('Scrolled to bottom on mounted', async () => {
|
||||
const messages = [
|
||||
{ type: 'error', message: 'msg 1' },
|
||||
{ type: 'error', message: 'msg 2' },
|
||||
{ type: 'error', message: 'msg 3' },
|
||||
{ type: 'error', message: 'msg 4' }
|
||||
]
|
||||
|
||||
const containerHeight = 160
|
||||
const borderWidth = 1
|
||||
const viewHeight = containerHeight - 2 * borderWidth
|
||||
const wrapper = shallowMount(Logs, {
|
||||
attachTo: place,
|
||||
propsData: { messages, style: `height: ${containerHeight}px` }
|
||||
})
|
||||
|
||||
await wrapper.vm.$nextTick()
|
||||
const height = wrapper.find('.logs-container').element.scrollHeight
|
||||
expect(wrapper.find('.logs-container').element.scrollTop)
|
||||
.to.equal(height - viewHeight)
|
||||
wrapper.destroy()
|
||||
})
|
||||
|
||||
it('Scrolled to bottom when a message added', async () => {
|
||||
const messages = [
|
||||
{ type: 'error', message: 'msg 1' },
|
||||
{ type: 'error', message: 'msg 2' },
|
||||
{ type: 'error', message: 'msg 3' },
|
||||
{ type: 'error', message: 'msg 4' }
|
||||
]
|
||||
|
||||
const containerHeight = 160
|
||||
const borderWidth = 1
|
||||
const viewHeight = containerHeight - 2 * borderWidth
|
||||
const wrapper = shallowMount(Logs, {
|
||||
attachTo: place,
|
||||
propsData: { messages, style: `height: ${containerHeight}px` }
|
||||
})
|
||||
|
||||
await wrapper.vm.$nextTick()
|
||||
messages.push({ type: 'error', message: 'msg 5' })
|
||||
|
||||
await wrapper.vm.$nextTick()
|
||||
const height = wrapper.find('.logs-container').element.scrollHeight
|
||||
expect(wrapper.find('.logs-container').element.scrollTop)
|
||||
.to.equal(height - viewHeight)
|
||||
wrapper.destroy()
|
||||
})
|
||||
|
||||
it('Serializes messages', async () => {
|
||||
const messages = [
|
||||
{ type: 'error', message: 'msg 1.', row: 0, hint: 'Try again later.' },
|
||||
{ type: 'error', message: 'msg 2!', row: 2, hint: undefined },
|
||||
{ type: 'error', message: 'msg 3?', hint: 'Be happy!' },
|
||||
{ type: 'error', message: 'msg 4' }
|
||||
]
|
||||
|
||||
const wrapper = shallowMount(Logs, {
|
||||
propsData: { messages }
|
||||
})
|
||||
|
||||
const logs = wrapper.findAll('.msg')
|
||||
expect(logs.at(0).text()).to.equal('Error in row 0. msg 1. Try again later.')
|
||||
expect(logs.at(1).text()).to.equal('Error in row 2. msg 2!')
|
||||
expect(logs.at(2).text()).to.equal('msg 3? Be happy!')
|
||||
expect(logs.at(3).text()).to.equal('msg 4.')
|
||||
})
|
||||
})
|
||||
220
tests/components/Splitpanes/Splitpanes.spec.js
Normal file
@@ -0,0 +1,220 @@
|
||||
import { expect } from 'chai'
|
||||
import { shallowMount } from '@vue/test-utils'
|
||||
import Splitpanes from '@/components/Splitpanes'
|
||||
|
||||
describe('Splitpanes.vue', () => {
|
||||
it('renders correctly - vertical', () => {
|
||||
// mount the component
|
||||
const wrapper = shallowMount(Splitpanes, {
|
||||
slots: {
|
||||
leftPane: '<div />',
|
||||
rightPane: '<div />'
|
||||
},
|
||||
propsData: {
|
||||
before: { size: 60, max: 100 },
|
||||
after: { size: 40, max: 100 }
|
||||
}
|
||||
})
|
||||
|
||||
expect(wrapper.findAll('.splitpanes-pane')).to.have.lengthOf(2)
|
||||
expect(wrapper.findAll('.splitpanes-pane').at(0).element.style.width).to.equal('60%')
|
||||
expect(wrapper.findAll('.splitpanes-pane').at(1).element.style.width).to.equal('40%')
|
||||
})
|
||||
|
||||
it('renders correctly - horizontal', () => {
|
||||
// mount the component
|
||||
const wrapper = shallowMount(Splitpanes, {
|
||||
slots: {
|
||||
leftPane: '<div />',
|
||||
rightPane: '<div />'
|
||||
},
|
||||
propsData: {
|
||||
before: { size: 60, max: 100 },
|
||||
after: { size: 40, max: 100 },
|
||||
horizontal: true
|
||||
}
|
||||
})
|
||||
|
||||
expect(wrapper.findAll('.splitpanes-pane')).to.have.lengthOf(2)
|
||||
expect(wrapper.findAll('.splitpanes-pane').at(0).element.style.height).to.equal('60%')
|
||||
expect(wrapper.findAll('.splitpanes-pane').at(1).element.style.height).to.equal('40%')
|
||||
})
|
||||
|
||||
it('toggles correctly', async () => {
|
||||
// mount the component
|
||||
const wrapper = shallowMount(Splitpanes, {
|
||||
slots: {
|
||||
leftPane: '<div />',
|
||||
rightPane: '<div />'
|
||||
},
|
||||
propsData: {
|
||||
before: { size: 60, max: 100 },
|
||||
after: { size: 40, max: 100 }
|
||||
}
|
||||
})
|
||||
|
||||
await wrapper.find('.toggle-btn').trigger('click')
|
||||
expect(wrapper.findAll('.splitpanes-pane').at(0).element.style.width).to.equal('0%')
|
||||
expect(wrapper.findAll('.splitpanes-pane').at(1).element.style.width).to.equal('100%')
|
||||
|
||||
await wrapper.find('.toggle-btn').trigger('click')
|
||||
expect(wrapper.findAll('.splitpanes-pane').at(0).element.style.width).to.equal('60%')
|
||||
expect(wrapper.findAll('.splitpanes-pane').at(1).element.style.width).to.equal('40%')
|
||||
|
||||
await wrapper.findAll('.toggle-btn').at(1).trigger('click')
|
||||
expect(wrapper.findAll('.splitpanes-pane').at(0).element.style.width).to.equal('100%')
|
||||
expect(wrapper.findAll('.splitpanes-pane').at(1).element.style.width).to.equal('0%')
|
||||
|
||||
await wrapper.find('.toggle-btn').trigger('click')
|
||||
expect(wrapper.findAll('.splitpanes-pane').at(0).element.style.width).to.equal('60%')
|
||||
expect(wrapper.findAll('.splitpanes-pane').at(1).element.style.width).to.equal('40%')
|
||||
})
|
||||
|
||||
it('drag - vertical', async () => {
|
||||
const root = document.createElement('div')
|
||||
const place = document.createElement('div')
|
||||
root.style.width = '600px'
|
||||
root.style.height = '500px'
|
||||
root.appendChild(place)
|
||||
document.body.appendChild(root)
|
||||
|
||||
// mount the component
|
||||
const wrapper = shallowMount(Splitpanes, {
|
||||
attachTo: place,
|
||||
slots: {
|
||||
leftPane: '<div />',
|
||||
rightPane: '<div />'
|
||||
},
|
||||
propsData: {
|
||||
before: { size: 60, max: 100 },
|
||||
after: { size: 40, max: 100 }
|
||||
}
|
||||
})
|
||||
|
||||
await wrapper.find('.splitpanes-splitter').trigger('mousedown')
|
||||
document.dispatchEvent(new MouseEvent('mousemove', {
|
||||
clientX: 300,
|
||||
clientY: 80
|
||||
}))
|
||||
document.dispatchEvent(new MouseEvent('mouseup'))
|
||||
await wrapper.vm.$nextTick()
|
||||
expect(wrapper.findAll('.splitpanes-pane').at(0).element.style.width).to.equal('50%')
|
||||
wrapper.destroy()
|
||||
root.remove()
|
||||
})
|
||||
|
||||
it('drag - horizontal', async () => {
|
||||
const root = document.createElement('div')
|
||||
const place = document.createElement('div')
|
||||
root.style.width = '600px'
|
||||
root.style.height = '500px'
|
||||
root.appendChild(place)
|
||||
document.body.appendChild(root)
|
||||
|
||||
// mount the component
|
||||
const wrapper = shallowMount(Splitpanes, {
|
||||
attachTo: place,
|
||||
slots: {
|
||||
leftPane: '<div />',
|
||||
rightPane: '<div />'
|
||||
},
|
||||
propsData: {
|
||||
before: { size: 10, max: 100 },
|
||||
after: { size: 90, max: 100 },
|
||||
horizontal: true
|
||||
}
|
||||
})
|
||||
|
||||
await wrapper.find('.splitpanes-splitter').trigger('mousedown')
|
||||
document.dispatchEvent(new MouseEvent('mousemove', {
|
||||
clientX: 10,
|
||||
clientY: 250
|
||||
}))
|
||||
document.dispatchEvent(new MouseEvent('mouseup'))
|
||||
await wrapper.vm.$nextTick()
|
||||
expect(wrapper.findAll('.splitpanes-pane').at(0).element.style.height).to.equal('50%')
|
||||
wrapper.destroy()
|
||||
root.remove()
|
||||
})
|
||||
|
||||
it('drag - horizontal - touch', async () => {
|
||||
const root = document.createElement('div')
|
||||
const place = document.createElement('div')
|
||||
root.style.width = '600px'
|
||||
root.style.height = '500px'
|
||||
root.appendChild(place)
|
||||
document.body.appendChild(root)
|
||||
|
||||
// mount the component
|
||||
const wrapper = shallowMount(Splitpanes, {
|
||||
attachTo: place,
|
||||
slots: {
|
||||
leftPane: '<div />',
|
||||
rightPane: '<div />'
|
||||
},
|
||||
propsData: {
|
||||
before: { size: 10, max: 100 },
|
||||
after: { size: 90, max: 100 },
|
||||
horizontal: true
|
||||
}
|
||||
})
|
||||
|
||||
window.ontouchstart = null
|
||||
await wrapper.find('.splitpanes-splitter').trigger('touchstart')
|
||||
const event = new TouchEvent('touchmove')
|
||||
Object.defineProperty(event, 'touches', {
|
||||
value: [{
|
||||
clientX: 10,
|
||||
clientY: 250
|
||||
}],
|
||||
writable: true
|
||||
})
|
||||
document.dispatchEvent(event)
|
||||
document.dispatchEvent(new MouseEvent('touchend'))
|
||||
await wrapper.vm.$nextTick()
|
||||
expect(wrapper.findAll('.splitpanes-pane').at(0).element.style.height).to.equal('50%')
|
||||
wrapper.destroy()
|
||||
root.remove()
|
||||
delete window.ontouchstart
|
||||
})
|
||||
|
||||
it('drag - vertical - touch', async () => {
|
||||
const root = document.createElement('div')
|
||||
const place = document.createElement('div')
|
||||
root.style.width = '600px'
|
||||
root.style.height = '500px'
|
||||
root.appendChild(place)
|
||||
document.body.appendChild(root)
|
||||
|
||||
// mount the component
|
||||
const wrapper = shallowMount(Splitpanes, {
|
||||
attachTo: place,
|
||||
slots: {
|
||||
leftPane: '<div />',
|
||||
rightPane: '<div />'
|
||||
},
|
||||
propsData: {
|
||||
before: { size: 60, max: 100 },
|
||||
after: { size: 40, max: 100 }
|
||||
}
|
||||
})
|
||||
window.ontouchstart = null
|
||||
|
||||
await wrapper.find('.splitpanes-splitter').trigger('touchstart')
|
||||
const event = new TouchEvent('touchmove')
|
||||
Object.defineProperty(event, 'touches', {
|
||||
value: [{
|
||||
clientX: 300,
|
||||
clientY: 80
|
||||
}],
|
||||
writable: true
|
||||
})
|
||||
document.dispatchEvent(event)
|
||||
document.dispatchEvent(new MouseEvent('touchend'))
|
||||
await wrapper.vm.$nextTick()
|
||||
expect(wrapper.findAll('.splitpanes-pane').at(0).element.style.width).to.equal('50%')
|
||||
wrapper.destroy()
|
||||
root.remove()
|
||||
delete window.ontouchstart
|
||||
})
|
||||
})
|
||||
108
tests/components/Splitpanes/splitter.spec.js
Normal file
@@ -0,0 +1,108 @@
|
||||
import { expect } from 'chai'
|
||||
import sinon from 'sinon'
|
||||
import splitter from '@/components/Splitpanes/splitter'
|
||||
|
||||
describe('splitter.js', () => {
|
||||
afterEach(() => {
|
||||
sinon.restore()
|
||||
})
|
||||
|
||||
it('getCurrentMouseDrag', () => {
|
||||
const container = document.createElement('div')
|
||||
container.style.width = '100px'
|
||||
container.style.height = '100px'
|
||||
container.style.position = 'fixed'
|
||||
container.style.top = '10px'
|
||||
container.style.left = '20px'
|
||||
|
||||
document.body.appendChild(container)
|
||||
|
||||
const event = new MouseEvent('mousemove', {
|
||||
clientX: 70,
|
||||
clientY: 80
|
||||
})
|
||||
|
||||
const mouseDrag = splitter.getCurrentMouseDrag(event, container)
|
||||
expect(mouseDrag.x).to.equal(50)
|
||||
expect(mouseDrag.y).to.equal(70)
|
||||
})
|
||||
|
||||
it('getCurrentDragPercentage - horisontal', () => {
|
||||
sinon.stub(splitter, 'getCurrentMouseDrag').returns({ x: 50, y: 70 })
|
||||
|
||||
const event = {}
|
||||
const isHorisontal = true
|
||||
const container = document.createElement('div')
|
||||
container.style.width = '200px'
|
||||
container.style.height = '140px'
|
||||
|
||||
document.body.appendChild(container)
|
||||
|
||||
const dragPercentage = splitter.getCurrentDragPercentage(event, container, isHorisontal)
|
||||
expect(dragPercentage).to.equal(50)
|
||||
})
|
||||
|
||||
it('getCurrentDragPercentage - vertical', () => {
|
||||
sinon.stub(splitter, 'getCurrentMouseDrag').returns({ x: 50, y: 70 })
|
||||
|
||||
const event = {}
|
||||
const isHorisontal = false
|
||||
const container = document.createElement('div')
|
||||
container.style.width = '200px'
|
||||
container.style.height = '140px'
|
||||
|
||||
document.body.appendChild(container)
|
||||
|
||||
const dragPercentage = splitter.getCurrentDragPercentage(event, container, isHorisontal)
|
||||
expect(dragPercentage).to.equal(25)
|
||||
})
|
||||
|
||||
it('calculateOffset', () => {
|
||||
sinon.stub(splitter, 'getCurrentDragPercentage').returns(25)
|
||||
|
||||
const event = {}
|
||||
const container = {}
|
||||
|
||||
const splitterInfo = {
|
||||
container,
|
||||
paneBeforeMax: 70,
|
||||
paneAfterMax: 80,
|
||||
isHorisontal: true
|
||||
}
|
||||
const offset = splitter.calculateOffset(event, splitterInfo)
|
||||
|
||||
expect(offset).to.equal(25)
|
||||
})
|
||||
|
||||
it('calculateOffset prevents dragging beyond paneBefore max', () => {
|
||||
sinon.stub(splitter, 'getCurrentDragPercentage').returns(75)
|
||||
|
||||
const event = {}
|
||||
const container = {}
|
||||
const splitterInfo = {
|
||||
container,
|
||||
paneBeforeMax: 70,
|
||||
paneAfterMax: 80,
|
||||
isHorisontal: true
|
||||
}
|
||||
const offset = splitter.calculateOffset(event, splitterInfo)
|
||||
|
||||
expect(offset).to.equal(70)
|
||||
})
|
||||
|
||||
it('calculateOffset prevents dragging beyond paneAfter max', () => {
|
||||
sinon.stub(splitter, 'getCurrentDragPercentage').returns(10)
|
||||
|
||||
const event = {}
|
||||
const container = {}
|
||||
const splitterInfo = {
|
||||
container,
|
||||
paneBeforeMax: 70,
|
||||
paneAfterMax: 80,
|
||||
isHorisontal: true
|
||||
}
|
||||
const offset = splitter.calculateOffset(event, splitterInfo)
|
||||
|
||||
expect(offset).to.equal(20)
|
||||
})
|
||||
})
|
||||
37
tests/components/SqlTable/Pager.spec.js
Normal file
@@ -0,0 +1,37 @@
|
||||
import { expect } from 'chai'
|
||||
import sinon from 'sinon'
|
||||
import { mount } from '@vue/test-utils'
|
||||
import Pager from '@/components/SqlTable/Pager'
|
||||
|
||||
describe('Pager.vue', () => {
|
||||
afterEach(() => {
|
||||
sinon.restore()
|
||||
})
|
||||
|
||||
it('emits input event with a page', async () => {
|
||||
const wrapper = mount(Pager, {
|
||||
propsData: {
|
||||
pageCount: 5
|
||||
}
|
||||
})
|
||||
|
||||
// click on 'next page' link
|
||||
await wrapper.find('.paginator-next').trigger('click')
|
||||
expect(wrapper.emitted('input')[0]).to.eql([2])
|
||||
|
||||
// click on the link to page 3 (it has index 2)
|
||||
await wrapper.findAll('.paginator-page-link').at(2).trigger('click')
|
||||
expect(wrapper.emitted('input')[1]).to.eql([3])
|
||||
})
|
||||
|
||||
it('changes the page when value is changed', async () => {
|
||||
const wrapper = mount(Pager, {
|
||||
propsData: {
|
||||
pageCount: 5
|
||||
}
|
||||
})
|
||||
|
||||
await wrapper.setProps({ value: 5 })
|
||||
expect(wrapper.emitted('input')[0]).to.eql([5])
|
||||
})
|
||||
})
|
||||
171
tests/lib/database/_sql.spec.js
Normal file
@@ -0,0 +1,171 @@
|
||||
import chai from 'chai'
|
||||
import sinon from 'sinon'
|
||||
import chaiAsPromised from 'chai-as-promised'
|
||||
import initSqlJs from 'sql.js'
|
||||
import Sql from '@/lib/database/_sql'
|
||||
chai.use(chaiAsPromised)
|
||||
const expect = chai.expect
|
||||
chai.should()
|
||||
|
||||
const getSQL = initSqlJs()
|
||||
|
||||
describe('_sql.js', () => {
|
||||
afterEach(() => {
|
||||
sinon.restore()
|
||||
})
|
||||
|
||||
it('returns a query result', async () => {
|
||||
const SQL = await getSQL
|
||||
const tempDb = new SQL.Database()
|
||||
tempDb.run(`
|
||||
CREATE TABLE test (
|
||||
id integer,
|
||||
name varchar(100),
|
||||
faculty varchar(100)
|
||||
);
|
||||
INSERT INTO test (id, name, faculty)
|
||||
VALUES
|
||||
( 1, 'Harry Potter', 'Griffindor'),
|
||||
( 2, 'Draco Malfoy', 'Slytherin');
|
||||
`)
|
||||
|
||||
const data = tempDb.export()
|
||||
const sql = await Sql.build()
|
||||
sql.open(data)
|
||||
const result = sql.exec('SELECT * from test')
|
||||
expect(result).to.have.lengthOf(1)
|
||||
expect(result[0].columns).to.eql(['id', 'name', 'faculty'])
|
||||
expect(result[0].values).to.have.lengthOf(2)
|
||||
expect(result[0].values[0]).to.eql([1, 'Harry Potter', 'Griffindor'])
|
||||
expect(result[0].values[1]).to.eql([2, 'Draco Malfoy', 'Slytherin'])
|
||||
})
|
||||
|
||||
it('throws an error if query is empty', async () => {
|
||||
const SQL = await getSQL
|
||||
const tempDb = new SQL.Database()
|
||||
tempDb.run(`
|
||||
CREATE TABLE test (
|
||||
id integer,
|
||||
name varchar(100),
|
||||
faculty varchar(100)
|
||||
);
|
||||
INSERT INTO test (id, name, faculty)
|
||||
VALUES
|
||||
( 1, 'Harry Potter', 'Griffindor'),
|
||||
( 2, 'Draco Malfoy', 'Slytherin');
|
||||
`)
|
||||
|
||||
const data = tempDb.export()
|
||||
const sql = await Sql.build()
|
||||
sql.open(data)
|
||||
expect(() => { sql.exec() }).to.throw('exec: Missing query string')
|
||||
})
|
||||
|
||||
it('imports', async () => {
|
||||
const data = {
|
||||
columns: ['id', 'name'],
|
||||
values: [
|
||||
[1, 'Harry Potter'],
|
||||
[2, 'Draco Malfoy'],
|
||||
[3, 'Hermione Granger'],
|
||||
[4, 'Ron Weasley']
|
||||
]
|
||||
}
|
||||
const progressCallback = sinon.stub()
|
||||
const progressCounterId = 1
|
||||
const sql = await Sql.build()
|
||||
sql.import(data.columns, data.values, progressCounterId, progressCallback, 2)
|
||||
const result = sql.exec('SELECT * from csv_import')
|
||||
expect(result).to.have.lengthOf(1)
|
||||
expect(result[0].columns).to.eql(['id', 'name'])
|
||||
expect(result[0].values).to.have.lengthOf(4)
|
||||
expect(result[0].values[0]).to.eql([1, 'Harry Potter'])
|
||||
expect(result[0].values[1]).to.eql([2, 'Draco Malfoy'])
|
||||
expect(result[0].values[2]).to.eql([3, 'Hermione Granger'])
|
||||
expect(result[0].values[3]).to.eql([4, 'Ron Weasley'])
|
||||
|
||||
expect(progressCallback.calledThrice).to.equal(true)
|
||||
expect(progressCallback.getCall(0).args[0]).to.eql({ progress: 0, id: 1 })
|
||||
expect(progressCallback.getCall(1).args[0]).to.eql({ progress: 50, id: 1 })
|
||||
expect(progressCallback.getCall(2).args[0]).to.eql({ progress: 100, id: 1 })
|
||||
})
|
||||
|
||||
it('exports', async () => {
|
||||
const sql = await Sql.build()
|
||||
sql.exec(`
|
||||
CREATE TABLE test (
|
||||
id integer,
|
||||
name varchar(100),
|
||||
faculty varchar(100)
|
||||
);
|
||||
INSERT INTO test (id, name, faculty)
|
||||
VALUES
|
||||
( 1, 'Harry Potter', 'Griffindor'),
|
||||
( 2, 'Draco Malfoy', 'Slytherin');
|
||||
`)
|
||||
const data = sql.export()
|
||||
const anotherSql = await Sql.build()
|
||||
anotherSql.open(data)
|
||||
const result = anotherSql.exec('SELECT * from test')
|
||||
expect(result).to.have.lengthOf(1)
|
||||
expect(result[0].columns).to.eql(['id', 'name', 'faculty'])
|
||||
expect(result[0].values).to.have.lengthOf(2)
|
||||
expect(result[0].values[0]).to.eql([1, 'Harry Potter', 'Griffindor'])
|
||||
expect(result[0].values[1]).to.eql([2, 'Draco Malfoy', 'Slytherin'])
|
||||
})
|
||||
|
||||
it('closes', async () => {
|
||||
const sql = await Sql.build()
|
||||
|
||||
// nothing breaks if close empty db
|
||||
sql.close()
|
||||
|
||||
sql.exec(`
|
||||
CREATE TABLE test (
|
||||
id integer,
|
||||
name varchar(100)
|
||||
);
|
||||
INSERT INTO test (id, name)
|
||||
VALUES
|
||||
( 1, 'Harry Potter'),
|
||||
( 2, 'Draco Malfoy');
|
||||
`)
|
||||
expect(sql.db.db).to.not.equal(null)
|
||||
sql.close()
|
||||
expect(sql.db.db).to.equal(null)
|
||||
})
|
||||
|
||||
it('overwrites', async () => {
|
||||
const sql = await Sql.build()
|
||||
sql.exec(`
|
||||
CREATE TABLE test (
|
||||
id integer,
|
||||
name varchar(100)
|
||||
);
|
||||
INSERT INTO test (id, name)
|
||||
VALUES
|
||||
( 1, 'foo'),
|
||||
( 2, 'bar');
|
||||
`)
|
||||
|
||||
let result = sql.exec('SELECT * from test')
|
||||
expect(result[0].values).to.have.lengthOf(2)
|
||||
|
||||
const data = {
|
||||
columns: ['id', 'name'],
|
||||
values: [
|
||||
[1, 'Harry Potter'],
|
||||
[2, 'Draco Malfoy'],
|
||||
[3, 'Hermione Granger'],
|
||||
[4, 'Ron Weasley']
|
||||
]
|
||||
}
|
||||
// rewrite the database by import
|
||||
sql.import(data.columns, data.values, 1, sinon.stub(), 2)
|
||||
result = sql.exec('SELECT * from csv_import')
|
||||
expect(result[0].values).to.have.lengthOf(4)
|
||||
|
||||
// test table oesn't exists anymore: the db was overwritten
|
||||
expect(() => { sql.exec('SELECT * from test') }).to.throw('no such table: test')
|
||||
})
|
||||
})
|
||||
34
tests/lib/database/_statements.spec.js
Normal file
@@ -0,0 +1,34 @@
|
||||
import { expect } from 'chai'
|
||||
import dbUtils from '@/lib/database/_statements'
|
||||
|
||||
describe('_statements.js', () => {
|
||||
it('generateChunks', () => {
|
||||
const arr = ['1', '2', '3', '4', '5']
|
||||
const size = 2
|
||||
const chunks = dbUtils.generateChunks(arr, size)
|
||||
const output = []
|
||||
for (const chunk of chunks) {
|
||||
output.push(chunk)
|
||||
}
|
||||
expect(output[0]).to.eql(['1', '2'])
|
||||
expect(output[1]).to.eql(['3', '4'])
|
||||
expect(output[2]).to.eql(['5'])
|
||||
})
|
||||
|
||||
it('getInsertStmt', () => {
|
||||
const columns = ['id', 'name']
|
||||
expect(dbUtils.getInsertStmt(columns))
|
||||
.to.equal('INSERT INTO csv_import ("id", "name") VALUES (?, ?);')
|
||||
})
|
||||
|
||||
it('getCreateStatement', () => {
|
||||
const columns = ['id', 'name', 'isAdmin', 'startDate']
|
||||
const values = [
|
||||
[1, 'foo', true, new Date()],
|
||||
[2, 'bar', false, new Date()]
|
||||
]
|
||||
expect(dbUtils.getCreateStatement(columns, values)).to.equal(
|
||||
'CREATE table csv_import("id" REAL, "name" TEXT, "isAdmin" INTEGER, "startDate" TEXT);'
|
||||
)
|
||||
})
|
||||
})
|
||||
245
tests/lib/database/database.spec.js
Normal file
@@ -0,0 +1,245 @@
|
||||
import chai from 'chai'
|
||||
import sinon from 'sinon'
|
||||
import chaiAsPromised from 'chai-as-promised'
|
||||
import initSqlJs from 'sql.js'
|
||||
import database from '@/lib/database'
|
||||
import fu from '@/lib/utils/fileIo'
|
||||
|
||||
chai.use(chaiAsPromised)
|
||||
const expect = chai.expect
|
||||
chai.should()
|
||||
|
||||
const getSQL = initSqlJs()
|
||||
let db
|
||||
|
||||
describe('database.js', () => {
|
||||
beforeEach(() => {
|
||||
db = database.getNewDatabase()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
db.shutDown()
|
||||
sinon.restore()
|
||||
})
|
||||
|
||||
it('creates schema', async () => {
|
||||
const SQL = await getSQL
|
||||
const tempDb = new SQL.Database()
|
||||
tempDb.run(`CREATE TABLE test (
|
||||
col1,
|
||||
col2 integer,
|
||||
col3 decimal(5,2),
|
||||
col4 varchar(30)
|
||||
)`)
|
||||
|
||||
const data = tempDb.export()
|
||||
const buffer = new Blob([data])
|
||||
buffer.name = 'foo.sqlite'
|
||||
|
||||
const { schema, dbName } = await db.loadDb(buffer)
|
||||
expect(dbName).to.equal('foo')
|
||||
expect(schema).to.have.lengthOf(1)
|
||||
expect(schema[0].name).to.equal('test')
|
||||
expect(schema[0].columns[0].name).to.equal('col1')
|
||||
expect(schema[0].columns[0].type).to.equal('N/A')
|
||||
expect(schema[0].columns[1].name).to.equal('col2')
|
||||
expect(schema[0].columns[1].type).to.equal('integer')
|
||||
expect(schema[0].columns[2].name).to.equal('col3')
|
||||
expect(schema[0].columns[2].type).to.equal('decimal(5, 2)')
|
||||
expect(schema[0].columns[3].name).to.equal('col4')
|
||||
expect(schema[0].columns[3].type).to.equal('varchar(30)')
|
||||
})
|
||||
|
||||
it('creates schema with virtual table', async () => {
|
||||
const SQL = await getSQL
|
||||
const tempDb = new SQL.Database()
|
||||
tempDb.run(`
|
||||
CREATE VIRTUAL TABLE test_virtual USING fts4(
|
||||
col1, col2,
|
||||
notindexed=col1, notindexed=col2,
|
||||
tokenize=unicode61 "tokenchars=.+#")
|
||||
`)
|
||||
|
||||
const data = tempDb.export()
|
||||
const buffer = new Blob([data])
|
||||
buffer.name = 'foo.sqlite'
|
||||
|
||||
const { schema } = await db.loadDb(buffer)
|
||||
expect(schema[0].name).to.equal('test_virtual')
|
||||
expect(schema[0].columns[0].name).to.equal('col1')
|
||||
expect(schema[0].columns[0].type).to.equal('N/A')
|
||||
expect(schema[0].columns[1].name).to.equal('col2')
|
||||
expect(schema[0].columns[1].type).to.equal('N/A')
|
||||
})
|
||||
|
||||
it('loadDb throws errors', async () => {
|
||||
const SQL = await getSQL
|
||||
const tempDb = new SQL.Database()
|
||||
tempDb.run('CREATE TABLE test (col1, col2)')
|
||||
|
||||
const data = tempDb.export()
|
||||
const buffer = new Blob([data])
|
||||
buffer.name = 'foo.sqlite'
|
||||
|
||||
sinon.stub(db.pw, 'postMessage').resolves({ error: new Error('foo') })
|
||||
|
||||
await expect(db.loadDb(buffer)).to.be.rejectedWith('foo')
|
||||
})
|
||||
|
||||
it('returns the last query result', async () => {
|
||||
const SQL = await getSQL
|
||||
const tempDb = new SQL.Database()
|
||||
tempDb.run(`
|
||||
CREATE TABLE test (
|
||||
id integer,
|
||||
name varchar(100),
|
||||
faculty varchar(100)
|
||||
);
|
||||
INSERT INTO test (id, name, faculty)
|
||||
VALUES
|
||||
( 1, 'Harry Potter', 'Griffindor'),
|
||||
( 2, 'Draco Malfoy', 'Slytherin');
|
||||
`)
|
||||
|
||||
const data = tempDb.export()
|
||||
const buffer = new Blob([data])
|
||||
buffer.name = 'foo.sqlite'
|
||||
|
||||
await db.loadDb(buffer)
|
||||
const result = await db.execute('SELECT * from test limit 1; SELECT * from test;')
|
||||
expect(result.columns).to.have.lengthOf(3)
|
||||
expect(result.columns).to.eql(['id', 'name', 'faculty'])
|
||||
expect(result.values).to.have.lengthOf(2)
|
||||
expect(result.values[0]).to.eql([1, 'Harry Potter', 'Griffindor'])
|
||||
expect(result.values[1]).to.eql([2, 'Draco Malfoy', 'Slytherin'])
|
||||
})
|
||||
|
||||
it('returns an error', async () => {
|
||||
const SQL = await getSQL
|
||||
const tempDb = new SQL.Database()
|
||||
tempDb.run(`
|
||||
CREATE TABLE test (
|
||||
id integer,
|
||||
name varchar(100),
|
||||
faculty varchar(100)
|
||||
);
|
||||
INSERT INTO test (id, name, faculty)
|
||||
VALUES
|
||||
( 1, 'Harry Potter', 'Griffindor'),
|
||||
( 2, 'Draco Malfoy', 'Slytherin');
|
||||
`)
|
||||
|
||||
const data = tempDb.export()
|
||||
const buffer = new Blob([data])
|
||||
buffer.name = 'foo.sqlite'
|
||||
await db.loadDb(buffer)
|
||||
await expect(db.execute('SELECT * from foo')).to.be.rejectedWith(/^no such table: foo$/)
|
||||
})
|
||||
|
||||
it('creates db', async () => {
|
||||
const data = {
|
||||
columns: ['id', 'name', 'faculty'],
|
||||
values: [
|
||||
[1, 'Harry Potter', 'Griffindor'],
|
||||
[2, 'Draco Malfoy', 'Slytherin']
|
||||
]
|
||||
}
|
||||
const progressHandler = sinon.spy()
|
||||
const progressCounterId = db.createProgressCounter(progressHandler)
|
||||
const { dbName, schema } = await db.importDb('foo', data, progressCounterId)
|
||||
expect(dbName).to.equal('foo')
|
||||
expect(schema).to.have.lengthOf(1)
|
||||
expect(schema[0].name).to.equal('csv_import')
|
||||
expect(schema[0].columns).to.have.lengthOf(3)
|
||||
expect(schema[0].columns[0]).to.eql({ name: 'id', type: 'real' })
|
||||
expect(schema[0].columns[1]).to.eql({ name: 'name', type: 'text' })
|
||||
expect(schema[0].columns[2]).to.eql({ name: 'faculty', type: 'text' })
|
||||
|
||||
const result = await db.execute('SELECT * from csv_import')
|
||||
expect(result.columns).to.eql(data.columns)
|
||||
expect(result.values).to.eql(data.values)
|
||||
|
||||
expect(progressHandler.calledTwice).to.equal(true)
|
||||
expect(progressHandler.firstCall.calledWith(0)).to.equal(true)
|
||||
expect(progressHandler.secondCall.calledWith(100)).to.equal(true)
|
||||
})
|
||||
|
||||
it('importDb throws errors', async () => {
|
||||
const data = {
|
||||
columns: ['id', 'name'],
|
||||
values: [
|
||||
[1, 'Harry Potter', 'Griffindor'],
|
||||
[2, 'Draco Malfoy', 'Slytherin']
|
||||
]
|
||||
}
|
||||
const progressHandler = sinon.stub()
|
||||
const progressCounterId = db.createProgressCounter(progressHandler)
|
||||
await expect(db.importDb('foo', data, progressCounterId))
|
||||
.to.be.rejectedWith('column index out of range')
|
||||
})
|
||||
|
||||
it('progressCounters', () => {
|
||||
const firstHandler = sinon.stub()
|
||||
const firstId = db.createProgressCounter(firstHandler)
|
||||
db.worker.dispatchEvent(new MessageEvent('message', {
|
||||
data: {
|
||||
progress: 50,
|
||||
id: firstId
|
||||
}
|
||||
}))
|
||||
expect(firstHandler.calledOnceWith(50)).to.equal(true)
|
||||
|
||||
const secondHandler = sinon.stub()
|
||||
const secondId = db.createProgressCounter(secondHandler)
|
||||
db.worker.dispatchEvent(new MessageEvent('message', {
|
||||
data: {
|
||||
progress: 70,
|
||||
id: secondId
|
||||
}
|
||||
}))
|
||||
expect(firstId).to.not.equals(secondId)
|
||||
expect(secondHandler.calledOnceWith(70)).to.equal(true)
|
||||
|
||||
db.worker.dispatchEvent(new MessageEvent('message', {
|
||||
data: {
|
||||
progress: 80,
|
||||
id: firstId
|
||||
}
|
||||
}))
|
||||
expect(firstHandler.calledTwice).to.equal(true)
|
||||
expect(firstHandler.secondCall.calledWith(80)).to.equal(true)
|
||||
|
||||
db.deleteProgressCounter(firstId)
|
||||
expect(db.importProgresses[firstId]).to.equal(undefined)
|
||||
})
|
||||
|
||||
it('exports db', async () => {
|
||||
sinon.stub(fu, 'exportToFile').resolves()
|
||||
|
||||
// create db with table foo
|
||||
const stmt = `
|
||||
CREATE TABLE foo(id, name);
|
||||
INSERT INTO foo VALUES (1, 'Harry Potter')
|
||||
`
|
||||
let result = await db.execute(stmt)
|
||||
|
||||
// export db to a file
|
||||
await db.export('fooDb.sqlite')
|
||||
expect(fu.exportToFile.called).to.equal(true)
|
||||
|
||||
// get data from export
|
||||
const data = fu.exportToFile.getCall(0).args[0]
|
||||
const file = new Blob([data])
|
||||
file.name = 'fooDb.sqlite'
|
||||
|
||||
// loadDb from exported data
|
||||
const anotherDb = database.getNewDatabase()
|
||||
await anotherDb.loadDb(file)
|
||||
|
||||
// check that new db works and has the same table and data
|
||||
result = await anotherDb.execute('SELECT * from foo')
|
||||
expect(result.columns).to.eql(['id', 'name'])
|
||||
expect(result.values).to.have.lengthOf(1)
|
||||
expect(result.values[0]).to.eql([1, 'Harry Potter'])
|
||||
})
|
||||
})
|
||||
267
tests/lib/storedQueries.spec.js
Normal file
@@ -0,0 +1,267 @@
|
||||
import { expect } from 'chai'
|
||||
import sinon from 'sinon'
|
||||
import storedQueries from '@/lib/storedQueries'
|
||||
import fu from '@/lib/utils/fileIo'
|
||||
|
||||
describe('storedQueries.js', () => {
|
||||
beforeEach(() => {
|
||||
localStorage.removeItem('myQueries')
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
sinon.restore()
|
||||
})
|
||||
|
||||
it('getStoredQueries returns emplty array when storage is empty', () => {
|
||||
const queries = storedQueries.getStoredQueries()
|
||||
expect(queries).to.eql([])
|
||||
})
|
||||
|
||||
it('updateStorage and getStoredQueries', () => {
|
||||
const data = [
|
||||
{ id: 1 },
|
||||
{ id: 2 }
|
||||
]
|
||||
storedQueries.updateStorage(data)
|
||||
const queries = storedQueries.getStoredQueries()
|
||||
expect(queries).to.eql(data)
|
||||
})
|
||||
|
||||
it('duplicateQuery', () => {
|
||||
const now = new Date()
|
||||
const nowPlusMinute = new Date(now.getTime() + 60 * 1000)
|
||||
const base = {
|
||||
id: 1,
|
||||
name: 'foo',
|
||||
query: 'SELECT * from foo',
|
||||
chart: [],
|
||||
createdAt: new Date(2021, 0, 1),
|
||||
isPredefined: true
|
||||
}
|
||||
|
||||
const copy = storedQueries.duplicateQuery(base)
|
||||
expect(copy).to.have.property('id').which.not.equal(base.id)
|
||||
expect(copy).to.have.property('name').which.equal(base.name + ' Copy')
|
||||
expect(copy).to.have.property('query').which.equal(base.query)
|
||||
expect(copy).to.have.property('chart').which.eql(base.chart)
|
||||
expect(copy).to.have.property('createdAt').which.within(now, nowPlusMinute)
|
||||
expect(copy).to.not.have.property('isPredefined')
|
||||
})
|
||||
|
||||
it('isTabNeedName returns false when the query has a name and is not predefined', () => {
|
||||
const tab = {
|
||||
initName: 'foo'
|
||||
}
|
||||
expect(storedQueries.isTabNeedName(tab)).to.equal(false)
|
||||
})
|
||||
|
||||
it('isTabNeedName returns true when the query has no name and is not predefined', () => {
|
||||
const tab = {
|
||||
initName: null,
|
||||
tempName: 'Untitled'
|
||||
}
|
||||
expect(storedQueries.isTabNeedName(tab)).to.equal(true)
|
||||
})
|
||||
|
||||
it('isTabNeedName returns true when the qiery is predefined', () => {
|
||||
const tab = {
|
||||
initName: 'foo',
|
||||
isPredefined: true
|
||||
}
|
||||
|
||||
expect(storedQueries.isTabNeedName(tab)).to.equal(true)
|
||||
})
|
||||
|
||||
it('serialiseQueries', () => {
|
||||
const queryList = [
|
||||
{
|
||||
id: 1,
|
||||
name: 'foo',
|
||||
query: 'SELECT from foo',
|
||||
chart: [],
|
||||
createdAt: '2020-11-03T14:17:49.524Z',
|
||||
isPredefined: true
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
name: 'bar',
|
||||
query: 'SELECT from bar',
|
||||
chart: [],
|
||||
createdAt: '2020-12-03T14:17:49.524Z'
|
||||
}
|
||||
]
|
||||
|
||||
const str = storedQueries.serialiseQueries(queryList)
|
||||
const parsedJson = JSON.parse(str)
|
||||
|
||||
expect(parsedJson).to.have.lengthOf(2)
|
||||
expect(parsedJson[1]).to.eql(queryList[1])
|
||||
expect(parsedJson[0].id).to.equal(queryList[0].id)
|
||||
expect(parsedJson[0].name).to.equal(queryList[0].name)
|
||||
expect(parsedJson[0].query).to.equal(queryList[0].query)
|
||||
expect(parsedJson[0].chart).to.eql(queryList[0].chart)
|
||||
expect(parsedJson[0].createdAt).to.eql(queryList[0].createdAt)
|
||||
expect(parsedJson[0].chart).to.not.have.property('isPredefined')
|
||||
})
|
||||
|
||||
it('deserialiseQueries return array for one query', () => {
|
||||
const str = `
|
||||
{
|
||||
"id": 1,
|
||||
"name": "foo",
|
||||
"query": "select * from foo",
|
||||
"chart": [],
|
||||
"createdAt": "2020-11-03T14:17:49.524Z"
|
||||
}
|
||||
`
|
||||
const query = storedQueries.deserialiseQueries(str)
|
||||
expect(query).to.eql([JSON.parse(str)])
|
||||
})
|
||||
|
||||
it('deserialiseQueries generates new id to avoid duplication', () => {
|
||||
storedQueries.updateStorage([{ id: 1 }])
|
||||
const str = `[
|
||||
{
|
||||
"id": 1,
|
||||
"name": "foo",
|
||||
"query": "select * from foo",
|
||||
"chart": [],
|
||||
"createdAt": "2020-11-03T14:17:49.524Z"
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"name": "bar",
|
||||
"query": "select * from bar",
|
||||
"chart": [],
|
||||
"createdAt": "2020-11-04T14:17:49.524Z"
|
||||
}
|
||||
]`
|
||||
|
||||
const queries = storedQueries.deserialiseQueries(str)
|
||||
const parsedStr = JSON.parse(str)
|
||||
expect(queries[1]).to.eql(parsedStr[1])
|
||||
expect(queries[0].id).to.not.equal(parsedStr[0].id)
|
||||
expect(queries[0]).to.have.property('id')
|
||||
expect(queries[0].id).to.not.equal(parsedStr[0].id)
|
||||
expect(queries[0].name).to.equal(parsedStr[0].name)
|
||||
expect(queries[0].query).to.equal(parsedStr[0].query)
|
||||
expect(queries[0].chart).to.eql(parsedStr[0].chart)
|
||||
expect(queries[0].createdAt).to.equal(parsedStr[0].createdAt)
|
||||
})
|
||||
|
||||
it('importQueries', async () => {
|
||||
const str = `
|
||||
{
|
||||
"id": 1,
|
||||
"name": "foo",
|
||||
"query": "select * from foo",
|
||||
"chart": [],
|
||||
"createdAt": "2020-11-03T14:17:49.524Z"
|
||||
}
|
||||
`
|
||||
sinon.stub(fu, 'importFile').returns(Promise.resolve(str))
|
||||
const queries = await storedQueries.importQueries()
|
||||
|
||||
expect(queries).to.eql([JSON.parse(str)])
|
||||
})
|
||||
|
||||
it('readPredefinedQueries', async () => {
|
||||
const str = `
|
||||
{
|
||||
"id": 1,
|
||||
"name": "foo",
|
||||
"query": "select * from foo",
|
||||
"chart": [],
|
||||
"createdAt": "2020-11-03T14:17:49.524Z"
|
||||
}
|
||||
`
|
||||
sinon.stub(fu, 'readFile').returns(Promise.resolve(new Response(str)))
|
||||
const queries = await storedQueries.readPredefinedQueries()
|
||||
expect(fu.readFile.calledOnceWith('./queries.json')).to.equal(true)
|
||||
expect(queries).to.eql(JSON.parse(str))
|
||||
})
|
||||
|
||||
it('save adds new query in the storage', () => {
|
||||
const now = new Date()
|
||||
const nowPlusMinute = new Date(now.getTime() + 60 * 1000)
|
||||
const tab = {
|
||||
id: 1,
|
||||
query: 'select * from foo',
|
||||
chart: [],
|
||||
initName: null,
|
||||
$refs: {
|
||||
chart: {
|
||||
getChartStateForSave () {
|
||||
return ['chart']
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
const value = storedQueries.save(tab, 'foo')
|
||||
expect(value.id).to.equal(tab.id)
|
||||
expect(value.name).to.equal('foo')
|
||||
expect(value.query).to.equal(tab.query)
|
||||
expect(value.chart).to.eql(['chart'])
|
||||
expect(value).to.have.property('createdAt').which.within(now, nowPlusMinute)
|
||||
const queries = storedQueries.getStoredQueries()
|
||||
expect(JSON.stringify(queries)).to.equal(JSON.stringify([value]))
|
||||
})
|
||||
|
||||
it('save updates existing query in the storage', () => {
|
||||
const tab = {
|
||||
id: 1,
|
||||
query: 'select * from foo',
|
||||
chart: [],
|
||||
initName: null,
|
||||
$refs: {
|
||||
chart: {
|
||||
getChartStateForSave () {
|
||||
return ['chart']
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const first = storedQueries.save(tab, 'foo')
|
||||
|
||||
tab.initName = 'foo'
|
||||
tab.query = 'select * from foo'
|
||||
storedQueries.save(tab)
|
||||
const queries = storedQueries.getStoredQueries()
|
||||
const second = queries[0]
|
||||
expect(queries).has.lengthOf(1)
|
||||
expect(second.id).to.equal(first.id)
|
||||
expect(second.name).to.equal(first.name)
|
||||
expect(second.query).to.equal(tab.query)
|
||||
expect(second.chart).to.eql(['chart'])
|
||||
expect(new Date(second.createdAt).getTime()).to.equal(first.createdAt.getTime())
|
||||
})
|
||||
|
||||
it("save adds a new query with new id if it's based on predefined query", () => {
|
||||
const now = new Date()
|
||||
const nowPlusMinute = new Date(now.getTime() + 60 * 1000)
|
||||
const tab = {
|
||||
id: 1,
|
||||
query: 'select * from foo',
|
||||
chart: [],
|
||||
initName: 'foo predefined',
|
||||
$refs: {
|
||||
chart: {
|
||||
getChartStateForSave () {
|
||||
return ['chart']
|
||||
}
|
||||
}
|
||||
},
|
||||
isPredefined: true
|
||||
}
|
||||
storedQueries.save(tab, 'foo')
|
||||
|
||||
const queries = storedQueries.getStoredQueries()
|
||||
expect(queries).has.lengthOf(1)
|
||||
expect(queries[0]).to.have.property('id').which.not.equal(tab.id)
|
||||
expect(queries[0].name).to.equal('foo')
|
||||
expect(queries[0].query).to.equal(tab.query)
|
||||
expect(queries[0].chart).to.eql(['chart'])
|
||||
expect(new Date(queries[0].createdAt)).to.be.within(now, nowPlusMinute)
|
||||
})
|
||||
})
|
||||
131
tests/lib/utils/fileIo.spec.js
Normal file
@@ -0,0 +1,131 @@
|
||||
import { expect } from 'chai'
|
||||
import fu from '@/lib/utils/fileIo'
|
||||
import sinon from 'sinon'
|
||||
|
||||
describe('fileIo.js', () => {
|
||||
afterEach(() => {
|
||||
sinon.restore()
|
||||
})
|
||||
|
||||
it('exportToFile (octet/stream by default)', () => {
|
||||
const spyAnchor = document.createElement('a')
|
||||
sinon.spy(spyAnchor, 'click')
|
||||
sinon.stub(document, 'createElement').returns(spyAnchor)
|
||||
sinon.spy(URL, 'createObjectURL')
|
||||
sinon.spy(URL, 'revokeObjectURL')
|
||||
sinon.spy(window, 'Blob')
|
||||
|
||||
fu.exportToFile('foo', 'foo.txt')
|
||||
|
||||
expect(document.createElement.calledOnceWith('a')).to.equal(true)
|
||||
|
||||
expect(window.Blob.calledOnceWith(['foo'], { type: 'octet/stream' })).to.equal(true)
|
||||
const blob = window.Blob.returnValues[0]
|
||||
expect(URL.createObjectURL.calledOnceWith(blob)).to.equal(true)
|
||||
|
||||
const url = URL.createObjectURL.returnValues[0]
|
||||
expect(spyAnchor.href).to.equal(url)
|
||||
|
||||
expect(spyAnchor.download).to.equal('foo.txt')
|
||||
|
||||
expect(spyAnchor.click.calledOnce).to.equal(true)
|
||||
expect(URL.revokeObjectURL.calledOnceWith(url)).to.equal(true)
|
||||
})
|
||||
|
||||
it('exportToFile', () => {
|
||||
const spyAnchor = document.createElement('a')
|
||||
sinon.spy(spyAnchor, 'click')
|
||||
sinon.stub(document, 'createElement').returns(spyAnchor)
|
||||
sinon.spy(URL, 'createObjectURL')
|
||||
sinon.spy(URL, 'revokeObjectURL')
|
||||
sinon.spy(window, 'Blob')
|
||||
|
||||
fu.exportToFile('foo', 'foo.html', 'text/html')
|
||||
|
||||
expect(document.createElement.calledOnceWith('a')).to.equal(true)
|
||||
|
||||
expect(window.Blob.calledOnceWith(['foo'], { type: 'text/html' })).to.equal(true)
|
||||
const blob = window.Blob.returnValues[0]
|
||||
expect(URL.createObjectURL.calledOnceWith(blob)).to.equal(true)
|
||||
|
||||
const url = URL.createObjectURL.returnValues[0]
|
||||
expect(spyAnchor.href).to.equal(url)
|
||||
|
||||
expect(spyAnchor.download).to.equal('foo.html')
|
||||
|
||||
expect(spyAnchor.click.calledOnce).to.equal(true)
|
||||
expect(URL.revokeObjectURL.calledOnceWith(url)).to.equal(true)
|
||||
})
|
||||
|
||||
it('importFile', async () => {
|
||||
const spyInput = document.createElement('input')
|
||||
sinon.stub(spyInput, 'click')
|
||||
|
||||
const blob = new Blob(['foo'])
|
||||
Object.defineProperty(spyInput, 'files', {
|
||||
value: [blob],
|
||||
writable: false
|
||||
})
|
||||
|
||||
sinon.stub(document, 'createElement').returns(spyInput)
|
||||
|
||||
setTimeout(() => { spyInput.dispatchEvent(new Event('change')) })
|
||||
|
||||
const data = await fu.importFile()
|
||||
expect(data).to.equal('foo')
|
||||
expect(document.createElement.calledOnceWith('input')).to.equal(true)
|
||||
expect(spyInput.type).to.equal('file')
|
||||
expect(spyInput.accept).to.equal('.json')
|
||||
expect(spyInput.click.calledOnce).to.equal(true)
|
||||
})
|
||||
|
||||
it('readFile', () => {
|
||||
sinon.spy(window, 'fetch')
|
||||
|
||||
fu.readFile('./foo.bar')
|
||||
expect(window.fetch.calledOnceWith('./foo.bar')).to.equal(true)
|
||||
})
|
||||
|
||||
it('readAsArrayBuffer resolves', async () => {
|
||||
const blob = new Blob(['foo'])
|
||||
const buffer = await fu.readAsArrayBuffer(blob)
|
||||
|
||||
const uint8Array = new Uint8Array(buffer)
|
||||
const text = new TextDecoder().decode(uint8Array)
|
||||
expect(text).to.equal('foo')
|
||||
})
|
||||
|
||||
it('readAsArrayBuffer rejects', async () => {
|
||||
const r = new FileReader()
|
||||
r.readAsArrayBuffer = () => {
|
||||
r.dispatchEvent(new Event('error'))
|
||||
}
|
||||
sinon.stub(window, 'FileReader').returns(r)
|
||||
|
||||
const blob = new Blob(['foo'])
|
||||
await expect(fu.readAsArrayBuffer(blob)).to.be.rejectedWith('Problem parsing input file.')
|
||||
})
|
||||
|
||||
it('isDatabase', () => {
|
||||
let file = { type: 'application/vnd.sqlite3' }
|
||||
expect(fu.isDatabase(file)).to.equal(true)
|
||||
|
||||
file = { type: 'application/x-sqlite3' }
|
||||
expect(fu.isDatabase(file)).to.equal(true)
|
||||
|
||||
file = { type: '', name: 'test.db' }
|
||||
expect(fu.isDatabase(file)).to.equal(true)
|
||||
|
||||
file = { type: '', name: 'test.sqlite' }
|
||||
expect(fu.isDatabase(file)).to.equal(true)
|
||||
|
||||
file = { type: '', name: 'test.sqlite3' }
|
||||
expect(fu.isDatabase(file)).to.equal(true)
|
||||
|
||||
file = { type: '', name: 'test.csv' }
|
||||
expect(fu.isDatabase(file)).to.equal(false)
|
||||
|
||||
file = { type: 'text', name: 'test.db' }
|
||||
expect(fu.isDatabase(file)).to.equal(false)
|
||||
})
|
||||
})
|
||||
30
tests/lib/utils/time.spec.js
Normal file
@@ -0,0 +1,30 @@
|
||||
import { expect } from 'chai'
|
||||
import time from '@/lib/utils/time'
|
||||
|
||||
describe('time.js', () => {
|
||||
it('getPeriod', () => {
|
||||
// 1.01.2021 13:00:00 000
|
||||
let start = new Date(2021, 0, 1, 13, 0, 0, 0)
|
||||
|
||||
// 1.01.2021 13:01:00 500
|
||||
let end = new Date(2021, 0, 1, 13, 1, 0, 500)
|
||||
|
||||
expect(time.getPeriod(start, end)).to.equal('60.500s')
|
||||
|
||||
// 1.01.2021 13:00:00 000
|
||||
start = new Date(2021, 0, 1, 13, 0, 0, 0)
|
||||
|
||||
// 1.01.2021 13:00:20 500
|
||||
end = new Date(2021, 0, 1, 13, 0, 20, 500)
|
||||
|
||||
expect(time.getPeriod(start, end)).to.equal('20.500s')
|
||||
|
||||
// 1.01.2021 13:00:00 000
|
||||
start = new Date(2021, 0, 1, 13, 0, 0, 0)
|
||||
|
||||
// 1.01.2021 13:00:00 45
|
||||
end = new Date(2021, 0, 1, 13, 0, 0, 45)
|
||||
|
||||
expect(time.getPeriod(start, end)).to.equal('0.045s')
|
||||
})
|
||||
})
|
||||
67
tests/store/actions.spec.js
Normal file
@@ -0,0 +1,67 @@
|
||||
import { expect } from 'chai'
|
||||
import actions from '@/store/actions'
|
||||
|
||||
const { addTab } = actions
|
||||
|
||||
describe('actions', () => {
|
||||
it('addTab adds new blank tab', async () => {
|
||||
const state = {
|
||||
tabs: [],
|
||||
untitledLastIndex: 0
|
||||
}
|
||||
|
||||
const id = await addTab({ state })
|
||||
expect(state.tabs[0].id).to.eql(id)
|
||||
expect(state.tabs[0].name).to.eql(null)
|
||||
expect(state.tabs[0].tempName).to.eql('Untitled')
|
||||
expect(state.tabs[0].isUnsaved).to.eql(true)
|
||||
expect(state.untitledLastIndex).to.equal(1)
|
||||
})
|
||||
|
||||
it('addTab adds tab from saved queries', async () => {
|
||||
const state = {
|
||||
tabs: [],
|
||||
untitledLastIndex: 0
|
||||
}
|
||||
const tab = {
|
||||
id: 1,
|
||||
name: 'test',
|
||||
tempName: null,
|
||||
query: 'SELECT * from foo',
|
||||
chart: {},
|
||||
isUnsaved: false
|
||||
}
|
||||
await addTab({ state }, tab)
|
||||
expect(state.tabs[0]).to.eql(tab)
|
||||
expect(state.untitledLastIndex).to.equal(0)
|
||||
})
|
||||
|
||||
it("addTab doesn't add anything when the query is already opened", async () => {
|
||||
const tab1 = {
|
||||
id: 1,
|
||||
name: 'test',
|
||||
tempName: null,
|
||||
query: 'SELECT * from foo',
|
||||
chart: {},
|
||||
isUnsaved: false
|
||||
}
|
||||
|
||||
const tab2 = {
|
||||
id: 2,
|
||||
name: 'bar',
|
||||
tempName: null,
|
||||
query: 'SELECT * from bar',
|
||||
chart: {},
|
||||
isUnsaved: false
|
||||
}
|
||||
|
||||
const state = {
|
||||
tabs: [tab1, tab2],
|
||||
untitledLastIndex: 0
|
||||
}
|
||||
|
||||
await addTab({ state }, tab1)
|
||||
expect(state.tabs).to.have.lengthOf(2)
|
||||
expect(state.untitledLastIndex).to.equal(0)
|
||||
})
|
||||
})
|
||||
376
tests/store/mutations.spec.js
Normal file
@@ -0,0 +1,376 @@
|
||||
import { expect } from 'chai'
|
||||
import sinon from 'sinon'
|
||||
import mutations from '@/store/mutations'
|
||||
const {
|
||||
saveSchema,
|
||||
updateTab,
|
||||
deleteTab,
|
||||
setCurrentTabId,
|
||||
setCurrentTab,
|
||||
updatePredefinedQueries,
|
||||
setDb
|
||||
} = mutations
|
||||
|
||||
describe('mutations', () => {
|
||||
it('setDb', () => {
|
||||
const state = {
|
||||
db: { shutDown: sinon.spy() }
|
||||
}
|
||||
|
||||
const oldDb = state.db
|
||||
const db = {}
|
||||
setDb(state, db)
|
||||
expect(state.db).to.equal(db)
|
||||
expect(oldDb.shutDown.calledOnce).to.equal(true)
|
||||
})
|
||||
|
||||
it('saveSchema', () => {
|
||||
const state = {}
|
||||
|
||||
const schema = [
|
||||
{
|
||||
name: 'table1',
|
||||
columns: [
|
||||
{ name: 'id', type: 'INTEGER' }
|
||||
]
|
||||
}
|
||||
]
|
||||
saveSchema(state, {
|
||||
dbName: 'test',
|
||||
schema
|
||||
})
|
||||
expect(state.dbName).to.equal('test')
|
||||
expect(state.schema).to.eql(schema)
|
||||
})
|
||||
|
||||
it('updateTab (save)', () => {
|
||||
const tab = {
|
||||
id: 1,
|
||||
name: 'test',
|
||||
tempName: null,
|
||||
query: 'SELECT * from foo',
|
||||
chart: {},
|
||||
isUnsaved: true,
|
||||
isPredefined: false
|
||||
}
|
||||
|
||||
const newTab = {
|
||||
index: 0,
|
||||
id: 1,
|
||||
name: 'new test',
|
||||
query: 'SELECT * from bar',
|
||||
isUnsaved: false
|
||||
}
|
||||
|
||||
const state = {
|
||||
tabs: [tab]
|
||||
}
|
||||
|
||||
updateTab(state, newTab)
|
||||
expect(state.tabs[0].id).to.equal(1)
|
||||
expect(state.tabs[0].name).to.equal('new test')
|
||||
expect(state.tabs[0].tempName).to.equal(null)
|
||||
expect(state.tabs[0].query).to.equal('SELECT * from bar')
|
||||
expect(state.tabs[0].isUnsaved).to.equal(false)
|
||||
})
|
||||
|
||||
it('updateTab (save predefined)', () => {
|
||||
const tab = {
|
||||
id: 1,
|
||||
name: 'test',
|
||||
tempName: null,
|
||||
query: 'SELECT * from foo',
|
||||
chart: {},
|
||||
isUnsaved: true,
|
||||
isPredefined: true
|
||||
}
|
||||
|
||||
const newTab = {
|
||||
index: 0,
|
||||
id: 2,
|
||||
name: 'new test',
|
||||
query: 'SELECT * from bar',
|
||||
chart: {},
|
||||
isUnsaved: false
|
||||
}
|
||||
|
||||
const state = {
|
||||
tabs: [tab],
|
||||
currentTabId: 1
|
||||
}
|
||||
|
||||
updateTab(state, newTab)
|
||||
expect(state.tabs).to.have.lengthOf(1)
|
||||
expect(state.currentTabId).to.equal(2)
|
||||
expect(state.tabs[0].id).to.equal(2)
|
||||
expect(state.tabs[0].name).to.equal('new test')
|
||||
expect(state.tabs[0].query).to.equal('SELECT * from bar')
|
||||
expect(state.tabs[0].isUnsaved).to.equal(false)
|
||||
expect(state.tabs[0].isPredefined).to.equal(undefined)
|
||||
})
|
||||
|
||||
it('updateTab (rename)', () => {
|
||||
const tab = {
|
||||
id: 1,
|
||||
name: 'test',
|
||||
tempName: null,
|
||||
query: 'SELECT * from foo',
|
||||
chart: {},
|
||||
isUnsaved: true
|
||||
}
|
||||
|
||||
const newTab = {
|
||||
index: 0,
|
||||
id: 1,
|
||||
name: 'new test'
|
||||
}
|
||||
|
||||
const state = {
|
||||
tabs: [tab]
|
||||
}
|
||||
|
||||
updateTab(state, newTab)
|
||||
expect(state.tabs).to.have.lengthOf(1)
|
||||
expect(state.tabs[0].id).to.equal(1)
|
||||
expect(state.tabs[0].name).to.equal('new test')
|
||||
expect(state.tabs[0].query).to.equal('SELECT * from foo')
|
||||
expect(state.tabs[0].isUnsaved).to.equal(true)
|
||||
})
|
||||
|
||||
it('updateTab (changes detected)', () => {
|
||||
const tab = {
|
||||
id: 1,
|
||||
name: 'test',
|
||||
tempName: null,
|
||||
query: 'SELECT * from foo',
|
||||
chart: {},
|
||||
isUnsaved: false,
|
||||
isPredefined: true
|
||||
}
|
||||
|
||||
const newTab = {
|
||||
index: 0,
|
||||
isUnsaved: true
|
||||
}
|
||||
|
||||
const state = {
|
||||
tabs: [tab]
|
||||
}
|
||||
|
||||
updateTab(state, newTab)
|
||||
expect(state.tabs).to.have.lengthOf(1)
|
||||
expect(state.tabs[0].id).to.equal(1)
|
||||
expect(state.tabs[0].name).to.equal('test')
|
||||
expect(state.tabs[0].query).to.equal('SELECT * from foo')
|
||||
expect(state.tabs[0].isUnsaved).to.equal(true)
|
||||
})
|
||||
|
||||
it('deleteTab (opened, first)', () => {
|
||||
const tab1 = {
|
||||
id: 1,
|
||||
name: 'foo',
|
||||
tempName: null,
|
||||
query: 'SELECT * from foo',
|
||||
chart: {},
|
||||
isUnsaved: false
|
||||
}
|
||||
|
||||
const tab2 = {
|
||||
id: 2,
|
||||
name: 'bar',
|
||||
tempName: null,
|
||||
query: 'SELECT * from bar',
|
||||
chart: {},
|
||||
isUnsaved: false
|
||||
}
|
||||
|
||||
const state = {
|
||||
tabs: [tab1, tab2],
|
||||
currentTabId: 1
|
||||
}
|
||||
|
||||
deleteTab(state, 0)
|
||||
expect(state.tabs).to.have.lengthOf(1)
|
||||
expect(state.tabs[0].id).to.equal(2)
|
||||
expect(state.currentTabId).to.equal(2)
|
||||
})
|
||||
|
||||
it('deleteTab (opened, last)', () => {
|
||||
const tab1 = {
|
||||
id: 1,
|
||||
name: 'foo',
|
||||
tempName: null,
|
||||
query: 'SELECT * from foo',
|
||||
chart: {},
|
||||
isUnsaved: false
|
||||
}
|
||||
|
||||
const tab2 = {
|
||||
id: 2,
|
||||
name: 'bar',
|
||||
tempName: null,
|
||||
query: 'SELECT * from bar',
|
||||
chart: {},
|
||||
isUnsaved: false
|
||||
}
|
||||
|
||||
const state = {
|
||||
tabs: [tab1, tab2],
|
||||
currentTabId: 2
|
||||
}
|
||||
|
||||
deleteTab(state, 1)
|
||||
expect(state.tabs).to.have.lengthOf(1)
|
||||
expect(state.tabs[0].id).to.equal(1)
|
||||
expect(state.currentTabId).to.equal(1)
|
||||
})
|
||||
|
||||
it('deleteTab (opened, in the middle)', () => {
|
||||
const tab1 = {
|
||||
id: 1,
|
||||
name: 'foo',
|
||||
tempName: null,
|
||||
query: 'SELECT * from foo',
|
||||
chart: {},
|
||||
isUnsaved: false
|
||||
}
|
||||
|
||||
const tab2 = {
|
||||
id: 2,
|
||||
name: 'bar',
|
||||
tempName: null,
|
||||
query: 'SELECT * from bar',
|
||||
chart: {},
|
||||
isUnsaved: false
|
||||
}
|
||||
|
||||
const tab3 = {
|
||||
id: 3,
|
||||
name: 'foobar',
|
||||
tempName: null,
|
||||
query: 'SELECT * from foobar',
|
||||
chart: {},
|
||||
isUnsaved: false
|
||||
}
|
||||
|
||||
const state = {
|
||||
tabs: [tab1, tab2, tab3],
|
||||
currentTabId: 2
|
||||
}
|
||||
|
||||
deleteTab(state, 1)
|
||||
expect(state.tabs).to.have.lengthOf(2)
|
||||
expect(state.tabs[0].id).to.equal(1)
|
||||
expect(state.tabs[1].id).to.equal(3)
|
||||
expect(state.currentTabId).to.equal(3)
|
||||
})
|
||||
|
||||
it('deleteTab (opened, single)', () => {
|
||||
const tab1 = {
|
||||
id: 1,
|
||||
name: 'foo',
|
||||
tempName: null,
|
||||
query: 'SELECT * from foo',
|
||||
chart: {},
|
||||
isUnsaved: false
|
||||
}
|
||||
|
||||
const state = {
|
||||
tabs: [tab1],
|
||||
currentTabId: 1
|
||||
}
|
||||
|
||||
deleteTab(state, 0)
|
||||
expect(state.tabs).to.have.lengthOf(0)
|
||||
expect(state.currentTabId).to.equal(null)
|
||||
})
|
||||
|
||||
it('deleteTab (not opened)', () => {
|
||||
const tab1 = {
|
||||
id: 1,
|
||||
name: 'foo',
|
||||
tempName: null,
|
||||
query: 'SELECT * from foo',
|
||||
chart: {},
|
||||
isUnsaved: false
|
||||
}
|
||||
|
||||
const tab2 = {
|
||||
id: 2,
|
||||
name: 'bar',
|
||||
tempName: null,
|
||||
query: 'SELECT * from bar',
|
||||
chart: {},
|
||||
isUnsaved: false
|
||||
}
|
||||
|
||||
const state = {
|
||||
tabs: [tab1, tab2],
|
||||
currentTabId: 1
|
||||
}
|
||||
|
||||
deleteTab(state, 1)
|
||||
expect(state.tabs).to.have.lengthOf(1)
|
||||
expect(state.tabs[0].id).to.equal(1)
|
||||
expect(state.currentTabId).to.equal(1)
|
||||
})
|
||||
|
||||
it('setCurrentTabId', () => {
|
||||
const state = {
|
||||
currentTabId: 1
|
||||
}
|
||||
|
||||
setCurrentTabId(state, 2)
|
||||
expect(state.currentTabId).to.equal(2)
|
||||
})
|
||||
|
||||
it('setCurrentTab', () => {
|
||||
const state = {
|
||||
currentTab: { id: 1 }
|
||||
}
|
||||
|
||||
setCurrentTab(state, { id: 2 })
|
||||
expect(state.currentTab).to.eql({ id: 2 })
|
||||
})
|
||||
|
||||
it('updatePredefinedQueries (single)', () => {
|
||||
const query = {
|
||||
id: 1,
|
||||
name: 'foo',
|
||||
query: 'SELECT * FROM foo',
|
||||
chart: {},
|
||||
createdAt: '2020-11-07T20:57:04.492Z'
|
||||
}
|
||||
|
||||
const state = {
|
||||
predefinedQueries: []
|
||||
}
|
||||
|
||||
updatePredefinedQueries(state, query)
|
||||
expect(state.predefinedQueries).to.eql([query])
|
||||
})
|
||||
|
||||
it('updatePredefinedQueries (array)', () => {
|
||||
const queries = [{
|
||||
id: 1,
|
||||
name: 'foo',
|
||||
query: 'SELECT * FROM foo',
|
||||
chart: {},
|
||||
createdAt: '2020-11-07T20:57:04.492Z'
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
name: 'bar',
|
||||
query: 'SELECT * FROM bar',
|
||||
chart: {},
|
||||
createdAt: '2020-11-07T20:57:04.492Z'
|
||||
}]
|
||||
|
||||
const state = {
|
||||
predefinedQueries: []
|
||||
}
|
||||
|
||||
updatePredefinedQueries(state, queries)
|
||||
expect(state.predefinedQueries).to.eql(queries)
|
||||
})
|
||||
})
|
||||
46
tests/tooltipMixin.spec.js
Normal file
@@ -0,0 +1,46 @@
|
||||
import { expect } from 'chai'
|
||||
import { mount } from '@vue/test-utils'
|
||||
import tooltipMixin from '@/tooltipMixin'
|
||||
|
||||
describe('tooltipMixin.js', () => {
|
||||
it('tooltip is hidden in initial', () => {
|
||||
const component = {
|
||||
template: '<div :style="tooltipStyle"></div>',
|
||||
mixins: [tooltipMixin]
|
||||
}
|
||||
const wrapper = mount(component)
|
||||
expect(wrapper.find('div').isVisible()).to.equal(false)
|
||||
})
|
||||
|
||||
it('tooltipStyle is correct when showTooltip', async () => {
|
||||
const component = {
|
||||
template: '<div :style="tooltipStyle"></div>',
|
||||
mixins: [tooltipMixin]
|
||||
}
|
||||
const wrapper = mount(component)
|
||||
await wrapper.vm.showTooltip(new MouseEvent('mouseover', {
|
||||
clientX: 10,
|
||||
clientY: 20
|
||||
}))
|
||||
expect(wrapper.vm.tooltipStyle).to.eql({
|
||||
visibility: 'visible',
|
||||
top: '8px',
|
||||
left: '22px'
|
||||
})
|
||||
expect(wrapper.find('div').isVisible()).to.equal(true)
|
||||
})
|
||||
|
||||
it('tooltip is not visible after hideTooltip', async () => {
|
||||
const component = {
|
||||
template: '<div :style="tooltipStyle"></div>',
|
||||
mixins: [tooltipMixin]
|
||||
}
|
||||
const wrapper = mount(component)
|
||||
await wrapper.vm.showTooltip(new MouseEvent('mouseover', {
|
||||
clientX: 10,
|
||||
clientY: 20
|
||||
}))
|
||||
await wrapper.vm.hideTooltip()
|
||||
expect(wrapper.find('div').isVisible()).to.equal(false)
|
||||
})
|
||||
})
|
||||
@@ -1,39 +0,0 @@
|
||||
/* import { expect } from 'chai'
|
||||
import { shallowMount } from '@vue/test-utils'
|
||||
import HelloWorld from '@/components/HelloWorld.vue'
|
||||
|
||||
describe('HelloWorld.vue', () => {
|
||||
it('renders props.msg when passed', () => {
|
||||
const msg = 'new message'
|
||||
const wrapper = shallowMount(HelloWorld, {
|
||||
propsData: { msg }
|
||||
})
|
||||
expect(wrapper.text()).to.include(msg)
|
||||
})
|
||||
})
|
||||
*/
|
||||
import { expect } from 'chai'
|
||||
import initSqlJs from 'sql.js'
|
||||
import db from '@/dataBase.js'
|
||||
|
||||
describe('dataBase.js', () => {
|
||||
it('creates schema', () => {
|
||||
const config = {
|
||||
locateFile: filename => `js/sql-wasm.wasm`
|
||||
}
|
||||
return initSqlJs(config)
|
||||
.then(SQL => {
|
||||
const dataBase = new SQL.Database()
|
||||
dataBase.run('CREATE TABLE test (col1, col2);')
|
||||
|
||||
const data = dataBase.export()
|
||||
const buffer = new Blob([data])
|
||||
return db.loadDb(buffer)
|
||||
})
|
||||
.then(schema => {
|
||||
expect(schema.length).to.equal(1)
|
||||
expect(schema[0][0]).to.equal('test')
|
||||
expect(schema[0][1]).to.equal('CREATE TABLE test (col1, col2)')
|
||||
})
|
||||
})
|
||||
})
|
||||
115
tests/views/MainView/Editor/Schema/Schema.spec.js
Normal file
@@ -0,0 +1,115 @@
|
||||
import { expect } from 'chai'
|
||||
import sinon from 'sinon'
|
||||
import { mount, createLocalVue } from '@vue/test-utils'
|
||||
import Vuex from 'vuex'
|
||||
import Schema from '@/views/Main/Editor/Schema'
|
||||
import TableDescription from '@/views/Main/Editor/Schema/TableDescription'
|
||||
|
||||
const localVue = createLocalVue()
|
||||
localVue.use(Vuex)
|
||||
|
||||
describe('Schema.vue', () => {
|
||||
afterEach(() => {
|
||||
sinon.restore()
|
||||
})
|
||||
|
||||
it('Renders DB name on initial', () => {
|
||||
// mock store state
|
||||
const state = {
|
||||
dbName: 'fooDB'
|
||||
}
|
||||
const store = new Vuex.Store({ state })
|
||||
|
||||
// mout the component
|
||||
const wrapper = mount(Schema, { store, localVue })
|
||||
|
||||
// check DB name and schema visibility
|
||||
expect(wrapper.find('.db-name').text()).to.equal('fooDB')
|
||||
expect(wrapper.find('.schema').isVisible()).to.equal(true)
|
||||
})
|
||||
|
||||
it('Schema visibility is toggled when click on DB name', async () => {
|
||||
// mock store state
|
||||
const state = {
|
||||
dbName: 'fooDB'
|
||||
}
|
||||
const store = new Vuex.Store({ state })
|
||||
|
||||
// mout the component
|
||||
const wrapper = mount(Schema, { store, localVue })
|
||||
|
||||
// click and check visibility
|
||||
await wrapper.find('.db-name').trigger('click')
|
||||
expect(wrapper.find('.schema').isVisible()).to.equal(false)
|
||||
await wrapper.find('.db-name').trigger('click')
|
||||
expect(wrapper.find('.schema').isVisible()).to.equal(true)
|
||||
})
|
||||
|
||||
it('Schema filter', async () => {
|
||||
// mock store state
|
||||
const state = {
|
||||
dbName: 'fooDB',
|
||||
schema: [
|
||||
{
|
||||
name: 'foo',
|
||||
columns: [
|
||||
{ name: 'id', type: 'INTEGER' },
|
||||
{ name: 'title', type: 'NVARCHAR(24)' }
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'bar',
|
||||
columns: [
|
||||
{ name: 'id', type: 'INTEGER' },
|
||||
{ name: 'price', type: 'INTEGER' }
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'foobar',
|
||||
columns: [
|
||||
{ name: 'id', type: 'INTEGER' },
|
||||
{ name: 'price', type: 'INTEGER' }
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
const store = new Vuex.Store({ state })
|
||||
|
||||
// mount the component
|
||||
const wrapper = mount(Schema, { store, localVue })
|
||||
|
||||
// apply filters and check the list of tables
|
||||
await wrapper.find('#schema-filter input').setValue('foo')
|
||||
let tables = wrapper.findAllComponents(TableDescription)
|
||||
expect(tables).to.have.lengthOf(2)
|
||||
expect(tables.at(0).vm.name).to.equal('foo')
|
||||
expect(tables.at(1).vm.name).to.equal('foobar')
|
||||
|
||||
await wrapper.find('#schema-filter input').setValue('bar')
|
||||
tables = wrapper.findAllComponents(TableDescription)
|
||||
expect(tables).to.have.lengthOf(2)
|
||||
expect(tables.at(0).vm.name).to.equal('bar')
|
||||
expect(tables.at(1).vm.name).to.equal('foobar')
|
||||
|
||||
await wrapper.find('#schema-filter input').setValue('')
|
||||
tables = wrapper.findAllComponents(TableDescription)
|
||||
expect(tables).to.have.lengthOf(3)
|
||||
expect(tables.at(0).vm.name).to.equal('foo')
|
||||
expect(tables.at(1).vm.name).to.equal('bar')
|
||||
expect(tables.at(2).vm.name).to.equal('foobar')
|
||||
})
|
||||
|
||||
it('exports db', async () => {
|
||||
const state = {
|
||||
dbName: 'fooDB',
|
||||
db: {
|
||||
export: sinon.stub().resolves()
|
||||
}
|
||||
}
|
||||
const store = new Vuex.Store({ state })
|
||||
const wrapper = mount(Schema, { store, localVue })
|
||||
|
||||
await wrapper.findComponent({ name: 'export-icon' }).trigger('click')
|
||||
expect(state.db.export.calledOnceWith('fooDB'))
|
||||
})
|
||||
})
|
||||