switch back to create-react-app

main
ChristopherBiscardi 2017-12-12 18:24:01 -08:00
parent 54c5f50c71
commit 40e7efad4c
No known key found for this signature in database
GPG Key ID: 703265E1DE405983
30 changed files with 10605 additions and 3413 deletions

View File

@ -0,0 +1,11 @@
const path = require("path");
module.exports = function override(config, env) {
config.module.rules.push({
test: /worker\.js$/,
include: path.resolve("./src"),
use: [{ loader: "worker-loader" }, { loader: "babel-loader" }]
});
return config;
};

View File

@ -1,38 +0,0 @@
'use strict';
// Grab NODE_ENV and REACT_APP_* environment variables and prepare them to be
// injected into the application via DefinePlugin in Webpack configuration.
var REACT_APP = /^REACT_APP_/i;
function getClientEnvironment(publicUrl) {
var raw = Object
.keys(process.env)
.filter(key => REACT_APP.test(key))
.reduce((env, key) => {
env[key] = process.env[key];
return env;
}, {
// Useful for determining whether were running in production mode.
// Most importantly, it switches React into the correct mode.
'NODE_ENV': process.env.NODE_ENV || 'development',
// Useful for resolving the correct path to static assets in `public`.
// For example, <img src={process.env.PUBLIC_URL + '/img/logo.png'} />.
// This should only be used as an escape hatch. Normally you would put
// images into the `src` and `import` them in code to get their paths.
'PUBLIC_URL': publicUrl
});
// Stringify all values so we can feed into Webpack DefinePlugin
var stringified = {
'process.env': Object
.keys(raw)
.reduce((env, key) => {
env[key] = JSON.stringify(raw[key]);
return env;
}, {})
};
return { raw, stringified };
}
module.exports = getClientEnvironment;

View File

@ -1,14 +0,0 @@
'use strict';
// This is a custom Jest transformer turning style imports into empty objects.
// http://facebook.github.io/jest/docs/tutorial-webpack.html
module.exports = {
process() {
return 'module.exports = {};';
},
getCacheKey() {
// The output is always the same.
return 'cssTransform';
},
};

View File

@ -1,12 +0,0 @@
'use strict';
const path = require('path');
// This is a custom Jest transformer turning file imports into filenames.
// http://facebook.github.io/jest/docs/tutorial-webpack.html
module.exports = {
process(src, filename) {
return 'module.exports = ' + JSON.stringify(path.basename(filename)) + ';';
},
};

View File

@ -1,80 +0,0 @@
'use strict';
var path = require('path');
var fs = require('fs');
var url = require('url');
// Make sure any symlinks in the project folder are resolved:
// https://github.com/facebookincubator/create-react-app/issues/637
var appDirectory = fs.realpathSync(process.cwd());
function resolveApp(relativePath) {
return path.resolve(appDirectory, relativePath);
}
// We support resolving modules according to `NODE_PATH`.
// This lets you use absolute paths in imports inside large monorepos:
// https://github.com/facebookincubator/create-react-app/issues/253.
// It works similar to `NODE_PATH` in Node itself:
// https://nodejs.org/api/modules.html#modules_loading_from_the_global_folders
// We will export `nodePaths` as an array of absolute paths.
// It will then be used by Webpack configs.
// Jest doesnt need this because it already handles `NODE_PATH` out of the box.
// Note that unlike in Node, only *relative* paths from `NODE_PATH` are honored.
// Otherwise, we risk importing Node.js core modules into an app instead of Webpack shims.
// https://github.com/facebookincubator/create-react-app/issues/1023#issuecomment-265344421
var nodePaths = (process.env.NODE_PATH || '')
.split(process.platform === 'win32' ? ';' : ':')
.filter(Boolean)
.filter(folder => !path.isAbsolute(folder))
.map(resolveApp);
var envPublicUrl = process.env.PUBLIC_URL;
function ensureSlash(path, needsSlash) {
var hasSlash = path.endsWith('/');
if (hasSlash && !needsSlash) {
return path.substr(path, path.length - 1);
} else if (!hasSlash && needsSlash) {
return path + '/';
} else {
return path;
}
}
function getPublicUrl(appPackageJson) {
return envPublicUrl || require(appPackageJson).homepage;
}
// We use `PUBLIC_URL` environment variable or "homepage" field to infer
// "public path" at which the app is served.
// Webpack needs to know it to put the right <script> hrefs into HTML even in
// single-page apps that may serve index.html for nested URLs like /todos/42.
// We can't use a relative path in HTML because we don't want to load something
// like /todos/42/static/js/bundle.7289d.js. We have to know the root.
function getServedPath(appPackageJson) {
var publicUrl = getPublicUrl(appPackageJson);
var servedUrl = envPublicUrl || (
publicUrl ? url.parse(publicUrl).pathname : '/'
);
return ensureSlash(servedUrl, true);
}
// config after eject: we're in ./config/
module.exports = {
appBuild: resolveApp('build'),
appPublic: resolveApp('public'),
appHtml: resolveApp('public/index.html'),
appIndexJs: resolveApp('src/index.js'),
appPackageJson: resolveApp('package.json'),
appSrc: resolveApp('src'),
yarnLockFile: resolveApp('yarn.lock'),
testsSetup: resolveApp('src/setupTests.js'),
appNodeModules: resolveApp('node_modules'),
nodePaths: nodePaths,
publicUrl: getPublicUrl(resolveApp('package.json')),
servedPath: getServedPath(resolveApp('package.json'))
};

View File

@ -1,16 +0,0 @@
'use strict';
if (typeof Promise === 'undefined') {
// Rejection tracking prevents a common issue where React gets into an
// inconsistent state due to an error, but it gets swallowed by a Promise,
// and the user has no idea what causes React's erratic future behavior.
require('promise/lib/rejection-tracking').enable();
window.Promise = require('promise/lib/es6-extensions.js');
}
// fetch() polyfill for making API calls.
require('whatwg-fetch');
// Object.assign() is commonly used with React.
// It will use the native implementation if it's present and isn't buggy.
Object.assign = require('object-assign');

View File

@ -1,226 +0,0 @@
'use strict';
var autoprefixer = require('autoprefixer');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin');
var InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
var WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin');
var getClientEnvironment = require('./env');
var paths = require('./paths');
// Webpack uses `publicPath` to determine where the app is being served from.
// In development, we always serve from the root. This makes config easier.
var publicPath = '/';
// `publicUrl` is just like `publicPath`, but we will provide it to our app
// as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
// Omit trailing slash as %PUBLIC_PATH%/xyz looks better than %PUBLIC_PATH%xyz.
var publicUrl = '';
// Get environment variables to inject into our app.
var env = getClientEnvironment(publicUrl);
// This is the development configuration.
// It is focused on developer experience and fast rebuilds.
// The production configuration is different and lives in a separate file.
module.exports = {
// You may want 'eval' instead if you prefer to see the compiled output in DevTools.
// See the discussion in https://github.com/facebookincubator/create-react-app/issues/343.
devtool: 'cheap-module-source-map',
// These are the "entry points" to our application.
// This means they will be the "root" imports that are included in JS bundle.
// The first two entry points enable "hot" CSS and auto-refreshes for JS.
entry: [
// Include an alternative client for WebpackDevServer. A client's job is to
// connect to WebpackDevServer by a socket and get notified about changes.
// When you save a file, the client will either apply hot updates (in case
// of CSS changes), or refresh the page (in case of JS changes). When you
// make a syntax error, this client will display a syntax error overlay.
// Note: instead of the default WebpackDevServer client, we use a custom one
// to bring better experience for Create React App users. You can replace
// the line below with these two lines if you prefer the stock client:
// require.resolve('webpack-dev-server/client') + '?/',
// require.resolve('webpack/hot/dev-server'),
require.resolve('react-dev-utils/webpackHotDevClient'),
// We ship a few polyfills by default:
require.resolve('./polyfills'),
// Finally, this is your app's code:
paths.appIndexJs
// We include the app code last so that if there is a runtime error during
// initialization, it doesn't blow up the WebpackDevServer client, and
// changing JS code would still trigger a refresh.
],
output: {
// Next line is not used in dev but WebpackDevServer crashes without it:
path: paths.appBuild,
// Add /* filename */ comments to generated require()s in the output.
pathinfo: true,
// This does not produce a real file. It's just the virtual path that is
// served by WebpackDevServer in development. This is the JS bundle
// containing code from all our entry points, and the Webpack runtime.
filename: 'static/js/bundle.js',
// This is the URL that app is served from. We use "/" in development.
publicPath: publicPath
},
resolve: {
// This allows you to set a fallback for where Webpack should look for modules.
// We read `NODE_PATH` environment variable in `paths.js` and pass paths here.
// We use `fallback` instead of `root` because we want `node_modules` to "win"
// if there any conflicts. This matches Node resolution mechanism.
// https://github.com/facebookincubator/create-react-app/issues/253
fallback: paths.nodePaths,
// These are the reasonable defaults supported by the Node ecosystem.
// We also include JSX as a common component filename extension to support
// some tools, although we do not recommend using it, see:
// https://github.com/facebookincubator/create-react-app/issues/290
extensions: ['.js', '.json', '.jsx', ''],
alias: {
// Support React Native Web
// https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
'react-native': 'react-native-web'
}
},
module: {
// First, run the linter.
// It's important to do this before Babel processes the JS.
preLoaders: [
{
test: /\.(js|jsx)$/,
loader: 'eslint',
include: paths.appSrc,
}
],
loaders: [
// ** ADDING/UPDATING LOADERS **
// The "url" loader handles all assets unless explicitly excluded.
// The `exclude` list *must* be updated with every change to loader extensions.
// When adding a new loader, you must add its `test`
// as a new entry in the `exclude` list for "url" loader.
// "url" loader embeds assets smaller than specified size as data URLs to avoid requests.
// Otherwise, it acts like the "file" loader.
{
exclude: [
/\.html$/,
// We have to write /\.(js|jsx)(\?.*)?$/ rather than just /\.(js|jsx)$/
// because you might change the hot reloading server from the custom one
// to Webpack's built-in webpack-dev-server/client?/, which would not
// get properly excluded by /\.(js|jsx)$/ because of the query string.
// Webpack 2 fixes this, but for now we include this hack.
// https://github.com/facebookincubator/create-react-app/issues/1713
/\.(js|jsx)(\?.*)?$/,
/\.css$/,
/\.json$/,
/\.svg$/,
/\.png$/,
],
loader: 'url',
query: {
limit: 10000,
name: 'static/media/[name].[hash:8].[ext]'
}
},
// Process JS with Babel.
{
test: /\.(js|jsx)$/,
include: paths.appSrc,
loader: 'babel',
query: {
// This is a feature of `babel-loader` for webpack (not Babel itself).
// It enables caching results in ./node_modules/.cache/babel-loader/
// directory for faster rebuilds.
cacheDirectory: true
}
},
// "postcss" loader applies autoprefixer to our CSS.
// "css" loader resolves paths in CSS and adds assets as dependencies.
// "style" loader turns CSS into JS modules that inject <style> tags.
// In production, we use a plugin to extract that CSS to a file, but
// in development "style" loader enables hot editing of CSS.
{
test: /\.css$/,
loader: 'style!css?importLoaders=1!postcss'
},
// JSON is not enabled by default in Webpack but both Node and Browserify
// allow it implicitly so we also enable it.
{
test: /\.json$/,
loader: 'json'
},
// "file" loader for svg
{
test: /\.svg$/,
loader: 'file',
query: {
name: 'static/media/[name].[hash:8].[ext]'
}
},
{
test: /worker\.js$/,
loaders: ['worker-loader', 'babel-loader'],
include: paths.appSrc,
use: [
{ loader: 'worker-loader' },
{ loader: 'babel-loader' }
]
},
{
// static image loader
test: /\.png$/,
loader: 'base64-inline-loader?name=[name].[ext]'
}
// ** STOP ** Are you adding a new loader?
// Remember to add the new extension(s) to the "url" loader exclusion list.
]
},
// We use PostCSS for autoprefixing only.
postcss: function() {
return [
autoprefixer({
browsers: [
'>1%',
'last 4 versions',
'Firefox ESR',
'not ie < 9', // React doesn't support IE8 anyway
]
}),
];
},
plugins: [
// Makes some environment variables available in index.html.
// The public URL is available as %PUBLIC_URL% in index.html, e.g.:
// <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
// In development, this will be an empty string.
new InterpolateHtmlPlugin(env.raw),
// Generates an `index.html` file with the <script> injected.
new HtmlWebpackPlugin({
inject: true,
template: paths.appHtml,
}),
// Makes some environment variables available to the JS code, for example:
// if (process.env.NODE_ENV === 'development') { ... }. See `./env.js`.
new webpack.DefinePlugin(env.stringified),
// This is necessary to emit hot updates (currently CSS only):
new webpack.HotModuleReplacementPlugin(),
// Watcher doesn't work well if you mistype casing in a path so we use
// a plugin that prints an error when you attempt to do this.
// See https://github.com/facebookincubator/create-react-app/issues/240
new CaseSensitivePathsPlugin(),
// If you require a missing module and then `npm install` it, you still have
// to restart the development server for Webpack to discover it. This plugin
// makes the discovery automatic so you don't have to restart.
// See https://github.com/facebookincubator/create-react-app/issues/186
new WatchMissingNodeModulesPlugin(paths.appNodeModules)
],
// Some libraries import Node modules but don't use them in the browser.
// Tell Webpack to provide empty mocks for them so importing them works.
node: {
fs: 'empty',
net: 'empty',
tls: 'empty'
}
};

View File

@ -1,281 +0,0 @@
'use strict';
var autoprefixer = require('autoprefixer');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var ManifestPlugin = require('webpack-manifest-plugin');
var InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
var paths = require('./paths');
var path = require('path');
var fs = require('fs')
var getClientEnvironment = require('./env');
var SentryPlugin = require('webpack-sentry-plugin');
// Webpack uses `publicPath` to determine where the app is being served from.
// It requires a trailing slash, or the file assets will get an incorrect path.
var publicPath = paths.servedPath;
// Some apps do not use client-side routing with pushState.
// For these, "homepage" can be set to "." to enable relative asset paths.
var shouldUseRelativeAssetPaths = publicPath === './';
// `publicUrl` is just like `publicPath`, but we will provide it to our app
// as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
// Omit trailing slash as %PUBLIC_URL%/xyz looks better than %PUBLIC_URL%xyz.
var publicUrl = publicPath.slice(0, -1);
// Get environment variables to inject into our app.
var env = getClientEnvironment(publicUrl);
// Assert this just to be safe.
// Development builds of React are slow and not intended for production.
if (env.stringified['process.env'].NODE_ENV !== '"production"') {
throw new Error('Production builds must have NODE_ENV=production.');
}
// Note: defined here because it will be used more than once.
const cssFilename = 'static/css/[name].[contenthash:8].css';
// ExtractTextPlugin expects the build output to be flat.
// (See https://github.com/webpack-contrib/extract-text-webpack-plugin/issues/27)
// However, our output is structured with css, js and media folders.
// To have this structure working with relative paths, we have to use custom options.
const extractTextPluginOptions = shouldUseRelativeAssetPaths
// Making sure that the publicPath goes back to to build folder.
? { publicPath: Array(cssFilename.split('/').length).join('../') }
: undefined;
// This is the production configuration.
// It compiles slowly and is focused on producing a fast and minimal bundle.
// The development configuration is different and lives in a separate file.
module.exports = {
// Don't attempt to continue if there are any errors.
bail: true,
// We generate sourcemaps in production. This is slow but gives good results.
// You can exclude the *.map files from the build during deployment.
devtool: 'source-map',
// In production, we only want to load the polyfills and the app code.
entry: [
require.resolve('./polyfills'),
paths.appIndexJs
],
output: {
// The build folder.
path: paths.appBuild,
// Generated JS file names (with nested folders).
// There will be one main bundle, and one file per asynchronous chunk.
// We don't currently advertise code splitting but Webpack supports it.
filename: 'static/js/[name].[hash:8].js',
chunkFilename: 'static/js/[name].[chunkhash:8].chunk.js',
// We inferred the "public path" (such as / or /my-project) from homepage.
publicPath: publicPath
},
resolve: {
// This allows you to set a fallback for where Webpack should look for modules.
// We read `NODE_PATH` environment variable in `paths.js` and pass paths here.
// We use `fallback` instead of `root` because we want `node_modules` to "win"
// if there any conflicts. This matches Node resolution mechanism.
// https://github.com/facebookincubator/create-react-app/issues/253
fallback: paths.nodePaths,
// These are the reasonable defaults supported by the Node ecosystem.
// We also include JSX as a common component filename extension to support
// some tools, although we do not recommend using it, see:
// https://github.com/facebookincubator/create-react-app/issues/290
extensions: ['.js', '.json', '.jsx', ''],
alias: {
// Support React Native Web
// https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
'react-native': 'react-native-web'
}
},
module: {
// First, run the linter.
// It's important to do this before Babel processes the JS.
preLoaders: [
{
test: /\.(js|jsx)$/,
loader: 'eslint',
include: paths.appSrc
}
],
loaders: [
// ** ADDING/UPDATING LOADERS **
// The "url" loader handles all assets unless explicitly excluded.
// The `exclude` list *must* be updated with every change to loader extensions.
// When adding a new loader, you must add its `test`
// as a new entry in the `exclude` list in the "url" loader.
// "url" loader embeds assets smaller than specified size as data URLs to avoid requests.
// Otherwise, it acts like the "file" loader.
{
exclude: [
/\.html$/,
/\.(js|jsx)$/,
/\.css$/,
/\.json$/,
/\.svg$/,
/\.png$/
],
loader: 'url',
query: {
limit: 10000,
name: 'static/media/[name].[hash:8].[ext]'
}
},
// Process JS with Babel.
{
test: /\.(js|jsx)$/,
include: paths.appSrc,
loader: 'babel',
},
{
test: /\.(js|jsx)$/,
include: path.resolve(fs.realpathSync(process.cwd()), 'node_modules/streamsaver'),
loader: 'babel',
},
// The notation here is somewhat confusing.
// "postcss" loader applies autoprefixer to our CSS.
// "css" loader resolves paths in CSS and adds assets as dependencies.
// "style" loader normally turns CSS into JS modules injecting <style>,
// but unlike in development configuration, we do something different.
// `ExtractTextPlugin` first applies the "postcss" and "css" loaders
// (second argument), then grabs the result CSS and puts it into a
// separate file in our build process. This way we actually ship
// a single CSS file in production instead of JS code injecting <style>
// tags. If you use code splitting, however, any async bundles will still
// use the "style" loader inside the async code so CSS from them won't be
// in the main CSS file.
{
test: /\.css$/,
loader: ExtractTextPlugin.extract(
'style',
'css?importLoaders=1!postcss',
extractTextPluginOptions
)
// Note: this won't work without `new ExtractTextPlugin()` in `plugins`.
},
// JSON is not enabled by default in Webpack but both Node and Browserify
// allow it implicitly so we also enable it.
{
test: /\.json$/,
loader: 'json'
},
// "file" loader for svg
{
test: /\.svg$/,
loader: 'file',
query: {
name: 'static/media/[name].[hash:8].[ext]'
}
},
{
test: /worker\.js$/,
loaders: ['worker-loader', 'babel-loader'],
include: paths.appSrc,
use: [
{ loader: 'worker-loader' },
{ loader: 'babel-loader' }
]
},
{
// static image loader
test: /\.png$/,
loader: 'base64-inline-loader?name=[name].[ext]'
}
// ** STOP ** Are you adding a new loader?
// Remember to add the new extension(s) to the "url" loader exclusion list.
]
},
// We use PostCSS for autoprefixing only.
postcss: function() {
return [
autoprefixer({
browsers: [
'>1%',
'last 4 versions',
'Firefox ESR',
'not ie < 9', // React doesn't support IE8 anyway
]
}),
];
},
plugins: [
// Makes some environment variables available in index.html.
// The public URL is available as %PUBLIC_URL% in index.html, e.g.:
// <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
// In production, it will be an empty string unless you specify "homepage"
// in `package.json`, in which case it will be the pathname of that URL.
new InterpolateHtmlPlugin(env.raw),
// Generates an `index.html` file with the <script> injected.
new HtmlWebpackPlugin({
inject: true,
template: paths.appHtml,
minify: {
removeComments: true,
collapseWhitespace: true,
removeRedundantAttributes: true,
useShortDoctype: true,
removeEmptyAttributes: true,
removeStyleLinkTypeAttributes: true,
keepClosingSlash: true,
minifyJS: true,
minifyCSS: true,
minifyURLs: true
}
}),
// Makes some environment variables available to the JS code, for example:
// if (process.env.NODE_ENV === 'production') { ... }. See `./env.js`.
// It is absolutely essential that NODE_ENV was set to production here.
// Otherwise React will be compiled in the very slow development mode.
new webpack.DefinePlugin(env.stringified),
// This helps ensure the builds are consistent if source hasn't changed:
new webpack.optimize.OccurrenceOrderPlugin(),
// Try to dedupe duplicated modules, if any:
new webpack.optimize.DedupePlugin(),
// Minify the code.
new webpack.optimize.UglifyJsPlugin({
compress: {
screw_ie8: true, // React doesn't support IE8
warnings: false
},
mangle: {
screw_ie8: true
},
output: {
comments: false,
screw_ie8: true
}
}),
// Note: this won't work without ExtractTextPlugin.extract(..) in `loaders`.
new ExtractTextPlugin(cssFilename),
// Generate a manifest file which contains a mapping of all asset filenames
// to their corresponding output file so that tools can pick it up without
// having to parse `index.html`.
new ManifestPlugin({
fileName: 'asset-manifest.json'
}),
new SentryPlugin({
organisation: 'commaai',
project: 'cabana',
apiKey: '7a932ab144984dd3979993cf61dbdd2a1489ac77af4d4f46b85d64598b9a4ca6',
release: function(hash) {
return hash; // webpack build hash
},
filenameTransform: function(filename) {
return `~${publicUrl}/${filename}`;
},
suppressConflictError: true
}),
new webpack.ExtendedAPIPlugin()
],
// Some libraries import Node modules but don't use them in the browser.
// Tell Webpack to provide empty mocks for them so importing them works.
node: {
fs: 'empty',
net: 'empty',
tls: 'empty'
}
};

