├── .nvmrc ├── .prettierrc ├── static └── images │ ├── robo-chart-2.png │ ├── robo-chart.gif │ ├── robo-chart.png │ └── spreadsheet-format.png ├── .eslintrc ├── src ├── utils │ ├── pieOptions.js │ ├── horizontalBarOptions.js │ ├── handleOptions.js │ ├── lineOptions.js │ └── processSpreadsheet.js ├── charts │ ├── horizontalBar.js │ ├── horizontalBarReverse.js │ ├── lineReverse.js │ ├── pie.js │ ├── line.js │ ├── pieReverse.js │ ├── barReverse.js │ └── bar.js ├── index.js └── chart.js ├── .babelrc ├── .gitignore ├── webpack.config.js ├── package.json └── README.md /.nvmrc: -------------------------------------------------------------------------------- 1 | v10.17.0 2 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true, 3 | "trailingComma": "all" 4 | } 5 | -------------------------------------------------------------------------------- /static/images/robo-chart-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/postlight/react-google-sheet-to-chart/HEAD/static/images/robo-chart-2.png -------------------------------------------------------------------------------- /static/images/robo-chart.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/postlight/react-google-sheet-to-chart/HEAD/static/images/robo-chart.gif -------------------------------------------------------------------------------- /static/images/robo-chart.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/postlight/react-google-sheet-to-chart/HEAD/static/images/robo-chart.png -------------------------------------------------------------------------------- /static/images/spreadsheet-format.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/postlight/react-google-sheet-to-chart/HEAD/static/images/spreadsheet-format.png -------------------------------------------------------------------------------- /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "parser": "babel-eslint", 3 | "extends": ["airbnb", "prettier", "prettier/react"], 4 | "env": { 5 | "browser": true, 6 | "node": true, 7 | "jest": true 8 | }, 9 | "rules": { 10 | "react/prop-types": 0 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/utils/pieOptions.js: -------------------------------------------------------------------------------- 1 | // predefined chart options for pie charts 2 | const options = { 3 | responsive: true, 4 | maintainAspectRatio: false, 5 | circumference: 360, 6 | rotation: -90, 7 | plugins: { 8 | title: { 9 | display: true, 10 | text: '', 11 | fontSize: 20, 12 | padding: 20, 13 | }, 14 | }, 15 | }; 16 | 17 | export default options; 18 | -------------------------------------------------------------------------------- /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ 3 | [ 4 | "@babel/preset-env", 5 | { 6 | "modules": "commonjs2", 7 | "targets": { 8 | "node": "current" 9 | } 10 | } 11 | ] 12 | ], 13 | "plugins": [ 14 | "@babel/plugin-proposal-object-rest-spread", 15 | "@babel/plugin-transform-react-jsx", 16 | "@babel/plugin-proposal-class-properties" 17 | ] 18 | } 19 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # production 12 | /build 13 | 14 | # misc 15 | .DS_Store 16 | .env 17 | .env.local 18 | .env.development.local 19 | .env.test.local 20 | .env.production.local 21 | 22 | npm-debug.log* 23 | yarn-debug.log* 24 | yarn-error.log* 25 | -------------------------------------------------------------------------------- /webpack.config.js: -------------------------------------------------------------------------------- 1 | var path = require('path'); 2 | module.exports = { 3 | entry: './src/index.js', 4 | output: { 5 | path: path.resolve(__dirname, 'build'), 6 | filename: 'index.js', 7 | libraryTarget: 'commonjs2', 8 | }, 9 | mode: 'production', 10 | module: { 11 | rules: [ 12 | { 13 | test: /\.js$/, 14 | include: path.resolve(__dirname, 'src'), 15 | exclude: /(node_modules|bower_components|build)/, 16 | use: { 17 | loader: 'babel-loader', 18 | options: { 19 | presets: ['@babel/preset-env'], 20 | plugins: [ 21 | '@babel/plugin-proposal-object-rest-spread', 22 | '@babel/plugin-transform-react-jsx', 23 | '@babel/plugin-proposal-class-properties', 24 | ], 25 | }, 26 | }, 27 | }, 28 | ], 29 | }, 30 | externals: { 31 | react: 'commonjs react', 32 | }, 33 | }; 34 | -------------------------------------------------------------------------------- /src/utils/horizontalBarOptions.js: -------------------------------------------------------------------------------- 1 | // predefined chart options for horizontal bar charts 2 | const options = { 3 | indexAxis: 'y', 4 | responsive: true, 5 | maintainAspectRatio: false, 6 | layout: { 7 | padding: { 8 | left: 10, 9 | right: 10, 10 | top: 10, 11 | bottom: 10, 12 | }, 13 | }, 14 | scales: { 15 | x: { 16 | display: true, 17 | grid: { display: false }, 18 | labels: [], 19 | id: 'x-axis-1', 20 | ticks: { 21 | beginAtZero: true, 22 | }, 23 | }, 24 | y: { 25 | display: true, 26 | position: 'left', 27 | id: 'y-axis-1', 28 | ticks: { 29 | beginAtZero: true, 30 | }, 31 | }, 32 | }, 33 | plugins: { 34 | title: { 35 | display: false, 36 | text: '', 37 | fontSize: 20, 38 | padding: 20, 39 | }, 40 | legend: { 41 | position: 'bottom', 42 | }, 43 | }, 44 | }; 45 | 46 | export default options; 47 | -------------------------------------------------------------------------------- /src/utils/handleOptions.js: -------------------------------------------------------------------------------- 1 | /* eslint-disable no-param-reassign */ 2 | /** 3 | * Update chartjs options object with the following arguments 4 | * 5 | * @param {object} options 6 | * @param {boolean} maintainAspectRatio 7 | * @param {string} chartTitle 8 | * @param {number} startFrom 9 | * @param {string} xsuffix 10 | * @param {string} ysuffix 11 | */ 12 | const handleOptions = ( 13 | options, 14 | maintainAspectRatio, 15 | chartTitle, 16 | startFrom, 17 | chartType, 18 | xsuffix, 19 | ysuffix, 20 | ) => { 21 | options.maintainAspectRatio = maintainAspectRatio; 22 | options.plugins.title.text = chartTitle; 23 | if (startFrom === 0) { 24 | options.scales.x.ticks = { beginAtZero: true }; 25 | options.scales.y.ticks = { beginAtZero: true }; 26 | } else if (chartType === 'horizontalBar') { 27 | options.scales.x.beginAtZero = false; 28 | options.scales.x.min = parseFloat(startFrom); 29 | } else { 30 | options.scales.y.beginAtZero = false; 31 | options.scales.y.min = parseFloat(startFrom); 32 | } 33 | 34 | options.scales.x.ticks.callback = function (value) { 35 | const label = this.chart.scales.x.getLabelForValue(value); 36 | return `${label}${xsuffix}`; 37 | }; 38 | options.scales.y.ticks.callback = function (value) { 39 | const label = this.chart.scales.y.getLabelForValue(value); 40 | return `${label}${ysuffix}`; 41 | }; 42 | }; 43 | 44 | export default handleOptions; 45 | -------------------------------------------------------------------------------- /src/utils/lineOptions.js: -------------------------------------------------------------------------------- 1 | import { Chart } from 'chart.js'; 2 | 3 | // predefined chart options for line charts 4 | const options = { 5 | responsive: true, 6 | maintainAspectRatio: false, 7 | layout: { 8 | padding: { 9 | left: 10, 10 | right: 10, 11 | top: 10, 12 | bottom: 10, 13 | }, 14 | }, 15 | hover: { 16 | mode: 'x', 17 | intersect: false, 18 | }, 19 | elements: { 20 | line: { 21 | tension: 0.4, 22 | }, 23 | }, 24 | scales: { 25 | x: { 26 | stacked: false, 27 | display: true, 28 | grid: { 29 | display: false, 30 | }, 31 | labels: [], 32 | id: 'x-axis-1', 33 | min: 0, 34 | ticks: { 35 | beginAtZero: true, 36 | }, 37 | }, 38 | y: { 39 | stacked: false, 40 | type: 'linear', 41 | display: true, 42 | position: 'left', 43 | id: 'y-axis-1', 44 | ticks: { 45 | beginAtZero: true, 46 | }, 47 | grid: { 48 | color: (context) => 49 | context.tick.value === 0 ? '#888' : Chart.defaults.borderColor, 50 | lineWidth: (context) => (context.tick.value === 0 ? 2 : 1), 51 | display: true, 52 | }, 53 | labels: { 54 | show: true, 55 | }, 56 | }, 57 | }, 58 | plugins: { 59 | title: { 60 | display: true, 61 | text: '', 62 | fontSize: 20, 63 | padding: 20, 64 | }, 65 | legend: { 66 | position: 'bottom', 67 | }, 68 | tooltip: { 69 | mode: 'x', 70 | intersect: false, 71 | callbacks: {}, 72 | }, 73 | }, 74 | }; 75 | 76 | export default options; 77 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@postlight/react-google-sheet-to-chart", 3 | "version": "1.0.3", 4 | "description": "Transform Google sheets to pretty charts!", 5 | "main": "build/index.js", 6 | "dependencies": { 7 | "axios": "^0.27.2", 8 | "chart.js": "^3.9.1", 9 | "randomcolor": "^0.6.2", 10 | "react-chartjs-2": "^4.3.1" 11 | }, 12 | "peerDependencies": { 13 | "react": "^16.0.0 || ^17.0.0 || ^18.0.0", 14 | "react-dom": "^16.0.0 || ^17.0.0 || ^18.0.0" 15 | }, 16 | "scripts": { 17 | "test": "echo \"Error: no test specified\" && exit 1", 18 | "start": "webpack --watch", 19 | "build": "webpack" 20 | }, 21 | "author": "Postlight", 22 | "contributors": [ 23 | "Alexi Akl " 24 | ], 25 | "repository": { 26 | "type": "git", 27 | "url": "git+https://github.com/postlight/react-google-sheet-to-chart" 28 | }, 29 | "homepage": "https://github.com/postlight/react-google-sheet-to-chart#readme", 30 | "bugs": { 31 | "url": "https://github.com/postlight/react-google-sheet-to-chart/issues" 32 | }, 33 | "keywords": [ 34 | "Sheet", 35 | "Chart", 36 | "Google", 37 | "React", 38 | "Component" 39 | ], 40 | "license": "Apache-2.0", 41 | "devDependencies": { 42 | "@babel/cli": "^7.18.10", 43 | "@babel/core": "^7.19.1", 44 | "@babel/plugin-proposal-class-properties": "^7.18.6", 45 | "@babel/plugin-proposal-object-rest-spread": "^7.18.9", 46 | "@babel/plugin-transform-react-jsx": "^7.19.0", 47 | "@babel/preset-env": "^7.19.1", 48 | "babel-loader": "^8.2.5", 49 | "webpack": "^5.74.0", 50 | "webpack-cli": "^4.10.0", 51 | "react": "^18.2.0", 52 | "react-dom": "^18.2.0" 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/charts/horizontalBar.js: -------------------------------------------------------------------------------- 1 | import { randomColor } from 'randomcolor'; 2 | import options from '../utils/horizontalBarOptions'; 3 | 4 | /** 5 | * Returns chart data specific for Horizontal Bar chart type 6 | * 7 | * @param {object} data chart data 8 | * @param {array} colors array of colors used to present data 9 | */ 10 | const getHorizontalBarChartData = (data, colors) => { 11 | const chartData = { 12 | labels: [], 13 | datasets: [], 14 | options, 15 | colors: [], 16 | }; 17 | 18 | let columnCount = 0; 19 | let colorIndex = 0; 20 | data.forEach((element, rowindex) => { 21 | if (columnCount === 0) { 22 | columnCount = element.length; 23 | } 24 | element.forEach((value, colindex) => { 25 | const numericalValue = value.replace(/[^\d.-]/g, ''); 26 | if (rowindex === 0) { 27 | if (value && value.length > 0) { 28 | chartData.labels.push(value); 29 | } 30 | } else if (colindex === 0) { 31 | if (value && value.length > 0) { 32 | const object = { data: [] }; 33 | let color = colors[colorIndex]; 34 | if (!colors || colorIndex >= colors.length) { 35 | color = randomColor(); 36 | } 37 | colorIndex += 1; 38 | object.borderColor = color; 39 | object.backgroundColor = color; 40 | object.borderWidth = 1; 41 | object.label = value; 42 | object.hoverBackgroundColor = color; 43 | object.hoverBorderColor = color; 44 | chartData.datasets.push(object); 45 | 46 | chartData.colors.push(color); 47 | } 48 | } else if (chartData.datasets[rowindex - 1]) { 49 | chartData.datasets[rowindex - 1].data.push(numericalValue); 50 | } 51 | }); 52 | }); 53 | return chartData; 54 | }; 55 | 56 | export default getHorizontalBarChartData; 57 | -------------------------------------------------------------------------------- /src/charts/horizontalBarReverse.js: -------------------------------------------------------------------------------- 1 | import { randomColor } from 'randomcolor'; 2 | import options from '../utils/horizontalBarOptions'; 3 | 4 | /** 5 | * Returns chart data specific for Horizontal Bar chart type with reversed axis processing 6 | * 7 | * @param {object} data chart data 8 | * @param {array} colors array of colors used to present data 9 | */ 10 | const getHorizontalBarReverseChartData = (data, colors) => { 11 | const chartData = { 12 | labels: [], 13 | datasets: [], 14 | options, 15 | colors: [], 16 | }; 17 | 18 | let columnCount = 0; 19 | let colorIndex = 0; 20 | data.forEach((element, rowindex) => { 21 | if (columnCount === 0) { 22 | columnCount = element.length; 23 | } 24 | element.forEach((value, colindex) => { 25 | const numericalValue = value.replace(/[^\d.-]/g, ''); 26 | if (rowindex === 0) { 27 | if (value && value.length > 0) { 28 | const object = { data: [] }; 29 | let color = colors[colorIndex]; 30 | if (!colors || colorIndex >= colors.length) { 31 | color = randomColor(); 32 | } 33 | colorIndex += 1; 34 | object.borderColor = color; 35 | object.backgroundColor = color; 36 | object.borderWidth = 1; 37 | object.label = value; 38 | object.hoverBackgroundColor = color; 39 | object.hoverBorderColor = color; 40 | chartData.datasets.push(object); 41 | 42 | chartData.colors.push(color); 43 | } 44 | } else if (colindex === 0) { 45 | if (value && value.length > 0) { 46 | chartData.labels.push(value); 47 | } 48 | } else if (chartData.datasets[colindex - 1]) { 49 | chartData.datasets[colindex - 1].data.push(numericalValue); 50 | } 51 | }); 52 | }); 53 | return chartData; 54 | }; 55 | 56 | export default getHorizontalBarReverseChartData; 57 | -------------------------------------------------------------------------------- /src/charts/lineReverse.js: -------------------------------------------------------------------------------- 1 | import randomColor from 'randomcolor'; 2 | import options from '../utils/lineOptions'; 3 | 4 | /** 5 | * Returns chart data specific for Line chart type with reversed axis processing 6 | * 7 | * @param {object} data chart data 8 | * @param {array} colors array of colors used to present data 9 | */ 10 | const getLineReverseChartData = (data, colors) => { 11 | const chartData = { 12 | labels: [], 13 | datasets: [], 14 | info: [], 15 | annotations: [], 16 | options, 17 | colors: [], 18 | }; 19 | 20 | let columnCount = 0; 21 | let colorIndex = 0; 22 | data.forEach((element, rowindex) => { 23 | if (columnCount === 0) { 24 | columnCount = element.length; 25 | } 26 | element.forEach((value, colindex) => { 27 | const numericalValue = value.replace(/[^\d.-]/g, ''); 28 | if (rowindex === 0) { 29 | if (value && value.length > 0) { 30 | chartData.labels.push(value); 31 | } 32 | } else if (colindex === 0) { 33 | if (value && value.length > 0) { 34 | const object = { data: [] }; 35 | let color = colors[colorIndex]; 36 | if (!colors || colorIndex >= colors.length) { 37 | color = randomColor(); 38 | } 39 | colorIndex += 1; 40 | object.borderColor = color; 41 | object.backgroundColor = color; 42 | object.pointBorderColor = color; 43 | object.pointBackgroundColor = color; 44 | object.pointHoverBackgroundColor = color; 45 | object.pointHoverBorderColor = color; 46 | object.fill = false; 47 | object.label = value; 48 | chartData.datasets.push(object); 49 | 50 | chartData.colors.push(color); 51 | } 52 | } else if (chartData.datasets[rowindex - 1]) { 53 | chartData.datasets[rowindex - 1].data.push(numericalValue); 54 | } 55 | }); 56 | }); 57 | 58 | chartData.options.scales.x.labels = chartData.labels; 59 | return chartData; 60 | }; 61 | 62 | export default getLineReverseChartData; 63 | -------------------------------------------------------------------------------- /src/charts/pie.js: -------------------------------------------------------------------------------- 1 | import { randomColor } from 'randomcolor'; 2 | import options from '../utils/pieOptions'; 3 | 4 | /** 5 | * Returns chart data specific for Pie chart type 6 | * 7 | * @param {object} data chart data 8 | * @param {boolean} semi true or false 9 | * @param {array} colors array of colors used to present data 10 | */ 11 | const getPieChartData = (data, semi, colors) => { 12 | const chartData = { 13 | data: { 14 | datasets: [], 15 | labels: [], 16 | }, 17 | options, 18 | colors: [], 19 | }; 20 | 21 | if (semi) { 22 | chartData.options.circumference = 180; 23 | chartData.options.rotation = -90; 24 | } else { 25 | chartData.options.circumference = 360; 26 | chartData.options.rotation = 0; 27 | } 28 | 29 | let colorIndex = 0; 30 | data.forEach((element, rowindex) => { 31 | element.forEach((value, colindex) => { 32 | const numericalValue = value.replace(/[^\d.-]/g, ''); 33 | if (rowindex === 0) { 34 | if (value && value.length > 0) { 35 | const object = { data: [], backgroundColor: [], label: '' }; 36 | object.label = value; 37 | chartData.data.datasets.push(object); 38 | } 39 | } else if (colindex === 0) { 40 | chartData.data.labels.push(value); 41 | } else { 42 | let color = colors[colorIndex]; 43 | if (!colors || colorIndex >= colors.length) { 44 | color = randomColor(); 45 | } 46 | colorIndex += 1; 47 | if (chartData.data.datasets[colindex - 1]) { 48 | chartData.data.datasets[colindex - 1].backgroundColor.push(color); 49 | chartData.data.datasets[colindex - 1].data.push(numericalValue); 50 | } 51 | chartData.colors.push(color); 52 | } 53 | }); 54 | }); 55 | 56 | const finalDatasets = []; 57 | chartData.data.datasets.forEach((dataset) => { 58 | if (dataset.data.length > 0) { 59 | finalDatasets.push(dataset); 60 | } 61 | }); 62 | 63 | chartData.data.datasets = finalDatasets; 64 | 65 | return chartData; 66 | }; 67 | 68 | export default getPieChartData; 69 | -------------------------------------------------------------------------------- /src/charts/line.js: -------------------------------------------------------------------------------- 1 | import { randomColor } from 'randomcolor'; 2 | import options from '../utils/lineOptions'; 3 | 4 | /** 5 | * Returns chart data specific for Line chart type 6 | * 7 | * @param {object} data chart data 8 | * @param {array} colors array of colors used to present data 9 | */ 10 | const getLineChartData = (data, colors) => { 11 | const chartData = { 12 | labels: [], 13 | datasets: [], 14 | info: [], 15 | annotations: [], 16 | options, 17 | colors: [], 18 | }; 19 | 20 | let columnCount = 0; 21 | let colorIndex = 0; 22 | data.forEach((element, rowindex) => { 23 | if (columnCount === 0) { 24 | columnCount = element.length; 25 | } 26 | element.forEach((value, colindex) => { 27 | const numericalValue = value.replace(/[^\d.-]/g, ''); 28 | if (rowindex === 0) { 29 | if (value && value.length > 0) { 30 | const object = { data: [] }; 31 | let color = colors[colorIndex]; 32 | if (!colors || colorIndex >= colors.length) { 33 | color = randomColor(); 34 | } 35 | colorIndex += 1; 36 | object.borderColor = color; 37 | object.backgroundColor = color; 38 | object.pointBorderColor = color; 39 | object.pointBackgroundColor = color; 40 | object.pointHoverBackgroundColor = color; 41 | object.pointHoverBorderColor = color; 42 | object.fill = false; 43 | object.label = value; 44 | chartData.datasets.push(object); 45 | 46 | chartData.colors.push(color); 47 | } 48 | } else if (colindex === 0) { 49 | chartData.labels.push(value); 50 | } else if (chartData.datasets[colindex - 1]) { 51 | chartData.datasets[colindex - 1].data.push(numericalValue); 52 | } 53 | }); 54 | let i = element.length; 55 | for (; i < columnCount; ) { 56 | if (chartData.datasets[i - 1]) { 57 | chartData.datasets[i - 1].data.push(0); 58 | } 59 | i += 1; 60 | } 61 | }); 62 | 63 | chartData.options.scales.x.labels = chartData.labels; 64 | return chartData; 65 | }; 66 | 67 | export default getLineChartData; 68 | -------------------------------------------------------------------------------- /src/utils/processSpreadsheet.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Spreadsheet processor brain 3 | * 4 | * Process values and stores them in an array 5 | * Use startr and startc to recursively check for better data to plot 6 | * 7 | * @param {array} values 8 | * @param {number} startr 9 | * @param {number} startc 10 | */ 11 | const processSpreadsheet = (values, startr = 0, startc = 0) => { 12 | const processedData = { 13 | data: [], 14 | start: '', 15 | end: '', 16 | startr: 0, 17 | startc: 0, 18 | }; 19 | let rowstart = -1; 20 | let colstart = 999999999; 21 | let colend = -1; 22 | let donerows = false; 23 | values.forEach((element, rowindex) => { 24 | if (rowindex >= startr) { 25 | if (element.length > 0 && !donerows) { 26 | if (rowstart < 0) { 27 | rowstart = rowindex + 1; 28 | } 29 | let donecols = false; 30 | const elements = []; 31 | element.forEach((value, colindex) => { 32 | if (colindex >= startc) { 33 | const trimmedValue = value.trim(); 34 | if (!donecols) { 35 | if (trimmedValue.length > 0) { 36 | elements.push(trimmedValue); 37 | if (colindex < colstart) { 38 | colstart = colindex; 39 | } 40 | if (colindex > colend) { 41 | colend = colindex; 42 | } 43 | } else if (elements.length > 0) { 44 | donecols = true; 45 | } 46 | } 47 | } 48 | }); 49 | processedData.data.push(elements); 50 | } else if (rowstart > 0) { 51 | donerows = true; 52 | } 53 | } 54 | }); 55 | 56 | const alphabet = 'abcdefghijklmnopqrstuvwxyz'.toUpperCase().split(''); 57 | const rowend = rowstart + processedData.data.length - 1; 58 | const gridStart = alphabet[colstart] + rowstart; 59 | const gridEnd = alphabet[colend] + rowend; 60 | processedData.startr = rowstart; 61 | processedData.startc = colstart; 62 | 63 | processedData.start = gridStart; 64 | processedData.end = gridEnd; 65 | 66 | return processedData; 67 | }; 68 | 69 | export default processSpreadsheet; 70 | -------------------------------------------------------------------------------- /src/charts/pieReverse.js: -------------------------------------------------------------------------------- 1 | import { randomColor } from 'randomcolor'; 2 | import options from '../utils/pieOptions'; 3 | 4 | /** 5 | * Returns chart data specific for Pie chart type with reversed axis processing 6 | * 7 | * @param {object} data chart data 8 | * @param {boolean} semi true or false 9 | * @param {array} colors array of colors used to present data 10 | */ 11 | const getPieReverseChartData = (data, semi, colors) => { 12 | const chartData = { 13 | data: { 14 | datasets: [], 15 | labels: [], 16 | }, 17 | options, 18 | colors: [], 19 | }; 20 | 21 | if (semi) { 22 | chartData.options.circumference = 180; 23 | chartData.options.rotation = -90; 24 | } else { 25 | chartData.options.circumference = 360; 26 | chartData.options.rotation = 0; 27 | } 28 | 29 | let colorIndex = 0; 30 | data.forEach((element, rowindex) => { 31 | element.forEach((value, colindex) => { 32 | const numericalValue = value.replace(/[^\d.-]/g, ''); 33 | if (colindex === 0) { 34 | if (value && value.length > 0) { 35 | const object = { data: [], backgroundColor: [], label: '' }; 36 | object.label = value; 37 | chartData.data.datasets.push(object); 38 | if (chartData.data.labels.length === 0) { 39 | chartData.data.labels.push(value); 40 | } 41 | } 42 | } else if (rowindex === 0) { 43 | chartData.data.labels.push(value); 44 | } else { 45 | let color = colors[colorIndex]; 46 | if (!colors || colorIndex >= colors.length) { 47 | color = randomColor(); 48 | } 49 | colorIndex += 1; 50 | if (chartData.data.datasets[rowindex - 1]) { 51 | chartData.data.datasets[rowindex - 1].backgroundColor.push(color); 52 | chartData.data.datasets[rowindex - 1].data.push(numericalValue); 53 | } 54 | chartData.colors.push(color); 55 | } 56 | }); 57 | }); 58 | 59 | const finalDatasets = []; 60 | chartData.data.datasets.forEach((dataset) => { 61 | if (dataset.data.length > 0) { 62 | finalDatasets.push(dataset); 63 | } 64 | }); 65 | 66 | chartData.data.datasets = finalDatasets; 67 | return chartData; 68 | }; 69 | 70 | export default getPieReverseChartData; 71 | -------------------------------------------------------------------------------- /src/charts/barReverse.js: -------------------------------------------------------------------------------- 1 | import { randomColor } from 'randomcolor'; 2 | import options from '../utils/lineOptions'; 3 | 4 | /** 5 | * Returns chart data specific for Bar chart type with reversed axis processing 6 | * 7 | * @param {object} data chart data 8 | * @param {boolean} stacked true or false 9 | * @param {array} colors array of colors used to present data 10 | */ 11 | const getBarReverseChartData = (data, stacked, colors) => { 12 | const chartData = { 13 | labels: [], 14 | datasets: [], 15 | info: [], 16 | annotations: [], 17 | options, 18 | colors: [], 19 | }; 20 | 21 | let columnCount = 0; 22 | let colorIndex = 0; 23 | data.forEach((element, rowindex) => { 24 | if (columnCount === 0) { 25 | columnCount = element.length; 26 | } 27 | element.forEach((value, colindex) => { 28 | const numericalValue = value.replace(/[^\d.-]/g, ''); 29 | 30 | if (rowindex === 0) { 31 | if (value && value.length > 0) { 32 | chartData.labels.push(value); 33 | } 34 | } else if (colindex === 0) { 35 | if (value && value.length > 0) { 36 | const object = { data: [] }; 37 | let color = colors[colorIndex]; 38 | if (!colors || colorIndex >= colors.length) { 39 | color = randomColor(); 40 | } 41 | colorIndex += 1; 42 | object.borderColor = color; 43 | object.backgroundColor = color; 44 | object.pointBorderColor = color; 45 | object.pointBackgroundColor = color; 46 | object.pointHoverBackgroundColor = color; 47 | object.pointHoverBorderColor = color; 48 | object.label = value; 49 | chartData.datasets.push(object); 50 | 51 | chartData.colors.push(color); 52 | } 53 | } else if (chartData.datasets[rowindex - 1]) { 54 | chartData.datasets[rowindex - 1].data.push(numericalValue); 55 | } 56 | }); 57 | }); 58 | 59 | chartData.options.scales.x.labels = chartData.labels; 60 | chartData.options.scales.x.stacked = stacked; 61 | chartData.options.scales.y.ticks = { 62 | beginAtZero: true, 63 | }; 64 | chartData.options.scales.x.ticks = { 65 | beginAtZero: true, 66 | }; 67 | return chartData; 68 | }; 69 | 70 | export default getBarReverseChartData; 71 | -------------------------------------------------------------------------------- /src/charts/bar.js: -------------------------------------------------------------------------------- 1 | import { randomColor } from 'randomcolor'; 2 | import options from '../utils/lineOptions'; 3 | 4 | /** 5 | * Returns chart data specific for Bar chart type 6 | * 7 | * @param {object} data chart data 8 | * @param {boolean} stacked true or false 9 | * @param {array} colors array of colors used to present data 10 | */ 11 | const getBarChartData = (data, stacked, colors) => { 12 | const chartData = { 13 | labels: [], 14 | datasets: [], 15 | info: [], 16 | annotations: [], 17 | options, 18 | colors: [], 19 | }; 20 | 21 | let columnCount = 0; 22 | let colorIndex = 0; 23 | data.forEach((element, rowindex) => { 24 | if (columnCount === 0) { 25 | columnCount = element.length; 26 | } 27 | element.forEach((value, colindex) => { 28 | const numericalValue = value.replace(/[^\d.-]/g, ''); 29 | 30 | if (rowindex === 0) { 31 | if (value && value.length > 0) { 32 | const object = { data: [] }; 33 | let color = colors[colorIndex]; 34 | if (!colors || colorIndex >= colors.length) { 35 | color = randomColor(); 36 | } 37 | colorIndex += 1; 38 | object.borderColor = color; 39 | object.backgroundColor = color; 40 | object.pointBorderColor = color; 41 | object.pointBackgroundColor = color; 42 | object.pointHoverBackgroundColor = color; 43 | object.pointHoverBorderColor = color; 44 | object.label = value; 45 | chartData.datasets.push(object); 46 | 47 | chartData.colors.push(color); 48 | } 49 | } else if (colindex === 0) { 50 | chartData.labels.push(value); 51 | } else if (chartData.datasets[colindex - 1]) { 52 | chartData.datasets[colindex - 1].data.push(numericalValue); 53 | } 54 | }); 55 | let i = element.length; 56 | for (; i < columnCount; ) { 57 | if (chartData.datasets[i - 1]) { 58 | chartData.datasets[i - 1].data.push(0); 59 | } 60 | i += 1; 61 | } 62 | }); 63 | 64 | chartData.options.scales.x.labels = chartData.labels; 65 | chartData.options.scales.x.stacked = stacked; 66 | chartData.options.scales.y.ticks = { 67 | beginAtZero: true, 68 | }; 69 | chartData.options.scales.x.ticks = { 70 | beginAtZero: true, 71 | }; 72 | 73 | return chartData; 74 | }; 75 | 76 | export default getBarChartData; 77 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | import React, { useState, useEffect } from 'react'; 2 | import axios from 'axios'; 3 | 4 | import processSpreadsheet from './utils/processSpreadsheet'; 5 | import getChart from './chart'; 6 | 7 | const GSHEETS_API = 'https://sheets.googleapis.com/v4/spreadsheets/'; 8 | /** 9 | * SmartChart component 10 | */ 11 | const SmartChart = (props) => { 12 | const [cdata, setCdata] = useState({}); 13 | const [fetchingData, setFetchingData] = useState(false); 14 | const [authError, setAuthError] = useState(false); 15 | const [fetchError, setFetchError] = useState(false); 16 | 17 | /** 18 | * Query Google sheets once the component mounts 19 | */ 20 | useEffect(() => { 21 | /** 22 | * Compose and run query using app state 23 | */ 24 | const runQuery = async () => { 25 | const { id, sheet, start, end, token } = props; 26 | if ( 27 | id && 28 | id.length > 5 && 29 | sheet && 30 | sheet.length > 0 && 31 | token && 32 | token.length > 0 33 | ) { 34 | let url = `${GSHEETS_API}${id}/values/${sheet}?key=${token}`; 35 | if (start && start.length > 0 && end && end.length > 0) { 36 | const grid = `!${start}:${end}`; 37 | url = `${GSHEETS_API}${id}/values/${sheet}${grid}?key=${token}`; 38 | } 39 | 40 | setFetchingData(true); 41 | setAuthError(false); 42 | setFetchError(false); 43 | 44 | try { 45 | const response = await axios.get(url); 46 | setFetchingData(false); 47 | process(response); 48 | } catch (error) { 49 | if (error.response && error.response.status === 403) { 50 | setAuthError(true); 51 | setFetchingData(false); 52 | } else { 53 | setFetchError(true); 54 | setFetchingData(false); 55 | } 56 | } 57 | } else { 58 | setFetchingData(false); 59 | } 60 | }; 61 | runQuery(); 62 | }, []); 63 | 64 | /** 65 | * Process fetched data, try to find best data to plot 66 | * @param {object} res query result 67 | */ 68 | const process = (res) => { 69 | if (res.data && res.data.values) { 70 | let processedData = processSpreadsheet(res.data.values); 71 | let done = false; 72 | while (processedData && processedData.data.length > 0 && !done) { 73 | const tempProcessedData = processSpreadsheet( 74 | res.data.values, 75 | processedData.startr + 1, 76 | processedData.startc + 1, 77 | ); 78 | if ( 79 | tempProcessedData && 80 | tempProcessedData.data.length > processedData.data.length 81 | ) { 82 | processedData = tempProcessedData; 83 | } else { 84 | done = true; 85 | } 86 | } 87 | 88 | setCdata(processedData); 89 | } 90 | }; 91 | 92 | if (fetchingData) { 93 | return ''; 94 | } 95 | 96 | if (authError) { 97 | return ( 98 |

99 | It looks like your Spreadsheet is private, please change its access to{' '} 100 | Anyone with the link and then try again 101 |

102 | ); 103 | } 104 | 105 | if (fetchError) { 106 | return

It looks like there is a connection issue, please try again.

; 107 | } 108 | 109 | /** 110 | * Support small screens 111 | * 112 | * @param {number} screenWidth screen width 113 | */ 114 | const getSmallScreenChartDimensions = (screenWidth) => { 115 | const width = (100 * screenWidth) / 100; 116 | const height = (95 * width) / 100; 117 | return [width, height]; 118 | }; 119 | 120 | const { data } = cdata; 121 | if (!data || data.length === 0) { 122 | return ''; 123 | } 124 | 125 | let maintainAspectRatio = true; 126 | let style = {}; 127 | if (window.innerWidth < 900) { 128 | maintainAspectRatio = false; 129 | const [width, height] = getSmallScreenChartDimensions(window.innerWidth); 130 | if (width && height) { 131 | style = { width, height }; 132 | } 133 | } 134 | 135 | const chart = getChart(data, maintainAspectRatio, props); 136 | return ( 137 |
138 |
{chart}
139 |
140 | ); 141 | }; 142 | 143 | export default SmartChart; 144 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # React Google Sheet to Chart 2 | 3 | [Postlight](https://postlight.com)'s React Google Sheet to Chart React component transforms Google Sheets to attractive charts in your webapp with minimal effort. Read all about it in [this handy introduction](https://postlight.com/trackchanges/transform-google-sheets-into-beautiful-charts-with-postlights-new-react-component). 4 | 5 | Try it now at the [demo site](https://robochart.netlify.com/) and check out the [demo site GitHub repository](https://github.com/postlight/robo-chart-web). 6 | 7 | ![Robo Chart preview](https://raw.githubusercontent.com/postlight/react-google-sheet-to-chart/master/static/images/robo-chart.gif) 8 | 9 | ## Installation 10 | 11 | The package can be installed via NPM: 12 | 13 | ```bash 14 | npm install @postlight/react-google-sheet-to-chart --save 15 | 16 | # or 17 | 18 | yarn add @postlight/react-google-sheet-to-chart 19 | ``` 20 | 21 | ## Usage 22 | 23 | To use this component, you'll need a Google API key. First **enable** Google Sheets API and then generate the API Key [here](https://console.cloud.google.com/apis/credentials) and restrict it to HTTP referrers (web sites). 24 | 25 | Second, you'll need a Google Sheet containing the data you wish to plot. (Be sure to check out [the spreadsheet format](#spreadsheet-format) guidelines.) 26 | 27 | Finally, import the React component and initialize it with at least three required props: 28 | 29 | - `id`: Spreadsheet ID, e.g. `1RE_JYUCXBXY2LNV5Tp5GegLnMue-CpfTVMxjdudZ8Js` (extractable from a Google sheet URL) 30 | - `sheet`: Sheet name to parse data from, e.g. `Sheet1` 31 | - `token`: The Google API key you created above 32 | 33 | ```javascript 34 | import RoboChart from '@postlight/react-google-sheet-to-chart'; 35 | 36 | // ...your component code and then... 37 | 38 | ; 43 | ``` 44 | 45 | ## Quick setup in an app 46 | 47 | - [Create a React app](https://github.com/facebook/create-react-app): 48 | 49 | ```shell 50 | yarn create react-app my-app 51 | cd my-app 52 | ``` 53 | 54 | - Install the package 55 | 56 | ```shell 57 | yarn add @postlight/react-google-sheet-to-chart 58 | ``` 59 | 60 | - Paste the following in `App.js` and replace `GOOGLE_SPREADSHEET_ID` and `GENERATED_GOOGLE_API_KEY` with appropriate values: 61 | 62 | ```javascript 63 | import React, { Component } from 'react'; 64 | import RoboChart from '@postlight/react-google-sheet-to-chart'; 65 | import './App.css'; 66 | 67 | const style = { width: '1200px', margin: '0 auto' }; 68 | class App extends Component { 69 | render() { 70 | return ( 71 |
72 | 77 |
78 | ); 79 | } 80 | } 81 | export default App; 82 | ``` 83 | 84 | - Start the project 85 | 86 | ```shell 87 | yarn start 88 | ``` 89 | 90 | ## Optional props 91 | 92 | - `start` e.g. "A5" (`start` and `end` create a custom range for your data) 93 | - `end` e.g. "E15" 94 | - `title` This is the chart title, e.g. "My Accounts" 95 | - `flipAxis` default: {false} 96 | - `startFrom` default: {0} 97 | - `stacked` Use only with type bar, default: {false} 98 | - `type` default: "line", should be one of: "line", "bar", "horizontalBar", "pie", "semi-pie", "doughnut", "semi-doughnut" 99 | - `colors` e.g. {['#a1a1a1', '#434343', '#ff0055']} 100 | - `xsuffix` Add a suffix to x-Axis labels, e.g. " USD" 101 | - `ysuffix` Add a suffix to y-Axis labels 102 | 103 | Example: 104 | 105 | ```javascript 106 | 114 | ``` 115 | 116 | ![Robo Chart preview](https://raw.githubusercontent.com/postlight/react-google-sheet-to-chart/master/static/images/robo-chart-2.png) 117 | 118 | ## Spreadsheet format 119 | 120 | In order to successfuly generate a chart, the Spreadsheet should have Row titles, Column titles and Values, example: 121 | 122 | ![Spreadsheet example](https://raw.githubusercontent.com/postlight/react-google-sheet-to-chart/master/static/images/spreadsheet-format.png) 123 | 124 | ## License 125 | 126 | Licensed under either of the below, at your preference: 127 | 128 | - Apache License, Version 2.0 129 | ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) 130 | - MIT license 131 | ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 132 | 133 | ## Contributing 134 | 135 | Unless it is explicitly stated otherwise, any contribution intentionally submitted for inclusion in the work, as defined in the Apache-2.0 license, shall be dual licensed as above without any additional terms or conditions. 136 | 137 | --- 138 | 139 | 🔬 A Labs project from your friends at [Postlight](https://postlight.com). Happy coding! 140 | -------------------------------------------------------------------------------- /src/chart.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { Line, Bar, Pie, Doughnut } from 'react-chartjs-2'; 3 | import 'chart.js/auto'; 4 | 5 | import getLineChartData from './charts/line'; 6 | import getLineReverseChartData from './charts/lineReverse'; 7 | import getHorizontalBarChartData from './charts/horizontalBar'; 8 | import getHorizontalBarReverseChartData from './charts/horizontalBarReverse'; 9 | import getBarChartData from './charts/bar'; 10 | import getBarReverseChartData from './charts/barReverse'; 11 | import getPieChartData from './charts/pie'; 12 | import getPieReverseChartData from './charts/pieReverse'; 13 | import handleOptions from './utils/handleOptions'; 14 | 15 | const getChart = (data, maintainAspectRatio, props) => { 16 | const { sheet } = props; 17 | let { startFrom, flipAxis, stacked, type, title, colors, xsuffix, ysuffix } = 18 | props; 19 | 20 | let chartData = {}; 21 | let datasets = {}; 22 | const columnCount = data[0].length; 23 | const rowCount = data.length; 24 | 25 | if (!colors) { 26 | colors = []; 27 | } 28 | if (!flipAxis) { 29 | flipAxis = false; 30 | } 31 | if (!stacked) { 32 | stacked = false; 33 | } 34 | if (!startFrom) { 35 | startFrom = 0; 36 | } 37 | if (!type) { 38 | type = 'line'; 39 | } 40 | if (!title) { 41 | title = sheet; 42 | } 43 | if (!xsuffix) { 44 | xsuffix = ''; 45 | } 46 | if (!ysuffix) { 47 | ysuffix = ''; 48 | } 49 | 50 | const flip = 51 | (rowCount > columnCount && flipAxis) || 52 | (rowCount <= columnCount && !flipAxis); 53 | const chartKey = `${type} ${title} ${startFrom} ${flipAxis} ${stacked} ${xsuffix} ${ysuffix}`; 54 | let chart; 55 | switch (type) { 56 | case 'line': 57 | if (flip) { 58 | chartData = getLineReverseChartData(data, colors); 59 | } else { 60 | chartData = getLineChartData(data, colors); 61 | } 62 | 63 | handleOptions( 64 | chartData.options, 65 | maintainAspectRatio, 66 | title, 67 | startFrom, 68 | type, 69 | xsuffix, 70 | ysuffix, 71 | ); 72 | 73 | datasets = { datasets: chartData.datasets, labels: chartData.labels }; 74 | chart = ( 75 | 76 | ); 77 | break; 78 | case 'bar': 79 | if (flip) { 80 | chartData = getBarReverseChartData(data, stacked, colors); 81 | } else { 82 | chartData = getBarChartData(data, stacked, colors); 83 | } 84 | 85 | handleOptions( 86 | chartData.options, 87 | maintainAspectRatio, 88 | title, 89 | startFrom, 90 | type, 91 | xsuffix, 92 | ysuffix, 93 | ); 94 | 95 | datasets = { datasets: chartData.datasets, labels: chartData.labels }; 96 | chart = ( 97 | 98 | ); 99 | break; 100 | case 'horizontalBar': 101 | if (flip) { 102 | chartData = getHorizontalBarReverseChartData(data, colors); 103 | } else { 104 | chartData = getHorizontalBarChartData(data, colors); 105 | } 106 | 107 | handleOptions( 108 | chartData.options, 109 | maintainAspectRatio, 110 | title, 111 | startFrom, 112 | type, 113 | xsuffix, 114 | ysuffix, 115 | ); 116 | 117 | datasets = { datasets: chartData.datasets, labels: chartData.labels }; 118 | chart = ( 119 | 120 | ); 121 | break; 122 | case 'pie': 123 | if (flip) { 124 | chartData = getPieReverseChartData(data, false, colors); 125 | } else { 126 | chartData = getPieChartData(data, false, colors); 127 | } 128 | 129 | chartData.options.maintainAspectRatio = maintainAspectRatio; 130 | chartData.options.plugins.title.text = title; 131 | chart = ( 132 | 133 | ); 134 | break; 135 | case 'semi-pie': 136 | if (flip) { 137 | chartData = getPieReverseChartData(data, true, colors); 138 | } else { 139 | chartData = getPieChartData(data, true, colors); 140 | } 141 | 142 | chartData.options.maintainAspectRatio = maintainAspectRatio; 143 | chartData.options.plugins.title.text = title; 144 | chart = ( 145 | 146 | ); 147 | break; 148 | case 'doughnut': 149 | if (flip) { 150 | chartData = getPieReverseChartData(data, false, colors); 151 | } else { 152 | chartData = getPieChartData(data, false, colors); 153 | } 154 | 155 | chartData.options.maintainAspectRatio = maintainAspectRatio; 156 | chartData.options.plugins.title.text = title; 157 | chart = ( 158 | 163 | ); 164 | break; 165 | case 'semi-doughnut': 166 | if (flip) { 167 | chartData = getPieReverseChartData(data, true, colors); 168 | } else { 169 | chartData = getPieChartData(data, true, colors); 170 | } 171 | 172 | chartData.options.maintainAspectRatio = maintainAspectRatio; 173 | chartData.options.plugins.title.text = title; 174 | chart = ( 175 | 180 | ); 181 | break; 182 | 183 | default: 184 | break; 185 | } 186 | 187 | return chart; 188 | }; 189 | 190 | export default getChart; 191 | --------------------------------------------------------------------------------