Repository: WebSheets/websheets
Branch: master
Commit: 0f3f8f9cb176
Files: 20
Total size: 22.7 KB
Directory structure:
gitextract_jmmls_9q/
├── .babelrc
├── .gitignore
├── .npmignore
├── .travis.yml
├── LICENSE.md
├── README.md
├── demo/
│ ├── index.html
│ ├── multi.html
│ └── no_iteration.html
├── index.js
├── mocha.opts
├── package.json
├── src/
│ ├── WebSheet.events.js
│ ├── WebSheet.js
│ ├── constants.js
│ ├── index.js
│ ├── utils/
│ │ └── events.js
│ └── websheet.css
├── test/
│ └── babelHook.js
└── webpack.config.js
================================================
FILE CONTENTS
================================================
================================================
FILE: .babelrc
================================================
{
"presets": ["es2015"]
}
================================================
FILE: .gitignore
================================================
.DS_Store
*.pyc
tags
TAGS
*.swp
*.egg-info
.emacs.desktop
.#*
dist
*~
.buildout
.emacs.d/.autosaves
.emacs.d/.emacs-places
.emacs.d/tramp
.zsh/cache
*.elc
.emacs.d/history
.emacs.d/site/nxhtml
.virtualenvs
.ipython
*.stackdump
node_modules/
Thumbs.db
desktop.ini
*.sublime-project
build/
================================================
FILE: .npmignore
================================================
dist/
src/
test/
*.html
================================================
FILE: .travis.yml
================================================
language: node_js
node_js:
- "4.1"
- "4.0"
- "5.7"
sudo: false
================================================
FILE: LICENSE.md
================================================
Copyright (c) 2016 Matt Basta
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
================================================
FILE: README.md
================================================
# Websheets
[](https://travis-ci.org/WebSheets/websheets)
An experiment to make a spreadsheet engine for the web.
## Features
- Formulas
+ Addition, subtraction, multiplication, division (with order of operations)
+ Ability to reference individual cells
+ Ability to pass ranges of cells (in two dimensions) as function arguments
+ Very large list of compatible Excel-style functions
+ Dynamically update as referenced values update
- Dynamically sized columns
- Keyboard interactions similar to Excel
- Drag and drop
+ Drag cell to move
+ Drag corner of cell to copy
+ Copied cells adjust their formulas
+ Support for pinning identifiers with `$` (e.g., `$A$1`, `A$2`)
- Import parsed data (`loadData`)
- Supports Excel-style circular reference convergence
================================================
FILE: demo/index.html
================================================
Websheets Demo
================================================
FILE: demo/multi.html
================================================
Websheets Demo
Sheet1
Sheet2
================================================
FILE: demo/no_iteration.html
================================================
Websheets Demo
================================================
FILE: index.js
================================================
module.exports = require('./build');
================================================
FILE: mocha.opts
================================================
--require babelHook
================================================
FILE: package.json
================================================
{
"name": "websheets",
"version": "0.3.1",
"description": "A spreadsheet component for the web",
"devDependencies": {
"babel-cli": "^6.4.5",
"babel-loader": "^6.2.1",
"babel-polyfill": "^6.3.14",
"babel-preset-es2015": "^6.3.13",
"babel-register": "^6.6.0",
"mocha": "^2.4.5",
"webpack": "^1.12.12"
},
"scripts": {
"build": "./node_modules/.bin/babel src --out-dir build --source-maps --no-babelrc --presets es2015",
"prepublish": "rm -rf build/* && npm run build ",
"test": "./node_modules/.bin/mocha --recursive",
"watch": "fswatch -0 src | xargs -0 -n 1 -I {} npm run web",
"web": "./node_modules/.bin/webpack --config=webpack.config.js --progress"
},
"main": "index.js",
"repository": {
"type": "git",
"url": "https://github.com/websheets/websheets.git"
},
"keywords": [
"spreadsheet",
"table",
"excel"
],
"author": "Matt Basta ",
"license": "MIT",
"bugs": {
"url": "https://github.com/websheets/websheets/issues"
},
"homepage": "https://github.com/websheets/websheets",
"dependencies": {
"websheets-core": "^0.2.2"
}
}
================================================
FILE: src/WebSheet.events.js
================================================
import {DRAG_HANDLE, DRAG_MOVE, DRAG_NONE} from './constants';
import {getCellID, getCellPos, parseExpression as parse} from 'websheets-core';
import {listen, unlisten} from './utils/events';
export function unbindEvents(self) {
unlisten(self.elem, 'focus');
unlisten(self.elem, 'blur');
unlisten(self.elem, 'keyup');
unlisten(self.elem, 'keydown');
unlisten(self.elem, 'mousedown');
unlisten(self.elem, 'mouseup');
unlisten(self.elem, 'mouseover');
};
export function initEvents(self) {
unbindEvents(self);
const {elem} = self;
listen(elem, 'focus', onFocus.bind(self));
listen(elem, 'blur', onBlur.bind(self));
listen(elem, 'keyup', onKeyup.bind(self));
listen(elem, 'keydown', onKeydown.bind(self));
listen(elem, 'mousedown', onMousedown.bind(self));
listen(elem, 'mouseup', onMouseup.bind(self));
listen(elem, 'mouseover', onMouseover.bind(self));
};
export function onFocus(e) {
const row = e.target.getAttribute('data-row') | 0;
const col = e.target.getAttribute('data-col') | 0;
e.target.value = (this.data[row] || [])[col] || '';
e.target.select(0, e.target.value.length);
e.target.parentNode.className = 'websheet-cell-wrapper websheet-has-focus';
};
export function onBlur(e) {
const row = e.target.getAttribute('data-row') | 0;
const col = e.target.getAttribute('data-col') | 0;
this.setValueAtPosition(row, col, e.target.value);
if (this.calculated[row] && col in this.calculated[row]) {
e.target.value = this.formatValue(
getCellID(row, col),
this.calculated[row][col]
);
}
e.target.parentNode.className = 'websheet-cell-wrapper';
};
export function onKeydown(e) {
var next;
if (e.keyCode === 37 && e.target.selectionStart === 0) {
next = this.getCell(e.target.getAttribute('data-id-prev-col'));
} else if (e.keyCode === 39 && e.target.selectionEnd === e.target.value.length) {
next = this.getCell(e.target.getAttribute('data-id-next-col'));
}
if (next) {
next.focus();
e.preventDefault();
}
};
export function onKeyup(e) {
var next;
if (e.keyCode === 13 || e.keyCode === 40) {
next = this.getCell(e.target.getAttribute('data-id-next-row'));
} else if (e.keyCode === 38) {
next = this.getCell(e.target.getAttribute('data-id-prev-row'));
}
if (next) {
next.focus();
}
};
export function onMousedown(e) {
const {target} = e;
if (!target.classList.contains('websheet-has-focus')) {
return;
}
e.preventDefault();
const id = this.dragSource = target.firstChild.getAttribute('data-id');
const pos = getCellPos(id);
// Assign the value of the currently focused cell's input to the cell, just
// incase it changed and hasn't been updated on the blur event.
this.setValueAtPosition(pos.row, pos.col, target.firstChild.value);
if (e.layerX > target.clientWidth - 10 && e.layerY > target.clientHeight - 10) {
// this.data[pos.row] = this.data[pos.row] || [];
// this.data[pos.row][pos.col] = target.value;
this.dragType = DRAG_HANDLE;
return;
}
this.dragType = DRAG_MOVE;
this.elem.className += ' websheet-grabbing';
};
export function onMouseup(e) {
const {target} = e;
if (this.dragType !== DRAG_NONE &&
target.classList.contains('websheet-cell')) {
let pos = getCellPos(this.dragSource);
let pos2 = getCellPos(target.getAttribute('data-id'));
if (this.dragType === DRAG_MOVE) {
this.setValueAtPosition(pos2.row, pos2.col, this.getValueAtPos(pos.row, pos.col) || '');
this.clearCell(pos.row, pos.col);
e.target.focus();
} else if (this.dragType === DRAG_HANDLE && (pos.row === pos2.row || pos.col === pos2.col)) {
const rawSource = this.getValueAtPos(pos.row, pos.col) || '';
const parsedSource = rawSource[0] === '=' && parse(rawSource.substr(1));
if (pos.row === pos2.row) {
let min = Math.min(pos.col, pos2.col);
for (let i = min; i <= Math.max(pos.col, pos2.col); i++) {
if (i === pos.col) continue;
if (parsedSource) {
let tmp = parsedSource.clone();
tmp.adjust(0, i - min);
this.setValueAtPosition(pos.row, i, '=' + tmp.toString());
} else {
this.setValueAtPosition(pos.row, i, rawSource);
}
}
} else if (pos.col === pos2.col) {
const min = Math.min(pos.row, pos2.row);
for (let i = min; i <= Math.max(pos.row, pos2.row); i++) {
if (i === pos.row) continue;
if (parsedSource) {
let tmp = parsedSource.clone();
tmp.adjust(i - min, 0);
this.setValueAtPosition(i, pos.col, '=' + tmp.toString());
} else {
this.setValueAtPosition(i, pos.col, rawSource);
}
}
} else {
console.error('Cannot drag handle diagonally');
}
}
}
this.elem.className = 'websheet';
this.dragType = DRAG_NONE;
this.dragSource = null;
const existing = this.elem.querySelectorAll('.websheet-cell-hover');
for (let i = 0; i < existing.length; i++) {
existing[i].classList.remove('websheet-cell-hover');
}
};
export function onMouseover(e) {
if (this.dragType === DRAG_NONE) return;
if (!e.target.classList.contains('websheet-cell')) return;
const toRemoveClassFrom = [];
const existing = this.elem.querySelectorAll('.websheet-cell-hover');
for (let i = 0; i < existing.length; i++) {
toRemoveClassFrom.push(existing[i].firstChild.dataset.id);
}
const targetID = e.target.dataset.id;
if (targetID === this.dragSource) {
return;
}
if (this.dragType === DRAG_HANDLE) {
const destPos = getCellPos(targetID);
const srcPos = getCellPos(this.dragSource);
if (destPos.col === srcPos.col) {
for (let i = Math.min(srcPos.row, destPos.row); i <= Math.max(srcPos.row, destPos.row); i++) {
const tmp = getCellID(i, srcPos.col);
const trcfTmp = toRemoveClassFrom.indexOf(tmp);
if (trcfTmp !== -1) {
toRemoveClassFrom.splice(trcfTmp, 1);
} else {
this.getCell(tmp).parentNode.classList.add('websheet-cell-hover');
}
}
} else if (destPos.row === srcPos.row) {
for (let i = Math.min(srcPos.col, destPos.col); i <= Math.max(srcPos.col, destPos.col); i++) {
const tmp = getCellID(srcPos.row, i);
const trcfTmp = toRemoveClassFrom.indexOf(tmp);
if (trcfTmp !== -1) {
toRemoveClassFrom.splice(trcfTmp, 1);
} else {
this.getCell(tmp).parentNode.classList.add('websheet-cell-hover');
}
}
}
} else {
e.target.parentNode.classList.add('websheet-cell-hover');
}
toRemoveClassFrom.forEach(id => {
this.getCell(id).parentNode.classList.remove('websheet-cell-hover');
});
};
================================================
FILE: src/WebSheet.js
================================================
import WebSheet, {Emitter, getCellID, getCellPos, parseExpression} from 'websheets-core';
import {DRAG_NONE} from './constants';
import {initEvents, unbindEvents} from './WebSheet.events';
import {listen, unlisten} from './utils/events';
const DEFAULT_COLUMN_WIDTH = 120; // px
const DEFAULT_BORDER_WIDTH = 1; // px
const defaultParams = {
noBrowser: false,
};
const WINDOW_MOUSEUP = Symbol('window.onmouseup');
export default class BrowserWebSheet extends WebSheet {
constructor(elem, params = {}) {
super(Object.assign({}, defaultParams, params));
this.elem = elem;
this.elem.className = 'websheet';
this.columnWidths = [];
for (let i = 0; i < this.width; i++) {
this.columnWidths.push(DEFAULT_COLUMN_WIDTH);
}
this.cellCache = {};
this.dragType = DRAG_NONE;
this.dragSource = null;
if (this.noBrowser || this.immutable) {
return;
}
listen(window, 'mouseup', this[WINDOW_MOUSEUP] = e => {
if (this.dragType === DRAG_NONE) {
return;
}
this.dragType = DRAG_NONE;
this.dragSource = null;
this.elem.className = 'websheet';
});
}
destroy() {
unlisten(window, 'mouseup', this[WINDOW_MOUSEUP]);
unbindEvents(this);
}
addColumn(rerender = true) {
this.columnWidths.push(DEFAULT_COLUMN_WIDTH);
super.addColumn(rerender);
}
calculateValueAtPosition(row, col, expression) {
const value = super.calculateValueAtPosition(row, col, expression);
if (typeof value === 'undefined') {
return;
}
const cellID = getCellID(row, col);
const elem = this.getCell(cellID);
if (elem) {
elem.value = this.formatValue(cellID, value);
}
}
clearCell(row, col) {
super.clearCell(row, col);
const cellID = getCellID(row, col);
const elem = this.getCell(cellID);
if (elem) {
elem.value = '';
}
}
forceRerender() {
if (this.noBrowser) {
return;
}
// First, update the element to be the correct dimensions.
let width = this.columnWidths.reduce((a, b) => a + b); // Get the width of each column
width += DEFAULT_BORDER_WIDTH;
// width -= this.width * DEFAULT_BORDER_WIDTH; // Account for border widths
this.elem.style.width = width + 'px';
while (this.elem.childNodes.length) {
this.elem.removeChild(this.elem.firstChild);
}
this.cellCache = {};
const workQueue = [];
// Create each row and cell
for (let i = 0; i < this.height; i++) {
const row = document.createElement('div');
row.style.width = `${width}px`;
row.className = 'websheet-row';
this.elem.appendChild(row);
const rowDataCache = this.data[i] || [];
const rowCalculatedCache = this.calculated[i] || [];
for (let j = 0; j < this.width; j++) {
const cellID = getCellID(i, j);
const cell = document.createElement('input');
cell.className = 'websheet-cell';
if (this.immutable) {
cell.readOnly = true;
}
const cellWrapper = document.createElement('div');
cellWrapper.className = 'websheet-cell-wrapper';
cellWrapper.style.width = (this.columnWidths[j] - 1) + 'px';
cellWrapper.appendChild(cell);
row.appendChild(cellWrapper);
let cellValue = null;
if (j in rowCalculatedCache &&
rowCalculatedCache[j] !== null &&
typeof rowCalculatedCache[j] !== 'undefined') {
cellValue = rowCalculatedCache[j];
} else if (j in rowDataCache &&
rowDataCache[j] !== null &&
typeof rowDataCache[j] !== 'undefined') {
cellValue = rowDataCache[j];
}
if (cellValue !== null) {
cell.value = this.formatValue(cellID, cellValue);
}
cell.title = cellID;
cell.setAttribute('data-id', cellID);
cell.setAttribute('data-id-prev-col', getCellID(i, j - 1));
cell.setAttribute('data-id-prev-row', getCellID(i - 1, j));
cell.setAttribute('data-id-next-col', getCellID(i, j + 1));
cell.setAttribute('data-id-next-row', getCellID(i + 1, j));
cell.setAttribute('data-row', i);
cell.setAttribute('data-col', j);
if (cell.value[0] === '=') {
workQueue.push(
this.setValueAtPosition.bind(this, i, j, cell.value, true)
);
}
}
}
if (!this.immutable || this.noBrowser) {
// Bind event handlers
initEvents(this);
}
workQueue.forEach(task => task());
}
getCell(id) {
if (this.noBrowser) return null;
if (id in this.cellCache) return this.cellCache[id];
return this.cellCache[id] = this.elem.querySelector(`[data-id="${id}"]`);
}
insertColumnBefore(idx) {
this.columnWidths.splice(idx, 0, DEFAULT_COLUMN_WIDTH);
super.insertColumnBefore(idx);
}
popColumn() {
if (this.width < 2) throw new Error('Cannot make spreadsheet that small');
this.columnWidths.pop();
super.popColumn();
}
removeColumn(idx) {
if (this.width < 2) throw new Error('Cannot make spreadsheet that small');
if (idx < 0 || idx >= this.width) throw new Error('Removing cells that do not exist');
this.columnWidths.splice(idx, 1);
super.removeColumn(idx);
}
setValueAtPosition(row, col, value, force = false) {
const updated = super.setValueAtPosition(row, col, value, force);
if (!updated || value[0] === '=') {
return;
}
const cellID = getCellID(row, col);
const elem = this.getCell(cellID);
if (elem) {
elem.value = this.formatValue(cellID, value);
}
}
};
================================================
FILE: src/constants.js
================================================
export const DRAG_HANDLE = 2;
export const DRAG_MOVE = 1;
export const DRAG_NONE = 0;
================================================
FILE: src/index.js
================================================
import {
Emitter,
getCellid,
getCellPos,
parseExpression,
WebSheet as HeadlessWebSheet,
WebSheetContext,
} from 'websheets-core';
import WebSheet from './WebSheet';
// This is because `export default` exports {default: WebSheet}
exports = module.exports = WebSheet;
export default WebSheet;
export {
Emitter,
getCellid,
getCellPos,
HeadlessWebSheet,
parseExpression,
WebSheetContext,
};
================================================
FILE: src/utils/events.js
================================================
const LISTENERS = Symbol('websheets listeners');
export function listen(elem, event, cb) {
if (!(LISTENERS in elem)) {
elem[LISTENERS] = {};
}
elem[LISTENERS][event] = elem[LISTENERS][event] || [];
elem[LISTENERS][event].push(cb);
elem.addEventListener(event, cb, elem !== window);
};
export function unlisten(elem, event, listenerToRemove = null) {
if (!elem[LISTENERS] || !elem[LISTENERS][event]) return;
elem[LISTENERS][event].forEach(listener => {
if (listenerToRemove && listener !== listenerToRemove) {
return;
}
elem.removeEventListener(event, listener, elem !== window);
});
};
================================================
FILE: src/websheet.css
================================================
.websheet,
.websheet *,
.websheet *:before,
.websheet *:after {
-webkit-box-sizing: content-box;
box-sizing: content-box;
}
.websheet.websheet-grabbing {
cursor: -webkit-grabbing;
cursor: grabbing;
}
.websheet-row {
display: block;
padding-right: 1px;
}
.websheet-row-sticky {
position: -webkit-sticky;
position: sticky;
top: 0;
z-index: 2;
}
.websheet-cell-wrapper {
border: 1px solid #000;
display: inline-block;
margin-bottom: -1px;
margin-right: -1px;
position: relative;
z-index: 1;
}
.websheet-cell-wrapper.websheet-has-focus {
border: 0;
cursor: -webkit-grab;
cursor: grab;
margin: -6px -6px -6px -5px !important; /* sorry not sorry */
padding: 6px;
z-index: 2;
}
.websheet-cell-wrapper:last-child {
margin-right: 0;
}
.websheet-row:last-child .websheet-cell-wrapper {
margin-bottom: 0;
}
.websheet-cell {
-moz-appearance: none;
-webkit-appearance: none;
background: transparent;
border: 0;
border-radius: 1px;
box-shadow: 0 0 0 0 rgba(51, 153, 255, 0.85);
display: block;
font-size: 13px;
height: 2em;
transition: box-shadow 0.15s, z-index 0.15s;
width: 100%;
}
.websheet-cell:focus {
border: 0 solid rgb(51, 153, 255);
box-shadow: 0 0 0 7px rgba(51, 153, 255, 0.85);
outline: none;
}
.websheet-cell-wrapper:after {
background: rgb(51, 153, 255);
border: 2px solid white;
border-radius: 4px;
bottom: 5px;
content: "";
display: block;
height: 5px;
opacity: 0;
position: absolute;
right: 5px;
transition: bottom 0.25s, right 0.25s, opacity 0.1s;
width: 5px;
}
.websheet-cell-wrapper.websheet-has-focus:after {
bottom: -4px;
cursor: crosshair;
opacity: 1;
right: -4px;
}
.websheet-cell-hover input {
background: rgb(51, 153, 255);
color: #fff;
}
================================================
FILE: test/babelHook.js
================================================
require('babel-polyfill');
require('babel-register');
================================================
FILE: webpack.config.js
================================================
var path = require('path');
var webpack = require('webpack');
module.exports = {
// devtool: 'source-maps',
entry: {
app: ['./src/index.js']
},
output: {
path: path.resolve(__dirname, 'dist', 'src'),
publicPath: '/',
filename: '/websheet.min.js',
library: 'WebSheet',
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
compress: {warnings: false},
mangle: {},
sourceMap: false,
}),
new webpack.optimize.DedupePlugin(),
],
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
},
],
},
};