View File

@ -23,113 +23,40 @@
"moment": "^2.18.1", "moment": "^2.18.1",
"prop-types": "^15.5.10", "prop-types": "^15.5.10",
"raven-js": "^3.16.0", "raven-js": "^3.16.0",
"react": "^15.6.1", "react": "^16.2.0",
"react-dom": "^15.6.1", "react-app-rewired": "^1.3.8",
"react-dom": "^16.2.0",
"react-infinite": "^0.11.0", "react-infinite": "^0.11.0",
"react-list": "^0.8.6", "react-list": "^0.8.6",
"react-measure": "^2.0.2", "react-measure": "^2.0.2",
"react-scripts": "1.0.17",
"react-test-renderer": "^15.6.1", "react-test-renderer": "^15.6.1",
"react-vega": "^3.0.0", "react-vega": "^3.0.0",
"react-visibility-sensor": "^3.10.1", "react-visibility-sensor": "^3.10.1",
"simple-statistics": "^4.1.0", "simple-statistics": "^4.1.0",
"socket.io-client": "^2.0.3", "socket.io-client": "^2.0.3",
"streamsaver": "^1.0.1", "streamsaver": "^1.0.1",
"vega": "git+ssh://git@github.com/commaai/vega.git#HEAD", "vega": "3.0.0",
"vega-tooltip": "^0.4.0" "vega-tooltip": "^0.4.0"
}, },
"devDependencies": { "devDependencies": {
"autoprefixer": "6.7.2",
"babel-core": "6.22.1",
"babel-eslint": "7.1.1",
"babel-jest": "18.0.0",
"babel-loader": "6.2.10",
"babel-preset-react-app": "^2.2.0",
"babel-runtime": "^6.20.0",
"case-sensitive-paths-webpack-plugin": "1.1.4",
"chalk": "1.1.3",
"connect-history-api-fallback": "1.3.0", "connect-history-api-fallback": "1.3.0",
"cross-spawn": "4.0.2", "cross-spawn": "4.0.2",
"css-loader": "0.26.1",
"detect-port": "1.1.0", "detect-port": "1.1.0",
"dotenv": "2.0.0", "dotenv": "2.0.0",
"enzyme": "^2.9.1", "enzyme": "^2.9.1",
"eslint": "3.16.1",
"eslint-config-react-app": "^0.6.2",
"eslint-loader": "1.6.0",
"eslint-plugin-flowtype": "2.21.0",
"eslint-plugin-import": "2.0.1",
"eslint-plugin-jsx-a11y": "4.0.0",
"eslint-plugin-react": "6.4.1",
"extract-text-webpack-plugin": "1.0.1",
"file-loader": "0.10.0",
"fs-extra": "0.30.0",
"html-webpack-plugin": "2.24.0",
"http-proxy-middleware": "0.17.3", "http-proxy-middleware": "0.17.3",
"jest": "18.1.0",
"json-loader": "0.5.4", "json-loader": "0.5.4",
"object-assign": "4.1.1",
"postcss-loader": "1.2.2",
"promise": "7.1.1",
"react-dev-utils": "^0.5.2",
"style-loader": "0.13.1",
"url-loader": "0.5.7",
"url-toolkit": "^2.1.1", "url-toolkit": "^2.1.1",
"webpack": "1.14.0",
"webpack-dev-server": "1.16.2",
"webpack-manifest-plugin": "1.1.0",
"webpack-sentry-plugin": "^1.14.0", "webpack-sentry-plugin": "^1.14.0",
"webworkify": "^1.4.0", "webworkify": "^1.4.0",
"whatwg-fetch": "2.0.2",
"worker-loader": "^0.8.0" "worker-loader": "^0.8.0"
}, },
"scripts": { "scripts": {
"start": "python simple-cors-http-server.py & python server.py & npm run sass & node scripts/start.js", "start": "react-app-rewired start",
"build": "node scripts/build.js", "build": "react-app-rewired build",
"test": "node scripts/test.js --env=jsdom", "test": "react-app-rewired test --env=jsdom",
"sass": "scss src/index.scss:src/index.css; sass --watch src/index.scss:src/index.css" "sass":
}, "scss src/index.scss:src/index.css; sass --watch src/index.scss:src/index.css"
"esLintConfig": {
"rules": {
"no-use-before-define": "off"
}
},
"jest": {
"globals": {
"config": {
"__JEST__": 1
}
},
"timers": "fake",
"collectCoverageFrom": [
"src/**/*.{js,jsx}"
],
"setupFiles": [
"<rootDir>/config/polyfills.js"
],
"testPathIgnorePatterns": [
"<rootDir>[/\\\\](build|docs|node_modules|scripts)[/\\\\]",
"<rootDir>/src/__tests__/res"
],
"testEnvironment": "node",
"testURL": "http://localhost",
"transform": {
"^.+\\.(js|jsx)$": "<rootDir>/node_modules/babel-jest",
"^.+\\.css$": "<rootDir>/config/jest/cssTransform.js",
"^(?!.*\\.(js|jsx|css|json)$)": "<rootDir>/config/jest/fileTransform.js"
},
"transformIgnorePatterns": [
"[/\\\\]node_modules[/\\\\].+\\.(js|jsx)$"
],
"moduleNameMapper": {
"^react-native$": "react-native-web"
}
},
"babel": {
"presets": [
"react-app"
]
},
"eslintConfig": {
"extends": "react-app"
} }
} }

View File

@ -1,21 +1,40 @@
<!doctype html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>comma cabana</title> <meta name="theme-color" content="#000000">
<!--
manifest.json provides metadata used when your web app is added to the
homescreen on Android. See https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json">
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head> </head>
<body> <body>
<noscript>
You need to enable JavaScript to run this app.
</noscript>
<div id="root"></div> <div id="root"></div>
<script> <!--
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ This HTML file is a template.
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), If you open it directly in the browser, you will see an empty page.
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-80079182-4', 'auto'); You can add webfonts, meta tags, or analytics to this file.
ga('send', 'pageview'); The build step will place the bundled scripts into the <body> tag.
</script> To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body> </body>
</html> </html>

View File

@ -0,0 +1,15 @@
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
}
],
"start_url": "./index.html",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}

View File

@ -1,158 +0,0 @@
'use strict';
// Do this as the first thing so that any code reading it knows the right env.
process.env.NODE_ENV = 'production';
// Load environment variables from .env file. Suppress warnings using silent
// if this file is missing. dotenv will never modify any environment variables
// that have already been set.
// https://github.com/motdotla/dotenv
require('dotenv').config({silent: true});
var chalk = require('chalk');
var fs = require('fs-extra');
var path = require('path');
var url = require('url');
var webpack = require('webpack');
var config = require('../config/webpack.config.prod');
var paths = require('../config/paths');
var checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
var FileSizeReporter = require('react-dev-utils/FileSizeReporter');
var measureFileSizesBeforeBuild = FileSizeReporter.measureFileSizesBeforeBuild;
var printFileSizesAfterBuild = FileSizeReporter.printFileSizesAfterBuild;
var useYarn = fs.existsSync(paths.yarnLockFile);
// Warn and crash if required files are missing
if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
process.exit(1);
}
// First, read the current file sizes in build directory.
// This lets us display how much they changed later.
measureFileSizesBeforeBuild(paths.appBuild).then(previousFileSizes => {
// Remove all content but keep the directory so that
// if you're in it, you don't end up in Trash
fs.emptyDirSync(paths.appBuild);
// Start the webpack build
build(previousFileSizes);
// Merge with the public folder
copyPublicFolder();
});
// Print out errors
function printErrors(summary, errors) {
console.log(chalk.red(summary));
console.log();
errors.forEach(err => {
console.log(err.message || err);
console.log();
});
}
// Create the production build and print the deployment instructions.
function build(previousFileSizes) {
console.log('Creating an optimized production build...');
webpack(config).run((err, stats) => {
if (err) {
printErrors('Failed to compile.', [err]);
process.exit(1);
}
if (stats.compilation.errors.length) {
printErrors('Failed to compile.', stats.compilation.errors);
process.exit(1);
}
if (process.env.CI && stats.compilation.warnings.length) {
printErrors('Failed to compile. When process.env.CI = true, warnings are treated as failures. Most CI servers set this automatically.', stats.compilation.warnings);
process.exit(1);
}
console.log(chalk.green('Compiled successfully.'));
console.log();
console.log('File sizes after gzip:');
console.log();
printFileSizesAfterBuild(stats, previousFileSizes);
console.log();
var appPackage = require(paths.appPackageJson);
var publicUrl = paths.publicUrl;
var publicPath = config.output.publicPath;
var publicPathname = url.parse(publicPath).pathname;
if (publicUrl && publicUrl.indexOf('.github.io/') !== -1) {
// "homepage": "http://user.github.io/project"
console.log('The project was built assuming it is hosted at ' + chalk.green(publicPathname) + '.');
console.log('You can control this with the ' + chalk.green('homepage') + ' field in your ' + chalk.cyan('package.json') + '.');
console.log();
console.log('The ' + chalk.cyan('build') + ' folder is ready to be deployed.');
console.log('To publish it at ' + chalk.green(publicUrl) + ', run:');
// If script deploy has been added to package.json, skip the instructions
if (typeof appPackage.scripts.deploy === 'undefined') {
console.log();
if (useYarn) {
console.log(' ' + chalk.cyan('yarn') + ' add --dev gh-pages');
} else {
console.log(' ' + chalk.cyan('npm') + ' install --save-dev gh-pages');
}
console.log();
console.log('Add the following script in your ' + chalk.cyan('package.json') + '.');
console.log();
console.log(' ' + chalk.dim('// ...'));
console.log(' ' + chalk.yellow('"scripts"') + ': {');
console.log(' ' + chalk.dim('// ...'));
console.log(' ' + chalk.yellow('"predeploy"') + ': ' + chalk.yellow('"npm run build",'));
console.log(' ' + chalk.yellow('"deploy"') + ': ' + chalk.yellow('"gh-pages -d build"'));
console.log(' }');
console.log();
console.log('Then run:');
}
console.log();
console.log(' ' + chalk.cyan(useYarn ? 'yarn' : 'npm') + ' run deploy');
console.log();
} else if (publicPath !== '/') {
// "homepage": "http://mywebsite.com/project"
console.log('The project was built assuming it is hosted at ' + chalk.green(publicPath) + '.');
console.log('You can control this with the ' + chalk.green('homepage') + ' field in your ' + chalk.cyan('package.json') + '.');
console.log();
console.log('The ' + chalk.cyan('build') + ' folder is ready to be deployed.');
console.log();
} else {
if (publicUrl) {
// "homepage": "http://mywebsite.com"
console.log('The project was built assuming it is hosted at ' + chalk.green(publicUrl) + '.');
console.log('You can control this with the ' + chalk.green('homepage') + ' field in your ' + chalk.cyan('package.json') + '.');
console.log();
} else {
// no homepage
console.log('The project was built assuming it is hosted at the server root.');
console.log('To override this, specify the ' + chalk.green('homepage') + ' in your ' + chalk.cyan('package.json') + '.');
console.log('For example, add this to build it for GitHub Pages:')
console.log();
console.log(' ' + chalk.green('"homepage"') + chalk.cyan(': ') + chalk.green('"http://myname.github.io/myapp"') + chalk.cyan(','));
console.log();
}
var build = path.relative(process.cwd(), paths.appBuild);
console.log('The ' + chalk.cyan(build) + ' folder is ready to be deployed.');
console.log('You may serve it with a static server:');
console.log();
if (useYarn) {
console.log(` ${chalk.cyan('yarn')} global add serve`);
} else {
console.log(` ${chalk.cyan('npm')} install -g serve`);
}
console.log(` ${chalk.cyan('serve')} -s build`);
console.log();
}
});
}
function copyPublicFolder() {
fs.copySync(paths.appPublic, paths.appBuild, {
dereference: true,
filter: file => file !== paths.appHtml
});
}

View File

@ -1,316 +0,0 @@
'use strict';
process.env.NODE_ENV = 'development';
// Load environment variables from .env file. Suppress warnings using silent
// if this file is missing. dotenv will never modify any environment variables
// that have already been set.
// https://github.com/motdotla/dotenv
require('dotenv').config({silent: true});
var chalk = require('chalk');
var webpack = require('webpack');
var WebpackDevServer = require('webpack-dev-server');
var historyApiFallback = require('connect-history-api-fallback');
var httpProxyMiddleware = require('http-proxy-middleware');
var detect = require('detect-port');
var clearConsole = require('react-dev-utils/clearConsole');
var checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
var formatWebpackMessages = require('react-dev-utils/formatWebpackMessages');
var getProcessForPort = require('react-dev-utils/getProcessForPort');
var openBrowser = require('react-dev-utils/openBrowser');
var prompt = require('react-dev-utils/prompt');
var fs = require('fs');
var config = require('../config/webpack.config.dev');
var paths = require('../config/paths');
var useYarn = fs.existsSync(paths.yarnLockFile);
var cli = useYarn ? 'yarn' : 'npm';
var isInteractive = process.stdout.isTTY;
// Warn and crash if required files are missing
if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
process.exit(1);
}
// Tools like Cloud9 rely on this.
var DEFAULT_PORT = parseInt(process.env.PORT, 10) || 3000;
var compiler;
var handleCompile;
// You can safely remove this after ejecting.
// We only use this block for testing of Create React App itself:
var isSmokeTest = process.argv.some(arg => arg.indexOf('--smoke-test') > -1);
if (isSmokeTest) {
handleCompile = function (err, stats) {
if (err || stats.hasErrors() || stats.hasWarnings()) {
process.exit(1);
} else {
process.exit(0);
}
};
}
function setupCompiler(host, port, protocol) {
// "Compiler" is a low-level interface to Webpack.
// It lets us listen to some events and provide our own custom messages.
compiler = webpack(config, handleCompile);
// "invalid" event fires when you have changed a file, and Webpack is
// recompiling a bundle. WebpackDevServer takes care to pause serving the
// bundle, so if you refresh, it'll wait instead of serving the old one.
// "invalid" is short for "bundle invalidated", it doesn't imply any errors.
compiler.plugin('invalid', function() {
if (isInteractive) {
clearConsole();
}
console.log('Compiling...');
});
var isFirstCompile = true;
// "done" event fires when Webpack has finished recompiling the bundle.
// Whether or not you have warnings or errors, you will get this event.
compiler.plugin('done', function(stats) {
if (isInteractive) {
clearConsole();
}
// We have switched off the default Webpack output in WebpackDevServer
// options so we are going to "massage" the warnings and errors and present
// them in a readable focused way.
var messages = formatWebpackMessages(stats.toJson({}, true));
var isSuccessful = !messages.errors.length && !messages.warnings.length;
var showInstructions = isSuccessful && (isInteractive || isFirstCompile);
if (isSuccessful) {
console.log(chalk.green('Compiled successfully!'));
}
if (showInstructions) {
console.log();
console.log('The app is running at:');
console.log();
console.log(' ' + chalk.cyan(protocol + '://' + host + ':' + port + '/'));
console.log();
console.log('Note that the development build is not optimized.');
console.log('To create a production build, use ' + chalk.cyan(cli + ' run build') + '.');
console.log();
isFirstCompile = false;
}
// If errors exist, only show errors.
if (messages.errors.length) {
console.log(chalk.red('Failed to compile.'));
console.log();
messages.errors.forEach(message => {
console.log(message);
console.log();
});
return;
}
// Show warnings if no errors were found.
if (messages.warnings.length) {
console.log(chalk.yellow('Compiled with warnings.'));
console.log();
messages.warnings.forEach(message => {
console.log(message);
console.log();
});
// Teach some ESLint tricks.
console.log('You may use special comments to disable some warnings.');
console.log('Use ' + chalk.yellow('// eslint-disable-next-line') + ' to ignore the next line.');
console.log('Use ' + chalk.yellow('/* eslint-disable */') + ' to ignore all warnings in a file.');
}
});
}
// We need to provide a custom onError function for httpProxyMiddleware.
// It allows us to log custom error messages on the console.
function onProxyError(proxy) {
return function(err, req, res){
var host = req.headers && req.headers.host;
console.log(
chalk.red('Proxy error:') + ' Could not proxy request ' + chalk.cyan(req.url) +
' from ' + chalk.cyan(host) + ' to ' + chalk.cyan(proxy) + '.'
);
console.log(
'See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (' +
chalk.cyan(err.code) + ').'
);
console.log();
// And immediately send the proper error response to the client.
// Otherwise, the request will eventually timeout with ERR_EMPTY_RESPONSE on the client side.
if (res.writeHead && !res.headersSent) {
res.writeHead(500);
}
res.end('Proxy error: Could not proxy request ' + req.url + ' from ' +
host + ' to ' + proxy + ' (' + err.code + ').'
);
}
}
function addMiddleware(devServer) {
// `proxy` lets you to specify a fallback server during development.
// Every unrecognized request will be forwarded to it.
var proxy = require(paths.appPackageJson).proxy;
devServer.use(historyApiFallback({
// Paths with dots should still use the history fallback.
// See https://github.com/facebookincubator/create-react-app/issues/387.
disableDotRule: true,
// For single page apps, we generally want to fallback to /index.html.
// However we also want to respect `proxy` for API calls.
// So if `proxy` is specified, we need to decide which fallback to use.
// We use a heuristic: if request `accept`s text/html, we pick /index.html.
// Modern browsers include text/html into `accept` header when navigating.
// However API calls like `fetch()` wont generally accept text/html.
// If this heuristic doesnt work well for you, dont use `proxy`.
htmlAcceptHeaders: proxy ?
['text/html'] :
['text/html', '*/*']
}));
if (proxy) {
if (typeof proxy !== 'string') {
console.log(chalk.red('When specified, "proxy" in package.json must be a string.'));
console.log(chalk.red('Instead, the type of "proxy" was "' + typeof proxy + '".'));
console.log(chalk.red('Either remove "proxy" from package.json, or make it a string.'));
process.exit(1);
}
// Otherwise, if proxy is specified, we will let it handle any request.
// There are a few exceptions which we won't send to the proxy:
// - /index.html (served as HTML5 history API fallback)
// - /*.hot-update.json (WebpackDevServer uses this too for hot reloading)
// - /sockjs-node/* (WebpackDevServer uses this for hot reloading)
// Tip: use https://jex.im/regulex/ to visualize the regex
var mayProxy = /^(?!\/(index\.html$|.*\.hot-update\.json$|sockjs-node\/)).*$/;
// Pass the scope regex both to Express and to the middleware for proxying
// of both HTTP and WebSockets to work without false positives.
var hpm = httpProxyMiddleware(pathname => mayProxy.test(pathname), {
target: proxy,
logLevel: 'silent',
onProxyReq: function(proxyReq) {
// Browers may send Origin headers even with same-origin
// requests. To prevent CORS issues, we have to change
// the Origin to match the target URL.
if (proxyReq.getHeader('origin')) {
proxyReq.setHeader('origin', proxy);
}
},
onError: onProxyError(proxy),
secure: false,
changeOrigin: true,
ws: true,
xfwd: true
});
devServer.use(mayProxy, hpm);
// Listen for the websocket 'upgrade' event and upgrade the connection.
// If this is not done, httpProxyMiddleware will not try to upgrade until
// an initial plain HTTP request is made.
devServer.listeningApp.on('upgrade', hpm.upgrade);
}
// Finally, by now we have certainly resolved the URL.
// It may be /index.html, so let the dev server try serving it again.
devServer.use(devServer.middleware);
}
function runDevServer(host, port, protocol) {
var devServer = new WebpackDevServer(compiler, {
// Enable gzip compression of generated files.
compress: true,
// Silence WebpackDevServer's own logs since they're generally not useful.
// It will still show compile warnings and errors with this setting.
clientLogLevel: 'none',
// By default WebpackDevServer serves physical files from current directory
// in addition to all the virtual build products that it serves from memory.
// This is confusing because those files wont automatically be available in
// production build folder unless we copy them. However, copying the whole
// project directory is dangerous because we may expose sensitive files.
// Instead, we establish a convention that only files in `public` directory
// get served. Our build script will copy `public` into the `build` folder.
// In `index.html`, you can get URL of `public` folder with %PUBLIC_URL%:
// <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
// In JavaScript code, you can access it with `process.env.PUBLIC_URL`.
// Note that we only recommend to use `public` folder as an escape hatch
// for files like `favicon.ico`, `manifest.json`, and libraries that are
// for some reason broken when imported through Webpack. If you just want to
// use an image, put it in `src` and `import` it from JavaScript instead.
contentBase: paths.appPublic,
// Enable hot reloading server. It will provide /sockjs-node/ endpoint
// for the WebpackDevServer client so it can learn when the files were
// updated. The WebpackDevServer client is included as an entry point
// in the Webpack development configuration. Note that only changes
// to CSS are currently hot reloaded. JS changes will refresh the browser.
hot: true,
// It is important to tell WebpackDevServer to use the same "root" path
// as we specified in the config. In development, we always serve from /.
publicPath: config.output.publicPath,
// WebpackDevServer is noisy by default so we emit custom message instead
// by listening to the compiler events with `compiler.plugin` calls above.
quiet: true,
// Reportedly, this avoids CPU overload on some systems.
// https://github.com/facebookincubator/create-react-app/issues/293
watchOptions: {
ignored: /node_modules/
},
// Enable HTTPS if the HTTPS environment variable is set to 'true'
https: protocol === "https",
host: host
});
// Our custom middleware proxies requests to /index.html or a remote API.
addMiddleware(devServer);
// Launch WebpackDevServer.
devServer.listen(port, err => {
if (err) {
return console.log(err);
}
if (isInteractive) {
clearConsole();
}
console.log(chalk.cyan('Starting the development server...'));
console.log();
openBrowser(protocol + '://' + host + ':' + port + '/');
});
}
function run(port) {
var protocol = process.env.HTTPS === 'true' ? "https" : "http";
var host = process.env.HOST || 'localhost';
setupCompiler(host, port, protocol);
runDevServer(host, port, protocol);
}
// We attempt to use the default port but if it is busy, we offer the user to
// run on a different port. `detect()` Promise resolves to the next free port.
detect(DEFAULT_PORT).then(port => {
if (port === DEFAULT_PORT) {
run(port);
return;
}
if (isInteractive) {
clearConsole();
var existingProcess = getProcessForPort(DEFAULT_PORT);
var question =
chalk.yellow('Something is already running on port ' + DEFAULT_PORT + '.' +
((existingProcess) ? ' Probably:\n ' + existingProcess : '')) +
'\n\nWould you like to run the app on another port instead?';
prompt(question, true).then(shouldChangePort => {
if (shouldChangePort) {
run(port);
}
});
} else {
console.log(chalk.red('Something is already running on port ' + DEFAULT_PORT + '.'));
}
});

View File

@ -1,21 +0,0 @@
'use strict';
process.env.NODE_ENV = 'test';
process.env.PUBLIC_URL = '';
// Load environment variables from .env file. Suppress warnings using silent
// if this file is missing. dotenv will never modify any environment variables
// that have already been set.
// https://github.com/motdotla/dotenv
require('dotenv').config({silent: true});
const jest = require('jest');
const argv = process.argv.slice(2);
// Watch unless on CI or in coverage mode
if (!process.env.CI && argv.indexOf('--coverage') < 0) {
argv.push('--watch');
}
jest.run(argv);

View File

@ -1,12 +0,0 @@
#!/usr/bin/env python2
from SimpleHTTPServer import SimpleHTTPRequestHandler
import BaseHTTPServer
class CORSRequestHandler (SimpleHTTPRequestHandler):
def end_headers (self):
self.send_header('Access-Control-Allow-Origin', '*')
SimpleHTTPRequestHandler.end_headers(self)
if __name__ == '__main__':
BaseHTTPServer.test(CORSRequestHandler, BaseHTTPServer.HTTPServer)

View File

@ -1,37 +1,39 @@
import React, { Component } from 'react'; import React, { Component } from "react";
import Moment from 'moment'; import Moment from "moment";
import PropTypes from 'prop-types'; import PropTypes from "prop-types";
import {USE_UNLOGGER, PART_SEGMENT_LENGTH, STREAMING_WINDOW} from './config'; import { USE_UNLOGGER, PART_SEGMENT_LENGTH, STREAMING_WINDOW } from "./config";
import * as GithubAuth from './api/github-auth'; import * as GithubAuth from "./api/github-auth";
import cx from 'classnames'; import cx from "classnames";
import { createWriteStream, supported, version } from 'streamsaver' import { createWriteStream, supported, version } from "streamsaver";
import auth from "./api/comma-auth";
import auth from './api/comma-auth'; import DBC from "./models/can/dbc";
import DBC from './models/can/dbc'; import Meta from "./components/Meta";
import Meta from './components/Meta'; import Explorer from "./components/Explorer";
import Explorer from './components/Explorer'; import * as Routes from "./api/routes";
import * as Routes from './api/routes'; import OnboardingModal from "./components/Modals/OnboardingModal";
import OnboardingModal from './components/Modals/OnboardingModal'; import SaveDbcModal from "./components/SaveDbcModal";
import SaveDbcModal from './components/SaveDbcModal'; import LoadDbcModal from "./components/LoadDbcModal";
import LoadDbcModal from './components/LoadDbcModal'; import debounce from "./utils/debounce";
const CanFetcher = require('./workers/can-fetcher.worker.js'); import EditMessageModal from "./components/EditMessageModal";
const LogCSVDownloader = require('./workers/dbc-csv-downloader.worker.js'); import LoadingBar from "./components/LoadingBar";
const MessageParser = require("./workers/message-parser.worker.js"); import {
const CanOffsetFinder = require('./workers/can-offset-finder.worker.js'); persistDbc,
const CanStreamerWorker = require('./workers/CanStreamerWorker.worker.js');
import debounce from './utils/debounce';
import EditMessageModal from './components/EditMessageModal';
import LoadingBar from './components/LoadingBar';
import {persistDbc,
fetchPersistedDbc, fetchPersistedDbc,
unpersistGithubAuthToken} from './api/localstorage'; unpersistGithubAuthToken
import OpenDbc from './api/OpenDbc'; } from "./api/localstorage";
import UnloggerClient from './api/unlogger'; import OpenDbc from "./api/OpenDbc";
import PandaReader from './api/panda-reader'; import UnloggerClient from "./api/unlogger";
import * as ObjectUtils from './utils/object'; import PandaReader from "./api/panda-reader";
import {hash} from './utils/string'; import * as ObjectUtils from "./utils/object";
import { hash } from "./utils/string";
const CanFetcher = require("./workers/can-fetcher.worker.js");
const LogCSVDownloader = require("./workers/dbc-csv-downloader.worker.js");
const MessageParser = require("./workers/message-parser.worker.js");
const CanOffsetFinder = require("./workers/can-offset-finder.worker.js");
const CanStreamerWorker = require("./workers/CanStreamerWorker.worker.js");
export default class CanExplorer extends Component { export default class CanExplorer extends Component {
static propTypes = { static propTypes = {
@ -42,7 +44,7 @@ export default class CanExplorer extends Component {
githubAuthToken: PropTypes.string, githubAuthToken: PropTypes.string,
autoplay: PropTypes.bool, autoplay: PropTypes.bool,
max: PropTypes.number, max: PropTypes.number,
url: PropTypes.string, url: PropTypes.string
}; };
constructor(props) { constructor(props) {
@ -62,9 +64,9 @@ export default class CanExplorer extends Component {
showSaveDbc: false, showSaveDbc: false,
showEditMessageModal: false, showEditMessageModal: false,
editMessageModalMessage: null, editMessageModalMessage: null,
dbc: (props.dbc ? props.dbc : new DBC()), dbc: props.dbc ? props.dbc : new DBC(),
dbcText: (props.dbc ? props.dbc.text() : (new DBC()).text()), dbcText: props.dbc ? props.dbc.text() : new DBC().text(),
dbcFilename: (props.dbcFilename ? props.dbcFilename : 'New_DBC'), dbcFilename: props.dbcFilename ? props.dbcFilename : "New_DBC",
dbcLastSaved: null, dbcLastSaved: null,
seekTime: 0, seekTime: 0,
seekIndex: 0, seekIndex: 0,
@ -75,7 +77,8 @@ export default class CanExplorer extends Component {
attemptingPandaConnection: false, attemptingPandaConnection: false,
pandaNoDeviceSelected: false, pandaNoDeviceSelected: false,
live: false, live: false,
isGithubAuthenticated: props.githubAuthToken !== null && props.githubAuthToken !== undefined, isGithubAuthenticated:
props.githubAuthToken !== null && props.githubAuthToken !== undefined
}; };
this.openDbcClient = new OpenDbc(props.githubAuthToken); this.openDbcClient = new OpenDbc(props.githubAuthToken);
@ -105,8 +108,12 @@ export default class CanExplorer extends Component {
this.initCanData = this.initCanData.bind(this); this.initCanData = this.initCanData.bind(this);
this.updateSelectedMessages = this.updateSelectedMessages.bind(this); this.updateSelectedMessages = this.updateSelectedMessages.bind(this);
this.handlePandaConnect = this.handlePandaConnect.bind(this); this.handlePandaConnect = this.handlePandaConnect.bind(this);
this.processStreamedCanMessages = this.processStreamedCanMessages.bind(this); this.processStreamedCanMessages = this.processStreamedCanMessages.bind(
this.onStreamedCanMessagesProcessed = this.onStreamedCanMessagesProcessed.bind(this); this
);
this.onStreamedCanMessagesProcessed = this.onStreamedCanMessagesProcessed.bind(
this
);
this.showingModal = this.showingModal.bind(this); this.showingModal = this.showingModal.bind(this);
this.lastMessageEntriesById = this.lastMessageEntriesById.bind(this); this.lastMessageEntriesById = this.lastMessageEntriesById.bind(this);
this.githubSignOut = this.githubSignOut.bind(this); this.githubSignOut = this.githubSignOut.bind(this);
@ -118,31 +125,52 @@ export default class CanExplorer extends Component {
const { max, url } = this.props; const { max, url } = this.props;
const { startTime } = Routes.parseRouteName(name); const { startTime } = Routes.parseRouteName(name);
const route = {fullname: name, proclog: max, url: url, start_time: startTime}; const route = {
this.setState({route, currentParts: [0, Math.min(max - 1, PART_SEGMENT_LENGTH - 1)]}, this.initCanData); fullname: name,
proclog: max,
url: url,
start_time: startTime
};
this.setState(
{
route,
currentParts: [0, Math.min(max - 1, PART_SEGMENT_LENGTH - 1)]
},
this.initCanData
);
} else if (auth.isAuthenticated() && !name) { } else if (auth.isAuthenticated() && !name) {
Routes.fetchRoutes().then((routes) => { Routes.fetchRoutes()
.then(routes => {
const _routes = []; const _routes = [];
Object.keys(routes).forEach((route) => { Object.keys(routes).forEach(route => {
_routes.push(routes[route]); _routes.push(routes[route]);
}) });
this.setState({ routes: _routes }); this.setState({ routes: _routes });
if (!_routes[name]) { if (!_routes[name]) {
this.showOnboarding(); this.showOnboarding();
} }
}).catch((err) => { })
.catch(err => {
this.showOnboarding(); this.showOnboarding();
}); });
} else if (dongleId && name) { } else if (dongleId && name) {
Routes.fetchRoutes(dongleId).then((routes) => { Routes.fetchRoutes(dongleId)
.then(routes => {
if (routes && routes[name]) { if (routes && routes[name]) {
const route = routes[name]; const route = routes[name];
const newState = {route, currentParts: [0, Math.min(route.proclog - 1, PART_SEGMENT_LENGTH - 1)]}; const newState = {
route,
currentParts: [
0,
Math.min(route.proclog - 1, PART_SEGMENT_LENGTH - 1)
]
};
this.setState(newState, this.initCanData); this.setState(newState, this.initCanData);
} else { } else {
this.showOnboarding(); this.showOnboarding();
} }
}).catch((err) => { })
.catch(err => {
this.showOnboarding(); this.showOnboarding();
}); });
} else { } else {
@ -154,10 +182,12 @@ export default class CanExplorer extends Component {
const { route } = this.state; const { route } = this.state;
const offsetFinder = new CanOffsetFinder(); const offsetFinder = new CanOffsetFinder();
offsetFinder.postMessage({partCount: route.proclog, offsetFinder.postMessage({
base: route.url}); partCount: route.proclog,
base: route.url
});
offsetFinder.onmessage = (e) => { offsetFinder.onmessage = e => {
const { canFrameOffset, firstCanTime } = e.data; const { canFrameOffset, firstCanTime } = e.data;
this.setState({ canFrameOffset, firstCanTime }, () => { this.setState({ canFrameOffset, firstCanTime }, () => {
@ -172,16 +202,20 @@ export default class CanExplorer extends Component {
this.persistDbc({ dbcFilename, dbc }); this.persistDbc({ dbcFilename, dbc });
if (route) { if (route) {
this.setState({dbc, this.setState(
{
dbc,
dbcFilename, dbcFilename,
dbcText: dbc.text(), dbcText: dbc.text(),
partsLoaded: 0, partsLoaded: 0,
selectedMessage: null, selectedMessage: null,
messages: {}}, () => { messages: {}
},
() => {
// Pass DBC text to webworker b/c can't pass instance of es6 class // Pass DBC text to webworker b/c can't pass instance of es6 class
this.spawnWorker(this.state.currentParts); this.spawnWorker(this.state.currentParts);
}); }
);
} else { } else {
this.setState({ dbc, dbcFilename, dbcText: dbc.text(), messages: {} }); this.setState({ dbc, dbcFilename, dbcText: dbc.text(), messages: {} });
} }
@ -189,7 +223,7 @@ export default class CanExplorer extends Component {
onDbcSaved(dbcFilename) { onDbcSaved(dbcFilename) {
const dbcLastSaved = Moment(); const dbcLastSaved = Moment();
this.setState({dbcLastSaved, dbcFilename}) this.setState({ dbcLastSaved, dbcFilename });
this.hideSaveDbc(); this.hideSaveDbc();
} }
@ -200,30 +234,38 @@ export default class CanExplorer extends Component {
// } // }
downloadRawLogAsCSV = () => { downloadRawLogAsCSV = () => {
console.log('downloadRawLogAsCSV:start'); console.log("downloadRawLogAsCSV:start");
// Trigger file processing and dowload in worker // Trigger file processing and dowload in worker
const { firstCanTime, canFrameOffset, route, currentParts, dbcFilename } = this.state; const {
firstCanTime,
canFrameOffset,
route,
currentParts,
dbcFilename
} = this.state;
const worker = new LogCSVDownloader(); const worker = new LogCSVDownloader();
const fileStream = createWriteStream(`${dbcFilename.replace(/\.dbc/g, '-')}${+new Date()}.csv`) const fileStream = createWriteStream(
const writer = fileStream.getWriter() `${dbcFilename.replace(/\.dbc/g, "-")}${+new Date()}.csv`
const encoder = new TextEncoder() );
const writer = fileStream.getWriter();
const encoder = new TextEncoder();
worker.onmessage = e => { worker.onmessage = e => {
const { progress, logData, shouldClose } = e.data; const { progress, logData, shouldClose } = e.data;
if (shouldClose) { if (shouldClose) {
console.log('downloadRawLogAsCSV:close'); console.log("downloadRawLogAsCSV:close");
writer.close() writer.close();
return; return;
} }
const uint8array = encoder.encode(logData + "\n") const uint8array = encoder.encode(logData + "\n");
writer.write(uint8array) writer.write(uint8array);
} };
worker.postMessage({ worker.postMessage({
base: route.url, base: route.url,
parts: [0, route.proclog], parts: [0, route.proclog],
canStartTime: firstCanTime - canFrameOffset, canStartTime: firstCanTime - canFrameOffset
}); });
} };
addAndRehydrateMessages(newMessages, options) { addAndRehydrateMessages(newMessages, options) {
// Adds new message entries to messages state // Adds new message entries to messages state
@ -234,12 +276,17 @@ export default class CanExplorer extends Component {
const messages = { ...this.state.messages }; const messages = { ...this.state.messages };
for (var key in newMessages) { for (var key in newMessages) {
// add message // add message
if ((options.replace !== true) && key in messages) { if (options.replace !== true && key in messages) {
messages[key].entries = messages[key].entries.concat(newMessages[key].entries); messages[key].entries = messages[key].entries.concat(
messages[key].byteStateChangeCounts = newMessages[key].byteStateChangeCounts; newMessages[key].entries
);
messages[key].byteStateChangeCounts =
newMessages[key].byteStateChangeCounts;
} else { } else {
messages[key] = newMessages[key]; messages[key] = newMessages[key];
messages[key].frame = this.state.dbc.messages.get(messages[key].address); messages[key].frame = this.state.dbc.messages.get(
messages[key].address
);
} }
} }
@ -252,7 +299,10 @@ export default class CanExplorer extends Component {
this.setState({ isLoading: true }); this.setState({ isLoading: true });
} }
const [minPart, maxPart] = parts; const [minPart, maxPart] = parts;
let part = minPart, prevMsgEntries = {}, prepend = false, spawnWorkerHash; let part = minPart,
prevMsgEntries = {},
prepend = false,
spawnWorkerHash;
if (options) { if (options) {
if (options.part) part = options.part; if (options.part) part = options.part;
if (options.prevMsgEntries) prevMsgEntries = options.prevMsgEntries; if (options.prevMsgEntries) prevMsgEntries = options.prevMsgEntries;
@ -269,10 +319,17 @@ export default class CanExplorer extends Component {
this.setState({ partsLoaded: 0 }); this.setState({ partsLoaded: 0 });
} }
const {dbc, dbcFilename, route, firstCanTime, canFrameOffset, maxByteStateChangeCount} = this.state; const {
dbc,
dbcFilename,
route,
firstCanTime,
canFrameOffset,
maxByteStateChangeCount
} = this.state;
var worker = new CanFetcher(); var worker = new CanFetcher();
worker.onmessage = (e) => { worker.onmessage = e => {
if (spawnWorkerHash !== this.state.spawnWorkerHash) { if (spawnWorkerHash !== this.state.spawnWorkerHash) {
// Parts changed, stop spawning workers. // Parts changed, stop spawning workers.
return; return;
@ -291,7 +348,10 @@ export default class CanExplorer extends Component {
maxByteStateChangeCount = this.state.maxByteStateChangeCount; maxByteStateChangeCount = this.state.maxByteStateChangeCount;
} }
const messages = this.addAndRehydrateMessages(newMessages, maxByteStateChangeCount); const messages = this.addAndRehydrateMessages(
newMessages,
maxByteStateChangeCount
);
const prevMsgEntries = {}; const prevMsgEntries = {};
for (let key in newMessages) { for (let key in newMessages) {
const msg = newMessages[key]; const msg = newMessages[key];
@ -299,18 +359,28 @@ export default class CanExplorer extends Component {
prevMsgEntries[key] = msg.entries[msg.entries.length - 1]; prevMsgEntries[key] = msg.entries[msg.entries.length - 1];
} }
this.setState(
this.setState({messages, {
partsLoaded: this.state.partsLoaded + 1}, () => { messages,
partsLoaded: this.state.partsLoaded + 1
},
() => {
if (part < maxPart) { if (part < maxPart) {
this.spawnWorker(parts, {part: part + 1, prevMsgEntries, spawnWorkerHash, prepend}); this.spawnWorker(parts, {
part: part + 1,
prevMsgEntries,
spawnWorkerHash,
prepend
});
} else { } else {
this.setState({ isLoading: false }); this.setState({ isLoading: false });
} }
})
} }
);
};
worker.postMessage({dbcText: dbc.text(), worker.postMessage({
dbcText: dbc.text(),
base: route.url, base: route.url,
num: part, num: part,
canStartTime: firstCanTime - canFrameOffset, canStartTime: firstCanTime - canFrameOffset,
@ -325,9 +395,15 @@ export default class CanExplorer extends Component {
showLoadDbc, showLoadDbc,
showSaveDbc, showSaveDbc,
showAddSignal, showAddSignal,
showEditMessageModal, showEditMessageModal
} = this.state; } = this.state;
return showOnboarding || showLoadDbc || showSaveDbc || showAddSignal || showEditMessageModal; return (
showOnboarding ||
showLoadDbc ||
showSaveDbc ||
showAddSignal ||
showEditMessageModal
);
} }
showOnboarding() { showOnboarding() {
@ -347,11 +423,11 @@ export default class CanExplorer extends Component {
} }
showSaveDbc() { showSaveDbc() {
this.setState({showSaveDbc: true}) this.setState({ showSaveDbc: true });
} }
hideSaveDbc() { hideSaveDbc() {
this.setState({showSaveDbc: false}) this.setState({ showSaveDbc: false });
} }
reparseMessages(messages) { reparseMessages(messages) {
@ -359,16 +435,18 @@ export default class CanExplorer extends Component {
const { dbc } = this.state; const { dbc } = this.state;
var worker = new MessageParser(); var worker = new MessageParser();
worker.onmessage = (e) => { worker.onmessage = e => {
let messages = e.data; let messages = e.data;
messages = this.addAndRehydrateMessages(messages, { replace: true }); messages = this.addAndRehydrateMessages(messages, { replace: true });
this.setState({messages, isLoading: false}) this.setState({ messages, isLoading: false });
} };
worker.postMessage({messages, worker.postMessage({
messages,
dbcText: dbc.text(), dbcText: dbc.text(),
canStartTime: this.state.firstCanTime}); canStartTime: this.state.firstCanTime
});
} }
updateMessageFrame(messageId, frame) { updateMessageFrame(messageId, frame) {
@ -383,7 +461,7 @@ export default class CanExplorer extends Component {
if (route) { if (route) {
persistDbc(route.fullname, { dbcFilename, dbc }); persistDbc(route.fullname, { dbcFilename, dbc });
} else { } else {
persistDbc('live', { dbcFilename, dbc }); persistDbc("live", { dbcFilename, dbc });
} }
} }
@ -402,8 +480,9 @@ export default class CanExplorer extends Component {
messages[message.id] = newMessage; messages[message.id] = newMessage;
this.setState({dbc, dbcText: dbc.text()}, this.setState({ dbc, dbcText: dbc.text() }, () =>
() => this.reparseMessages(messages)); this.reparseMessages(messages)
);
} }
partChangeDebounced = debounce(() => { partChangeDebounced = debounce(() => {
@ -414,7 +493,7 @@ export default class CanExplorer extends Component {
onPartChange(part) { onPartChange(part) {
let { currentParts, canFrameOffset, route, messages } = this.state; let { currentParts, canFrameOffset, route, messages } = this.state;
if (canFrameOffset === -1 || part + PART_SEGMENT_LENGTH > route.proclog) { if (canFrameOffset === -1 || part + PART_SEGMENT_LENGTH > route.proclog) {
return return;
} }
// determine new parts to load, whether to prepend or append // determine new parts to load, whether to prepend or append
@ -424,16 +503,22 @@ export default class CanExplorer extends Component {
currentParts = [part, part + currentPartSpan - 1]; currentParts = [part, part + currentPartSpan - 1];
// update messages to only preserve entries in new part range // update messages to only preserve entries in new part range
const messagesKvPairs = Object.entries(messages) const messagesKvPairs = Object.entries(messages).map(
.map(([messageId, message]) => ([messageId, message]) => [
[messageId, {...message, messageId,
{
...message,
entries: [] entries: []
} }
]); ]
);
messages = ObjectUtils.fromArray(messagesKvPairs); messages = ObjectUtils.fromArray(messagesKvPairs);
// update state then load new parts // update state then load new parts
this.setState({currentParts, messages, seekTime: part * 60}, this.partChangeDebounced); this.setState(
{ currentParts, messages, seekTime: part * 60 },
this.partChangeDebounced
);
} }
showEditMessageModal(msgKey) { showEditMessageModal(msgKey) {
@ -442,11 +527,12 @@ export default class CanExplorer extends Component {
msg.frame = this.state.dbc.createFrame(msg.address); msg.frame = this.state.dbc.createFrame(msg.address);
} }
this.setState({
this.setState({showEditMessageModal: true, showEditMessageModal: true,
editMessageModalMessage: msgKey, editMessageModalMessage: msgKey,
messages: this.state.messages, messages: this.state.messages,
dbcText: this.state.dbc.text()}); dbcText: this.state.dbc.text()
});
} }
hideEditMessageModal() { hideEditMessageModal() {
@ -454,18 +540,19 @@ export default class CanExplorer extends Component {
} }
onMessageFrameEdited(messageFrame) { onMessageFrameEdited(messageFrame) {
const {messages, const {
messages,
route, route,
dbcFilename, dbcFilename,
dbc, dbc,
editMessageModalMessage} = this.state; editMessageModalMessage
} = this.state;
const message = Object.assign({}, messages[editMessageModalMessage]); const message = Object.assign({}, messages[editMessageModalMessage]);
message.frame = messageFrame; message.frame = messageFrame;
dbc.messages.set(messageFrame.id, messageFrame); dbc.messages.set(messageFrame.id, messageFrame);
this.persistDbc({ dbcFilename, dbc }); this.persistDbc({ dbcFilename, dbc });
messages[editMessageModalMessage] = message; messages[editMessageModalMessage] = message;
this.setState({ messages, dbc, dbcText: dbc.text() }); this.setState({ messages, dbc, dbcText: dbc.text() });
this.hideEditMessageModal(); this.hideEditMessageModal();
@ -483,12 +570,12 @@ export default class CanExplorer extends Component {
const msg = this.state.messages[this.state.selectedMessage]; const msg = this.state.messages[this.state.selectedMessage];
let seekIndex; let seekIndex;
if (msg) { if (msg) {
seekIndex = msg.entries.findIndex((e) => e.relTime >= seekTime); seekIndex = msg.entries.findIndex(e => e.relTime >= seekTime);
if (seekIndex === -1) { if (seekIndex === -1) {
seekIndex = 0 seekIndex = 0;
} }
} else { } else {
seekIndex = 0 seekIndex = 0;
} }
this.setState({ seekIndex, seekTime }); this.setState({ seekIndex, seekTime });
@ -499,7 +586,7 @@ export default class CanExplorer extends Component {
const msg = messages[msgKey]; const msg = messages[msgKey];
if (seekTime > 0 && msg.entries.length > 0) { if (seekTime > 0 && msg.entries.length > 0) {
seekIndex = msg.entries.findIndex((e) => e.relTime >= seekTime); seekIndex = msg.entries.findIndex(e => e.relTime >= seekTime);
if (seekIndex === -1) { if (seekIndex === -1) {
seekIndex = 0; seekIndex = 0;
} }
@ -521,12 +608,16 @@ export default class CanExplorer extends Component {
loginWithGithub() { loginWithGithub() {
const { route } = this.state; const { route } = this.state;
return ( return (
<a href={GithubAuth.authorizeUrl(route && route.fullname ? route.fullname : '')} <a
className='button button--dark button--inline'> href={GithubAuth.authorizeUrl(
<i className='fa fa-github'></i> route && route.fullname ? route.fullname : ""
)}
className="button button--dark button--inline"
>
<i className="fa fa-github" />
<span> Log in with Github</span> <span> Log in with Github</span>
</a> </a>
) );
} }
lastMessageEntriesById(obj, [msgId, message]) { lastMessageEntriesById(obj, [msgId, message]) {
@ -536,23 +627,35 @@ export default class CanExplorer extends Component {
processStreamedCanMessages(newCanMessages) { processStreamedCanMessages(newCanMessages) {
const { dbcText } = this.state; const { dbcText } = this.state;
const {firstCanTime, lastBusTime, messages, maxByteStateChangeCount} = this.state; const {
firstCanTime,
lastBusTime,
messages,
maxByteStateChangeCount
} = this.state;
// map msg id to arrays // map msg id to arrays
const prevMsgEntries = Object.entries(messages).reduce(this.lastMessageEntriesById, {}); const prevMsgEntries = Object.entries(messages).reduce(
this.lastMessageEntriesById,
{}
);
const byteStateChangeCountsByMessage = Object.entries(messages).reduce( const byteStateChangeCountsByMessage = Object.entries(messages).reduce(
(obj, [msgId, msg]) => { (obj, [msgId, msg]) => {
obj[msgId] = msg.byteStateChangeCounts obj[msgId] = msg.byteStateChangeCounts;
return obj; return obj;
}, {}); },
{}
);
this.canStreamerWorker.postMessage({ newCanMessages, this.canStreamerWorker.postMessage({
newCanMessages,
prevMsgEntries, prevMsgEntries,
firstCanTime, firstCanTime,
dbcText, dbcText,
lastBusTime, lastBusTime,
byteStateChangeCountsByMessage, byteStateChangeCountsByMessage,
maxByteStateChangeCount }); maxByteStateChangeCount
});
} }
firstEntryIndexInsideStreamingWindow(entries) { firstEntryIndexInsideStreamingWindow(entries) {
@ -580,7 +683,9 @@ export default class CanExplorer extends Component {
const lastEntryTime = message.entries[message.entries.length - 1].relTime; const lastEntryTime = message.entries[message.entries.length - 1].relTime;
const entrySpan = lastEntryTime - message.entries[0].relTime; const entrySpan = lastEntryTime - message.entries[0].relTime;
if (entrySpan > STREAMING_WINDOW) { if (entrySpan > STREAMING_WINDOW) {
const newEntryFloor = this.firstEntryIndexInsideStreamingWindow(message.entries); const newEntryFloor = this.firstEntryIndexInsideStreamingWindow(
message.entries
);
message.entries = message.entries.slice(newEntryFloor); message.entries = message.entries.slice(newEntryFloor);
messages[messageId] = message; messages[messageId] = message;
} }
@ -590,7 +695,13 @@ export default class CanExplorer extends Component {
} }
_onStreamedCanMessagesProcessed(data) { _onStreamedCanMessagesProcessed(data) {
let {newMessages, seekTime, lastBusTime, firstCanTime, maxByteStateChangeCount} = data; let {
newMessages,
seekTime,
lastBusTime,
firstCanTime,
maxByteStateChangeCount
} = data;
if (maxByteStateChangeCount < this.state.maxByteStateChangeCount) { if (maxByteStateChangeCount < this.state.maxByteStateChangeCount) {
maxByteStateChangeCount = this.state.maxByteStateChangeCount; maxByteStateChangeCount = this.state.maxByteStateChangeCount;
@ -599,10 +710,20 @@ export default class CanExplorer extends Component {
let messages = this.addAndRehydrateMessages(newMessages); let messages = this.addAndRehydrateMessages(newMessages);
messages = this.enforceStreamingMessageWindow(messages); messages = this.enforceStreamingMessageWindow(messages);
let { seekIndex, selectedMessages } = this.state; let { seekIndex, selectedMessages } = this.state;
if (selectedMessages.length > 0 && messages[selectedMessages[0]] !== undefined) { if (
selectedMessages.length > 0 &&
messages[selectedMessages[0]] !== undefined
) {
seekIndex = messages[selectedMessages[0]].entries.length - 1; seekIndex = messages[selectedMessages[0]].entries.length - 1;
} }
this.setState({messages, seekTime, seekIndex, lastBusTime, firstCanTime, maxByteStateChangeCount}); this.setState({
messages,
seekTime,
seekIndex,
lastBusTime,
firstCanTime,
maxByteStateChangeCount
});
} }
onStreamedCanMessagesProcessed(e) { onStreamedCanMessagesProcessed(e) {
@ -612,20 +733,25 @@ export default class CanExplorer extends Component {
handlePandaConnect(e) { handlePandaConnect(e) {
this.setState({ attemptingPandaConnection: true, live: true }); this.setState({ attemptingPandaConnection: true, live: true });
const persistedDbc = fetchPersistedDbc('live'); const persistedDbc = fetchPersistedDbc("live");
if (persistedDbc) { if (persistedDbc) {
const { dbc, dbcText } = persistedDbc; const { dbc, dbcText } = persistedDbc;
this.setState({ dbc, dbcText }); this.setState({ dbc, dbcText });
} }
this.canStreamerWorker = new CanStreamerWorker(); this.canStreamerWorker = new CanStreamerWorker();
this.canStreamerWorker.onmessage = this.onStreamedCanMessagesProcessed; this.canStreamerWorker.onmessage = this.onStreamedCanMessagesProcessed;
this.pandaReader.setOnMessagesReceivedCallback(this.processStreamedCanMessages); this.pandaReader.setOnMessagesReceivedCallback(
this.pandaReader.connect().then(() => { this.processStreamedCanMessages
);
this.pandaReader
.connect()
.then(() => {
this.pandaReader.readLoop(); this.pandaReader.readLoop();
this.setState({ attemptingPandaConnection: false }); this.setState({ attemptingPandaConnection: false });
this.setState({ showOnboarding: false }); this.setState({ showOnboarding: false });
this.setState({ showLoadDbc: true }); this.setState({ showLoadDbc: true });
}).catch((err) => { })
.catch(err => {
console.log(err); console.log(err);
this.setState({ attemptingPandaConnection: false }); this.setState({ attemptingPandaConnection: false });
}); });
@ -640,26 +766,36 @@ export default class CanExplorer extends Component {
render() { render() {
return ( return (
<div id='cabana' className={ cx({ 'is-showing-modal': this.showingModal() }) }> <div
{this.state.isLoading ? id="cabana"
<LoadingBar className={cx({ "is-showing-modal": this.showingModal() })}
isLoading={this.state.isLoading} >
/> : null} {this.state.isLoading ? (
<div className='cabana-header'> <LoadingBar isLoading={this.state.isLoading} />
<a className='cabana-header-logo' href=''>Comma Cabana</a> ) : null}
<div className='cabana-header-account'> <div className="cabana-header">
{this.state.isGithubAuthenticated ? <a className="cabana-header-logo" href="">
Comma Cabana
</a>
<div className="cabana-header-account">
{this.state.isGithubAuthenticated ? (
<div> <div>
<p>GitHub Authenticated</p> <p>GitHub Authenticated</p>
<p className='cabana-header-account-signout' <p
onClick={this.githubSignOut}>Sign out</p> className="cabana-header-account-signout"
onClick={this.githubSignOut}
>
Sign out
</p>
</div> </div>
: this.loginWithGithub() ) : (
} this.loginWithGithub()
)}
</div> </div>
</div> </div>
<div className='cabana-window'> <div className="cabana-window">
<Meta url={this.state.route ? this.state.route.url : null} <Meta
url={this.state.route ? this.state.route.url : null}
messages={this.state.messages} messages={this.state.messages}
selectedMessages={this.state.selectedMessages} selectedMessages={this.state.selectedMessages}
updateSelectedMessages={this.updateSelectedMessages} updateSelectedMessages={this.updateSelectedMessages}
@ -681,7 +817,7 @@ export default class CanExplorer extends Component {
live={this.state.live} live={this.state.live}
saveLog={debounce(this.downloadRawLogAsCSV, 500)} saveLog={debounce(this.downloadRawLogAsCSV, 500)}
/> />
{this.state.route || this.state.live ? {this.state.route || this.state.live ? (
<Explorer <Explorer
url={this.state.route ? this.state.route.url : null} url={this.state.route ? this.state.route.url : null}
live={this.state.live} live={this.state.live}
@ -699,28 +835,32 @@ export default class CanExplorer extends Component {
autoplay={this.props.autoplay} autoplay={this.props.autoplay}
showEditMessageModal={this.showEditMessageModal} showEditMessageModal={this.showEditMessageModal}
onPartChange={this.onPartChange} onPartChange={this.onPartChange}
routeStartTime={this.state.route ? this.state.route.start_time : Moment()} routeStartTime={
this.state.route ? this.state.route.start_time : Moment()
}
partsCount={this.state.route ? this.state.route.proclog : 0} partsCount={this.state.route ? this.state.route.proclog : 0}
/> />
: null} ) : null}
</div> </div>
{ this.state.showOnboarding ? {this.state.showOnboarding ? (
<OnboardingModal <OnboardingModal
handlePandaConnect={this.handlePandaConnect} handlePandaConnect={this.handlePandaConnect}
attemptingPandaConnection={this.state.attemptingPandaConnection} attemptingPandaConnection={this.state.attemptingPandaConnection}
routes={this.state.routes} routes={this.state.routes}
/> : null } />
) : null}
{this.state.showLoadDbc ? {this.state.showLoadDbc ? (
<LoadDbcModal <LoadDbcModal
onDbcSelected={this.onDbcSelected} onDbcSelected={this.onDbcSelected}
handleClose={this.hideLoadDbc} handleClose={this.hideLoadDbc}
openDbcClient={this.openDbcClient} openDbcClient={this.openDbcClient}
loginWithGithub={this.loginWithGithub()} loginWithGithub={this.loginWithGithub()}
/> : null} />
) : null}
{this.state.showSaveDbc ? {this.state.showSaveDbc ? (
<SaveDbcModal <SaveDbcModal
dbc={this.state.dbc} dbc={this.state.dbc}
sourceDbcFilename={this.state.dbcFilename} sourceDbcFilename={this.state.dbcFilename}
@ -729,15 +869,16 @@ export default class CanExplorer extends Component {
openDbcClient={this.openDbcClient} openDbcClient={this.openDbcClient}
hasGithubAuth={this.props.githubAuthToken !== null} hasGithubAuth={this.props.githubAuthToken !== null}
loginWithGithub={this.loginWithGithub()} loginWithGithub={this.loginWithGithub()}
/> : null} />
) : null}
{this.state.showEditMessageModal ? {this.state.showEditMessageModal ? (
<EditMessageModal <EditMessageModal
handleClose={this.hideEditMessageModal} handleClose={this.hideEditMessageModal}
handleSave={this.onMessageFrameEdited} handleSave={this.onMessageFrameEdited}
message={this.state.messages[this.state.editMessageModalMessage]} message={this.state.messages[this.state.editMessageModalMessage]}
/> : null} />
) : null}
</div> </div>
); );
} }

View File

@ -1,8 +1,9 @@
import React, {Component} from 'react'; import React, { Component } from "react";
import PropTypes from 'prop-types'; import PropTypes from "prop-types";
require('element-closest');
import CanGraph from './CanGraph'; import CanGraph from "./CanGraph";
require("element-closest");
export default class CanGraphList extends Component { export default class CanGraphList extends Component {
static propTypes = { static propTypes = {
@ -14,7 +15,7 @@ export default class CanGraphList extends Component {
onSegmentChanged: PropTypes.func.isRequired, onSegmentChanged: PropTypes.func.isRequired,
onSignalUnplotPressed: PropTypes.func.isRequired, onSignalUnplotPressed: PropTypes.func.isRequired,
segment: PropTypes.array.isRequired, segment: PropTypes.array.isRequired,
mergePlots: PropTypes.func.isRequired, mergePlots: PropTypes.func.isRequired
}; };
constructor(props) { constructor(props) {
@ -24,7 +25,7 @@ export default class CanGraphList extends Component {
draggingSignal: {}, draggingSignal: {},
dragPos: null, dragPos: null,
dragShift: null, dragShift: null,
graphToReceiveDrop: null, graphToReceiveDrop: null
}; };
this.plotListRef = null; this.plotListRef = null;
@ -37,16 +38,19 @@ export default class CanGraphList extends Component {
} }
onGraphDragStart(messageId, signalUid, shiftX, shiftY) { onGraphDragStart(messageId, signalUid, shiftX, shiftY) {
this.setState({draggingSignal: {messageId, signalUid}, this.setState({
dragShift: {x: shiftX, y: shiftY}}); draggingSignal: { messageId, signalUid },
dragShift: { x: shiftX, y: shiftY }
});
} }
determineDraggingGraph() { determineDraggingGraph() {
const { draggingSignal } = this.state; const { draggingSignal } = this.state;
return this.plotRefs.find( return this.plotRefs.find(
({ messageId, signalUid }) => ({ messageId, signalUid }) =>
draggingSignal.messageId === messageId draggingSignal.messageId === messageId &&
&& draggingSignal.signalUid === signalUid); draggingSignal.signalUid === signalUid
);
} }
onMouseMove(e) { onMouseMove(e) {
@ -63,11 +67,14 @@ export default class CanGraphList extends Component {
draggingGraph.ref.hidden = true; draggingGraph.ref.hidden = true;
const ele = document.elementFromPoint(e.clientX, e.clientY); const ele = document.elementFromPoint(e.clientX, e.clientY);
draggingGraph.ref.hidden = false; draggingGraph.ref.hidden = false;
const closestPlot = ele.closest('.cabana-explorer-visuals-plot'); const closestPlot = ele.closest(".cabana-explorer-visuals-plot");
const closestPlotRef = this.plotRefs.find(({ref, messageId, signalUid}) => const closestPlotRef = this.plotRefs.find(
!(messageId === draggingGraph.messageId ({ ref, messageId, signalUid }) =>
&& signalUid === draggingGraph.signalUid) !(
&& ref.isEqualNode(closestPlot)); messageId === draggingGraph.messageId &&
signalUid === draggingGraph.signalUid
) && ref.isEqualNode(closestPlot)
);
if (closestPlotRef) { if (closestPlotRef) {
this.setState({ graphToReceiveDrop: closestPlotRef }); this.setState({ graphToReceiveDrop: closestPlotRef });
} else { } else {
@ -82,19 +89,27 @@ export default class CanGraphList extends Component {
onGraphDragEnd() { onGraphDragEnd() {
if (this.state.graphToReceiveDrop !== null) { if (this.state.graphToReceiveDrop !== null) {
this.props.mergePlots({fromPlot: this.state.draggingSignal, toPlot: this.state.graphToReceiveDrop}); this.props.mergePlots({
fromPlot: this.state.draggingSignal,
toPlot: this.state.graphToReceiveDrop
});
} }
this.setState({draggingSignal: {}, this.setState({
draggingSignal: {},
dragShift: null, dragShift: null,
dragPos: null, dragPos: null,
graphToReceiveDrop: null}); graphToReceiveDrop: null
});
} }
addCanGraphRef(ref, messageId, signalUid) { addCanGraphRef(ref, messageId, signalUid) {
if (ref) { if (ref) {
let { plotRefs } = this; let { plotRefs } = this;
plotRefs = plotRefs.filter((ref) => !(ref.messageId === messageId && ref.signalUid === signalUid)) plotRefs = plotRefs
.filter(
ref => !(ref.messageId === messageId && ref.signalUid === signalUid)
)
.concat([{ messageId, signalUid, ref }]); .concat([{ messageId, signalUid, ref }]);
this.plotRefs = plotRefs; this.plotRefs = plotRefs;
} }
@ -104,22 +119,32 @@ export default class CanGraphList extends Component {
const { draggingSignal, graphToReceiveDrop } = this.state; const { draggingSignal, graphToReceiveDrop } = this.state;
const { messageId, signalUid } = plottedSignals[0]; const { messageId, signalUid } = plottedSignals[0];
const msg = this.props.messages[messageId]; const msg = this.props.messages[messageId];
const signal = Object.values(msg.frame.signals).find((s) => s.uid === signalUid); const signal = Object.values(msg.frame.signals).find(
s => s.uid === signalUid
);
const isDragging = draggingSignal.signalUid === signalUid && draggingSignal.messageId === messageId; const isDragging =
const canReceiveGraphDrop = (graphToReceiveDrop draggingSignal.signalUid === signalUid &&
&& graphToReceiveDrop.signalUid === signalUid draggingSignal.messageId === messageId;
&& graphToReceiveDrop.messageId === messageId); const canReceiveGraphDrop =
plottedSignals = plottedSignals.map((plottedSignal) => { graphToReceiveDrop &&
return {messageName: this.props.messages[plottedSignal.messageId].frame.name, graphToReceiveDrop.signalUid === signalUid &&
...plottedSignal} graphToReceiveDrop.messageId === messageId;
plottedSignals = plottedSignals.map(plottedSignal => {
return {
messageName: this.props.messages[plottedSignal.messageId].frame.name,
...plottedSignal
};
}); });
const key = plottedSignals.reduce( const key = plottedSignals.reduce(
(key, {messageId, signalUid}) => key + messageId + '_' + signalUid, (key, { messageId, signalUid }) => key + messageId + "_" + signalUid,
''); ""
);
return ( return (
<CanGraph <CanGraph
onGraphRefAvailable={(ref) => {this.addCanGraphRef(ref, messageId, signalUid)}} onGraphRefAvailable={ref => {
this.addCanGraphRef(ref, messageId, signalUid);
}}
key={key} key={key}
unplot={this.props.onSignalUnplotPressed} unplot={this.props.onSignalUnplotPressed}
messages={this.props.messages} messages={this.props.messages}
@ -147,12 +172,16 @@ export default class CanGraphList extends Component {
} }
render() { render() {
return (<div className='cabana-explorer-visuals-plots' return (
<div
className="cabana-explorer-visuals-plots"
ref={this.onPlotListRefReady} ref={this.onPlotListRefReady}
onMouseMove={this.onMouseMove} onMouseMove={this.onMouseMove}
onMouseLeave={this.onGraphDragEnd} onMouseLeave={this.onGraphDragEnd}
onMouseUp={this.onGraphDragEnd}> onMouseUp={this.onGraphDragEnd}
>
{this.props.plottedSignals.map(this.renderSignalPlot)} {this.props.plottedSignals.map(this.renderSignalPlot)}
</div>); </div>
);
} }
} }

View File

@ -1,13 +1,13 @@
import React, {Component} from 'react'; import React, { Component } from "react";
import cx from 'classnames'; import cx from "classnames";
import PropTypes from 'prop-types'; import PropTypes from "prop-types";
import Clipboard from 'clipboard'; import Clipboard from "clipboard";
require('core-js/fn/array/includes');
const {ckmeans} = require('simple-statistics');
import {modifyQueryParameters} from '../utils/url'; import { modifyQueryParameters } from "../utils/url";
import MessageBytes from './MessageBytes'; import MessageBytes from "./MessageBytes";
import {GITHUB_AUTH_TOKEN_KEY} from '../config'; import { GITHUB_AUTH_TOKEN_KEY } from "../config";
require("core-js/fn/array/includes");
const { ckmeans } = require("simple-statistics");
export default class Meta extends Component { export default class Meta extends Component {
static propTypes = { static propTypes = {
@ -30,17 +30,18 @@ export default class Meta extends Component {
seekTime: PropTypes.number, seekTime: PropTypes.number,
loginWithGithub: PropTypes.element, loginWithGithub: PropTypes.element,
isDemo: PropTypes.bool, isDemo: PropTypes.bool,
live: PropTypes.bool, live: PropTypes.bool
}; };
constructor(props) { constructor(props) {
super(props); super(props);
const { dbcLastSaved } = props; const { dbcLastSaved } = props;
this.state = { this.state = {
filterText: 'Filter', filterText: "Filter",
lastSaved: dbcLastSaved !== null ? this.props.dbcLastSaved.fromNow() : null, lastSaved:
dbcLastSaved !== null ? this.props.dbcLastSaved.fromNow() : null,
hoveredMessages: [], hoveredMessages: [],
orderedMessageKeys: [], orderedMessageKeys: []
}; };
this.onFilterChanged = this.onFilterChanged.bind(this); this.onFilterChanged = this.onFilterChanged.bind(this);
this.onFilterFocus = this.onFilterFocus.bind(this); this.onFilterFocus = this.onFilterFocus.bind(this);
@ -52,7 +53,7 @@ export default class Meta extends Component {
componentWillMount() { componentWillMount() {
this.lastSavedTimer = setInterval(() => { this.lastSavedTimer = setInterval(() => {
if (this.props.dbcLastSaved !== null) { if (this.props.dbcLastSaved !== null) {
this.setState({lastSaved: this.props.dbcLastSaved.fromNow()}) this.setState({ lastSaved: this.props.dbcLastSaved.fromNow() });
} }
}, 30000); }, 30000);
} }
@ -62,26 +63,38 @@ export default class Meta extends Component {
} }
componentWillReceiveProps(nextProps) { componentWillReceiveProps(nextProps) {
if(nextProps.lastSaved !== this.props.lastSaved && typeof nextProps === 'object') { if (
this.setState({lastSaved: nextProps.dbcLastSaved.fromNow()}) nextProps.lastSaved !== this.props.lastSaved &&
typeof nextProps === "object"
) {
this.setState({ lastSaved: nextProps.dbcLastSaved.fromNow() });
} }
const nextMsgKeys = Object.keys(nextProps.messages); const nextMsgKeys = Object.keys(nextProps.messages);
if(JSON.stringify(nextMsgKeys) !== JSON.stringify(Object.keys(this.props.messages))) { if (
JSON.stringify(nextMsgKeys) !==
JSON.stringify(Object.keys(this.props.messages))
) {
const orderedMessageKeys = this.sortMessages(nextProps.messages); const orderedMessageKeys = this.sortMessages(nextProps.messages);
this.setState({ hoveredMessages: [], orderedMessageKeys }); this.setState({ hoveredMessages: [], orderedMessageKeys });
} else if((this.state.orderedMessageKeys.length === 0) } else if (
|| (!this.props.live && this.props.messages && nextProps.messages this.state.orderedMessageKeys.length === 0 ||
&& this.byteCountsDidUpdate(this.props.messages, nextProps.messages))) { (!this.props.live &&
this.props.messages &&
nextProps.messages &&
this.byteCountsDidUpdate(this.props.messages, nextProps.messages))
) {
const orderedMessageKeys = this.sortMessages(nextProps.messages); const orderedMessageKeys = this.sortMessages(nextProps.messages);
this.setState({ orderedMessageKeys }); this.setState({ orderedMessageKeys });
} }
} }
byteCountsDidUpdate(prevMessages, nextMessages) { byteCountsDidUpdate(prevMessages, nextMessages) {
return Object.entries(nextMessages).some(([msgId, msg]) => return Object.entries(nextMessages).some(
JSON.stringify(msg.byteStateChangeCounts) ([msgId, msg]) =>
!== JSON.stringify(prevMessages[msgId].byteStateChangeCounts)); JSON.stringify(msg.byteStateChangeCounts) !==
JSON.stringify(prevMessages[msgId].byteStateChangeCounts)
);
} }
sortMessages(messages) { sortMessages(messages) {
@ -92,7 +105,8 @@ export default class Meta extends Component {
// yield a count-descending, address-ascending order. // yield a count-descending, address-ascending order.
if (Object.keys(messages).length === 0) return []; if (Object.keys(messages).length === 0) return [];
const messagesByEntryCount = Object.entries(messages).reduce((partialMapping, [msgId, msg]) => { const messagesByEntryCount = Object.entries(messages).reduce(
(partialMapping, [msgId, msg]) => {
const entryCountKey = msg.entries.length.toString(); // js object keys are strings const entryCountKey = msg.entries.length.toString(); // js object keys are strings
if (!partialMapping[entryCountKey]) { if (!partialMapping[entryCountKey]) {
partialMapping[entryCountKey] = [msg]; partialMapping[entryCountKey] = [msg];
@ -100,12 +114,21 @@ export default class Meta extends Component {
partialMapping[entryCountKey].push(msg); partialMapping[entryCountKey].push(msg);
} }
return partialMapping; return partialMapping;
}, {}); },
{}
);
const entryCounts = Object.keys(messagesByEntryCount).map((count) => parseInt(count, 10)); const entryCounts = Object.keys(messagesByEntryCount).map(count =>
const binnedEntryCounts = ckmeans(entryCounts, Math.min(entryCounts.length, 10)); parseInt(count, 10)
const sortedKeys = binnedEntryCounts.map((bin) => );
bin.map((entryCount) => messagesByEntryCount[entryCount.toString()]) const binnedEntryCounts = ckmeans(
entryCounts,
Math.min(entryCounts.length, 10)
);
const sortedKeys = binnedEntryCounts
.map(bin =>
bin
.map(entryCount => messagesByEntryCount[entryCount.toString()])
.reduce((messages, partial) => messages.concat(partial), []) .reduce((messages, partial) => messages.concat(partial), [])
.sort((msg1, msg2) => { .sort((msg1, msg2) => {
if (msg1.address < msg2.address) { if (msg1.address < msg2.address) {
@ -114,8 +137,9 @@ export default class Meta extends Component {
return -1; return -1;
} }
}) })
.map((msg) => msg.id) .map(msg => msg.id)
).reduce((keys, bin) => keys.concat(bin), []) )
.reduce((keys, bin) => keys.concat(bin), [])
.reverse(); .reverse();
return sortedKeys; return sortedKeys;
@ -123,31 +147,33 @@ export default class Meta extends Component {
onFilterChanged(e) { onFilterChanged(e) {
let val = e.target.value; let val = e.target.value;
if(val.trim() === 'Filter') val = ''; if (val.trim() === "Filter") val = "";
this.setState({filterText: val}) this.setState({ filterText: val });
} }
onFilterFocus(e) { onFilterFocus(e) {
if(this.state.filterText.trim() === 'Filter') { if (this.state.filterText.trim() === "Filter") {
this.setState({filterText: ''}) this.setState({ filterText: "" });
} }
} }
onFilterUnfocus(e) { onFilterUnfocus(e) {
if(this.state.filterText.trim() === '') { if (this.state.filterText.trim() === "") {
this.setState({filterText: 'Filter'}) this.setState({ filterText: "Filter" });
} }
} }
msgFilter(msg) { msgFilter(msg) {
const { filterText } = this.state; const { filterText } = this.state;
const msgName = (msg.frame ? msg.frame.name : ''); const msgName = msg.frame ? msg.frame.name : "";
return (filterText === 'Filter' return (
|| filterText === '' filterText === "Filter" ||
|| msg.id.toLowerCase().indexOf(filterText.toLowerCase()) !== -1 filterText === "" ||
|| msgName.toLowerCase().indexOf(filterText.toLowerCase()) !== -1); msg.id.toLowerCase().indexOf(filterText.toLowerCase()) !== -1 ||
msgName.toLowerCase().indexOf(filterText.toLowerCase()) !== -1
);
} }
lastSavedPretty() { lastSavedPretty() {
@ -165,13 +191,13 @@ export default class Meta extends Component {
onMessageHoverEnd(key) { onMessageHoverEnd(key) {
let { hoveredMessages } = this.state; let { hoveredMessages } = this.state;
hoveredMessages = hoveredMessages.filter((m) => m !== key); hoveredMessages = hoveredMessages.filter(m => m !== key);
this.setState({ hoveredMessages }); this.setState({ hoveredMessages });
} }
onMsgRemoveClick(key) { onMsgRemoveClick(key) {
let { selectedMessages } = this.state; let { selectedMessages } = this.state;
selectedMessages = selectedMessages.filter((m) => m !== key); selectedMessages = selectedMessages.filter(m => m !== key);
this.props.onMessageUnselected(key); this.props.onMessageUnselected(key);
this.setState({ selectedMessages }); this.setState({ selectedMessages });
} }
@ -188,23 +214,32 @@ export default class Meta extends Component {
orderedMessages() { orderedMessages() {
const { orderedMessageKeys } = this.state; const { orderedMessageKeys } = this.state;
const { messages } = this.props; const { messages } = this.props;
return orderedMessageKeys.map((key) => messages[key]); return orderedMessageKeys.map(key => messages[key]);
} }
selectedMessageClass(messageId) { selectedMessageClass(messageId) {
return (this.props.selectedMessages.includes(messageId) ? 'is-selected' : null); return this.props.selectedMessages.includes(messageId)
? "is-selected"
: null;
} }
renderMessageBytes(msg) { renderMessageBytes(msg) {
return ( return (
<tr onClick={() => {this.onMessageSelected(msg.id)}} <tr
onClick={() => {
this.onMessageSelected(msg.id);
}}
key={msg.id} key={msg.id}
className={cx('cabana-meta-messages-list-item', this.selectedMessageClass(msg.id))}> className={cx(
<td>{msg.frame ? msg.frame.name : 'undefined'}</td> "cabana-meta-messages-list-item",
this.selectedMessageClass(msg.id)
)}
>
<td>{msg.frame ? msg.frame.name : "undefined"}</td>
<td>{msg.id}</td> <td>{msg.id}</td>
<td>{msg.entries.length}</td> <td>{msg.entries.length}</td>
<td> <td>
<div className='cabana-meta-messages-list-item-bytes'> <div className="cabana-meta-messages-list-item-bytes">
<MessageBytes <MessageBytes
key={msg.id} key={msg.id}
message={msg} message={msg}
@ -228,7 +263,7 @@ export default class Meta extends Component {
return <p>Loading messages...</p>; return <p>Loading messages...</p>;
} }
return ( return (
<table cellPadding='5'> <table cellPadding="5">
<thead> <thead>
<tr> <tr>
<td>Name</td> <td>Name</td>
@ -237,9 +272,7 @@ export default class Meta extends Component {
<td>Bytes</td> <td>Bytes</td>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>{this.renderMessages()}</tbody>
{this.renderMessages()}
</tbody>
</table> </table>
); );
} }
@ -247,71 +280,86 @@ export default class Meta extends Component {
shareUrl() { shareUrl() {
const add = { const add = {
max: this.props.route.proclog, max: this.props.route.proclog,
url: this.props.route.url, url: this.props.route.url
}; };
const remove = [GITHUB_AUTH_TOKEN_KEY]; // don't share github access const remove = [GITHUB_AUTH_TOKEN_KEY]; // don't share github access
const shareUrl = modifyQueryParameters({ add, remove }) const shareUrl = modifyQueryParameters({ add, remove });
return shareUrl; return shareUrl;
} }
saveable() { saveable() {
try { try {
'serviceWorker' in navigator && !!new ReadableStream() && !!new WritableStream() "serviceWorker" in navigator &&
return 'saveable'; !!new ReadableStream() &&
!!new WritableStream(); // eslint-disable-line no-undef
return "saveable";
} catch (e) { } catch (e) {
return false; return false;
} }
} }
render() { render() {
return ( return (
<div className='cabana-meta'> <div className="cabana-meta">
<div className='cabana-meta-header'> <div className="cabana-meta-header">
<h5 className='cabana-meta-header-label t-capline'>Currently editing:</h5> <h5 className="cabana-meta-header-label t-capline">
<strong className='cabana-meta-header-filename'>{this.props.dbcFilename}</strong> Currently editing:
{this.props.dbcLastSaved !== null ? </h5>
<div className='cabana-meta-header-last-saved'> <strong className="cabana-meta-header-filename">
{this.props.dbcFilename}
</strong>
{this.props.dbcLastSaved !== null ? (
<div className="cabana-meta-header-last-saved">
<p>Last saved: {this.lastSavedPretty()}</p> <p>Last saved: {this.lastSavedPretty()}</p>
</div> </div>
: null ) : null}
}
<div className={`cabana-meta-header-actions ${this.saveable()}`}> <div className={`cabana-meta-header-actions ${this.saveable()}`}>
<div className='cabana-meta-header-action'> <div className="cabana-meta-header-action">
<button onClick={this.props.showLoadDbc}>Load DBC</button> <button onClick={this.props.showLoadDbc}>Load DBC</button>
</div> </div>
{this.saveable() && <div className='cabana-meta-header-action'> {this.saveable() && (
<div className="cabana-meta-header-action">
<button onClick={this.props.saveLog}>Save Log</button> <button onClick={this.props.saveLog}>Save Log</button>
</div> </div>
} )}
{this.props.route ? {this.props.route ? (
<div className='cabana-meta-header-action special-wide' <div
className="cabana-meta-header-action special-wide"
data-clipboard-text={this.shareUrl()} data-clipboard-text={this.shareUrl()}
data-clipboard-action='copy' data-clipboard-action="copy"
ref={(ref) => ref ? new Clipboard(ref) : null}> ref={ref => (ref ? new Clipboard(ref) : null)}
<a className='button' >
<a
className="button"
href={this.shareUrl()} href={this.shareUrl()}
onClick={(e) => e.preventDefault()}>Copy Share Link</a> onClick={e => e.preventDefault()}
</div> : null} >
<div className='cabana-meta-header-action'> Copy Share Link
</a>
</div>
) : null}
<div className="cabana-meta-header-action">
<button onClick={this.props.showSaveDbc}>Save DBC</button> <button onClick={this.props.showSaveDbc}>Save DBC</button>
</div> </div>
</div> </div>
</div> </div>
<div className='cabana-meta-messages'> <div className="cabana-meta-messages">
<div className='cabana-meta-messages-header'> <div className="cabana-meta-messages-header">
<h5 className='t-capline'>Available messages</h5> <h5 className="t-capline">Available messages</h5>
</div> </div>
<div className='cabana-meta-messages-window'> <div className="cabana-meta-messages-window">
<div className='cabana-meta-messages-filter'> <div className="cabana-meta-messages-filter">
<div className='form-field form-field--small'> <div className="form-field form-field--small">
<input type="text" <input
type="text"
value={this.state.filterText} value={this.state.filterText}
onFocus={this.onFilterFocus} onFocus={this.onFilterFocus}
onBlur={this.onFilterUnfocus} onBlur={this.onFilterUnfocus}
onChange={this.onFilterChanged} /> onChange={this.onFilterChanged}
/>
</div> </div>
</div> </div>
<div className='cabana-meta-messages-list'> <div className="cabana-meta-messages-list">
{this.renderAvailableMessagesList()} {this.renderAvailableMessagesList()}
</div> </div>
</div> </div>

View File

@ -1,9 +1,9 @@
// SignalLegend.js // SignalLegend.js
import React, {Component} from 'react'; import React, { Component } from "react";
import PropTypes from 'prop-types'; import PropTypes from "prop-types";
require('core-js/fn/array/includes');
import SignalLegendEntry from './SignalLegendEntry'; import SignalLegendEntry from "./SignalLegendEntry";
require("core-js/fn/array/includes");
export default class SignalLegend extends Component { export default class SignalLegend extends Component {
static propTypes = { static propTypes = {
@ -22,8 +22,8 @@ export default class SignalLegend extends Component {
constructor(props) { constructor(props) {
super(props); super(props);
this.state = { this.state = {
expandedSignals: [], expandedSignals: []
} };
this.toggleExpandSignal = this.toggleExpandSignal.bind(this); this.toggleExpandSignal = this.toggleExpandSignal.bind(this);
} }
@ -31,9 +31,9 @@ export default class SignalLegend extends Component {
const { expandedSignals } = this.state; const { expandedSignals } = this.state;
if (!expandedSignals.includes(s.uid)) { if (!expandedSignals.includes(s.uid)) {
const updatedExpandedSignals = [...expandedSignals, s.uid]; const updatedExpandedSignals = [...expandedSignals, s.uid];
this.setState({expandedSignals: updatedExpandedSignals}) this.setState({ expandedSignals: updatedExpandedSignals });
} else { } else {
const updatedExpandedSignals = expandedSignals.filter((i) => i !== s.uid) const updatedExpandedSignals = expandedSignals.filter(i => i !== s.uid);
this.setState({ expandedSignals: updatedExpandedSignals }); this.setState({ expandedSignals: updatedExpandedSignals });
} }
} }
@ -56,7 +56,8 @@ export default class SignalLegend extends Component {
const { colors } = signals[signalName]; const { colors } = signals[signalName];
const isHighlighted = highlightedSignal === signalName; const isHighlighted = highlightedSignal === signalName;
return <SignalLegendEntry return (
<SignalLegendEntry
key={signal.uid} key={signal.uid}
signal={signal} signal={signal}
isHighlighted={isHighlighted} isHighlighted={isHighlighted}
@ -69,19 +70,17 @@ export default class SignalLegend extends Component {
onSignalPlotChange={this.props.onSignalPlotChange} onSignalPlotChange={this.props.onSignalPlotChange}
toggleExpandSignal={this.toggleExpandSignal} toggleExpandSignal={this.toggleExpandSignal}
isPlotted={this.props.plottedSignalUids.indexOf(signal.uid) !== -1} isPlotted={this.props.plottedSignalUids.indexOf(signal.uid) !== -1}
isExpanded={this.checkExpandedSignal(signal.uid)}/>; isExpanded={this.checkExpandedSignal(signal.uid)}
/>
);
}); });
const signalRows = signalRowsNested const signalRows = signalRowsNested
.filter((row) => row != null) .filter(row => row != null)
.reduce((a, b) => { .reduce((a, b) => {
return a.concat(b) return a.concat(b);
}, []); }, []);
return ( return <div className="cabana-explorer-signals-legend">{signalRows}</div>;
<div className='cabana-explorer-signals-legend'>
{signalRows}
</div>
);
} }
} }

View File

@ -1,43 +1,47 @@
import Sentry from './logging/Sentry'; import Sentry from "./logging/Sentry";
Sentry.init(); import React from "react";
import ReactDOM from "react-dom";
import React from 'react'; import CanExplorer from "./CanExplorer";
import ReactDOM from 'react-dom'; import AcuraDbc from "./acura-dbc";
import CanExplorer from './CanExplorer'; import { getUrlParameter, modifyQueryParameters } from "./utils/url";
import AcuraDbc from './acura-dbc'; import { GITHUB_AUTH_TOKEN_KEY } from "./config";
import {getUrlParameter, modifyQueryParameters} from './utils/url'; import {
import {GITHUB_AUTH_TOKEN_KEY} from './config'; fetchPersistedDbc,
import {fetchPersistedDbc,
fetchPersistedGithubAuthToken, fetchPersistedGithubAuthToken,
persistGithubAuthToken} from './api/localstorage'; persistGithubAuthToken
require('core-js/fn/object/entries'); } from "./api/localstorage";
require('core-js/fn/object/values'); import "./index.css";
import './index.css';
const routeFullName = getUrlParameter('route'); Sentry.init();
require("core-js/fn/object/entries");
require("core-js/fn/object/values");
const routeFullName = getUrlParameter("route");
let isDemo = !routeFullName; let isDemo = !routeFullName;
let props = { autoplay: true, isDemo }; let props = { autoplay: true, isDemo };
let persistedDbc = null; let persistedDbc = null;
if (routeFullName) { if (routeFullName) {
const [dongleId, route] = routeFullName.split('|'); const [dongleId, route] = routeFullName.split("|");
props.dongleId = dongleId; props.dongleId = dongleId;
props.name = route; props.name = route;
persistedDbc = fetchPersistedDbc(routeFullName); persistedDbc = fetchPersistedDbc(routeFullName);
let max = getUrlParameter('max'), url = getUrlParameter('url'); let max = getUrlParameter("max"),
url = getUrlParameter("url");
if (max && url) { if (max && url) {
props.max = max; props.max = max;
props.url = url; props.url = url;
} }
} else if(getUrlParameter('demo')) { } else if (getUrlParameter("demo")) {
props.max = 12; props.max = 12;
props.url = 'https://chffrprivate.blob.core.windows.net/chffrprivate3/v2/cb38263377b873ee/78392b99580c5920227cc5b43dff8a70_2017-06-12--18-51-47'; props.url =
props.name = '2017-06-12--18-51-47'; "https://chffrprivate.blob.core.windows.net/chffrprivate3/v2/cb38263377b873ee/78392b99580c5920227cc5b43dff8a70_2017-06-12--18-51-47";
props.dongleId = 'cb38263377b873ee'; props.name = "2017-06-12--18-51-47";
props.dongleId = "cb38263377b873ee";
props.dbc = AcuraDbc; props.dbc = AcuraDbc;
props.dbcFilename = 'acura_ilx_2016_can.dbc'; props.dbcFilename = "acura_ilx_2016_can.dbc";
// lots of 404s on this one // lots of 404s on this one
// props.max = 752; // props.max = 752;
@ -66,24 +70,22 @@ const authTokenQueryParam = getUrlParameter(GITHUB_AUTH_TOKEN_KEY);
if (authTokenQueryParam !== null) { if (authTokenQueryParam !== null) {
props.githubAuthToken = authTokenQueryParam; props.githubAuthToken = authTokenQueryParam;
persistGithubAuthToken(authTokenQueryParam); persistGithubAuthToken(authTokenQueryParam);
const urlNoAuthToken = modifyQueryParameters({remove: [GITHUB_AUTH_TOKEN_KEY]}); const urlNoAuthToken = modifyQueryParameters({
remove: [GITHUB_AUTH_TOKEN_KEY]
});
window.location.href = urlNoAuthToken; window.location.href = urlNoAuthToken;
} else { } else {
props.githubAuthToken = fetchPersistedGithubAuthToken(); props.githubAuthToken = fetchPersistedGithubAuthToken();
} }
if (routeFullName || isDemo) { if (routeFullName || isDemo) {
ReactDOM.render( ReactDOM.render(<CanExplorer {...props} />, document.getElementById("root"));
<CanExplorer
{...props} />,
document.getElementById('root')
);
} else { } else {
const img = document.createElement('img'); const img = document.createElement("img");
img.src = process.env.PUBLIC_URL + '/img/cabana.jpg'; img.src = process.env.PUBLIC_URL + "/img/cabana.jpg";
img.style.width = '100%'; img.style.width = "100%";
const comment = document.createComment('7/6/17'); const comment = document.createComment("7/6/17");
document.getElementById('root').appendChild(img); document.getElementById("root").appendChild(img);
document.getElementById('root').appendChild(comment); document.getElementById("root").appendChild(comment);
} }

View File

@ -1,4 +1,5 @@
// Vendored from https://github.com/rapid7/le_js, which is broken with webpack. // Vendored from https://github.com/rapid7/le_js, which is broken with webpack.
/* eslint-disable */
if (typeof window === 'undefined') { // eslint-disable-line no-use-before-define if (typeof window === 'undefined') { // eslint-disable-line no-use-before-define
var window = self; var window = self;

View File

@ -1,26 +1,26 @@
const UINT64 = require('cuint').UINT64 import Bitarray from "../bitarray";
import Bitarray from '../bitarray'; import leftPad from "left-pad";
import leftPad from 'left-pad'; import CloudLog from "../../logging/CloudLog";
require('core-js/fn/array/from'); import Signal from "./signal";
require('core-js/fn/number/is-integer'); import Frame from "./frame";
require('core-js/es6/map'); import BoardUnit from "./BoardUnit";
require('core-js/es6/symbol'); import DbcUtils from "../../utils/dbc";
require('core-js/fn/symbol/iterator');
import CloudLog from '../../logging/CloudLog'; const UINT64 = require("cuint").UINT64;
import Signal from './signal'; require("core-js/fn/array/from");
import Frame from './frame'; require("core-js/fn/number/is-integer");
import BoardUnit from './BoardUnit'; require("core-js/es6/map");
import DbcUtils from '../../utils/dbc'; require("core-js/es6/symbol");
require("core-js/fn/symbol/iterator");
const DBC_COMMENT_RE = /^CM_ *"(.*)";/ const DBC_COMMENT_RE = /^CM_ *"(.*)";/;
const DBC_COMMENT_MULTI_LINE_RE = /^CM_ *"(.*)/ const DBC_COMMENT_MULTI_LINE_RE = /^CM_ *"(.*)/;
const MSG_RE = /^BO_ (\w+) (\w+) *: (\w+) (\w+)/ const MSG_RE = /^BO_ (\w+) (\w+) *: (\w+) (\w+)/;
const SIGNAL_RE = /^SG_ (\w+) : (\d+)\|(\d+)@(\d+)([+|-]) \(([0-9.+-eE]+),([0-9.+-eE]+)\) \[([0-9.+-eE]+)\|([0-9.+-eE]+)\] "(.*)" (.*)/ const SIGNAL_RE = /^SG_ (\w+) : (\d+)\|(\d+)@(\d+)([+|-]) \(([0-9.+-eE]+),([0-9.+-eE]+)\) \[([0-9.+-eE]+)\|([0-9.+-eE]+)\] "(.*)" (.*)/;
// Multiplexed signal // Multiplexed signal
const MP_SIGNAL_RE = /^SG_ (\w+) (\w+) *: (\d+)\|(\d+)@(\d+)([+|-]) \(([0-9.+-eE]+),([0-9.+-eE]+)\) \[([0-9.+-eE]+)\|([0-9.+-eE]+)\] "(.*)" (.*)/ const MP_SIGNAL_RE = /^SG_ (\w+) (\w+) *: (\d+)\|(\d+)@(\d+)([+|-]) \(([0-9.+-eE]+),([0-9.+-eE]+)\) \[([0-9.+-eE]+)\|([0-9.+-eE]+)\] "(.*)" (.*)/;
const VAL_RE = /^VAL_ (\w+) (\w+) (.*);/; const VAL_RE = /^VAL_ (\w+) (\w+) (.*);/;
const VAL_TABLE_RE = /^VAL_TABLE_ (\w+) (.*);/; const VAL_TABLE_RE = /^VAL_TABLE_ (\w+) (.*);/;
@ -28,7 +28,7 @@ const VAL_TABLE_RE = /^VAL_TABLE_ (\w+) (.*);/;
const MSG_TRANSMITTER_RE = /^BO_TX_BU_ ([0-9]+) *: *(.+);/; const MSG_TRANSMITTER_RE = /^BO_TX_BU_ ([0-9]+) *: *(.+);/;
const SIGNAL_COMMENT_RE = /^CM_ SG_ *(\w+) *(\w+) *"(.*)";/; const SIGNAL_COMMENT_RE = /^CM_ SG_ *(\w+) *(\w+) *"(.*)";/;
const SIGNAL_COMMENT_MULTI_LINE_RE = /^CM_ SG_ *(\w+) *(\w+) *"(.*)/ const SIGNAL_COMMENT_MULTI_LINE_RE = /^CM_ SG_ *(\w+) *(\w+) *"(.*)/;
// Message Comments (CM_ BO_ ) // Message Comments (CM_ BO_ )
const MESSAGE_COMMENT_RE = /^CM_ BO_ *(\w+) *"(.*)";/; const MESSAGE_COMMENT_RE = /^CM_ BO_ *(\w+) *"(.*)";/;
@ -84,9 +84,10 @@ export default class DBC {
messageNames.push(msg.name); messageNames.push(msg.name);
} }
let msgNum = 1, msgName; let msgNum = 1,
msgName;
do { do {
msgName = 'NEW_MSG_' + msgNum; msgName = "NEW_MSG_" + msgNum;
msgNum++; msgNum++;
} while (messageNames.indexOf(msgName) !== -1); } while (messageNames.indexOf(msgName) !== -1);
@ -94,16 +95,15 @@ export default class DBC {
} }
updateBoardUnits() { updateBoardUnits() {
const boardUnitNames = this.boardUnits.map((bu) => bu.name); const boardUnitNames = this.boardUnits.map(bu => bu.name);
const missingBoardUnits = const missingBoardUnits = Array.from(this.messages.entries())
Array.from(this.messages.entries())
.map(([msgId, frame]) => Object.values(frame.signals)) .map(([msgId, frame]) => Object.values(frame.signals))
.reduce((arr, signals) => arr.concat(signals), []) .reduce((arr, signals) => arr.concat(signals), [])
.map((signal) => signal.receiver) .map(signal => signal.receiver)
.reduce((arr, receivers) => arr.concat(receivers), []) .reduce((arr, receivers) => arr.concat(receivers), [])
.filter((recv, idx, array) => array.indexOf(recv) === idx) .filter((recv, idx, array) => array.indexOf(recv) === idx)
.filter((recv) => boardUnitNames.indexOf(recv) === -1) .filter(recv => boardUnitNames.indexOf(recv) === -1)
.map((recv) => new BoardUnit(recv)); .map(recv => new BoardUnit(recv));
this.boardUnits = this.boardUnits.concat(missingBoardUnits); this.boardUnits = this.boardUnits.concat(missingBoardUnits);
} }
@ -112,52 +112,57 @@ export default class DBC {
this.updateBoardUnits(); this.updateBoardUnits();
let txt = 'VERSION ""\n\n\n'; let txt = 'VERSION ""\n\n\n';
txt += 'NS_ :' + this._newSymbols(); txt += "NS_ :" + this._newSymbols();
txt += '\n\nBS_:\n'; txt += "\n\nBS_:\n";
const boardUnitsText = this.boardUnits.map((bu) => bu.text()) const boardUnitsText = this.boardUnits.map(bu => bu.text()).join(" ");
.join(" "); txt += "\nBU_: " + boardUnitsText + "\n\n\n";
txt += '\nBU_: ' + boardUnitsText + '\n\n\n';
const frames = []; const frames = [];
for (let frame of this.messages.values()) { for (let frame of this.messages.values()) {
frames.push(frame); frames.push(frame);
} }
txt += frames.map((f) => f.text()).join("\n\n") + '\n\n'; txt += frames.map(f => f.text()).join("\n\n") + "\n\n";
const messageTxs = frames.map((f) => [f.id, f.transmitters.slice(1)]) const messageTxs = frames
.map(f => [f.id, f.transmitters.slice(1)])
.filter(([addr, txs]) => txs.length > 0); .filter(([addr, txs]) => txs.length > 0);
txt += messageTxs.map(([addr, txs]) => txt +=
`BO_TX_BU_ ${addr} : ${txs.join(",")};`) messageTxs
.join("\n") + '\n\n\n'; .map(([addr, txs]) => `BO_TX_BU_ ${addr} : ${txs.join(",")};`)
.join("\n") + "\n\n\n";
txt += this.boardUnits.filter((bu) => bu.comment !== null) txt += this.boardUnits
.map((bu) => .filter(bu => bu.comment !== null)
`CM_ BU_ ${bu.name} "${bu.comment}";`) .map(bu => `CM_ BU_ ${bu.name} "${bu.comment}";`)
.join("\n"); .join("\n");
txt += frames.filter((f) => f.comment !== null) txt += frames
.map((msg) => `CM_ BO_ ${msg.address} "${msg.comment}";`) .filter(f => f.comment !== null)
.map(msg => `CM_ BO_ ${msg.address} "${msg.comment}";`)
.join("\n"); .join("\n");
const signalsByMsgId = frames.map((f) => const signalsByMsgId = frames
Object.values(f.signals) .map(f => Object.values(f.signals).map(sig => [f.id, sig]))
.map((sig) => [f.id, sig]))
.reduce((s1, s2) => s1.concat(s2), []); .reduce((s1, s2) => s1.concat(s2), []);
txt += signalsByMsgId.filter(([msgAddr, sig]) => sig.comment !== null) txt +=
.map(([msgAddr, sig]) => signalsByMsgId
`CM_ SG_ ${msgAddr} ${sig.name} "${sig.comment}";`) .filter(([msgAddr, sig]) => sig.comment !== null)
.join("\n") + '\n'; .map(
([msgAddr, sig]) => `CM_ SG_ ${msgAddr} ${sig.name} "${sig.comment}";`
)
.join("\n") + "\n";
txt += signalsByMsgId.filter(([msgAddr, sig]) => sig.valueDescriptions.size > 0) txt +=
signalsByMsgId
.filter(([msgAddr, sig]) => sig.valueDescriptions.size > 0)
.map(([msgAddr, sig]) => sig.valueDescriptionText(msgAddr)) .map(([msgAddr, sig]) => sig.valueDescriptionText(msgAddr))
.join("\n") + '\n'; .join("\n") + "\n";
txt += this.comments.map((comment) => `CM_ "${comment}";`) txt += this.comments.map(comment => `CM_ "${comment}";`).join("\n");
.join("\n");
return (txt.trim()) + '\n'; return txt.trim() + "\n";
} }
getMessageName(msgId) { getMessageName(msgId) {
@ -173,9 +178,11 @@ export default class DBC {
} }
createFrame(msgId) { createFrame(msgId) {
const msg = new Frame({name: this.nextNewFrameName(), const msg = new Frame({
name: this.nextNewFrameName(),
id: msgId, id: msgId,
size: 8}); size: 8
});
this.messages.set(msgId, msg); this.messages.set(msgId, msg);
return msg; return msg;
@ -213,7 +220,7 @@ export default class DBC {
let id = 0; let id = 0;
let followUp = null; let followUp = null;
const lines = dbcString.split('\n') const lines = dbcString.split("\n");
for (let i = 0; i < lines.length; i++) { for (let i = 0; i < lines.length; i++) {
let line = lines[i].trim(); let line = lines[i].trim();
@ -221,7 +228,7 @@ export default class DBC {
if (followUp != null) { if (followUp != null) {
const { type, data } = followUp; const { type, data } = followUp;
line = line.replace(/\" *;/, ''); line = line.replace(/\" *;/, "");
let followUpLine = `\n${line.substr(0, line.length)}`; let followUpLine = `\n${line.substr(0, line.length)}`;
if (line.indexOf('"') !== -1) { if (line.indexOf('"') !== -1) {
followUp = null; followUp = null;
@ -239,81 +246,123 @@ export default class DBC {
} else if (type === FOLLOW_UP_DBC_COMMENT) { } else if (type === FOLLOW_UP_DBC_COMMENT) {
const comment = data; const comment = data;
const partialComment = this.comments[this.comments.length - 1]; const partialComment = this.comments[this.comments.length - 1];
this.comments[this.comments.length - 1] = partialComment + followUpLine; this.comments[this.comments.length - 1] =
partialComment + followUpLine;
} }
} }
if (line.indexOf("BO_ ") === 0) { if (line.indexOf("BO_ ") === 0) {
let matches = line.match(MSG_RE) let matches = line.match(MSG_RE);
if (matches === null) { if (matches === null) {
warnings.push(`failed to parse message definition on line ${i + 1} -- ${line}`); warnings.push(
continue `failed to parse message definition on line ${i + 1} -- ${line}`
);
continue;
} }
let [idString, name, size, transmitter] = matches.slice(1); let [idString, name, size, transmitter] = matches.slice(1);
id = parseInt(idString, 0); // 0 radix parses hex or dec id = parseInt(idString, 0); // 0 radix parses hex or dec
size = parseInt(size, 10); size = parseInt(size, 10);
const frame = new Frame({name, id, size, transmitters: [transmitter]}) const frame = new Frame({
name,
id,
size,
transmitters: [transmitter]
});
messages.set(id, frame); messages.set(id, frame);
} else if (line.indexOf("SG_") === 0) { } else if (line.indexOf("SG_") === 0) {
let matches = line.match(SIGNAL_RE); let matches = line.match(SIGNAL_RE);
if (matches === null) { if (matches === null) {
matches = line.match(MP_SIGNAL_RE); matches = line.match(MP_SIGNAL_RE);
if (matches === null) { if (matches === null) {
warnings.push(`failed to parse signal definition on line ${i + 1} -- ${line}`); warnings.push(
`failed to parse signal definition on line ${i + 1} -- ${line}`
);
continue; continue;
} }
// for now, ignore multiplex which is matches[1] // for now, ignore multiplex which is matches[1]
matches = matches[1] + matches.slice(3); matches = matches[1] + matches.slice(3);
} else { } else {
matches = matches.slice(1) matches = matches.slice(1);
} }
let [name, startBit, size, isLittleEndian, isSigned, let [
factor, offset, min, max, unit, receiverStr] = matches; name,
startBit,
size,
isLittleEndian,
isSigned,
factor,
offset,
min,
max,
unit,
receiverStr
] = matches;
startBit = parseInt(startBit, 10); startBit = parseInt(startBit, 10);
size = parseInt(size, 10); size = parseInt(size, 10);
isLittleEndian = parseInt(isLittleEndian, 10) === 1 isLittleEndian = parseInt(isLittleEndian, 10) === 1;
isSigned = isSigned === '-' isSigned = isSigned === "-";
factor = floatOrInt(factor); factor = floatOrInt(factor);
offset = floatOrInt(offset); offset = floatOrInt(offset);
min = floatOrInt(min); min = floatOrInt(min);
max = floatOrInt(max); max = floatOrInt(max);
const receiver = receiverStr.split(",").map((s) => s.trim()); const receiver = receiverStr.split(",").map(s => s.trim());
const signalProperties= {name, startBit, size, isLittleEndian, const signalProperties = {
isSigned, factor, offset, unit, min, max, name,
receiver}; startBit,
size,
isLittleEndian,
isSigned,
factor,
offset,
unit,
min,
max,
receiver
};
const signal = new Signal(signalProperties); const signal = new Signal(signalProperties);
if (messages.get(id) !== undefined) { if (messages.get(id) !== undefined) {
messages.get(id).signals[name] = signal; messages.get(id).signals[name] = signal;
} else { } else {
CloudLog.warn('importDbcString: could not add signal: ' + name + ' due to missing message: ' + id); CloudLog.warn(
"importDbcString: could not add signal: " +
name +
" due to missing message: " +
id
);
} }
} else if (line.indexOf("VAL_ ") === 0) { } else if (line.indexOf("VAL_ ") === 0) {
let matches = line.match(VAL_RE); let matches = line.match(VAL_RE);
if (matches !== null) { if (matches !== null) {
let [messageId, signalName, vals] = matches.slice(1); let [messageId, signalName, vals] = matches.slice(1);
vals = vals.split('"') vals = vals
.map((s) => s.trim()) .split('"')
.filter((s) => s.length > 0); .map(s => s.trim())
.filter(s => s.length > 0);
messageId = parseInt(messageId, 10); messageId = parseInt(messageId, 10);
const msg = messages.get(messageId); const msg = messages.get(messageId);
const signal = msg.signals[signalName]; const signal = msg.signals[signalName];
if (signal === undefined) { if (signal === undefined) {
warnings.push(`could not find signal for value description on line ${i + 1} -- ${line}`); warnings.push(
`could not find signal for value description on line ${i +
1} -- ${line}`
);
continue; continue;
} }
for (let i = 0; i < vals.length; i += 2) { for (let i = 0; i < vals.length; i += 2) {
const value = vals[i].trim(), description = vals[i + 1].trim(); const value = vals[i].trim(),
description = vals[i + 1].trim();
signal.valueDescriptions.set(value, description); signal.valueDescriptions.set(value, description);
} }
} else { } else {
warnings.push(`failed to parse value description on line ${i + 1} -- ${line}`); warnings.push(
`failed to parse value description on line ${i + 1} -- ${line}`
);
} }
} else if (line.indexOf("VAL_TABLE_ ") === 0) { } else if (line.indexOf("VAL_TABLE_ ") === 0) {
let matches = line.match(VAL_TABLE_RE); let matches = line.match(VAL_TABLE_RE);
@ -321,30 +370,37 @@ export default class DBC {
if (matches !== null) { if (matches !== null) {
const table = new Map(); const table = new Map();
let [tableName, items] = matches.slice(1); let [tableName, items] = matches.slice(1);
items = items.split('"') items = items
.map((s) => s.trim()) .split('"')
.filter((s) => s.length > 0); .map(s => s.trim())
.filter(s => s.length > 0);
for (let i = 0; i < items.length; i += 2) { for (let i = 0; i < items.length; i += 2) {
const key = items[i], value = items[i + 1]; const key = items[i],
value = items[i + 1];
table.set(key, value); table.set(key, value);
} }
valueTables.set(tableName, table); valueTables.set(tableName, table);
} else { } else {
warnings.push(`failed to parse value table on line ${i + 1} -- ${line}`); warnings.push(
`failed to parse value table on line ${i + 1} -- ${line}`
);
} }
} else if (line.indexOf("BO_TX_BU_ ") === 0) { } else if (line.indexOf("BO_TX_BU_ ") === 0) {
let matches = line.match(MSG_TRANSMITTER_RE); let matches = line.match(MSG_TRANSMITTER_RE);
if (matches !== null) { if (matches !== null) {
let [messageId, transmitter] = matches.slice(1); let [messageId, transmitter] = matches.slice(1);
messageId = parseInt(messageId, 10) messageId = parseInt(messageId, 10);
const msg = messages.get(messageId); const msg = messages.get(messageId);
msg.transmitters.push(transmitter); msg.transmitters.push(transmitter);
messages.set(messageId, msg); messages.set(messageId, msg);
} else { } else {
warnings.push(`failed to parse message transmitter definition on line ${i + 1} -- ${line}`); warnings.push(
`failed to parse message transmitter definition on line ${i +
1} -- ${line}`
);
} }
} else if (line.indexOf("CM_ SG_ ") === 0) { } else if (line.indexOf("CM_ SG_ ") === 0) {
let matches = line.match(SIGNAL_COMMENT_RE); let matches = line.match(SIGNAL_COMMENT_RE);
@ -354,7 +410,9 @@ export default class DBC {
hasFollowUp = true; hasFollowUp = true;
} }
if (matches === null) { if (matches === null) {
warnings.push(`failed to parse signal comment on line ${i + 1} -- ${line}`); warnings.push(
`failed to parse signal comment on line ${i + 1} -- ${line}`
);
continue; continue;
} }
@ -363,13 +421,19 @@ export default class DBC {
messageId = parseInt(messageId, 10); messageId = parseInt(messageId, 10);
const msg = messages.get(messageId); const msg = messages.get(messageId);
if (msg === undefined) { if (msg === undefined) {
warnings.push(`failed to parse signal comment on line ${i + 1} -- ${line}: warnings.push(`failed to parse signal comment on line ${i + 1} -- ${
message id ${messageId} does not exist prior to this line`); line
}:
message id ${
messageId
} does not exist prior to this line`);
continue; continue;
} }
const signal = msg.signals[signalName]; const signal = msg.signals[signalName];
if (signal === undefined) { if (signal === undefined) {
warnings.push(`failed to parse signal comment on line ${i + 1} -- ${line}`); warnings.push(
`failed to parse signal comment on line ${i + 1} -- ${line}`
);
continue; continue;
} else { } else {
signal.comment = comment; signal.comment = comment;
@ -377,7 +441,7 @@ export default class DBC {
} }
if (hasFollowUp) { if (hasFollowUp) {
followUp = {type: FOLLOW_UP_SIGNAL_COMMENT, data: signal} followUp = { type: FOLLOW_UP_SIGNAL_COMMENT, data: signal };
} }
} else if (line.indexOf("CM_ BO_ ") === 0) { } else if (line.indexOf("CM_ BO_ ") === 0) {
let matches = line.match(MESSAGE_COMMENT_RE); let matches = line.match(MESSAGE_COMMENT_RE);
@ -386,7 +450,9 @@ export default class DBC {
matches = line.match(MESSAGE_COMMENT_MULTI_LINE_RE); matches = line.match(MESSAGE_COMMENT_MULTI_LINE_RE);
hasFollowUp = true; hasFollowUp = true;
if (matches === null) { if (matches === null) {
warnings.push(`failed to message comment on line ${i + 1} -- ${line}`); warnings.push(
`failed to message comment on line ${i + 1} -- ${line}`
);
continue; continue;
} }
} }
@ -404,30 +470,35 @@ export default class DBC {
if (matches !== null) { if (matches !== null) {
const [boardUnitNameStr] = matches.slice(1); const [boardUnitNameStr] = matches.slice(1);
const newBoardUnits = boardUnitNameStr.split(' ') const newBoardUnits = boardUnitNameStr
.map((s) => s.trim()) .split(" ")
.filter((s) => s.length > 0) .map(s => s.trim())
.map((name) => new BoardUnit(name)); .filter(s => s.length > 0)
.map(name => new BoardUnit(name));
boardUnits = boardUnits.concat(newBoardUnits); boardUnits = boardUnits.concat(newBoardUnits);
} else { } else {
warnings.push(`failed to parse board unit definition on line ${i + 1} -- ${line}`); warnings.push(
`failed to parse board unit definition on line ${i + 1} -- ${line}`
);
continue; continue;
} }
} else if (line.indexOf("CM_ BU_ ") === 0) { } else if (line.indexOf("CM_ BU_ ") === 0) {
let matches = line.match(BOARD_UNIT_COMMENT_RE); let matches = line.match(BOARD_UNIT_COMMENT_RE);
let hasFollowUp = false; let hasFollowUp = false;
if (matches === null) { if (matches === null) {
matches = line.match(BOARD_UNIT_COMMENT_MULTI_LINE_RE) matches = line.match(BOARD_UNIT_COMMENT_MULTI_LINE_RE);
hasFollowUp = true; hasFollowUp = true;
if (matches === null) { if (matches === null) {
warnings.push(`failed to parse board unit comment on line ${i + 1} -- ${line}`); warnings.push(
`failed to parse board unit comment on line ${i + 1} -- ${line}`
);
continue; continue;
} }
} }
let [boardUnitName, comment] = matches.slice(1); let [boardUnitName, comment] = matches.slice(1);
let boardUnit = boardUnits.find((bu) => bu.name === boardUnitName); let boardUnit = boardUnits.find(bu => bu.name === boardUnitName);
if (boardUnit) { if (boardUnit) {
boardUnit.comment = comment; boardUnit.comment = comment;
} }
@ -441,7 +512,9 @@ export default class DBC {
if (matches === null) { if (matches === null) {
matches = line.match(DBC_COMMENT_MULTI_LINE_RE); matches = line.match(DBC_COMMENT_MULTI_LINE_RE);
if (matches === null) { if (matches === null) {
warnings.push(`failed to parse dbc comment on line ${i + 1} -- ${line}`); warnings.push(
`failed to parse dbc comment on line ${i + 1} -- ${line}`
);
continue; continue;
} else { } else {
hasFollowUp = true; hasFollowUp = true;
@ -488,12 +561,15 @@ export default class DBC {
} }
let rightHandAnd = UINT64((1 << signalSpec.size) - 1); let rightHandAnd = UINT64((1 << signalSpec.size) - 1);
let ival = (value.shiftr(dataBitPos)).and(rightHandAnd).toNumber(); let ival = value
.shiftr(dataBitPos)
.and(rightHandAnd)
.toNumber();
if(signalSpec.isSigned && (ival & (1<<(signalSpec.size - 1)))) { if (signalSpec.isSigned && ival & (1 << (signalSpec.size - 1))) {
ival -= 1<<signalSpec.size ival -= 1 << signalSpec.size;
} }
ival = (ival * signalSpec.factor) + signalSpec.offset; ival = ival * signalSpec.factor + signalSpec.offset;
return ival; return ival;
} }
@ -509,10 +585,10 @@ export default class DBC {
} }
let ival = Bitarray.extract(bitArr, startBit, signalSpec.size); let ival = Bitarray.extract(bitArr, startBit, signalSpec.size);
if(signalSpec.isSigned && (ival & (1<<(signalSpec.size - 1)))) { if (signalSpec.isSigned && ival & (1 << (signalSpec.size - 1))) {
ival -= 1<<signalSpec.size ival -= 1 << signalSpec.size;
} }
ival = (ival * signalSpec.factor) + signalSpec.offset; ival = ival * signalSpec.factor + signalSpec.offset;
return ival; return ival;
} }
@ -520,11 +596,11 @@ export default class DBC {
let buffer = Buffer.from(data); let buffer = Buffer.from(data);
if (data.length % 8 !== 0) { if (data.length % 8 !== 0) {
// pad data it's 64 bits long // pad data it's 64 bits long
const paddedDataHex = leftPad(buffer.toString('hex'), 16, '0'); const paddedDataHex = leftPad(buffer.toString("hex"), 16, "0");
buffer = Buffer.from(paddedDataHex); buffer = Buffer.from(paddedDataHex);
} }
const hexData = buffer.toString('hex'); const hexData = buffer.toString("hex");
const bufferSwapped = Buffer.from(buffer).swap64(); const bufferSwapped = Buffer.from(buffer).swap64();
const bits = Bitarray.fromBytes(data); const bits = Bitarray.fromBytes(data);
@ -536,7 +612,7 @@ export default class DBC {
const { signals } = this.messages.get(messageId); const { signals } = this.messages.get(messageId);
const signalValuesByName = {}; const signalValuesByName = {};
Object.values(signals).forEach((signalSpec) => { Object.values(signals).forEach(signalSpec => {
let value; let value;
if (signalSpec.size > 32) { if (signalSpec.size > 32) {
value = this.valueForInt64Signal(signalSpec, hexData); value = this.valueForInt64Signal(signalSpec, hexData);
@ -550,23 +626,28 @@ export default class DBC {
} }
getChffrMetricMappings() { getChffrMetricMappings() {
const metricComment = this.comments.find((comment) => comment.indexOf('CHFFR_METRIC') === 0); const metricComment = this.comments.find(
comment => comment.indexOf("CHFFR_METRIC") === 0
);
if (!metricComment) { if (!metricComment) {
return null; return null;
} }
return metricComment return metricComment
.split(';') .split(";")
.map((metric) => metric.trim().split(' ')) .map(metric => metric.trim().split(" "))
.reduce((metrics, [_, messageId, signalName, metricName, factor, offset ]) => { .reduce(
(metrics, [_, messageId, signalName, metricName, factor, offset]) => {
metrics[metricName] = { metrics[metricName] = {
messageId: parseInt(messageId), messageId: parseInt(messageId),
signalName, signalName,
factor: parseFloat(factor), factor: parseFloat(factor),
offset: parseFloat(offset), offset: parseFloat(offset)
}; };
return metrics; return metrics;
}, {}); },
{}
);
} }
_newSymbols() { _newSymbols() {

View File

@ -1,13 +1,15 @@
const UINT64 = require('cuint').UINT64 import { hash } from "../../utils/string";
require('core-js/fn/array/from'); import Bitarray from "../bitarray";
require('core-js/es6/map');
import {hash} from '../../utils/string';
import Bitarray from '../bitarray';
import DbcUtils from '../../utils/dbc'; import DbcUtils from "../../utils/dbc";
const UINT64 = require("cuint").UINT64;
require("core-js/fn/array/from");
require("core-js/es6/map");
export default class Signal { export default class Signal {
constructor({name, constructor({
name,
startBit = 0, startBit = 0,
size = 0, size = 0,
isLittleEndian = true, isLittleEndian = true,
@ -16,15 +18,15 @@ export default class Signal {
factor = 1, factor = 1,
offset = 0, offset = 0,
unit = "", unit = "",
receiver = ['XXX'], receiver = ["XXX"],
comment = null, comment = null,
multiplex = null, multiplex = null,
min = null, min = null,
max = null, max = null,
valueDescriptions = new Map() valueDescriptions = new Map()
}) { }) {
Object.assign(this, Object.assign(this, {
{name, name,
startBit, startBit,
size, size,
isLittleEndian, isLittleEndian,
@ -36,7 +38,8 @@ export default class Signal {
receiver, receiver,
comment, comment,
multiplex, multiplex,
valueDescriptions}); valueDescriptions
});
const uid = Math.random().toString(36); const uid = Math.random().toString(36);
@ -53,22 +56,25 @@ export default class Signal {
} }
text() { text() {
const multiplex = this.multiplex ? ' ' + this.multiplex : ''; const multiplex = this.multiplex ? " " + this.multiplex : "";
const byteOrder = this.isLittleEndian ? 1 : 0; const byteOrder = this.isLittleEndian ? 1 : 0;
const signedChar = this.isSigned ? '-' : '+'; const signedChar = this.isSigned ? "-" : "+";
return `SG_ ${this.name}${multiplex} : ` + return (
`SG_ ${this.name}${multiplex} : ` +
`${this.startBit}|${this.size}@${byteOrder}${signedChar}` + `${this.startBit}|${this.size}@${byteOrder}${signedChar}` +
` (${this.factor},${this.offset})` + ` (${this.factor},${this.offset})` +
` [${this.min}|${this.max}]` + ` [${this.min}|${this.max}]` +
` "${this.unit}" ${this.receiver}` ` "${this.unit}" ${this.receiver}`
);
} }
valueDescriptionText(msgId) { valueDescriptionText(msgId) {
const entryPairs = Array.from(this.valueDescriptions.entries()); const entryPairs = Array.from(this.valueDescriptions.entries());
const values = entryPairs.reduce((str, const values = entryPairs.reduce(
[value, desc]) => str + value + ` "${desc}" `, (str, [value, desc]) => str + value + ` "${desc}" `,
''); ""
);
return `VAL_ ${msgId} ${this.name} ${values};`; return `VAL_ ${msgId} ${this.name} ${values};`;
} }
@ -137,18 +143,17 @@ export default class Signal {
if (this.isSigned) { if (this.isSigned) {
rawRange /= 2; rawRange /= 2;
} }
return [(this.isSigned ? -1 * rawRange : 0), return [this.isSigned ? -1 * rawRange : 0, rawRange - 1];
rawRange - 1]
} }
calculateMin() { calculateMin() {
const rawMin = this.calculateRawRange()[0]; const rawMin = this.calculateRawRange()[0];
return this.offset + (rawMin * this.factor); return this.offset + rawMin * this.factor;
} }
calculateMax() { calculateMax() {
const rawMax = this.calculateRawRange()[1]; const rawMax = this.calculateRawRange()[1];
return this.offset + (rawMax * this.factor); return this.offset + rawMax * this.factor;
} }
valueForInt32Signal(signalSpec, bits, bitsSwapped) { valueForInt32Signal(signalSpec, bits, bitsSwapped) {
@ -163,10 +168,10 @@ export default class Signal {
} }
let ival = Bitarray.extract(bitArr, startBit, signalSpec.size); let ival = Bitarray.extract(bitArr, startBit, signalSpec.size);
if(signalSpec.isSigned && (ival & (1<<(signalSpec.size - 1)))) { if (signalSpec.isSigned && ival & (1 << (signalSpec.size - 1))) {
ival -= 1<<signalSpec.size ival -= 1 << signalSpec.size;
} }
ival = (ival * signalSpec.factor) + signalSpec.offset; ival = ival * signalSpec.factor + signalSpec.offset;
return ival; return ival;
} }
@ -191,12 +196,15 @@ export default class Signal {
} }
let rightHandAnd = UINT64((1 << signalSpec.size) - 1); let rightHandAnd = UINT64((1 << signalSpec.size) - 1);
let ival = (value.shiftr(dataBitPos)).and(rightHandAnd).toNumber(); let ival = value
.shiftr(dataBitPos)
.and(rightHandAnd)
.toNumber();
if(signalSpec.isSigned && (ival & (1<<(signalSpec.size - 1)))) { if (signalSpec.isSigned && ival & (1 << (signalSpec.size - 1))) {
ival -= 1<<signalSpec.size ival -= 1 << signalSpec.size;
} }
ival = (ival * signalSpec.factor) + signalSpec.offset; ival = ival * signalSpec.factor + signalSpec.offset;
return ival; return ival;
} }
@ -210,18 +218,20 @@ export default class Signal {
} }
equals(otherSignal) { equals(otherSignal) {
return (otherSignal.name === this.name return (
&& otherSignal.startBit === this.startBit otherSignal.name === this.name &&
&& otherSignal.size === this.size otherSignal.startBit === this.startBit &&
&& otherSignal.isLittleEndian === this.isLittleEndian otherSignal.size === this.size &&
&& otherSignal.isSigned === this.isSigned otherSignal.isLittleEndian === this.isLittleEndian &&
&& otherSignal.isFloat === this.isFloat otherSignal.isSigned === this.isSigned &&
&& otherSignal.factor === this.factor otherSignal.isFloat === this.isFloat &&
&& otherSignal.offset === this.offset otherSignal.factor === this.factor &&
&& otherSignal.unit === this.unit otherSignal.offset === this.offset &&
&& otherSignal.receiver.length===this.receiver.length otherSignal.unit === this.unit &&
&& otherSignal.receiver.every((v,i)=> v === this.receiver[i]) otherSignal.receiver.length === this.receiver.length &&
&& otherSignal.comment === this.comment otherSignal.receiver.every((v, i) => v === this.receiver[i]) &&
&& otherSignal.multiplex === this.multiplex); otherSignal.comment === this.comment &&
otherSignal.multiplex === this.multiplex
);
} }
} }

View File

@ -1,24 +1,30 @@
/* eslint-disable no-restricted-globals*/
export function objToQuery(obj) { export function objToQuery(obj) {
return Object.keys(obj).map(k => k + '=' + encodeURIComponent(decodeURIComponent(obj[k]))).join('&'); return Object.keys(obj)
.map(k => k + "=" + encodeURIComponent(decodeURIComponent(obj[k])))
.join("&");
} }
export function getUrlParameter(name) { export function getUrlParameter(name) {
var location = window.location; var location = window.location;
name = name.replace(/[[]/, '\\[').replace(/[\]]/, '\\]'); name = name.replace(/[[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp('[\\?&]' + name + '=([^&#]*)'); var regex = new RegExp("[\\?&]" + name + "=([^&#]*)");
var results = regex.exec(location.search); var results = regex.exec(location.search);
return results === null ? null : decodeURIComponent(results[1].replace(/\+/g, ' ')); return results === null
? null
: decodeURIComponent(results[1].replace(/\+/g, " "));
} }
export function modifyQueryParameters({ add, remove }) { export function modifyQueryParameters({ add, remove }) {
var regex = new RegExp('[\\?&]([^&#]+)=([^&#]*)'); var regex = new RegExp("[\\?&]([^&#]+)=([^&#]*)");
var results = regex.exec(location.search); var results = regex.exec(location.search);
let params = {}; let params = {};
if (results != null) { if (results != null) {
for (let i = 1; i < results.length - 1; i += 2) { for (let i = 1; i < results.length - 1; i += 2) {
let key = results[i], value = results[i+1]; let key = results[i],
value = results[i + 1];
params[key] = value; params[key] = value;
} }
for (let key in params) { for (let key in params) {
@ -31,5 +37,5 @@ export function modifyQueryParameters({add, remove}) {
params = add; params = add;
} }
return location.origin + location.pathname + '?' + objToQuery(params); return location.origin + location.pathname + "?" + objToQuery(params);
} }

View File

@ -1,14 +1,17 @@
import DBC from '../models/can/dbc'; /* eslint-env worker */
import DbcUtils from '../utils/dbc'; /* eslint-disable no-restricted-globals */
import DBC from "../models/can/dbc";
import DbcUtils from "../utils/dbc";
function processStreamedCanMessages(
function processStreamedCanMessages(newCanMessages, newCanMessages,
prevMsgEntries, prevMsgEntries,
firstCanTime, firstCanTime,
dbc, dbc,
lastBusTime, lastBusTime,
byteStateChangeCountsByMessage, byteStateChangeCountsByMessage,
maxByteStateChangeCount) { maxByteStateChangeCount
) {
const messages = {}; const messages = {};
let lastCanTime; let lastCanTime;
@ -42,7 +45,7 @@ function processStreamedCanMessages(newCanMessages,
if (busTime >= prevBusTime) { if (busTime >= prevBusTime) {
busTimeSum += busTime - prevBusTime; busTimeSum += busTime - prevBusTime;
} else { } else {
busTimeSum += (0x10000 - prevBusTime) + busTime; busTimeSum += 0x10000 - prevBusTime + busTime;
} }
const message = [...canMessages[i]]; const message = [...canMessages[i]];
message[1] = time + busTimeSum / 500000.0; message[1] = time + busTimeSum / 500000.0;
@ -51,35 +54,63 @@ function processStreamedCanMessages(newCanMessages,
firstCanTime = message[1]; firstCanTime = message[1];
} }
const msgEntry = DbcUtils.addCanMessage(message, dbc, firstCanTime, messages, prevMsgEntries, byteStateChangeCountsByMessage); const msgEntry = DbcUtils.addCanMessage(
message,
dbc,
firstCanTime,
messages,
prevMsgEntries,
byteStateChangeCountsByMessage
);
if (i === canMessages.length - 1) { if (i === canMessages.length - 1) {
lastCanTime = msgEntry.relTime; lastCanTime = msgEntry.relTime;
} }
} }
lastBusTime = canMessages[canMessages.length - 1][1]; lastBusTime = canMessages[canMessages.length - 1][1];
const newMaxByteStateChangeCount = DbcUtils.findMaxByteStateChangeCount(messages); const newMaxByteStateChangeCount = DbcUtils.findMaxByteStateChangeCount(
messages
);
if (newMaxByteStateChangeCount > maxByteStateChangeCount) { if (newMaxByteStateChangeCount > maxByteStateChangeCount) {
maxByteStateChangeCount = newMaxByteStateChangeCount; maxByteStateChangeCount = newMaxByteStateChangeCount;
} }
Object.keys(messages).forEach((key) => { Object.keys(messages).forEach(key => {
messages[key] = DbcUtils.setMessageByteColors(messages[key], maxByteStateChangeCount); messages[key] = DbcUtils.setMessageByteColors(
messages[key],
maxByteStateChangeCount
);
}); });
} }
self.postMessage({newMessages: messages, seekTime: lastCanTime, lastBusTime, firstCanTime, maxByteStateChangeCount}); self.postMessage({
newMessages: messages,
seekTime: lastCanTime,
lastBusTime,
firstCanTime,
maxByteStateChangeCount
});
} }
self.onmessage = function(e) { self.onmessage = function(e) {
const {newCanMessages, prevMsgEntries, firstCanTime, dbcText, lastBusTime, byteStateChangeCountsByMessage, maxByteStateChangeCount} = e.data; const {
newCanMessages,
prevMsgEntries,
firstCanTime,
dbcText,
lastBusTime,
byteStateChangeCountsByMessage,
maxByteStateChangeCount
} = e.data;
const dbc = new DBC(dbcText); const dbc = new DBC(dbcText);
processStreamedCanMessages(newCanMessages, processStreamedCanMessages(
newCanMessages,
prevMsgEntries, prevMsgEntries,
firstCanTime, firstCanTime,
dbc, dbc,
lastBusTime, lastBusTime,
byteStateChangeCountsByMessage, byteStateChangeCountsByMessage,
maxByteStateChangeCount); maxByteStateChangeCount
} );
};

View File

@ -1,21 +1,28 @@
import Sentry from '../logging/Sentry'; /* eslint-disable no-restricted-globals */
import Sentry from "../logging/Sentry";
import NumpyLoader from "../utils/loadnpy";
import DBC from "../models/can/dbc";
import DbcUtils from "../utils/dbc";
import * as CanApi from "../api/can";
var window = self; var window = self;
require('core-js/fn/object/values'); require("core-js/fn/object/values");
import NumpyLoader from '../utils/loadnpy';
import DBC from '../models/can/dbc';
import DbcUtils from '../utils/dbc';
import * as CanApi from '../api/can';
const Int64LE = require('int64-buffer').Int64LE const Int64LE = require("int64-buffer").Int64LE;
async function loadCanPart(dbc, base, num, canStartTime, prevMsgEntries, maxByteStateChangeCount) { async function loadCanPart(
dbc,
base,
num,
canStartTime,
prevMsgEntries,
maxByteStateChangeCount
) {
var messages = {}; var messages = {};
const {times, const { times, sources, addresses, datas } = await CanApi.fetchCanPart(
sources, base,
addresses, num
datas} = await CanApi.fetchCanPart(base, num); );
for (var i = 0; i < times.length; i++) { for (var i = 0; i < times.length; i++) {
var t = times[i]; var t = times[i];
@ -26,44 +33,72 @@ async function loadCanPart(dbc, base, num, canStartTime, prevMsgEntries, maxByte
var addressNum = address.toNumber(); var addressNum = address.toNumber();
var data = datas.slice(i * 8, (i + 1) * 8); var data = datas.slice(i * 8, (i + 1) * 8);
if (messages[id] === undefined) messages[id] = DbcUtils.createMessageSpec(dbc, address.toNumber(), id, src); if (messages[id] === undefined)
messages[id] = DbcUtils.createMessageSpec(
dbc,
address.toNumber(),
id,
src
);
const prevMsgEntry = messages[id].entries.length > 0 ? const prevMsgEntry =
messages[id].entries[messages[id].entries.length - 1] messages[id].entries.length > 0
: ? messages[id].entries[messages[id].entries.length - 1]
(prevMsgEntries[id] || null); : prevMsgEntries[id] || null;
const {msgEntry, const { msgEntry, byteStateChangeCounts } = DbcUtils.parseMessage(
byteStateChangeCounts} = DbcUtils.parseMessage(dbc, dbc,
t, t,
address.toNumber(), address.toNumber(),
data, data,
canStartTime, canStartTime,
prevMsgEntry); prevMsgEntry
messages[id].byteStateChangeCounts = byteStateChangeCounts.map((count, idx) => );
messages[id].byteStateChangeCounts[idx] + count messages[id].byteStateChangeCounts = byteStateChangeCounts.map(
(count, idx) => messages[id].byteStateChangeCounts[idx] + count
); );
messages[id].entries.push(msgEntry); messages[id].entries.push(msgEntry);
} }
const newMaxByteStateChangeCount = DbcUtils.findMaxByteStateChangeCount(messages); const newMaxByteStateChangeCount = DbcUtils.findMaxByteStateChangeCount(
messages
);
if (newMaxByteStateChangeCount > maxByteStateChangeCount) { if (newMaxByteStateChangeCount > maxByteStateChangeCount) {
maxByteStateChangeCount = newMaxByteStateChangeCount; maxByteStateChangeCount = newMaxByteStateChangeCount;
} }
Object.keys(messages).forEach((key) => { Object.keys(messages).forEach(key => {
messages[key] = DbcUtils.setMessageByteColors(messages[key], maxByteStateChangeCount); messages[key] = DbcUtils.setMessageByteColors(
messages[key],
maxByteStateChangeCount
);
}); });
self.postMessage({newMessages: messages, self.postMessage({
maxByteStateChangeCount}); newMessages: messages,
maxByteStateChangeCount
});
self.close(); self.close();
} }
self.onmessage = function(e) { self.onmessage = function(e) {
const {dbcText, base, num, canStartTime, prevMsgEntries, maxByteStateChangeCount} = e.data; const {
dbcText,
base,
num,
canStartTime,
prevMsgEntries,
maxByteStateChangeCount
} = e.data;
const dbc = new DBC(dbcText); const dbc = new DBC(dbcText);
loadCanPart(dbc, base, num, canStartTime, prevMsgEntries, maxByteStateChangeCount); loadCanPart(
} dbc,
base,
num,
canStartTime,
prevMsgEntries,
maxByteStateChangeCount
);
};

View File

@ -1,15 +1,16 @@
import Sentry from '../logging/Sentry'; /* eslint-disable no-restricted-globals */
import Sentry from "../logging/Sentry";
import * as CanApi from "../api/can";
var window = self; var window = self;
require('core-js/fn/object/values'); require("core-js/fn/object/values");
import * as CanApi from '../api/can';
function calcCanFrameOffset(firstCanPart, partCanTimes) { function calcCanFrameOffset(firstCanPart, partCanTimes) {
const firstCanTime = partCanTimes[0]; const firstCanTime = partCanTimes[0];
const firstPartLastCanTime = partCanTimes[partCanTimes.length - 1]; const firstPartLastCanTime = partCanTimes[partCanTimes.length - 1];
return (60 * firstCanPart return 60 * firstCanPart + (60 - (firstPartLastCanTime - firstCanTime));
+ (60 - (firstPartLastCanTime - firstCanTime)));
} }
async function fetchCanTimes(base, part) { async function fetchCanTimes(base, part) {

View File

@ -1,23 +1,30 @@
/* eslint-env worker */
/* eslint-disable no-restricted-globals */
// import Sentry from '../logging/Sentry'; // import Sentry from '../logging/Sentry';
import NumpyLoader from "../utils/loadnpy";
import * as CanApi from "../api/can";
var window = self; var window = self;
require('core-js/fn/object/values'); require("core-js/fn/object/values");
import NumpyLoader from '../utils/loadnpy';
import * as CanApi from '../api/can';
const Int64LE = require("int64-buffer").Int64LE;
const Int64LE = require('int64-buffer').Int64LE
function transformData(data) {} function transformData(data) {}
async function fetchAndPostData(base, currentPart, [minPart, maxPart], canStartTime) { async function fetchAndPostData(
console.log('\n\nfetchAndPostData', `${currentPart} of ${maxPart}`); base,
currentPart,
[minPart, maxPart],
canStartTime
) {
console.log("\n\nfetchAndPostData", `${currentPart} of ${maxPart}`);
// if we've exhausted the parts, close up shop // if we've exhausted the parts, close up shop
if (currentPart > maxPart) { if (currentPart > maxPart) {
self.postMessage({ self.postMessage({
progress: 100, progress: 100,
shouldClose: true shouldClose: true
}) });
self.close(); self.close();
return; return;
} }
@ -26,18 +33,20 @@ async function fetchAndPostData(base, currentPart, [minPart, maxPart], canStartT
try { try {
awaitedData = await CanApi.fetchCanPart(base, currentPart); awaitedData = await CanApi.fetchCanPart(base, currentPart);
} catch (e) { } catch (e) {
console.log('fetchCanPart missing part', e) console.log("fetchCanPart missing part", e);
return fetchAndPostData(base, currentPart+1, [minPart, maxPart], canStartTime) return fetchAndPostData(
base,
currentPart + 1,
[minPart, maxPart],
canStartTime
);
} }
const { const { times, sources, addresses, datas } = awaitedData;
times,
sources,
addresses,
datas,
} = awaitedData;
// times is a float64array, which we want to be a normal array for now // times is a float64array, which we want to be a normal array for now
const logData = [].slice.call(times).map((t, i) => { const logData = [].slice
.call(times)
.map((t, i) => {
var src = Int64LE(sources, i * 8).toString(10); var src = Int64LE(sources, i * 8).toString(10);
var address = Int64LE(addresses, i * 8); var address = Int64LE(addresses, i * 8);
var addressHexStr = address.toString(16); var addressHexStr = address.toString(16);
@ -46,30 +55,38 @@ async function fetchAndPostData(base, currentPart, [minPart, maxPart], canStartT
var addressNum = address.toNumber(); var addressNum = address.toNumber();
var data = datas.slice(i * 8, (i + 1) * 8); var data = datas.slice(i * 8, (i + 1) * 8);
return `${t-canStartTime},${addressNum},${src},${Buffer.from(data).toString('hex')}\n` return `${t - canStartTime},${addressNum},${src},${Buffer.from(
}).join('') data
).toString("hex")}\n`;
})
.join("");
console.log('posting message') console.log("posting message");
self.postMessage({ self.postMessage({
progress: 10, progress: 10,
logData, logData,
shouldClose: false shouldClose: false
}) });
fetchAndPostData(base, currentPart+1, [minPart, maxPart], canStartTime) fetchAndPostData(base, currentPart + 1, [minPart, maxPart], canStartTime);
} }
self.onmessage = function(e) { self.onmessage = function(e) {
console.log('onmessage worker') console.log("onmessage worker");
self.postMessage({ self.postMessage({
progress: 0, progress: 0,
logData: 'time,addr,bus,data', logData: "time,addr,bus,data",
shouldClose: false shouldClose: false
}) });
const {base, parts, canStartTime, prevMsgEntries, maxByteStateChangeCount} = e.data; const {
base,
parts,
canStartTime,
prevMsgEntries,
maxByteStateChangeCount
} = e.data;
// const dbc = new DBC(dbcText); // const dbc = new DBC(dbcText);
// saveDBC(dbc, base, num, canStartTime); // saveDBC(dbc, base, num, canStartTime);
fetchAndPostData(base, parts[0], parts, canStartTime) fetchAndPostData(base, parts[0], parts, canStartTime);
} };

View File

@ -1,25 +1,40 @@
import Sentry from '../logging/Sentry'; /* eslint-env worker */
/* eslint-disable no-restricted-globals */
import Sentry from "../logging/Sentry";
import DBC from "../models/can/dbc";
import DbcUtils from "../utils/dbc";
var window = self; var window = self;
require('core-js/fn/object/values'); require("core-js/fn/object/values");
import DBC from '../models/can/dbc';
import DbcUtils from '../utils/dbc';
function reparseEntry(entry, address, dbc, canStartTime, prevMsgEntry) { function reparseEntry(entry, address, dbc, canStartTime, prevMsgEntry) {
const data = Buffer.from(entry.hexData, 'hex'); const data = Buffer.from(entry.hexData, "hex");
return DbcUtils.parseMessage(dbc, entry.time, address, data, canStartTime, prevMsgEntry); return DbcUtils.parseMessage(
dbc,
entry.time,
address,
data,
canStartTime,
prevMsgEntry
);
} }
self.onmessage = function(e) { self.onmessage = function(e) {
const { messages, dbcText, canStartTime } = e.data; const { messages, dbcText, canStartTime } = e.data;
const dbc = new DBC(dbcText); const dbc = new DBC(dbcText);
Object.keys(messages).forEach((messageId) => { Object.keys(messages).forEach(messageId => {
const message = messages[messageId]; const message = messages[messageId];
for (var i = 0; i < message.entries.length; i++) { for (var i = 0; i < message.entries.length; i++) {
const entry = message.entries[i]; const entry = message.entries[i];
const prevMsgEntry = i > 0 ? message.entries[i - 1] : null; const prevMsgEntry = i > 0 ? message.entries[i - 1] : null;
const {msgEntry} = reparseEntry(entry, message.address, dbc, canStartTime, prevMsgEntry); const { msgEntry } = reparseEntry(
entry,
message.address,
dbc,
canStartTime,
prevMsgEntry
);
message.entries[i] = msgEntry; message.entries[i] = msgEntry;
} }
@ -28,4 +43,4 @@ self.onmessage = function(e) {
self.postMessage(messages); self.postMessage(messages);
self.close(); self.close();
} };

7978
yarn.lock 100644

File diff suppressed because it is too large Load Diff