code
stringlengths
24
2.07M
docstring
stringlengths
25
85.3k
func_name
stringlengths
1
92
language
stringclasses
1 value
repo
stringlengths
5
64
path
stringlengths
4
172
url
stringlengths
44
218
license
stringclasses
7 values
function hasAny(str, substrings) { for (var i = 0; i < substrings.length; i++) if (str.indexOf(substrings[i]) > -1) return true; return false; }
Encloses a value around quotes if needed (makes a value safe for CSV insertion)
hasAny
javascript
mholt/PapaParse
papaparse.js
https://github.com/mholt/PapaParse/blob/master/papaparse.js
MIT
function ChunkStreamer(config) { this._handle = null; this._finished = false; this._completed = false; this._halted = false; this._input = null; this._baseIndex = 0; this._partialLine = ''; this._rowCount = 0; this._start = 0; this._nextChunk = null; this.isFirstChunk = true; this._completeResults = { data: [], errors: [], meta: {} }; replaceConfig.call(this, config); this.parseChunk = function(chunk, isFakeChunk) { // First chunk pre-processing const skipFirstNLines = parseInt(this._config.skipFirstNLines) || 0; if (this.isFirstChunk && skipFirstNLines > 0) { let _newline = this._config.newline; if (!_newline) { const quoteChar = this._config.quoteChar || '"'; _newline = this._handle.guessLineEndings(chunk, quoteChar); } const splitChunk = chunk.split(_newline); chunk = [...splitChunk.slice(skipFirstNLines)].join(_newline); } if (this.isFirstChunk && isFunction(this._config.beforeFirstChunk)) { var modifiedChunk = this._config.beforeFirstChunk(chunk); if (modifiedChunk !== undefined) chunk = modifiedChunk; } this.isFirstChunk = false; this._halted = false; // Rejoin the line we likely just split in two by chunking the file var aggregate = this._partialLine + chunk; this._partialLine = ''; var results = this._handle.parse(aggregate, this._baseIndex, !this._finished); if (this._handle.paused() || this._handle.aborted()) { this._halted = true; return; } var lastIndex = results.meta.cursor; if (!this._finished) { this._partialLine = aggregate.substring(lastIndex - this._baseIndex); this._baseIndex = lastIndex; } if (results && results.data) this._rowCount += results.data.length; var finishedIncludingPreview = this._finished || (this._config.preview && this._rowCount >= this._config.preview); if (IS_PAPA_WORKER) { global.postMessage({ results: results, workerId: Papa.WORKER_ID, finished: finishedIncludingPreview }); } else if (isFunction(this._config.chunk) && !isFakeChunk) { this._config.chunk(results, this._handle); if (this._handle.paused() || this._handle.aborted()) { this._halted = true; return; } results = undefined; this._completeResults = undefined; } if (!this._config.step && !this._config.chunk) { this._completeResults.data = this._completeResults.data.concat(results.data); this._completeResults.errors = this._completeResults.errors.concat(results.errors); this._completeResults.meta = results.meta; } if (!this._completed && finishedIncludingPreview && isFunction(this._config.complete) && (!results || !results.meta.aborted)) { this._config.complete(this._completeResults, this._input); this._completed = true; } if (!finishedIncludingPreview && (!results || !results.meta.paused)) this._nextChunk(); return results; }; this._sendError = function(error) { if (isFunction(this._config.error)) this._config.error(error); else if (IS_PAPA_WORKER && this._config.error) { global.postMessage({ workerId: Papa.WORKER_ID, error: error, finished: false }); } }; function replaceConfig(config) { // Deep-copy the config so we can edit it var configCopy = copy(config); configCopy.chunkSize = parseInt(configCopy.chunkSize); // parseInt VERY important so we don't concatenate strings! if (!config.step && !config.chunk) configCopy.chunkSize = null; // disable Range header if not streaming; bad values break IIS - see issue #196 this._handle = new ParserHandle(configCopy); this._handle.streamer = this; this._config = configCopy; // persist the copy to the caller } }
ChunkStreamer is the base prototype for various streamer implementations.
ChunkStreamer
javascript
mholt/PapaParse
papaparse.js
https://github.com/mholt/PapaParse/blob/master/papaparse.js
MIT
function replaceConfig(config) { // Deep-copy the config so we can edit it var configCopy = copy(config); configCopy.chunkSize = parseInt(configCopy.chunkSize); // parseInt VERY important so we don't concatenate strings! if (!config.step && !config.chunk) configCopy.chunkSize = null; // disable Range header if not streaming; bad values break IIS - see issue #196 this._handle = new ParserHandle(configCopy); this._handle.streamer = this; this._config = configCopy; // persist the copy to the caller }
ChunkStreamer is the base prototype for various streamer implementations.
replaceConfig
javascript
mholt/PapaParse
papaparse.js
https://github.com/mholt/PapaParse/blob/master/papaparse.js
MIT
function NetworkStreamer(config) { config = config || {}; if (!config.chunkSize) config.chunkSize = Papa.RemoteChunkSize; ChunkStreamer.call(this, config); var xhr; if (IS_WORKER) { this._nextChunk = function() { this._readChunk(); this._chunkLoaded(); }; } else { this._nextChunk = function() { this._readChunk(); }; } this.stream = function(url) { this._input = url; this._nextChunk(); // Starts streaming }; this._readChunk = function() { if (this._finished) { this._chunkLoaded(); return; } xhr = new XMLHttpRequest(); if (this._config.withCredentials) { xhr.withCredentials = this._config.withCredentials; } if (!IS_WORKER) { xhr.onload = bindFunction(this._chunkLoaded, this); xhr.onerror = bindFunction(this._chunkError, this); } xhr.open(this._config.downloadRequestBody ? 'POST' : 'GET', this._input, !IS_WORKER); // Headers can only be set when once the request state is OPENED if (this._config.downloadRequestHeaders) { var headers = this._config.downloadRequestHeaders; for (var headerName in headers) { xhr.setRequestHeader(headerName, headers[headerName]); } } if (this._config.chunkSize) { var end = this._start + this._config.chunkSize - 1; // minus one because byte range is inclusive xhr.setRequestHeader('Range', 'bytes=' + this._start + '-' + end); } try { xhr.send(this._config.downloadRequestBody); } catch (err) { this._chunkError(err.message); } if (IS_WORKER && xhr.status === 0) this._chunkError(); }; this._chunkLoaded = function() { if (xhr.readyState !== 4) return; if (xhr.status < 200 || xhr.status >= 400) { this._chunkError(); return; } // Use chunckSize as it may be a diference on reponse lentgh due to characters with more than 1 byte this._start += this._config.chunkSize ? this._config.chunkSize : xhr.responseText.length; this._finished = !this._config.chunkSize || this._start >= getFileSize(xhr); this.parseChunk(xhr.responseText); }; this._chunkError = function(errorMessage) { var errorText = xhr.statusText || errorMessage; this._sendError(new Error(errorText)); }; function getFileSize(xhr) { var contentRange = xhr.getResponseHeader('Content-Range'); if (contentRange === null) { // no content range, then finish! return -1; } return parseInt(contentRange.substring(contentRange.lastIndexOf('/') + 1)); } }
ChunkStreamer is the base prototype for various streamer implementations.
NetworkStreamer
javascript
mholt/PapaParse
papaparse.js
https://github.com/mholt/PapaParse/blob/master/papaparse.js
MIT
function getFileSize(xhr) { var contentRange = xhr.getResponseHeader('Content-Range'); if (contentRange === null) { // no content range, then finish! return -1; } return parseInt(contentRange.substring(contentRange.lastIndexOf('/') + 1)); }
ChunkStreamer is the base prototype for various streamer implementations.
getFileSize
javascript
mholt/PapaParse
papaparse.js
https://github.com/mholt/PapaParse/blob/master/papaparse.js
MIT
function FileStreamer(config) { config = config || {}; if (!config.chunkSize) config.chunkSize = Papa.LocalChunkSize; ChunkStreamer.call(this, config); var reader, slice; // FileReader is better than FileReaderSync (even in worker) - see http://stackoverflow.com/q/24708649/1048862 // But Firefox is a pill, too - see issue #76: https://github.com/mholt/PapaParse/issues/76 var usingAsyncReader = typeof FileReader !== 'undefined'; // Safari doesn't consider it a function - see issue #105 this.stream = function(file) { this._input = file; slice = file.slice || file.webkitSlice || file.mozSlice; if (usingAsyncReader) { reader = new FileReader(); // Preferred method of reading files, even in workers reader.onload = bindFunction(this._chunkLoaded, this); reader.onerror = bindFunction(this._chunkError, this); } else reader = new FileReaderSync(); // Hack for running in a web worker in Firefox this._nextChunk(); // Starts streaming }; this._nextChunk = function() { if (!this._finished && (!this._config.preview || this._rowCount < this._config.preview)) this._readChunk(); }; this._readChunk = function() { var input = this._input; if (this._config.chunkSize) { var end = Math.min(this._start + this._config.chunkSize, this._input.size); input = slice.call(input, this._start, end); } var txt = reader.readAsText(input, this._config.encoding); if (!usingAsyncReader) this._chunkLoaded({ target: { result: txt } }); // mimic the async signature }; this._chunkLoaded = function(event) { // Very important to increment start each time before handling results this._start += this._config.chunkSize; this._finished = !this._config.chunkSize || this._start >= this._input.size; this.parseChunk(event.target.result); }; this._chunkError = function() { this._sendError(reader.error); }; }
ChunkStreamer is the base prototype for various streamer implementations.
FileStreamer
javascript
mholt/PapaParse
papaparse.js
https://github.com/mholt/PapaParse/blob/master/papaparse.js
MIT
function StringStreamer(config) { config = config || {}; ChunkStreamer.call(this, config); var remaining; this.stream = function(s) { remaining = s; return this._nextChunk(); }; this._nextChunk = function() { if (this._finished) return; var size = this._config.chunkSize; var chunk; if(size) { chunk = remaining.substring(0, size); remaining = remaining.substring(size); } else { chunk = remaining; remaining = ''; } this._finished = !remaining; return this.parseChunk(chunk); }; }
ChunkStreamer is the base prototype for various streamer implementations.
StringStreamer
javascript
mholt/PapaParse
papaparse.js
https://github.com/mholt/PapaParse/blob/master/papaparse.js
MIT
function ReadableStreamStreamer(config) { config = config || {}; ChunkStreamer.call(this, config); var queue = []; var parseOnData = true; var streamHasEnded = false; this.pause = function() { ChunkStreamer.prototype.pause.apply(this, arguments); this._input.pause(); }; this.resume = function() { ChunkStreamer.prototype.resume.apply(this, arguments); this._input.resume(); }; this.stream = function(stream) { this._input = stream; this._input.on('data', this._streamData); this._input.on('end', this._streamEnd); this._input.on('error', this._streamError); }; this._checkIsFinished = function() { if (streamHasEnded && queue.length === 1) { this._finished = true; } }; this._nextChunk = function() { this._checkIsFinished(); if (queue.length) { this.parseChunk(queue.shift()); } else { parseOnData = true; } }; this._streamData = bindFunction(function(chunk) { try { queue.push(typeof chunk === 'string' ? chunk : chunk.toString(this._config.encoding)); if (parseOnData) { parseOnData = false; this._checkIsFinished(); this.parseChunk(queue.shift()); } } catch (error) { this._streamError(error); } }, this); this._streamError = bindFunction(function(error) { this._streamCleanUp(); this._sendError(error); }, this); this._streamEnd = bindFunction(function() { this._streamCleanUp(); streamHasEnded = true; this._streamData(''); }, this); this._streamCleanUp = bindFunction(function() { this._input.removeListener('data', this._streamData); this._input.removeListener('end', this._streamEnd); this._input.removeListener('error', this._streamError); }, this); }
ChunkStreamer is the base prototype for various streamer implementations.
ReadableStreamStreamer
javascript
mholt/PapaParse
papaparse.js
https://github.com/mholt/PapaParse/blob/master/papaparse.js
MIT
function DuplexStreamStreamer(_config) { var Duplex = require('stream').Duplex; var config = copy(_config); var parseOnWrite = true; var writeStreamHasFinished = false; var parseCallbackQueue = []; var stream = null; this._onCsvData = function(results) { var data = results.data; if (!stream.push(data) && !this._handle.paused()) { // the writeable consumer buffer has filled up // so we need to pause until more items // can be processed this._handle.pause(); } }; this._onCsvComplete = function() { // node will finish the read stream when // null is pushed stream.push(null); }; config.step = bindFunction(this._onCsvData, this); config.complete = bindFunction(this._onCsvComplete, this); ChunkStreamer.call(this, config); this._nextChunk = function() { if (writeStreamHasFinished && parseCallbackQueue.length === 1) { this._finished = true; } if (parseCallbackQueue.length) { parseCallbackQueue.shift()(); } else { parseOnWrite = true; } }; this._addToParseQueue = function(chunk, callback) { // add to queue so that we can indicate // completion via callback // node will automatically pause the incoming stream // when too many items have been added without their // callback being invoked parseCallbackQueue.push(bindFunction(function() { this.parseChunk(typeof chunk === 'string' ? chunk : chunk.toString(config.encoding)); if (isFunction(callback)) { return callback(); } }, this)); if (parseOnWrite) { parseOnWrite = false; this._nextChunk(); } }; this._onRead = function() { if (this._handle.paused()) { // the writeable consumer can handle more data // so resume the chunk parsing this._handle.resume(); } }; this._onWrite = function(chunk, encoding, callback) { this._addToParseQueue(chunk, callback); }; this._onWriteComplete = function() { writeStreamHasFinished = true; // have to write empty string // so parser knows its done this._addToParseQueue(''); }; this.getStream = function() { return stream; }; stream = new Duplex({ readableObjectMode: true, decodeStrings: false, read: bindFunction(this._onRead, this), write: bindFunction(this._onWrite, this) }); stream.once('finish', bindFunction(this._onWriteComplete, this)); }
ChunkStreamer is the base prototype for various streamer implementations.
DuplexStreamStreamer
javascript
mholt/PapaParse
papaparse.js
https://github.com/mholt/PapaParse/blob/master/papaparse.js
MIT
function ParserHandle(_config) { // One goal is to minimize the use of regular expressions... var MAX_FLOAT = Math.pow(2, 53); var MIN_FLOAT = -MAX_FLOAT; var FLOAT = /^\s*-?(\d+\.?|\.\d+|\d+\.\d+)([eE][-+]?\d+)?\s*$/; var ISO_DATE = /^((\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z)))$/; var self = this; var _stepCounter = 0; // Number of times step was called (number of rows parsed) var _rowCounter = 0; // Number of rows that have been parsed so far var _input; // The input being parsed var _parser; // The core parser being used var _paused = false; // Whether we are paused or not var _aborted = false; // Whether the parser has aborted or not var _delimiterError; // Temporary state between delimiter detection and processing results var _fields = []; // Fields are from the header row of the input, if there is one var _results = { // The last results returned from the parser data: [], errors: [], meta: {} }; if (isFunction(_config.step)) { var userStep = _config.step; _config.step = function(results) { _results = results; if (needsHeaderRow()) processResults(); else // only call user's step function after header row { processResults(); // It's possbile that this line was empty and there's no row here after all if (_results.data.length === 0) return; _stepCounter += results.data.length; if (_config.preview && _stepCounter > _config.preview) _parser.abort(); else { _results.data = _results.data[0]; userStep(_results, self); } } }; } /** * Parses input. Most users won't need, and shouldn't mess with, the baseIndex * and ignoreLastRow parameters. They are used by streamers (wrapper functions) * when an input comes in multiple chunks, like from a file. */ this.parse = function(input, baseIndex, ignoreLastRow) { var quoteChar = _config.quoteChar || '"'; if (!_config.newline) _config.newline = this.guessLineEndings(input, quoteChar); _delimiterError = false; if (!_config.delimiter) { var delimGuess = guessDelimiter(input, _config.newline, _config.skipEmptyLines, _config.comments, _config.delimitersToGuess); if (delimGuess.successful) _config.delimiter = delimGuess.bestDelimiter; else { _delimiterError = true; // add error after parsing (otherwise it would be overwritten) _config.delimiter = Papa.DefaultDelimiter; } _results.meta.delimiter = _config.delimiter; } else if(isFunction(_config.delimiter)) { _config.delimiter = _config.delimiter(input); _results.meta.delimiter = _config.delimiter; } var parserConfig = copy(_config); if (_config.preview && _config.header) parserConfig.preview++; // to compensate for header row _input = input; _parser = new Parser(parserConfig); _results = _parser.parse(_input, baseIndex, ignoreLastRow); processResults(); return _paused ? { meta: { paused: true } } : (_results || { meta: { paused: false } }); }; this.paused = function() { return _paused; }; this.pause = function() { _paused = true; _parser.abort(); // If it is streaming via "chunking", the reader will start appending correctly already so no need to substring, // otherwise we can get duplicate content within a row _input = isFunction(_config.chunk) ? "" : _input.substring(_parser.getCharIndex()); }; this.resume = function() { if(self.streamer._halted) { _paused = false; self.streamer.parseChunk(_input, true); } else { // Bugfix: #636 In case the processing hasn't halted yet // wait for it to halt in order to resume setTimeout(self.resume, 3); } }; this.aborted = function() { return _aborted; }; this.abort = function() { _aborted = true; _parser.abort(); _results.meta.aborted = true; if (isFunction(_config.complete)) _config.complete(_results); _input = ''; }; this.guessLineEndings = function(input, quoteChar) { input = input.substring(0, 1024 * 1024); // max length 1 MB // Replace all the text inside quotes var re = new RegExp(escapeRegExp(quoteChar) + '([^]*?)' + escapeRegExp(quoteChar), 'gm'); input = input.replace(re, ''); var r = input.split('\r'); var n = input.split('\n'); var nAppearsFirst = (n.length > 1 && n[0].length < r[0].length); if (r.length === 1 || nAppearsFirst) return '\n'; var numWithN = 0; for (var i = 0; i < r.length; i++) { if (r[i][0] === '\n') numWithN++; } return numWithN >= r.length / 2 ? '\r\n' : '\r'; }; function testEmptyLine(s) { return _config.skipEmptyLines === 'greedy' ? s.join('').trim() === '' : s.length === 1 && s[0].length === 0; } function testFloat(s) { if (FLOAT.test(s)) { var floatValue = parseFloat(s); if (floatValue > MIN_FLOAT && floatValue < MAX_FLOAT) { return true; } } return false; } function processResults() { if (_results && _delimiterError) { addError('Delimiter', 'UndetectableDelimiter', 'Unable to auto-detect delimiting character; defaulted to \'' + Papa.DefaultDelimiter + '\''); _delimiterError = false; } if (_config.skipEmptyLines) { _results.data = _results.data.filter(function(d) { return !testEmptyLine(d); }); } if (needsHeaderRow()) fillHeaderFields(); return applyHeaderAndDynamicTypingAndTransformation(); } function needsHeaderRow() { return _config.header && _fields.length === 0; } function fillHeaderFields() { if (!_results) return; function addHeader(header, i) { header = stripBom(header); if (isFunction(_config.transformHeader)) header = _config.transformHeader(header, i); _fields.push(header); } if (Array.isArray(_results.data[0])) { for (var i = 0; needsHeaderRow() && i < _results.data.length; i++) _results.data[i].forEach(addHeader); _results.data.splice(0, 1); } // if _results.data[0] is not an array, we are in a step where _results.data is the row. else _results.data.forEach(addHeader); } function shouldApplyDynamicTyping(field) { // Cache function values to avoid calling it for each row if (_config.dynamicTypingFunction && _config.dynamicTyping[field] === undefined) { _config.dynamicTyping[field] = _config.dynamicTypingFunction(field); } return (_config.dynamicTyping[field] || _config.dynamicTyping) === true; } function parseDynamic(field, value) { if (shouldApplyDynamicTyping(field)) { if (value === 'true' || value === 'TRUE') return true; else if (value === 'false' || value === 'FALSE') return false; else if (testFloat(value)) return parseFloat(value); else if (ISO_DATE.test(value)) return new Date(value); else return (value === '' ? null : value); } return value; } function applyHeaderAndDynamicTypingAndTransformation() { if (!_results || (!_config.header && !_config.dynamicTyping && !_config.transform)) return _results; function processRow(rowSource, i) { var row = _config.header ? {} : []; var j; for (j = 0; j < rowSource.length; j++) { var field = j; var value = rowSource[j]; if (_config.header) field = j >= _fields.length ? '__parsed_extra' : _fields[j]; if (_config.transform) value = _config.transform(value,field); value = parseDynamic(field, value); if (field === '__parsed_extra') { row[field] = row[field] || []; row[field].push(value); } else row[field] = value; } if (_config.header) { if (j > _fields.length) addError('FieldMismatch', 'TooManyFields', 'Too many fields: expected ' + _fields.length + ' fields but parsed ' + j, _rowCounter + i); else if (j < _fields.length) addError('FieldMismatch', 'TooFewFields', 'Too few fields: expected ' + _fields.length + ' fields but parsed ' + j, _rowCounter + i); } return row; } var incrementBy = 1; if (!_results.data.length || Array.isArray(_results.data[0])) { _results.data = _results.data.map(processRow); incrementBy = _results.data.length; } else _results.data = processRow(_results.data, 0); if (_config.header && _results.meta) _results.meta.fields = _fields; _rowCounter += incrementBy; return _results; } function guessDelimiter(input, newline, skipEmptyLines, comments, delimitersToGuess) { var bestDelim, bestDelta, fieldCountPrevRow, maxFieldCount; delimitersToGuess = delimitersToGuess || [',', '\t', '|', ';', Papa.RECORD_SEP, Papa.UNIT_SEP]; for (var i = 0; i < delimitersToGuess.length; i++) { var delim = delimitersToGuess[i]; var delta = 0, avgFieldCount = 0, emptyLinesCount = 0; fieldCountPrevRow = undefined; var preview = new Parser({ comments: comments, delimiter: delim, newline: newline, preview: 10 }).parse(input); for (var j = 0; j < preview.data.length; j++) { if (skipEmptyLines && testEmptyLine(preview.data[j])) { emptyLinesCount++; continue; } var fieldCount = preview.data[j].length; avgFieldCount += fieldCount; if (typeof fieldCountPrevRow === 'undefined') { fieldCountPrevRow = fieldCount; continue; } else if (fieldCount > 0) { delta += Math.abs(fieldCount - fieldCountPrevRow); fieldCountPrevRow = fieldCount; } } if (preview.data.length > 0) avgFieldCount /= (preview.data.length - emptyLinesCount); if ((typeof bestDelta === 'undefined' || delta <= bestDelta) && (typeof maxFieldCount === 'undefined' || avgFieldCount > maxFieldCount) && avgFieldCount > 1.99) { bestDelta = delta; bestDelim = delim; maxFieldCount = avgFieldCount; } } _config.delimiter = bestDelim; return { successful: !!bestDelim, bestDelimiter: bestDelim }; } function addError(type, code, msg, row) { var error = { type: type, code: code, message: msg }; if(row !== undefined) { error.row = row; } _results.errors.push(error); } }
ChunkStreamer is the base prototype for various streamer implementations.
ParserHandle
javascript
mholt/PapaParse
papaparse.js
https://github.com/mholt/PapaParse/blob/master/papaparse.js
MIT
function testEmptyLine(s) { return _config.skipEmptyLines === 'greedy' ? s.join('').trim() === '' : s.length === 1 && s[0].length === 0; }
Parses input. Most users won't need, and shouldn't mess with, the baseIndex and ignoreLastRow parameters. They are used by streamers (wrapper functions) when an input comes in multiple chunks, like from a file.
testEmptyLine
javascript
mholt/PapaParse
papaparse.js
https://github.com/mholt/PapaParse/blob/master/papaparse.js
MIT
function testFloat(s) { if (FLOAT.test(s)) { var floatValue = parseFloat(s); if (floatValue > MIN_FLOAT && floatValue < MAX_FLOAT) { return true; } } return false; }
Parses input. Most users won't need, and shouldn't mess with, the baseIndex and ignoreLastRow parameters. They are used by streamers (wrapper functions) when an input comes in multiple chunks, like from a file.
testFloat
javascript
mholt/PapaParse
papaparse.js
https://github.com/mholt/PapaParse/blob/master/papaparse.js
MIT
function processResults() { if (_results && _delimiterError) { addError('Delimiter', 'UndetectableDelimiter', 'Unable to auto-detect delimiting character; defaulted to \'' + Papa.DefaultDelimiter + '\''); _delimiterError = false; } if (_config.skipEmptyLines) { _results.data = _results.data.filter(function(d) { return !testEmptyLine(d); }); } if (needsHeaderRow()) fillHeaderFields(); return applyHeaderAndDynamicTypingAndTransformation(); }
Parses input. Most users won't need, and shouldn't mess with, the baseIndex and ignoreLastRow parameters. They are used by streamers (wrapper functions) when an input comes in multiple chunks, like from a file.
processResults
javascript
mholt/PapaParse
papaparse.js
https://github.com/mholt/PapaParse/blob/master/papaparse.js
MIT
function needsHeaderRow() { return _config.header && _fields.length === 0; }
Parses input. Most users won't need, and shouldn't mess with, the baseIndex and ignoreLastRow parameters. They are used by streamers (wrapper functions) when an input comes in multiple chunks, like from a file.
needsHeaderRow
javascript
mholt/PapaParse
papaparse.js
https://github.com/mholt/PapaParse/blob/master/papaparse.js
MIT
function fillHeaderFields() { if (!_results) return; function addHeader(header, i) { header = stripBom(header); if (isFunction(_config.transformHeader)) header = _config.transformHeader(header, i); _fields.push(header); } if (Array.isArray(_results.data[0])) { for (var i = 0; needsHeaderRow() && i < _results.data.length; i++) _results.data[i].forEach(addHeader); _results.data.splice(0, 1); } // if _results.data[0] is not an array, we are in a step where _results.data is the row. else _results.data.forEach(addHeader); }
Parses input. Most users won't need, and shouldn't mess with, the baseIndex and ignoreLastRow parameters. They are used by streamers (wrapper functions) when an input comes in multiple chunks, like from a file.
fillHeaderFields
javascript
mholt/PapaParse
papaparse.js
https://github.com/mholt/PapaParse/blob/master/papaparse.js
MIT
function addHeader(header, i) { header = stripBom(header); if (isFunction(_config.transformHeader)) header = _config.transformHeader(header, i); _fields.push(header); }
Parses input. Most users won't need, and shouldn't mess with, the baseIndex and ignoreLastRow parameters. They are used by streamers (wrapper functions) when an input comes in multiple chunks, like from a file.
addHeader
javascript
mholt/PapaParse
papaparse.js
https://github.com/mholt/PapaParse/blob/master/papaparse.js
MIT
function shouldApplyDynamicTyping(field) { // Cache function values to avoid calling it for each row if (_config.dynamicTypingFunction && _config.dynamicTyping[field] === undefined) { _config.dynamicTyping[field] = _config.dynamicTypingFunction(field); } return (_config.dynamicTyping[field] || _config.dynamicTyping) === true; }
Parses input. Most users won't need, and shouldn't mess with, the baseIndex and ignoreLastRow parameters. They are used by streamers (wrapper functions) when an input comes in multiple chunks, like from a file.
shouldApplyDynamicTyping
javascript
mholt/PapaParse
papaparse.js
https://github.com/mholt/PapaParse/blob/master/papaparse.js
MIT
function parseDynamic(field, value) { if (shouldApplyDynamicTyping(field)) { if (value === 'true' || value === 'TRUE') return true; else if (value === 'false' || value === 'FALSE') return false; else if (testFloat(value)) return parseFloat(value); else if (ISO_DATE.test(value)) return new Date(value); else return (value === '' ? null : value); } return value; }
Parses input. Most users won't need, and shouldn't mess with, the baseIndex and ignoreLastRow parameters. They are used by streamers (wrapper functions) when an input comes in multiple chunks, like from a file.
parseDynamic
javascript
mholt/PapaParse
papaparse.js
https://github.com/mholt/PapaParse/blob/master/papaparse.js
MIT
function applyHeaderAndDynamicTypingAndTransformation() { if (!_results || (!_config.header && !_config.dynamicTyping && !_config.transform)) return _results; function processRow(rowSource, i) { var row = _config.header ? {} : []; var j; for (j = 0; j < rowSource.length; j++) { var field = j; var value = rowSource[j]; if (_config.header) field = j >= _fields.length ? '__parsed_extra' : _fields[j]; if (_config.transform) value = _config.transform(value,field); value = parseDynamic(field, value); if (field === '__parsed_extra') { row[field] = row[field] || []; row[field].push(value); } else row[field] = value; } if (_config.header) { if (j > _fields.length) addError('FieldMismatch', 'TooManyFields', 'Too many fields: expected ' + _fields.length + ' fields but parsed ' + j, _rowCounter + i); else if (j < _fields.length) addError('FieldMismatch', 'TooFewFields', 'Too few fields: expected ' + _fields.length + ' fields but parsed ' + j, _rowCounter + i); } return row; } var incrementBy = 1; if (!_results.data.length || Array.isArray(_results.data[0])) { _results.data = _results.data.map(processRow); incrementBy = _results.data.length; } else _results.data = processRow(_results.data, 0); if (_config.header && _results.meta) _results.meta.fields = _fields; _rowCounter += incrementBy; return _results; }
Parses input. Most users won't need, and shouldn't mess with, the baseIndex and ignoreLastRow parameters. They are used by streamers (wrapper functions) when an input comes in multiple chunks, like from a file.
applyHeaderAndDynamicTypingAndTransformation
javascript
mholt/PapaParse
papaparse.js
https://github.com/mholt/PapaParse/blob/master/papaparse.js
MIT
function processRow(rowSource, i) { var row = _config.header ? {} : []; var j; for (j = 0; j < rowSource.length; j++) { var field = j; var value = rowSource[j]; if (_config.header) field = j >= _fields.length ? '__parsed_extra' : _fields[j]; if (_config.transform) value = _config.transform(value,field); value = parseDynamic(field, value); if (field === '__parsed_extra') { row[field] = row[field] || []; row[field].push(value); } else row[field] = value; } if (_config.header) { if (j > _fields.length) addError('FieldMismatch', 'TooManyFields', 'Too many fields: expected ' + _fields.length + ' fields but parsed ' + j, _rowCounter + i); else if (j < _fields.length) addError('FieldMismatch', 'TooFewFields', 'Too few fields: expected ' + _fields.length + ' fields but parsed ' + j, _rowCounter + i); } return row; }
Parses input. Most users won't need, and shouldn't mess with, the baseIndex and ignoreLastRow parameters. They are used by streamers (wrapper functions) when an input comes in multiple chunks, like from a file.
processRow
javascript
mholt/PapaParse
papaparse.js
https://github.com/mholt/PapaParse/blob/master/papaparse.js
MIT
function guessDelimiter(input, newline, skipEmptyLines, comments, delimitersToGuess) { var bestDelim, bestDelta, fieldCountPrevRow, maxFieldCount; delimitersToGuess = delimitersToGuess || [',', '\t', '|', ';', Papa.RECORD_SEP, Papa.UNIT_SEP]; for (var i = 0; i < delimitersToGuess.length; i++) { var delim = delimitersToGuess[i]; var delta = 0, avgFieldCount = 0, emptyLinesCount = 0; fieldCountPrevRow = undefined; var preview = new Parser({ comments: comments, delimiter: delim, newline: newline, preview: 10 }).parse(input); for (var j = 0; j < preview.data.length; j++) { if (skipEmptyLines && testEmptyLine(preview.data[j])) { emptyLinesCount++; continue; } var fieldCount = preview.data[j].length; avgFieldCount += fieldCount; if (typeof fieldCountPrevRow === 'undefined') { fieldCountPrevRow = fieldCount; continue; } else if (fieldCount > 0) { delta += Math.abs(fieldCount - fieldCountPrevRow); fieldCountPrevRow = fieldCount; } } if (preview.data.length > 0) avgFieldCount /= (preview.data.length - emptyLinesCount); if ((typeof bestDelta === 'undefined' || delta <= bestDelta) && (typeof maxFieldCount === 'undefined' || avgFieldCount > maxFieldCount) && avgFieldCount > 1.99) { bestDelta = delta; bestDelim = delim; maxFieldCount = avgFieldCount; } } _config.delimiter = bestDelim; return { successful: !!bestDelim, bestDelimiter: bestDelim }; }
Parses input. Most users won't need, and shouldn't mess with, the baseIndex and ignoreLastRow parameters. They are used by streamers (wrapper functions) when an input comes in multiple chunks, like from a file.
guessDelimiter
javascript
mholt/PapaParse
papaparse.js
https://github.com/mholt/PapaParse/blob/master/papaparse.js
MIT
function addError(type, code, msg, row) { var error = { type: type, code: code, message: msg }; if(row !== undefined) { error.row = row; } _results.errors.push(error); }
Parses input. Most users won't need, and shouldn't mess with, the baseIndex and ignoreLastRow parameters. They are used by streamers (wrapper functions) when an input comes in multiple chunks, like from a file.
addError
javascript
mholt/PapaParse
papaparse.js
https://github.com/mholt/PapaParse/blob/master/papaparse.js
MIT
function Parser(config) { // Unpack the config object config = config || {}; var delim = config.delimiter; var newline = config.newline; var comments = config.comments; var step = config.step; var preview = config.preview; var fastMode = config.fastMode; var quoteChar; var renamedHeaders = null; var headerParsed = false; if (config.quoteChar === undefined || config.quoteChar === null) { quoteChar = '"'; } else { quoteChar = config.quoteChar; } var escapeChar = quoteChar; if (config.escapeChar !== undefined) { escapeChar = config.escapeChar; } // Delimiter must be valid if (typeof delim !== 'string' || Papa.BAD_DELIMITERS.indexOf(delim) > -1) delim = ','; // Comment character must be valid if (comments === delim) throw new Error('Comment character same as delimiter'); else if (comments === true) comments = '#'; else if (typeof comments !== 'string' || Papa.BAD_DELIMITERS.indexOf(comments) > -1) comments = false; // Newline must be valid: \r, \n, or \r\n if (newline !== '\n' && newline !== '\r' && newline !== '\r\n') newline = '\n'; // We're gonna need these at the Parser scope var cursor = 0; var aborted = false; this.parse = function(input, baseIndex, ignoreLastRow) { // For some reason, in Chrome, this speeds things up (!?) if (typeof input !== 'string') throw new Error('Input must be a string'); // We don't need to compute some of these every time parse() is called, // but having them in a more local scope seems to perform better var inputLen = input.length, delimLen = delim.length, newlineLen = newline.length, commentsLen = comments.length; var stepIsFunction = isFunction(step); // Establish starting state cursor = 0; var data = [], errors = [], row = [], lastCursor = 0; if (!input) return returnable(); if (fastMode || (fastMode !== false && input.indexOf(quoteChar) === -1)) { var rows = input.split(newline); for (var i = 0; i < rows.length; i++) { row = rows[i]; cursor += row.length; if (i !== rows.length - 1) cursor += newline.length; else if (ignoreLastRow) return returnable(); if (comments && row.substring(0, commentsLen) === comments) continue; if (stepIsFunction) { data = []; pushRow(row.split(delim)); doStep(); if (aborted) return returnable(); } else pushRow(row.split(delim)); if (preview && i >= preview) { data = data.slice(0, preview); return returnable(true); } } return returnable(); } var nextDelim = input.indexOf(delim, cursor); var nextNewline = input.indexOf(newline, cursor); var quoteCharRegex = new RegExp(escapeRegExp(escapeChar) + escapeRegExp(quoteChar), 'g'); var quoteSearch = input.indexOf(quoteChar, cursor); // Parser loop for (;;) { // Field has opening quote if (input[cursor] === quoteChar) { // Start our search for the closing quote where the cursor is quoteSearch = cursor; // Skip the opening quote cursor++; for (;;) { // Find closing quote quoteSearch = input.indexOf(quoteChar, quoteSearch + 1); //No other quotes are found - no other delimiters if (quoteSearch === -1) { if (!ignoreLastRow) { // No closing quote... what a pity errors.push({ type: 'Quotes', code: 'MissingQuotes', message: 'Quoted field unterminated', row: data.length, // row has yet to be inserted index: cursor }); } return finish(); } // Closing quote at EOF if (quoteSearch === inputLen - 1) { var value = input.substring(cursor, quoteSearch).replace(quoteCharRegex, quoteChar); return finish(value); } // If this quote is escaped, it's part of the data; skip it // If the quote character is the escape character, then check if the next character is the escape character if (quoteChar === escapeChar && input[quoteSearch + 1] === escapeChar) { quoteSearch++; continue; } // If the quote character is not the escape character, then check if the previous character was the escape character if (quoteChar !== escapeChar && quoteSearch !== 0 && input[quoteSearch - 1] === escapeChar) { continue; } if(nextDelim !== -1 && nextDelim < (quoteSearch + 1)) { nextDelim = input.indexOf(delim, (quoteSearch + 1)); } if(nextNewline !== -1 && nextNewline < (quoteSearch + 1)) { nextNewline = input.indexOf(newline, (quoteSearch + 1)); } // Check up to nextDelim or nextNewline, whichever is closest var checkUpTo = nextNewline === -1 ? nextDelim : Math.min(nextDelim, nextNewline); var spacesBetweenQuoteAndDelimiter = extraSpaces(checkUpTo); // Closing quote followed by delimiter or 'unnecessary spaces + delimiter' if (input.substr(quoteSearch + 1 + spacesBetweenQuoteAndDelimiter, delimLen) === delim) { row.push(input.substring(cursor, quoteSearch).replace(quoteCharRegex, quoteChar)); cursor = quoteSearch + 1 + spacesBetweenQuoteAndDelimiter + delimLen; // If char after following delimiter is not quoteChar, we find next quote char position if (input[quoteSearch + 1 + spacesBetweenQuoteAndDelimiter + delimLen] !== quoteChar) { quoteSearch = input.indexOf(quoteChar, cursor); } nextDelim = input.indexOf(delim, cursor); nextNewline = input.indexOf(newline, cursor); break; } var spacesBetweenQuoteAndNewLine = extraSpaces(nextNewline); // Closing quote followed by newline or 'unnecessary spaces + newLine' if (input.substring(quoteSearch + 1 + spacesBetweenQuoteAndNewLine, quoteSearch + 1 + spacesBetweenQuoteAndNewLine + newlineLen) === newline) { row.push(input.substring(cursor, quoteSearch).replace(quoteCharRegex, quoteChar)); saveRow(quoteSearch + 1 + spacesBetweenQuoteAndNewLine + newlineLen); nextDelim = input.indexOf(delim, cursor); // because we may have skipped the nextDelim in the quoted field quoteSearch = input.indexOf(quoteChar, cursor); // we search for first quote in next line if (stepIsFunction) { doStep(); if (aborted) return returnable(); } if (preview && data.length >= preview) return returnable(true); break; } // Checks for valid closing quotes are complete (escaped quotes or quote followed by EOF/delimiter/newline) -- assume these quotes are part of an invalid text string errors.push({ type: 'Quotes', code: 'InvalidQuotes', message: 'Trailing quote on quoted field is malformed', row: data.length, // row has yet to be inserted index: cursor }); quoteSearch++; continue; } continue; } // Comment found at start of new line if (comments && row.length === 0 && input.substring(cursor, cursor + commentsLen) === comments) { if (nextNewline === -1) // Comment ends at EOF return returnable(); cursor = nextNewline + newlineLen; nextNewline = input.indexOf(newline, cursor); nextDelim = input.indexOf(delim, cursor); continue; } // Next delimiter comes before next newline, so we've reached end of field if (nextDelim !== -1 && (nextDelim < nextNewline || nextNewline === -1)) { row.push(input.substring(cursor, nextDelim)); cursor = nextDelim + delimLen; // we look for next delimiter char nextDelim = input.indexOf(delim, cursor); continue; } // End of row if (nextNewline !== -1) { row.push(input.substring(cursor, nextNewline)); saveRow(nextNewline + newlineLen); if (stepIsFunction) { doStep(); if (aborted) return returnable(); } if (preview && data.length >= preview) return returnable(true); continue; } break; } return finish(); function pushRow(row) { data.push(row); lastCursor = cursor; } /** * checks if there are extra spaces after closing quote and given index without any text * if Yes, returns the number of spaces */ function extraSpaces(index) { var spaceLength = 0; if (index !== -1) { var textBetweenClosingQuoteAndIndex = input.substring(quoteSearch + 1, index); if (textBetweenClosingQuoteAndIndex && textBetweenClosingQuoteAndIndex.trim() === '') { spaceLength = textBetweenClosingQuoteAndIndex.length; } } return spaceLength; } /** * Appends the remaining input from cursor to the end into * row, saves the row, calls step, and returns the results. */ function finish(value) { if (ignoreLastRow) return returnable(); if (typeof value === 'undefined') value = input.substring(cursor); row.push(value); cursor = inputLen; // important in case parsing is paused pushRow(row); if (stepIsFunction) doStep(); return returnable(); } /** * Appends the current row to the results. It sets the cursor * to newCursor and finds the nextNewline. The caller should * take care to execute user's step function and check for * preview and end parsing if necessary. */ function saveRow(newCursor) { cursor = newCursor; pushRow(row); row = []; nextNewline = input.indexOf(newline, cursor); } /** Returns an object with the results, errors, and meta. */ function returnable(stopped) { if (config.header && !baseIndex && data.length && !headerParsed) { const result = data[0]; const headerCount = Object.create(null); // To track the count of each base header const usedHeaders = new Set(result); // To track used headers and avoid duplicates let duplicateHeaders = false; for (let i = 0; i < result.length; i++) { let header = stripBom(result[i]); if (isFunction(config.transformHeader)) header = config.transformHeader(header, i); if (!headerCount[header]) { headerCount[header] = 1; result[i] = header; } else { let newHeader; let suffixCount = headerCount[header]; // Find a unique new header do { newHeader = `${header}_${suffixCount}`; suffixCount++; } while (usedHeaders.has(newHeader)); usedHeaders.add(newHeader); // Mark this new Header as used result[i] = newHeader; headerCount[header]++; duplicateHeaders = true; if (renamedHeaders === null) { renamedHeaders = {}; } renamedHeaders[newHeader] = header; } usedHeaders.add(header); // Ensure the original header is marked as used } if (duplicateHeaders) { console.warn('Duplicate headers found and renamed.'); } headerParsed = true; } return { data: data, errors: errors, meta: { delimiter: delim, linebreak: newline, aborted: aborted, truncated: !!stopped, cursor: lastCursor + (baseIndex || 0), renamedHeaders: renamedHeaders } }; } /** Executes the user's step function and resets data & errors. */ function doStep() { step(returnable()); data = []; errors = []; } }; /** Sets the abort flag */ this.abort = function() { aborted = true; }; /** Gets the cursor position */ this.getCharIndex = function() { return cursor; }; }
The core parser implements speedy and correct CSV parsing
Parser
javascript
mholt/PapaParse
papaparse.js
https://github.com/mholt/PapaParse/blob/master/papaparse.js
MIT
function pushRow(row) { data.push(row); lastCursor = cursor; }
The core parser implements speedy and correct CSV parsing
pushRow
javascript
mholt/PapaParse
papaparse.js
https://github.com/mholt/PapaParse/blob/master/papaparse.js
MIT
function extraSpaces(index) { var spaceLength = 0; if (index !== -1) { var textBetweenClosingQuoteAndIndex = input.substring(quoteSearch + 1, index); if (textBetweenClosingQuoteAndIndex && textBetweenClosingQuoteAndIndex.trim() === '') { spaceLength = textBetweenClosingQuoteAndIndex.length; } } return spaceLength; }
checks if there are extra spaces after closing quote and given index without any text if Yes, returns the number of spaces
extraSpaces
javascript
mholt/PapaParse
papaparse.js
https://github.com/mholt/PapaParse/blob/master/papaparse.js
MIT
function finish(value) { if (ignoreLastRow) return returnable(); if (typeof value === 'undefined') value = input.substring(cursor); row.push(value); cursor = inputLen; // important in case parsing is paused pushRow(row); if (stepIsFunction) doStep(); return returnable(); }
Appends the remaining input from cursor to the end into row, saves the row, calls step, and returns the results.
finish
javascript
mholt/PapaParse
papaparse.js
https://github.com/mholt/PapaParse/blob/master/papaparse.js
MIT
function saveRow(newCursor) { cursor = newCursor; pushRow(row); row = []; nextNewline = input.indexOf(newline, cursor); }
Appends the current row to the results. It sets the cursor to newCursor and finds the nextNewline. The caller should take care to execute user's step function and check for preview and end parsing if necessary.
saveRow
javascript
mholt/PapaParse
papaparse.js
https://github.com/mholt/PapaParse/blob/master/papaparse.js
MIT
function returnable(stopped) { if (config.header && !baseIndex && data.length && !headerParsed) { const result = data[0]; const headerCount = Object.create(null); // To track the count of each base header const usedHeaders = new Set(result); // To track used headers and avoid duplicates let duplicateHeaders = false; for (let i = 0; i < result.length; i++) { let header = stripBom(result[i]); if (isFunction(config.transformHeader)) header = config.transformHeader(header, i); if (!headerCount[header]) { headerCount[header] = 1; result[i] = header; } else { let newHeader; let suffixCount = headerCount[header]; // Find a unique new header do { newHeader = `${header}_${suffixCount}`; suffixCount++; } while (usedHeaders.has(newHeader)); usedHeaders.add(newHeader); // Mark this new Header as used result[i] = newHeader; headerCount[header]++; duplicateHeaders = true; if (renamedHeaders === null) { renamedHeaders = {}; } renamedHeaders[newHeader] = header; } usedHeaders.add(header); // Ensure the original header is marked as used } if (duplicateHeaders) { console.warn('Duplicate headers found and renamed.'); } headerParsed = true; } return { data: data, errors: errors, meta: { delimiter: delim, linebreak: newline, aborted: aborted, truncated: !!stopped, cursor: lastCursor + (baseIndex || 0), renamedHeaders: renamedHeaders } }; }
Returns an object with the results, errors, and meta.
returnable
javascript
mholt/PapaParse
papaparse.js
https://github.com/mholt/PapaParse/blob/master/papaparse.js
MIT
function doStep() { step(returnable()); data = []; errors = []; }
Executes the user's step function and resets data & errors.
doStep
javascript
mholt/PapaParse
papaparse.js
https://github.com/mholt/PapaParse/blob/master/papaparse.js
MIT
function mainThreadReceivedMessage(e) { var msg = e.data; var worker = workers[msg.workerId]; var aborted = false; if (msg.error) worker.userError(msg.error, msg.file); else if (msg.results && msg.results.data) { var abort = function() { aborted = true; completeWorker(msg.workerId, { data: [], errors: [], meta: { aborted: true } }); }; var handle = { abort: abort, pause: notImplemented, resume: notImplemented }; if (isFunction(worker.userStep)) { for (var i = 0; i < msg.results.data.length; i++) { worker.userStep({ data: msg.results.data[i], errors: msg.results.errors, meta: msg.results.meta }, handle); if (aborted) break; } delete msg.results; // free memory ASAP } else if (isFunction(worker.userChunk)) { worker.userChunk(msg.results, handle, msg.file); delete msg.results; } } if (msg.finished && !aborted) completeWorker(msg.workerId, msg.results); }
Callback when main thread receives a message
mainThreadReceivedMessage
javascript
mholt/PapaParse
papaparse.js
https://github.com/mholt/PapaParse/blob/master/papaparse.js
MIT
abort = function() { aborted = true; completeWorker(msg.workerId, { data: [], errors: [], meta: { aborted: true } }); }
Callback when main thread receives a message
abort
javascript
mholt/PapaParse
papaparse.js
https://github.com/mholt/PapaParse/blob/master/papaparse.js
MIT
function completeWorker(workerId, results) { var worker = workers[workerId]; if (isFunction(worker.userComplete)) worker.userComplete(results); worker.terminate(); delete workers[workerId]; }
Callback when main thread receives a message
completeWorker
javascript
mholt/PapaParse
papaparse.js
https://github.com/mholt/PapaParse/blob/master/papaparse.js
MIT
function notImplemented() { throw new Error('Not implemented.'); }
Callback when main thread receives a message
notImplemented
javascript
mholt/PapaParse
papaparse.js
https://github.com/mholt/PapaParse/blob/master/papaparse.js
MIT
function workerThreadReceivedMessage(e) { var msg = e.data; if (typeof Papa.WORKER_ID === 'undefined' && msg) Papa.WORKER_ID = msg.workerId; if (typeof msg.input === 'string') { global.postMessage({ workerId: Papa.WORKER_ID, results: Papa.parse(msg.input, msg.config), finished: true }); } else if ((global.File && msg.input instanceof File) || msg.input instanceof Object) // thank you, Safari (see issue #106) { var results = Papa.parse(msg.input, msg.config); if (results) global.postMessage({ workerId: Papa.WORKER_ID, results: results, finished: true }); } }
Callback when worker thread receives a message
workerThreadReceivedMessage
javascript
mholt/PapaParse
papaparse.js
https://github.com/mholt/PapaParse/blob/master/papaparse.js
MIT
function copy(obj) { if (typeof obj !== 'object' || obj === null) return obj; var cpy = Array.isArray(obj) ? [] : {}; for (var key in obj) cpy[key] = copy(obj[key]); return cpy; }
Makes a deep copy of an array or object (mostly)
copy
javascript
mholt/PapaParse
papaparse.js
https://github.com/mholt/PapaParse/blob/master/papaparse.js
MIT
function bindFunction(f, self) { return function() { f.apply(self, arguments); }; }
Makes a deep copy of an array or object (mostly)
bindFunction
javascript
mholt/PapaParse
papaparse.js
https://github.com/mholt/PapaParse/blob/master/papaparse.js
MIT
function isFunction(func) { return typeof func === 'function'; }
Makes a deep copy of an array or object (mostly)
isFunction
javascript
mholt/PapaParse
papaparse.js
https://github.com/mholt/PapaParse/blob/master/papaparse.js
MIT
function unpackConfig() { if (typeof _config !== 'object') return; if (typeof _config.delimiter === 'string' && !Papa.BAD_DELIMITERS.filter(function(value) { return _config.delimiter.indexOf(value) !== -1; }).length) { _delimiter = _config.delimiter; } if (typeof _config.quotes === 'boolean' || Array.isArray(_config.quotes)) _quotes = _config.quotes; if (typeof _config.skipEmptyLines === 'boolean' || typeof _config.skipEmptyLines === 'string') _skipEmptyLines = _config.skipEmptyLines; if (typeof _config.newline === 'string') _newline = _config.newline; if (typeof _config.quoteChar === 'string') _quoteChar = _config.quoteChar; if (typeof _config.header === 'boolean') _writeHeader = _config.header; if (Array.isArray(_config.columns)) { if (_config.columns.length === 0) throw new Error('Option columns is empty'); _columns = _config.columns; } if (_config.escapeChar !== undefined) { _escapedQuote = _config.escapeChar + _quoteChar; } }
the columns (keys) we expect when we unparse objects
unpackConfig
javascript
mholt/PapaParse
docs/resources/js/papaparse.js
https://github.com/mholt/PapaParse/blob/master/docs/resources/js/papaparse.js
MIT
function objectKeys(obj) { if (typeof obj !== 'object') return []; var keys = []; for (var key in obj) keys.push(key); return keys; }
Turns an object's keys into an array
objectKeys
javascript
mholt/PapaParse
docs/resources/js/papaparse.js
https://github.com/mholt/PapaParse/blob/master/docs/resources/js/papaparse.js
MIT
function serialize(fields, data, skipEmptyLines) { var csv = ''; if (typeof fields === 'string') fields = JSON.parse(fields); if (typeof data === 'string') data = JSON.parse(data); var hasHeader = Array.isArray(fields) && fields.length > 0; var dataKeyedByField = !(Array.isArray(data[0])); // If there a header row, write it first if (hasHeader && _writeHeader) { for (var i = 0; i < fields.length; i++) { if (i > 0) csv += _delimiter; csv += safe(fields[i], i); } if (data.length > 0) csv += _newline; } // Then write out the data for (var row = 0; row < data.length; row++) { var maxCol = hasHeader ? fields.length : data[row].length; var emptyLine = false; var nullLine = hasHeader ? Object.keys(data[row]).length === 0 : data[row].length === 0; if (skipEmptyLines && !hasHeader) { emptyLine = skipEmptyLines === 'greedy' ? data[row].join('').trim() === '' : data[row].length === 1 && data[row][0].length === 0; } if (skipEmptyLines === 'greedy' && hasHeader) { var line = []; for (var c = 0; c < maxCol; c++) { var cx = dataKeyedByField ? fields[c] : c; line.push(data[row][cx]); } emptyLine = line.join('').trim() === ''; } if (!emptyLine) { for (var col = 0; col < maxCol; col++) { if (col > 0 && !nullLine) csv += _delimiter; var colIdx = hasHeader && dataKeyedByField ? fields[col] : col; csv += safe(data[row][colIdx], col); } if (row < data.length - 1 && (!skipEmptyLines || (maxCol > 0 && !nullLine))) { csv += _newline; } } } return csv; }
The double for loop that iterates the data and writes out a CSV string including header row
serialize
javascript
mholt/PapaParse
docs/resources/js/papaparse.js
https://github.com/mholt/PapaParse/blob/master/docs/resources/js/papaparse.js
MIT
function safe(str, col) { if (typeof str === 'undefined' || str === null) return ''; if (str.constructor === Date) return JSON.stringify(str).slice(1, 25); str = str.toString().replace(quoteCharRegex, _escapedQuote); var needsQuotes = (typeof _quotes === 'boolean' && _quotes) || (Array.isArray(_quotes) && _quotes[col]) || hasAny(str, Papa.BAD_DELIMITERS) || str.indexOf(_delimiter) > -1 || str.charAt(0) === ' ' || str.charAt(str.length - 1) === ' '; return needsQuotes ? _quoteChar + str + _quoteChar : str; }
Encloses a value around quotes if needed (makes a value safe for CSV insertion)
safe
javascript
mholt/PapaParse
docs/resources/js/papaparse.js
https://github.com/mholt/PapaParse/blob/master/docs/resources/js/papaparse.js
MIT
function hasAny(str, substrings) { for (var i = 0; i < substrings.length; i++) if (str.indexOf(substrings[i]) > -1) return true; return false; }
Encloses a value around quotes if needed (makes a value safe for CSV insertion)
hasAny
javascript
mholt/PapaParse
docs/resources/js/papaparse.js
https://github.com/mholt/PapaParse/blob/master/docs/resources/js/papaparse.js
MIT
function ChunkStreamer(config) { this._handle = null; this._finished = false; this._completed = false; this._halted = false; this._input = null; this._baseIndex = 0; this._partialLine = ''; this._rowCount = 0; this._start = 0; this._nextChunk = null; this.isFirstChunk = true; this._completeResults = { data: [], errors: [], meta: {} }; replaceConfig.call(this, config); this.parseChunk = function(chunk, isFakeChunk) { // First chunk pre-processing const skipFirstNLines = parseInt(this._config.skipFirstNLines) || 0; if (this.isFirstChunk && skipFirstNLines > 0) { let _newline = this._config.newline; if (!_newline) { const quoteChar = this._config.quoteChar || '"'; _newline = this._handle.guessLineEndings(chunk, quoteChar); } const splitChunk = chunk.split(_newline); chunk = [...splitChunk.slice(skipFirstNLines)].join(_newline); } if (this.isFirstChunk && isFunction(this._config.beforeFirstChunk)) { var modifiedChunk = this._config.beforeFirstChunk(chunk); if (modifiedChunk !== undefined) chunk = modifiedChunk; } this.isFirstChunk = false; this._halted = false; // Rejoin the line we likely just split in two by chunking the file var aggregate = this._partialLine + chunk; this._partialLine = ''; var results = this._handle.parse(aggregate, this._baseIndex, !this._finished); if (this._handle.paused() || this._handle.aborted()) { this._halted = true; return; } var lastIndex = results.meta.cursor; if (!this._finished) { this._partialLine = aggregate.substring(lastIndex - this._baseIndex); this._baseIndex = lastIndex; } if (results && results.data) this._rowCount += results.data.length; var finishedIncludingPreview = this._finished || (this._config.preview && this._rowCount >= this._config.preview); if (IS_PAPA_WORKER) { global.postMessage({ results: results, workerId: Papa.WORKER_ID, finished: finishedIncludingPreview }); } else if (isFunction(this._config.chunk) && !isFakeChunk) { this._config.chunk(results, this._handle); if (this._handle.paused() || this._handle.aborted()) { this._halted = true; return; } results = undefined; this._completeResults = undefined; } if (!this._config.step && !this._config.chunk) { this._completeResults.data = this._completeResults.data.concat(results.data); this._completeResults.errors = this._completeResults.errors.concat(results.errors); this._completeResults.meta = results.meta; } if (!this._completed && finishedIncludingPreview && isFunction(this._config.complete) && (!results || !results.meta.aborted)) { this._config.complete(this._completeResults, this._input); this._completed = true; } if (!finishedIncludingPreview && (!results || !results.meta.paused)) this._nextChunk(); return results; }; this._sendError = function(error) { if (isFunction(this._config.error)) this._config.error(error); else if (IS_PAPA_WORKER && this._config.error) { global.postMessage({ workerId: Papa.WORKER_ID, error: error, finished: false }); } }; function replaceConfig(config) { // Deep-copy the config so we can edit it var configCopy = copy(config); configCopy.chunkSize = parseInt(configCopy.chunkSize); // parseInt VERY important so we don't concatenate strings! if (!config.step && !config.chunk) configCopy.chunkSize = null; // disable Range header if not streaming; bad values break IIS - see issue #196 this._handle = new ParserHandle(configCopy); this._handle.streamer = this; this._config = configCopy; // persist the copy to the caller } }
ChunkStreamer is the base prototype for various streamer implementations.
ChunkStreamer
javascript
mholt/PapaParse
docs/resources/js/papaparse.js
https://github.com/mholt/PapaParse/blob/master/docs/resources/js/papaparse.js
MIT
function replaceConfig(config) { // Deep-copy the config so we can edit it var configCopy = copy(config); configCopy.chunkSize = parseInt(configCopy.chunkSize); // parseInt VERY important so we don't concatenate strings! if (!config.step && !config.chunk) configCopy.chunkSize = null; // disable Range header if not streaming; bad values break IIS - see issue #196 this._handle = new ParserHandle(configCopy); this._handle.streamer = this; this._config = configCopy; // persist the copy to the caller }
ChunkStreamer is the base prototype for various streamer implementations.
replaceConfig
javascript
mholt/PapaParse
docs/resources/js/papaparse.js
https://github.com/mholt/PapaParse/blob/master/docs/resources/js/papaparse.js
MIT
function NetworkStreamer(config) { config = config || {}; if (!config.chunkSize) config.chunkSize = Papa.RemoteChunkSize; ChunkStreamer.call(this, config); var xhr; if (IS_WORKER) { this._nextChunk = function() { this._readChunk(); this._chunkLoaded(); }; } else { this._nextChunk = function() { this._readChunk(); }; } this.stream = function(url) { this._input = url; this._nextChunk(); // Starts streaming }; this._readChunk = function() { if (this._finished) { this._chunkLoaded(); return; } xhr = new XMLHttpRequest(); if (this._config.withCredentials) { xhr.withCredentials = this._config.withCredentials; } if (!IS_WORKER) { xhr.onload = bindFunction(this._chunkLoaded, this); xhr.onerror = bindFunction(this._chunkError, this); } xhr.open('GET', this._input, !IS_WORKER); // Headers can only be set when once the request state is OPENED if (this._config.downloadRequestHeaders) { var headers = this._config.downloadRequestHeaders; for (var headerName in headers) { xhr.setRequestHeader(headerName, headers[headerName]); } } if (this._config.chunkSize) { var end = this._start + this._config.chunkSize - 1; // minus one because byte range is inclusive xhr.setRequestHeader('Range', 'bytes=' + this._start + '-' + end); } try { xhr.send(); } catch (err) { this._chunkError(err.message); } if (IS_WORKER && xhr.status === 0) this._chunkError(); else this._start += this._config.chunkSize; }; this._chunkLoaded = function() { if (xhr.readyState !== 4) return; if (xhr.status < 200 || xhr.status >= 400) { this._chunkError(); return; } this._finished = !this._config.chunkSize || this._start > getFileSize(xhr); this.parseChunk(xhr.responseText); }; this._chunkError = function(errorMessage) { var errorText = xhr.statusText || errorMessage; this._sendError(new Error(errorText)); }; function getFileSize(xhr) { var contentRange = xhr.getResponseHeader('Content-Range'); if (contentRange === null) { // no content range, then finish! return -1; } return parseInt(contentRange.substr(contentRange.lastIndexOf('/') + 1)); } }
ChunkStreamer is the base prototype for various streamer implementations.
NetworkStreamer
javascript
mholt/PapaParse
docs/resources/js/papaparse.js
https://github.com/mholt/PapaParse/blob/master/docs/resources/js/papaparse.js
MIT
function getFileSize(xhr) { var contentRange = xhr.getResponseHeader('Content-Range'); if (contentRange === null) { // no content range, then finish! return -1; } return parseInt(contentRange.substr(contentRange.lastIndexOf('/') + 1)); }
ChunkStreamer is the base prototype for various streamer implementations.
getFileSize
javascript
mholt/PapaParse
docs/resources/js/papaparse.js
https://github.com/mholt/PapaParse/blob/master/docs/resources/js/papaparse.js
MIT
function FileStreamer(config) { config = config || {}; if (!config.chunkSize) config.chunkSize = Papa.LocalChunkSize; ChunkStreamer.call(this, config); var reader, slice; // FileReader is better than FileReaderSync (even in worker) - see http://stackoverflow.com/q/24708649/1048862 // But Firefox is a pill, too - see issue #76: https://github.com/mholt/PapaParse/issues/76 var usingAsyncReader = typeof FileReader !== 'undefined'; // Safari doesn't consider it a function - see issue #105 this.stream = function(file) { this._input = file; slice = file.slice || file.webkitSlice || file.mozSlice; if (usingAsyncReader) { reader = new FileReader(); // Preferred method of reading files, even in workers reader.onload = bindFunction(this._chunkLoaded, this); reader.onerror = bindFunction(this._chunkError, this); } else reader = new FileReaderSync(); // Hack for running in a web worker in Firefox this._nextChunk(); // Starts streaming }; this._nextChunk = function() { if (!this._finished && (!this._config.preview || this._rowCount < this._config.preview)) this._readChunk(); }; this._readChunk = function() { var input = this._input; if (this._config.chunkSize) { var end = Math.min(this._start + this._config.chunkSize, this._input.size); input = slice.call(input, this._start, end); } var txt = reader.readAsText(input, this._config.encoding); if (!usingAsyncReader) this._chunkLoaded({ target: { result: txt } }); // mimic the async signature }; this._chunkLoaded = function(event) { // Very important to increment start each time before handling results this._start += this._config.chunkSize; this._finished = !this._config.chunkSize || this._start >= this._input.size; this.parseChunk(event.target.result); }; this._chunkError = function() { this._sendError(reader.error); }; }
ChunkStreamer is the base prototype for various streamer implementations.
FileStreamer
javascript
mholt/PapaParse
docs/resources/js/papaparse.js
https://github.com/mholt/PapaParse/blob/master/docs/resources/js/papaparse.js
MIT
function StringStreamer(config) { config = config || {}; ChunkStreamer.call(this, config); var remaining; this.stream = function(s) { remaining = s; return this._nextChunk(); }; this._nextChunk = function() { if (this._finished) return; var size = this._config.chunkSize; var chunk = size ? remaining.substr(0, size) : remaining; remaining = size ? remaining.substr(size) : ''; this._finished = !remaining; return this.parseChunk(chunk); }; }
ChunkStreamer is the base prototype for various streamer implementations.
StringStreamer
javascript
mholt/PapaParse
docs/resources/js/papaparse.js
https://github.com/mholt/PapaParse/blob/master/docs/resources/js/papaparse.js
MIT
function ReadableStreamStreamer(config) { config = config || {}; ChunkStreamer.call(this, config); var queue = []; var parseOnData = true; var streamHasEnded = false; this.pause = function() { ChunkStreamer.prototype.pause.apply(this, arguments); this._input.pause(); }; this.resume = function() { ChunkStreamer.prototype.resume.apply(this, arguments); this._input.resume(); }; this.stream = function(stream) { this._input = stream; this._input.on('data', this._streamData); this._input.on('end', this._streamEnd); this._input.on('error', this._streamError); }; this._checkIsFinished = function() { if (streamHasEnded && queue.length === 1) { this._finished = true; } }; this._nextChunk = function() { this._checkIsFinished(); if (queue.length) { this.parseChunk(queue.shift()); } else { parseOnData = true; } }; this._streamData = bindFunction(function(chunk) { try { queue.push(typeof chunk === 'string' ? chunk : chunk.toString(this._config.encoding)); if (parseOnData) { parseOnData = false; this._checkIsFinished(); this.parseChunk(queue.shift()); } } catch (error) { this._streamError(error); } }, this); this._streamError = bindFunction(function(error) { this._streamCleanUp(); this._sendError(error); }, this); this._streamEnd = bindFunction(function() { this._streamCleanUp(); streamHasEnded = true; this._streamData(''); }, this); this._streamCleanUp = bindFunction(function() { this._input.removeListener('data', this._streamData); this._input.removeListener('end', this._streamEnd); this._input.removeListener('error', this._streamError); }, this); }
ChunkStreamer is the base prototype for various streamer implementations.
ReadableStreamStreamer
javascript
mholt/PapaParse
docs/resources/js/papaparse.js
https://github.com/mholt/PapaParse/blob/master/docs/resources/js/papaparse.js
MIT
function DuplexStreamStreamer(_config) { var Duplex = require('stream').Duplex; var config = copy(_config); var parseOnWrite = true; var writeStreamHasFinished = false; var parseCallbackQueue = []; var stream = null; this._onCsvData = function(results) { var data = results.data; if (!stream.push(data) && !this._handle.paused()) { // the writeable consumer buffer has filled up // so we need to pause until more items // can be processed this._handle.pause(); } }; this._onCsvComplete = function() { // node will finish the read stream when // null is pushed stream.push(null); }; config.step = bindFunction(this._onCsvData, this); config.complete = bindFunction(this._onCsvComplete, this); ChunkStreamer.call(this, config); this._nextChunk = function() { if (writeStreamHasFinished && parseCallbackQueue.length === 1) { this._finished = true; } if (parseCallbackQueue.length) { parseCallbackQueue.shift()(); } else { parseOnWrite = true; } }; this._addToParseQueue = function(chunk, callback) { // add to queue so that we can indicate // completion via callback // node will automatically pause the incoming stream // when too many items have been added without their // callback being invoked parseCallbackQueue.push(bindFunction(function() { this.parseChunk(typeof chunk === 'string' ? chunk : chunk.toString(config.encoding)); if (isFunction(callback)) { return callback(); } }, this)); if (parseOnWrite) { parseOnWrite = false; this._nextChunk(); } }; this._onRead = function() { if (this._handle.paused()) { // the writeable consumer can handle more data // so resume the chunk parsing this._handle.resume(); } }; this._onWrite = function(chunk, encoding, callback) { this._addToParseQueue(chunk, callback); }; this._onWriteComplete = function() { writeStreamHasFinished = true; // have to write empty string // so parser knows its done this._addToParseQueue(''); }; this.getStream = function() { return stream; }; stream = new Duplex({ readableObjectMode: true, decodeStrings: false, read: bindFunction(this._onRead, this), write: bindFunction(this._onWrite, this) }); stream.once('finish', bindFunction(this._onWriteComplete, this)); }
ChunkStreamer is the base prototype for various streamer implementations.
DuplexStreamStreamer
javascript
mholt/PapaParse
docs/resources/js/papaparse.js
https://github.com/mholt/PapaParse/blob/master/docs/resources/js/papaparse.js
MIT
function ParserHandle(_config) { // One goal is to minimize the use of regular expressions... var FLOAT = /^\s*-?(\d*\.?\d+|\d+\.?\d*)(e[-+]?\d+)?\s*$/i; var ISO_DATE = /(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))/; var self = this; var _stepCounter = 0; // Number of times step was called (number of rows parsed) var _rowCounter = 0; // Number of rows that have been parsed so far var _input; // The input being parsed var _parser; // The core parser being used var _paused = false; // Whether we are paused or not var _aborted = false; // Whether the parser has aborted or not var _delimiterError; // Temporary state between delimiter detection and processing results var _fields = []; // Fields are from the header row of the input, if there is one var _results = { // The last results returned from the parser data: [], errors: [], meta: {} }; if (isFunction(_config.step)) { var userStep = _config.step; _config.step = function(results) { _results = results; if (needsHeaderRow()) processResults(); else // only call user's step function after header row { processResults(); // It's possbile that this line was empty and there's no row here after all if (_results.data.length === 0) return; _stepCounter += results.data.length; if (_config.preview && _stepCounter > _config.preview) _parser.abort(); else userStep(_results, self); } }; } /** * Parses input. Most users won't need, and shouldn't mess with, the baseIndex * and ignoreLastRow parameters. They are used by streamers (wrapper functions) * when an input comes in multiple chunks, like from a file. */ this.parse = function(input, baseIndex, ignoreLastRow) { var quoteChar = _config.quoteChar || '"'; if (!_config.newline) _config.newline = this.guessLineEndings(input, quoteChar); _delimiterError = false; if (!_config.delimiter) { var delimGuess = guessDelimiter(input, _config.newline, _config.skipEmptyLines, _config.comments, _config.delimitersToGuess); if (delimGuess.successful) _config.delimiter = delimGuess.bestDelimiter; else { _delimiterError = true; // add error after parsing (otherwise it would be overwritten) _config.delimiter = Papa.DefaultDelimiter; } _results.meta.delimiter = _config.delimiter; } else if(isFunction(_config.delimiter)) { _config.delimiter = _config.delimiter(input); _results.meta.delimiter = _config.delimiter; } var parserConfig = copy(_config); if (_config.preview && _config.header) parserConfig.preview++; // to compensate for header row _input = input; _parser = new Parser(parserConfig); _results = _parser.parse(_input, baseIndex, ignoreLastRow); processResults(); return _paused ? { meta: { paused: true } } : (_results || { meta: { paused: false } }); }; this.paused = function() { return _paused; }; this.pause = function() { _paused = true; _parser.abort(); _input = _input.substr(_parser.getCharIndex()); }; this.resume = function() { if(self.streamer._halted) { _paused = false; self.streamer.parseChunk(_input, true); } else { // Bugfix: #636 In case the processing hasn't halted yet // wait for it to halt in order to resume setTimeout(this.resume, 3); } }; this.aborted = function() { return _aborted; }; this.abort = function() { _aborted = true; _parser.abort(); _results.meta.aborted = true; if (isFunction(_config.complete)) _config.complete(_results); _input = ''; }; this.guessLineEndings = function(input, quoteChar) { input = input.substr(0, 1024 * 1024); // max length 1 MB // Replace all the text inside quotes var re = new RegExp(escapeRegExp(quoteChar) + '([^]*?)' + escapeRegExp(quoteChar), 'gm'); input = input.replace(re, ''); var r = input.split('\r'); var n = input.split('\n'); var nAppearsFirst = (n.length > 1 && n[0].length < r[0].length); if (r.length === 1 || nAppearsFirst) return '\n'; var numWithN = 0; for (var i = 0; i < r.length; i++) { if (r[i][0] === '\n') numWithN++; } return numWithN >= r.length / 2 ? '\r\n' : '\r'; }; function testEmptyLine(s) { return _config.skipEmptyLines === 'greedy' ? s.join('').trim() === '' : s.length === 1 && s[0].length === 0; } function processResults() { if (_results && _delimiterError) { addError('Delimiter', 'UndetectableDelimiter', 'Unable to auto-detect delimiting character; defaulted to \'' + Papa.DefaultDelimiter + '\''); _delimiterError = false; } if (_config.skipEmptyLines) { for (var i = 0; i < _results.data.length; i++) if (testEmptyLine(_results.data[i])) _results.data.splice(i--, 1); } if (needsHeaderRow()) fillHeaderFields(); return applyHeaderAndDynamicTypingAndTransformation(); } function needsHeaderRow() { return _config.header && _fields.length === 0; } function fillHeaderFields() { if (!_results) return; function addHeder(header) { if (isFunction(_config.transformHeader)) header = _config.transformHeader(header); _fields.push(header); } if (Array.isArray(_results.data[0])) { for (var i = 0; needsHeaderRow() && i < _results.data.length; i++) _results.data[i].forEach(addHeder); _results.data.splice(0, 1); } // if _results.data[0] is not an array, we are in a step where _results.data is the row. else _results.data.forEach(addHeder); } function shouldApplyDynamicTyping(field) { // Cache function values to avoid calling it for each row if (_config.dynamicTypingFunction && _config.dynamicTyping[field] === undefined) { _config.dynamicTyping[field] = _config.dynamicTypingFunction(field); } return (_config.dynamicTyping[field] || _config.dynamicTyping) === true; } function parseDynamic(field, value) { if (shouldApplyDynamicTyping(field)) { if (value === 'true' || value === 'TRUE') return true; else if (value === 'false' || value === 'FALSE') return false; else if (FLOAT.test(value)) return parseFloat(value); else if (ISO_DATE.test(value)) return new Date(value); else return (value === '' ? null : value); } return value; } function applyHeaderAndDynamicTypingAndTransformation() { if (!_results || (!_config.header && !_config.dynamicTyping && !_config.transform)) return _results; function processRow(rowSource, i) { var row = _config.header ? {} : []; var j; for (j = 0; j < rowSource.length; j++) { var field = j; var value = rowSource[j]; if (_config.header) field = j >= _fields.length ? '__parsed_extra' : _fields[j]; if (_config.transform) value = _config.transform(value,field); value = parseDynamic(field, value); if (field === '__parsed_extra') { row[field] = row[field] || []; row[field].push(value); } else row[field] = value; } if (_config.header) { if (j > _fields.length) addError('FieldMismatch', 'TooManyFields', 'Too many fields: expected ' + _fields.length + ' fields but parsed ' + j, _rowCounter + i); else if (j < _fields.length) addError('FieldMismatch', 'TooFewFields', 'Too few fields: expected ' + _fields.length + ' fields but parsed ' + j, _rowCounter + i); } return row; } var incrementBy = 1; if (!_results.data[0] || Array.isArray(_results.data[0])) { _results.data = _results.data.map(processRow); incrementBy = _results.data.length; } else _results.data = processRow(_results.data, 0); if (_config.header && _results.meta) _results.meta.fields = _fields; _rowCounter += incrementBy; return _results; } function guessDelimiter(input, newline, skipEmptyLines, comments, delimitersToGuess) { var bestDelim, bestDelta, fieldCountPrevRow; delimitersToGuess = delimitersToGuess || [',', '\t', '|', ';', Papa.RECORD_SEP, Papa.UNIT_SEP]; for (var i = 0; i < delimitersToGuess.length; i++) { var delim = delimitersToGuess[i]; var delta = 0, avgFieldCount = 0, emptyLinesCount = 0; fieldCountPrevRow = undefined; var preview = new Parser({ comments: comments, delimiter: delim, newline: newline, preview: 10 }).parse(input); for (var j = 0; j < preview.data.length; j++) { if (skipEmptyLines && testEmptyLine(preview.data[j])) { emptyLinesCount++; continue; } var fieldCount = preview.data[j].length; avgFieldCount += fieldCount; if (typeof fieldCountPrevRow === 'undefined') { fieldCountPrevRow = 0; continue; } else if (fieldCount > 1) { delta += Math.abs(fieldCount - fieldCountPrevRow); fieldCountPrevRow = fieldCount; } } if (preview.data.length > 0) avgFieldCount /= (preview.data.length - emptyLinesCount); if ((typeof bestDelta === 'undefined' || delta > bestDelta) && avgFieldCount > 1.99) { bestDelta = delta; bestDelim = delim; } } _config.delimiter = bestDelim; return { successful: !!bestDelim, bestDelimiter: bestDelim }; } function addError(type, code, msg, row) { _results.errors.push({ type: type, code: code, message: msg, row: row }); } }
ChunkStreamer is the base prototype for various streamer implementations.
ParserHandle
javascript
mholt/PapaParse
docs/resources/js/papaparse.js
https://github.com/mholt/PapaParse/blob/master/docs/resources/js/papaparse.js
MIT
function testEmptyLine(s) { return _config.skipEmptyLines === 'greedy' ? s.join('').trim() === '' : s.length === 1 && s[0].length === 0; }
Parses input. Most users won't need, and shouldn't mess with, the baseIndex and ignoreLastRow parameters. They are used by streamers (wrapper functions) when an input comes in multiple chunks, like from a file.
testEmptyLine
javascript
mholt/PapaParse
docs/resources/js/papaparse.js
https://github.com/mholt/PapaParse/blob/master/docs/resources/js/papaparse.js
MIT
function processResults() { if (_results && _delimiterError) { addError('Delimiter', 'UndetectableDelimiter', 'Unable to auto-detect delimiting character; defaulted to \'' + Papa.DefaultDelimiter + '\''); _delimiterError = false; } if (_config.skipEmptyLines) { for (var i = 0; i < _results.data.length; i++) if (testEmptyLine(_results.data[i])) _results.data.splice(i--, 1); } if (needsHeaderRow()) fillHeaderFields(); return applyHeaderAndDynamicTypingAndTransformation(); }
Parses input. Most users won't need, and shouldn't mess with, the baseIndex and ignoreLastRow parameters. They are used by streamers (wrapper functions) when an input comes in multiple chunks, like from a file.
processResults
javascript
mholt/PapaParse
docs/resources/js/papaparse.js
https://github.com/mholt/PapaParse/blob/master/docs/resources/js/papaparse.js
MIT
function needsHeaderRow() { return _config.header && _fields.length === 0; }
Parses input. Most users won't need, and shouldn't mess with, the baseIndex and ignoreLastRow parameters. They are used by streamers (wrapper functions) when an input comes in multiple chunks, like from a file.
needsHeaderRow
javascript
mholt/PapaParse
docs/resources/js/papaparse.js
https://github.com/mholt/PapaParse/blob/master/docs/resources/js/papaparse.js
MIT
function fillHeaderFields() { if (!_results) return; function addHeder(header) { if (isFunction(_config.transformHeader)) header = _config.transformHeader(header); _fields.push(header); } if (Array.isArray(_results.data[0])) { for (var i = 0; needsHeaderRow() && i < _results.data.length; i++) _results.data[i].forEach(addHeder); _results.data.splice(0, 1); } // if _results.data[0] is not an array, we are in a step where _results.data is the row. else _results.data.forEach(addHeder); }
Parses input. Most users won't need, and shouldn't mess with, the baseIndex and ignoreLastRow parameters. They are used by streamers (wrapper functions) when an input comes in multiple chunks, like from a file.
fillHeaderFields
javascript
mholt/PapaParse
docs/resources/js/papaparse.js
https://github.com/mholt/PapaParse/blob/master/docs/resources/js/papaparse.js
MIT
function addHeder(header) { if (isFunction(_config.transformHeader)) header = _config.transformHeader(header); _fields.push(header); }
Parses input. Most users won't need, and shouldn't mess with, the baseIndex and ignoreLastRow parameters. They are used by streamers (wrapper functions) when an input comes in multiple chunks, like from a file.
addHeder
javascript
mholt/PapaParse
docs/resources/js/papaparse.js
https://github.com/mholt/PapaParse/blob/master/docs/resources/js/papaparse.js
MIT
function shouldApplyDynamicTyping(field) { // Cache function values to avoid calling it for each row if (_config.dynamicTypingFunction && _config.dynamicTyping[field] === undefined) { _config.dynamicTyping[field] = _config.dynamicTypingFunction(field); } return (_config.dynamicTyping[field] || _config.dynamicTyping) === true; }
Parses input. Most users won't need, and shouldn't mess with, the baseIndex and ignoreLastRow parameters. They are used by streamers (wrapper functions) when an input comes in multiple chunks, like from a file.
shouldApplyDynamicTyping
javascript
mholt/PapaParse
docs/resources/js/papaparse.js
https://github.com/mholt/PapaParse/blob/master/docs/resources/js/papaparse.js
MIT
function parseDynamic(field, value) { if (shouldApplyDynamicTyping(field)) { if (value === 'true' || value === 'TRUE') return true; else if (value === 'false' || value === 'FALSE') return false; else if (FLOAT.test(value)) return parseFloat(value); else if (ISO_DATE.test(value)) return new Date(value); else return (value === '' ? null : value); } return value; }
Parses input. Most users won't need, and shouldn't mess with, the baseIndex and ignoreLastRow parameters. They are used by streamers (wrapper functions) when an input comes in multiple chunks, like from a file.
parseDynamic
javascript
mholt/PapaParse
docs/resources/js/papaparse.js
https://github.com/mholt/PapaParse/blob/master/docs/resources/js/papaparse.js
MIT
function applyHeaderAndDynamicTypingAndTransformation() { if (!_results || (!_config.header && !_config.dynamicTyping && !_config.transform)) return _results; function processRow(rowSource, i) { var row = _config.header ? {} : []; var j; for (j = 0; j < rowSource.length; j++) { var field = j; var value = rowSource[j]; if (_config.header) field = j >= _fields.length ? '__parsed_extra' : _fields[j]; if (_config.transform) value = _config.transform(value,field); value = parseDynamic(field, value); if (field === '__parsed_extra') { row[field] = row[field] || []; row[field].push(value); } else row[field] = value; } if (_config.header) { if (j > _fields.length) addError('FieldMismatch', 'TooManyFields', 'Too many fields: expected ' + _fields.length + ' fields but parsed ' + j, _rowCounter + i); else if (j < _fields.length) addError('FieldMismatch', 'TooFewFields', 'Too few fields: expected ' + _fields.length + ' fields but parsed ' + j, _rowCounter + i); } return row; } var incrementBy = 1; if (!_results.data[0] || Array.isArray(_results.data[0])) { _results.data = _results.data.map(processRow); incrementBy = _results.data.length; } else _results.data = processRow(_results.data, 0); if (_config.header && _results.meta) _results.meta.fields = _fields; _rowCounter += incrementBy; return _results; }
Parses input. Most users won't need, and shouldn't mess with, the baseIndex and ignoreLastRow parameters. They are used by streamers (wrapper functions) when an input comes in multiple chunks, like from a file.
applyHeaderAndDynamicTypingAndTransformation
javascript
mholt/PapaParse
docs/resources/js/papaparse.js
https://github.com/mholt/PapaParse/blob/master/docs/resources/js/papaparse.js
MIT
function processRow(rowSource, i) { var row = _config.header ? {} : []; var j; for (j = 0; j < rowSource.length; j++) { var field = j; var value = rowSource[j]; if (_config.header) field = j >= _fields.length ? '__parsed_extra' : _fields[j]; if (_config.transform) value = _config.transform(value,field); value = parseDynamic(field, value); if (field === '__parsed_extra') { row[field] = row[field] || []; row[field].push(value); } else row[field] = value; } if (_config.header) { if (j > _fields.length) addError('FieldMismatch', 'TooManyFields', 'Too many fields: expected ' + _fields.length + ' fields but parsed ' + j, _rowCounter + i); else if (j < _fields.length) addError('FieldMismatch', 'TooFewFields', 'Too few fields: expected ' + _fields.length + ' fields but parsed ' + j, _rowCounter + i); } return row; }
Parses input. Most users won't need, and shouldn't mess with, the baseIndex and ignoreLastRow parameters. They are used by streamers (wrapper functions) when an input comes in multiple chunks, like from a file.
processRow
javascript
mholt/PapaParse
docs/resources/js/papaparse.js
https://github.com/mholt/PapaParse/blob/master/docs/resources/js/papaparse.js
MIT
function guessDelimiter(input, newline, skipEmptyLines, comments, delimitersToGuess) { var bestDelim, bestDelta, fieldCountPrevRow; delimitersToGuess = delimitersToGuess || [',', '\t', '|', ';', Papa.RECORD_SEP, Papa.UNIT_SEP]; for (var i = 0; i < delimitersToGuess.length; i++) { var delim = delimitersToGuess[i]; var delta = 0, avgFieldCount = 0, emptyLinesCount = 0; fieldCountPrevRow = undefined; var preview = new Parser({ comments: comments, delimiter: delim, newline: newline, preview: 10 }).parse(input); for (var j = 0; j < preview.data.length; j++) { if (skipEmptyLines && testEmptyLine(preview.data[j])) { emptyLinesCount++; continue; } var fieldCount = preview.data[j].length; avgFieldCount += fieldCount; if (typeof fieldCountPrevRow === 'undefined') { fieldCountPrevRow = 0; continue; } else if (fieldCount > 1) { delta += Math.abs(fieldCount - fieldCountPrevRow); fieldCountPrevRow = fieldCount; } } if (preview.data.length > 0) avgFieldCount /= (preview.data.length - emptyLinesCount); if ((typeof bestDelta === 'undefined' || delta > bestDelta) && avgFieldCount > 1.99) { bestDelta = delta; bestDelim = delim; } } _config.delimiter = bestDelim; return { successful: !!bestDelim, bestDelimiter: bestDelim }; }
Parses input. Most users won't need, and shouldn't mess with, the baseIndex and ignoreLastRow parameters. They are used by streamers (wrapper functions) when an input comes in multiple chunks, like from a file.
guessDelimiter
javascript
mholt/PapaParse
docs/resources/js/papaparse.js
https://github.com/mholt/PapaParse/blob/master/docs/resources/js/papaparse.js
MIT
function addError(type, code, msg, row) { _results.errors.push({ type: type, code: code, message: msg, row: row }); }
Parses input. Most users won't need, and shouldn't mess with, the baseIndex and ignoreLastRow parameters. They are used by streamers (wrapper functions) when an input comes in multiple chunks, like from a file.
addError
javascript
mholt/PapaParse
docs/resources/js/papaparse.js
https://github.com/mholt/PapaParse/blob/master/docs/resources/js/papaparse.js
MIT
function Parser(config) { // Unpack the config object config = config || {}; var delim = config.delimiter; var newline = config.newline; var comments = config.comments; var step = config.step; var preview = config.preview; var fastMode = config.fastMode; var quoteChar; /** Allows for no quoteChar by setting quoteChar to undefined in config */ if (config.quoteChar === undefined) { quoteChar = '"'; } else { quoteChar = config.quoteChar; } var escapeChar = quoteChar; if (config.escapeChar !== undefined) { escapeChar = config.escapeChar; } // Delimiter must be valid if (typeof delim !== 'string' || Papa.BAD_DELIMITERS.indexOf(delim) > -1) delim = ','; // Comment character must be valid if (comments === delim) throw new Error('Comment character same as delimiter'); else if (comments === true) comments = '#'; else if (typeof comments !== 'string' || Papa.BAD_DELIMITERS.indexOf(comments) > -1) comments = false; // Newline must be valid: \r, \n, or \r\n if (newline !== '\n' && newline !== '\r' && newline !== '\r\n') newline = '\n'; // We're gonna need these at the Parser scope var cursor = 0; var aborted = false; this.parse = function(input, baseIndex, ignoreLastRow) { // For some reason, in Chrome, this speeds things up (!?) if (typeof input !== 'string') throw new Error('Input must be a string'); // We don't need to compute some of these every time parse() is called, // but having them in a more local scope seems to perform better var inputLen = input.length, delimLen = delim.length, newlineLen = newline.length, commentsLen = comments.length; var stepIsFunction = isFunction(step); // Establish starting state cursor = 0; var data = [], errors = [], row = [], lastCursor = 0; if (!input) return returnable(); if (fastMode || (fastMode !== false && input.indexOf(quoteChar) === -1)) { var rows = input.split(newline); for (var i = 0; i < rows.length; i++) { row = rows[i]; cursor += row.length; if (i !== rows.length - 1) cursor += newline.length; else if (ignoreLastRow) return returnable(); if (comments && row.substr(0, commentsLen) === comments) continue; if (stepIsFunction) { data = []; pushRow(row.split(delim)); doStep(); if (aborted) return returnable(); } else pushRow(row.split(delim)); if (preview && i >= preview) { data = data.slice(0, preview); return returnable(true); } } return returnable(); } var nextDelim = input.indexOf(delim, cursor); var nextNewline = input.indexOf(newline, cursor); var quoteCharRegex = new RegExp(escapeRegExp(escapeChar) + escapeRegExp(quoteChar), 'g'); var quoteSearch = input.indexOf(quoteChar, cursor); // Parser loop for (;;) { // Field has opening quote if (input[cursor] === quoteChar) { // Start our search for the closing quote where the cursor is quoteSearch = cursor; // Skip the opening quote cursor++; for (;;) { // Find closing quote quoteSearch = input.indexOf(quoteChar, quoteSearch + 1); //No other quotes are found - no other delimiters if (quoteSearch === -1) { if (!ignoreLastRow) { // No closing quote... what a pity errors.push({ type: 'Quotes', code: 'MissingQuotes', message: 'Quoted field unterminated', row: data.length, // row has yet to be inserted index: cursor }); } return finish(); } // Closing quote at EOF if (quoteSearch === inputLen - 1) { var value = input.substring(cursor, quoteSearch).replace(quoteCharRegex, quoteChar); return finish(value); } // If this quote is escaped, it's part of the data; skip it // If the quote character is the escape character, then check if the next character is the escape character if (quoteChar === escapeChar && input[quoteSearch + 1] === escapeChar) { quoteSearch++; continue; } // If the quote character is not the escape character, then check if the previous character was the escape character if (quoteChar !== escapeChar && quoteSearch !== 0 && input[quoteSearch - 1] === escapeChar) { continue; } // Check up to nextDelim or nextNewline, whichever is closest var checkUpTo = nextNewline === -1 ? nextDelim : Math.min(nextDelim, nextNewline); var spacesBetweenQuoteAndDelimiter = extraSpaces(checkUpTo); // Closing quote followed by delimiter or 'unnecessary spaces + delimiter' if (input[quoteSearch + 1 + spacesBetweenQuoteAndDelimiter] === delim) { row.push(input.substring(cursor, quoteSearch).replace(quoteCharRegex, quoteChar)); cursor = quoteSearch + 1 + spacesBetweenQuoteAndDelimiter + delimLen; // If char after following delimiter is not quoteChar, we find next quote char position if (input[quoteSearch + 1 + spacesBetweenQuoteAndDelimiter + delimLen] !== quoteChar) { quoteSearch = input.indexOf(quoteChar, cursor); } nextDelim = input.indexOf(delim, cursor); nextNewline = input.indexOf(newline, cursor); break; } var spacesBetweenQuoteAndNewLine = extraSpaces(nextNewline); // Closing quote followed by newline or 'unnecessary spaces + newLine' if (input.substr(quoteSearch + 1 + spacesBetweenQuoteAndNewLine, newlineLen) === newline) { row.push(input.substring(cursor, quoteSearch).replace(quoteCharRegex, quoteChar)); saveRow(quoteSearch + 1 + spacesBetweenQuoteAndNewLine + newlineLen); nextDelim = input.indexOf(delim, cursor); // because we may have skipped the nextDelim in the quoted field quoteSearch = input.indexOf(quoteChar, cursor); // we search for first quote in next line if (stepIsFunction) { doStep(); if (aborted) return returnable(); } if (preview && data.length >= preview) return returnable(true); break; } // Checks for valid closing quotes are complete (escaped quotes or quote followed by EOF/delimiter/newline) -- assume these quotes are part of an invalid text string errors.push({ type: 'Quotes', code: 'InvalidQuotes', message: 'Trailing quote on quoted field is malformed', row: data.length, // row has yet to be inserted index: cursor }); quoteSearch++; continue; } continue; } // Comment found at start of new line if (comments && row.length === 0 && input.substr(cursor, commentsLen) === comments) { if (nextNewline === -1) // Comment ends at EOF return returnable(); cursor = nextNewline + newlineLen; nextNewline = input.indexOf(newline, cursor); nextDelim = input.indexOf(delim, cursor); continue; } // Next delimiter comes before next newline, so we've reached end of field if (nextDelim !== -1 && (nextDelim < nextNewline || nextNewline === -1)) { // we check, if we have quotes, because delimiter char may be part of field enclosed in quotes if (quoteSearch !== -1) { // we have quotes, so we try to find the next delimiter not enclosed in quotes and also next starting quote char var nextDelimObj = getNextUnqotedDelimiter(nextDelim, quoteSearch, nextNewline); // if we have next delimiter char which is not enclosed in quotes if (nextDelimObj && nextDelimObj.nextDelim) { nextDelim = nextDelimObj.nextDelim; quoteSearch = nextDelimObj.quoteSearch; row.push(input.substring(cursor, nextDelim)); cursor = nextDelim + delimLen; // we look for next delimiter char nextDelim = input.indexOf(delim, cursor); continue; } } else { row.push(input.substring(cursor, nextDelim)); cursor = nextDelim + delimLen; nextDelim = input.indexOf(delim, cursor); continue; } } // End of row if (nextNewline !== -1) { row.push(input.substring(cursor, nextNewline)); saveRow(nextNewline + newlineLen); if (stepIsFunction) { doStep(); if (aborted) return returnable(); } if (preview && data.length >= preview) return returnable(true); continue; } break; } return finish(); function pushRow(row) { data.push(row); lastCursor = cursor; } /** * checks if there are extra spaces after closing quote and given index without any text * if Yes, returns the number of spaces */ function extraSpaces(index) { var spaceLength = 0; if (index !== -1) { var textBetweenClosingQuoteAndIndex = input.substring(quoteSearch + 1, index); if (textBetweenClosingQuoteAndIndex && textBetweenClosingQuoteAndIndex.trim() === '') { spaceLength = textBetweenClosingQuoteAndIndex.length; } } return spaceLength; } /** * Appends the remaining input from cursor to the end into * row, saves the row, calls step, and returns the results. */ function finish(value) { if (ignoreLastRow) return returnable(); if (typeof value === 'undefined') value = input.substr(cursor); row.push(value); cursor = inputLen; // important in case parsing is paused pushRow(row); if (stepIsFunction) doStep(); return returnable(); } /** * Appends the current row to the results. It sets the cursor * to newCursor and finds the nextNewline. The caller should * take care to execute user's step function and check for * preview and end parsing if necessary. */ function saveRow(newCursor) { cursor = newCursor; pushRow(row); row = []; nextNewline = input.indexOf(newline, cursor); } /** Returns an object with the results, errors, and meta. */ function returnable(stopped, step) { var isStep = step || false; return { data: isStep ? data[0] : data, errors: errors, meta: { delimiter: delim, linebreak: newline, aborted: aborted, truncated: !!stopped, cursor: lastCursor + (baseIndex || 0) } }; } /** Executes the user's step function and resets data & errors. */ function doStep() { step(returnable(undefined, true)); data = []; errors = []; } /** Gets the delimiter character, which is not inside the quoted field */ function getNextUnqotedDelimiter(nextDelim, quoteSearch, newLine) { var result = { nextDelim: undefined, quoteSearch: undefined }; // get the next closing quote character var nextQuoteSearch = input.indexOf(quoteChar, quoteSearch + 1); // if next delimiter is part of a field enclosed in quotes if (nextDelim > quoteSearch && nextDelim < nextQuoteSearch && (nextQuoteSearch < newLine || newLine === -1)) { // get the next delimiter character after this one var nextNextDelim = input.indexOf(delim, nextQuoteSearch); // if there is no next delimiter, return default result if (nextNextDelim === -1) { return result; } // find the next opening quote char position if (nextNextDelim > nextQuoteSearch) { nextQuoteSearch = input.indexOf(quoteChar, nextQuoteSearch + 1); } // try to get the next delimiter position result = getNextUnqotedDelimiter(nextNextDelim, nextQuoteSearch, newLine); } else { result = { nextDelim: nextDelim, quoteSearch: quoteSearch }; } return result; } }; /** Sets the abort flag */ this.abort = function() { aborted = true; }; /** Gets the cursor position */ this.getCharIndex = function() { return cursor; }; }
The core parser implements speedy and correct CSV parsing
Parser
javascript
mholt/PapaParse
docs/resources/js/papaparse.js
https://github.com/mholt/PapaParse/blob/master/docs/resources/js/papaparse.js
MIT
function pushRow(row) { data.push(row); lastCursor = cursor; }
Allows for no quoteChar by setting quoteChar to undefined in config
pushRow
javascript
mholt/PapaParse
docs/resources/js/papaparse.js
https://github.com/mholt/PapaParse/blob/master/docs/resources/js/papaparse.js
MIT
function extraSpaces(index) { var spaceLength = 0; if (index !== -1) { var textBetweenClosingQuoteAndIndex = input.substring(quoteSearch + 1, index); if (textBetweenClosingQuoteAndIndex && textBetweenClosingQuoteAndIndex.trim() === '') { spaceLength = textBetweenClosingQuoteAndIndex.length; } } return spaceLength; }
checks if there are extra spaces after closing quote and given index without any text if Yes, returns the number of spaces
extraSpaces
javascript
mholt/PapaParse
docs/resources/js/papaparse.js
https://github.com/mholt/PapaParse/blob/master/docs/resources/js/papaparse.js
MIT
function finish(value) { if (ignoreLastRow) return returnable(); if (typeof value === 'undefined') value = input.substr(cursor); row.push(value); cursor = inputLen; // important in case parsing is paused pushRow(row); if (stepIsFunction) doStep(); return returnable(); }
Appends the remaining input from cursor to the end into row, saves the row, calls step, and returns the results.
finish
javascript
mholt/PapaParse
docs/resources/js/papaparse.js
https://github.com/mholt/PapaParse/blob/master/docs/resources/js/papaparse.js
MIT
function saveRow(newCursor) { cursor = newCursor; pushRow(row); row = []; nextNewline = input.indexOf(newline, cursor); }
Appends the current row to the results. It sets the cursor to newCursor and finds the nextNewline. The caller should take care to execute user's step function and check for preview and end parsing if necessary.
saveRow
javascript
mholt/PapaParse
docs/resources/js/papaparse.js
https://github.com/mholt/PapaParse/blob/master/docs/resources/js/papaparse.js
MIT
function returnable(stopped, step) { var isStep = step || false; return { data: isStep ? data[0] : data, errors: errors, meta: { delimiter: delim, linebreak: newline, aborted: aborted, truncated: !!stopped, cursor: lastCursor + (baseIndex || 0) } }; }
Returns an object with the results, errors, and meta.
returnable
javascript
mholt/PapaParse
docs/resources/js/papaparse.js
https://github.com/mholt/PapaParse/blob/master/docs/resources/js/papaparse.js
MIT
function doStep() { step(returnable(undefined, true)); data = []; errors = []; }
Executes the user's step function and resets data & errors.
doStep
javascript
mholt/PapaParse
docs/resources/js/papaparse.js
https://github.com/mholt/PapaParse/blob/master/docs/resources/js/papaparse.js
MIT
function mainThreadReceivedMessage(e) { var msg = e.data; var worker = workers[msg.workerId]; var aborted = false; if (msg.error) worker.userError(msg.error, msg.file); else if (msg.results && msg.results.data) { var abort = function() { aborted = true; completeWorker(msg.workerId, { data: [], errors: [], meta: { aborted: true } }); }; var handle = { abort: abort, pause: notImplemented, resume: notImplemented }; if (isFunction(worker.userStep)) { for (var i = 0; i < msg.results.data.length; i++) { worker.userStep({ data: msg.results.data[i], errors: msg.results.errors, meta: msg.results.meta }, handle); if (aborted) break; } delete msg.results; // free memory ASAP } else if (isFunction(worker.userChunk)) { worker.userChunk(msg.results, handle, msg.file); delete msg.results; } } if (msg.finished && !aborted) completeWorker(msg.workerId, msg.results); }
Callback when main thread receives a message
mainThreadReceivedMessage
javascript
mholt/PapaParse
docs/resources/js/papaparse.js
https://github.com/mholt/PapaParse/blob/master/docs/resources/js/papaparse.js
MIT
abort = function() { aborted = true; completeWorker(msg.workerId, { data: [], errors: [], meta: { aborted: true } }); }
Callback when main thread receives a message
abort
javascript
mholt/PapaParse
docs/resources/js/papaparse.js
https://github.com/mholt/PapaParse/blob/master/docs/resources/js/papaparse.js
MIT
function completeWorker(workerId, results) { var worker = workers[workerId]; if (isFunction(worker.userComplete)) worker.userComplete(results); worker.terminate(); delete workers[workerId]; }
Callback when main thread receives a message
completeWorker
javascript
mholt/PapaParse
docs/resources/js/papaparse.js
https://github.com/mholt/PapaParse/blob/master/docs/resources/js/papaparse.js
MIT
function notImplemented() { throw new Error('Not implemented.'); }
Callback when main thread receives a message
notImplemented
javascript
mholt/PapaParse
docs/resources/js/papaparse.js
https://github.com/mholt/PapaParse/blob/master/docs/resources/js/papaparse.js
MIT
function workerThreadReceivedMessage(e) { var msg = e.data; if (typeof Papa.WORKER_ID === 'undefined' && msg) Papa.WORKER_ID = msg.workerId; if (typeof msg.input === 'string') { global.postMessage({ workerId: Papa.WORKER_ID, results: Papa.parse(msg.input, msg.config), finished: true }); } else if ((global.File && msg.input instanceof File) || msg.input instanceof Object) // thank you, Safari (see issue #106) { var results = Papa.parse(msg.input, msg.config); if (results) global.postMessage({ workerId: Papa.WORKER_ID, results: results, finished: true }); } }
Callback when worker thread receives a message
workerThreadReceivedMessage
javascript
mholt/PapaParse
docs/resources/js/papaparse.js
https://github.com/mholt/PapaParse/blob/master/docs/resources/js/papaparse.js
MIT
function copy(obj) { if (typeof obj !== 'object' || obj === null) return obj; var cpy = Array.isArray(obj) ? [] : {}; for (var key in obj) cpy[key] = copy(obj[key]); return cpy; }
Makes a deep copy of an array or object (mostly)
copy
javascript
mholt/PapaParse
docs/resources/js/papaparse.js
https://github.com/mholt/PapaParse/blob/master/docs/resources/js/papaparse.js
MIT
function bindFunction(f, self) { return function() { f.apply(self, arguments); }; }
Makes a deep copy of an array or object (mostly)
bindFunction
javascript
mholt/PapaParse
docs/resources/js/papaparse.js
https://github.com/mholt/PapaParse/blob/master/docs/resources/js/papaparse.js
MIT
function isFunction(func) { return typeof func === 'function'; }
Makes a deep copy of an array or object (mostly)
isFunction
javascript
mholt/PapaParse
docs/resources/js/papaparse.js
https://github.com/mholt/PapaParse/blob/master/docs/resources/js/papaparse.js
MIT
logError = function logError( error ) { if ( window && window.console && window.console.error ) { window.console.error( error ); } }
setValue() sets the Placard triggering DOM element's display value @param {String} the value to be displayed @param {Boolean} If you want to explicitly suppress the application of ellipsis, pass `true`. This would typically only be done from internal functions (like `applyEllipsis`) that want to avoid circular logic. Otherwise, the value of the option applyEllipsis will be used. @return {Object} jQuery object representing the DOM element whose value was set
logError
javascript
ExactTarget/fuelux
dist/js/fuelux.js
https://github.com/ExactTarget/fuelux/blob/master/dist/js/fuelux.js
BSD-3-Clause
Radio = function Radio( element, options ) { this.options = $.extend( {}, $.fn.radio.defaults, options ); if ( element.tagName.toLowerCase() !== 'label' ) { logError( 'Radio must be initialized on the `label` that wraps the `input` element. See https://github.com/ExactTarget/fuelux/blob/master/reference/markup/radio.html for example of proper markup. Call `.radio()` on the `<label>` not the `<input>`' ); return; } // cache elements this.$label = $( element ); this.$radio = this.$label.find( 'input[type="radio"]' ); this.groupName = this.$radio.attr( 'name' ); // don't cache group itself since items can be added programmatically if ( !this.options.ignoreVisibilityCheck && this.$radio.css( 'visibility' ).match( /hidden|collapse/ ) ) { logError( 'For accessibility reasons, in order for tab and space to function on radio, `visibility` must not be set to `hidden` or `collapse`. See https://github.com/ExactTarget/fuelux/pull/1996 for more details.' ); } // determine if a toggle container is specified var containerSelector = this.$radio.attr( 'data-toggle' ); this.$toggleContainer = $( containerSelector ); // handle internal events this.$radio.on( 'change', $.proxy( this.itemchecked, this ) ); // set default state this.setInitialState(); }
setValue() sets the Placard triggering DOM element's display value @param {String} the value to be displayed @param {Boolean} If you want to explicitly suppress the application of ellipsis, pass `true`. This would typically only be done from internal functions (like `applyEllipsis`) that want to avoid circular logic. Otherwise, the value of the option applyEllipsis will be used. @return {Object} jQuery object representing the DOM element whose value was set
Radio
javascript
ExactTarget/fuelux
dist/js/fuelux.js
https://github.com/ExactTarget/fuelux/blob/master/dist/js/fuelux.js
BSD-3-Clause
Search = function( element, options ) { this.$element = $( element ); this.$repeater = $( element ).closest( '.repeater' ); this.options = $.extend( {}, $.fn.search.defaults, options ); if ( this.$element.attr( 'data-searchOnKeyPress' ) === 'true' ) { this.options.searchOnKeyPress = true; } this.$button = this.$element.find( 'button' ); this.$input = this.$element.find( 'input' ); this.$icon = this.$element.find( '.glyphicon, .fuelux-icon' ); this.$button.on( 'click.fu.search', $.proxy( this.buttonclicked, this ) ); this.$input.on( 'keyup.fu.search', $.proxy( this.keypress, this ) ); if ( this.$repeater.length > 0 ) { this.$repeater.on( 'rendered.fu.repeater', $.proxy( this.clearPending, this ) ); } this.activeSearch = ''; }
setValue() sets the Placard triggering DOM element's display value @param {String} the value to be displayed @param {Boolean} If you want to explicitly suppress the application of ellipsis, pass `true`. This would typically only be done from internal functions (like `applyEllipsis`) that want to avoid circular logic. Otherwise, the value of the option applyEllipsis will be used. @return {Object} jQuery object representing the DOM element whose value was set
Search
javascript
ExactTarget/fuelux
dist/js/fuelux.js
https://github.com/ExactTarget/fuelux/blob/master/dist/js/fuelux.js
BSD-3-Clause
Selectlist = function( element, options ) { this.$element = $( element ); this.options = $.extend( {}, $.fn.selectlist.defaults, options ); this.$button = this.$element.find( '.btn.dropdown-toggle' ); this.$hiddenField = this.$element.find( '.hidden-field' ); this.$label = this.$element.find( '.selected-label' ); this.$dropdownMenu = this.$element.find( '.dropdown-menu' ); this.$element.on( 'click.fu.selectlist', '.dropdown-menu a', $.proxy( this.itemClicked, this ) ); this.setDefaultSelection(); if ( options.resize === 'auto' || this.$element.attr( 'data-resize' ) === 'auto' ) { this.resize(); } // if selectlist is empty or is one item, disable it var items = this.$dropdownMenu.children( 'li' ); if ( items.length === 0 ) { this.disable(); this.doSelect( $( this.options.emptyLabelHTML ) ); } // support jumping focus to first letter in dropdown when key is pressed this.$element.on( 'shown.bs.dropdown', function() { var $this = $( this ); // attach key listener when dropdown is shown $( document ).on( 'keypress.fu.selectlist', function( e ) { // get the key that was pressed var key = String.fromCharCode( e.which ); // look the items to find the first item with the first character match and set focus $this.find( "li" ).each( function( idx, item ) { if ( $( item ).text().charAt( 0 ).toLowerCase() === key ) { $( item ).children( 'a' ).focus(); return false; } } ); } ); } ); // unbind key event when dropdown is hidden this.$element.on( 'hide.bs.dropdown', function() { $( document ).off( 'keypress.fu.selectlist' ); } ); }
setValue() sets the Placard triggering DOM element's display value @param {String} the value to be displayed @param {Boolean} If you want to explicitly suppress the application of ellipsis, pass `true`. This would typically only be done from internal functions (like `applyEllipsis`) that want to avoid circular logic. Otherwise, the value of the option applyEllipsis will be used. @return {Object} jQuery object representing the DOM element whose value was set
Selectlist
javascript
ExactTarget/fuelux
dist/js/fuelux.js
https://github.com/ExactTarget/fuelux/blob/master/dist/js/fuelux.js
BSD-3-Clause
Spinbox = function Spinbox( element, options ) { this.$element = $( element ); this.$element.find( '.btn' ).on( 'click', function( e ) { //keep spinbox from submitting if they forgot to say type="button" on their spinner buttons e.preventDefault(); } ); this.options = $.extend( {}, $.fn.spinbox.defaults, options ); this.options.step = this.$element.data( 'step' ) || this.options.step; if ( this.options.value < this.options.min ) { this.options.value = this.options.min; } else if ( this.options.max < this.options.value ) { this.options.value = this.options.max; } this.$input = this.$element.find( '.spinbox-input' ); this.$input.on( 'focusout.fu.spinbox', this.$input, $.proxy( this.change, this ) ); this.$element.on( 'keydown.fu.spinbox', this.$input, $.proxy( this.keydown, this ) ); this.$element.on( 'keyup.fu.spinbox', this.$input, $.proxy( this.keyup, this ) ); if ( this.options.hold ) { this.$element.on( 'mousedown.fu.spinbox', '.spinbox-up', $.proxy( function() { this.startSpin( true ); }, this ) ); this.$element.on( 'mouseup.fu.spinbox', '.spinbox-up, .spinbox-down', $.proxy( this.stopSpin, this ) ); this.$element.on( 'mouseout.fu.spinbox', '.spinbox-up, .spinbox-down', $.proxy( this.stopSpin, this ) ); this.$element.on( 'mousedown.fu.spinbox', '.spinbox-down', $.proxy( function() { this.startSpin( false ); }, this ) ); } else { this.$element.on( 'click.fu.spinbox', '.spinbox-up', $.proxy( function() { this.step( true ); }, this ) ); this.$element.on( 'click.fu.spinbox', '.spinbox-down', $.proxy( function() { this.step( false ); }, this ) ); } this.switches = { count: 1, enabled: true }; if ( this.options.speed === 'medium' ) { this.switches.speed = 300; } else if ( this.options.speed === 'fast' ) { this.switches.speed = 100; } else { this.switches.speed = 500; } this.options.defaultUnit = _isUnitLegal( this.options.defaultUnit, this.options.units ) ? this.options.defaultUnit : ''; this.unit = this.options.defaultUnit; this.lastValue = this.options.value; this.render(); if ( this.options.disabled ) { this.disable(); } }
setValue() sets the Placard triggering DOM element's display value @param {String} the value to be displayed @param {Boolean} If you want to explicitly suppress the application of ellipsis, pass `true`. This would typically only be done from internal functions (like `applyEllipsis`) that want to avoid circular logic. Otherwise, the value of the option applyEllipsis will be used. @return {Object} jQuery object representing the DOM element whose value was set
Spinbox
javascript
ExactTarget/fuelux
dist/js/fuelux.js
https://github.com/ExactTarget/fuelux/blob/master/dist/js/fuelux.js
BSD-3-Clause
_limitToStep = function _limitToStep( number, step ) { return Math.round( number / step ) * step; }
setValue() sets the Placard triggering DOM element's display value @param {String} the value to be displayed @param {Boolean} If you want to explicitly suppress the application of ellipsis, pass `true`. This would typically only be done from internal functions (like `applyEllipsis`) that want to avoid circular logic. Otherwise, the value of the option applyEllipsis will be used. @return {Object} jQuery object representing the DOM element whose value was set
_limitToStep
javascript
ExactTarget/fuelux
dist/js/fuelux.js
https://github.com/ExactTarget/fuelux/blob/master/dist/js/fuelux.js
BSD-3-Clause
_isUnitLegal = function _isUnitLegal( unit, validUnits ) { var legalUnit = false; var suspectUnit = unit.toLowerCase(); $.each( validUnits, function( i, validUnit ) { validUnit = validUnit.toLowerCase(); if ( suspectUnit === validUnit ) { legalUnit = true; return false; //break out of the loop } } ); return legalUnit; }
setValue() sets the Placard triggering DOM element's display value @param {String} the value to be displayed @param {Boolean} If you want to explicitly suppress the application of ellipsis, pass `true`. This would typically only be done from internal functions (like `applyEllipsis`) that want to avoid circular logic. Otherwise, the value of the option applyEllipsis will be used. @return {Object} jQuery object representing the DOM element whose value was set
_isUnitLegal
javascript
ExactTarget/fuelux
dist/js/fuelux.js
https://github.com/ExactTarget/fuelux/blob/master/dist/js/fuelux.js
BSD-3-Clause
_applyLimits = function _applyLimits( value ) { // if unreadable if ( isNaN( parseFloat( value ) ) ) { return value; } // if not within range return the limit if ( value > this.options.max ) { if ( this.options.cycle ) { value = this.options.min; } else { value = this.options.max; } } else if ( value < this.options.min ) { if ( this.options.cycle ) { value = this.options.max; } else { value = this.options.min; } } if ( this.options.limitToStep && this.options.step ) { value = _limitToStep( value, this.options.step ); //force round direction so that it stays within bounds if ( value > this.options.max ) { value = value - this.options.step; } else if ( value < this.options.min ) { value = value + this.options.step; } } return value; }
setValue() sets the Placard triggering DOM element's display value @param {String} the value to be displayed @param {Boolean} If you want to explicitly suppress the application of ellipsis, pass `true`. This would typically only be done from internal functions (like `applyEllipsis`) that want to avoid circular logic. Otherwise, the value of the option applyEllipsis will be used. @return {Object} jQuery object representing the DOM element whose value was set
_applyLimits
javascript
ExactTarget/fuelux
dist/js/fuelux.js
https://github.com/ExactTarget/fuelux/blob/master/dist/js/fuelux.js
BSD-3-Clause
Tree = function Tree( element, options ) { this.$element = $( element ); this.options = $.extend( {}, $.fn.tree.defaults, options ); this.$element.attr( 'tabindex', '0' ); if ( this.options.itemSelect ) { this.$element.on( 'click.fu.tree', '.tree-item', $.proxy( function callSelect( ev ) { this.selectItem( ev.currentTarget ); }, this ) ); } this.$element.on( 'click.fu.tree', '.tree-branch-name', $.proxy( function callToggle( ev ) { this.toggleFolder( ev.currentTarget ); }, this ) ); this.$element.on( 'click.fu.tree', '.tree-overflow', $.proxy( function callPopulate( ev ) { this.populate( $( ev.currentTarget ) ); }, this ) ); // folderSelect default is true if ( this.options.folderSelect ) { this.$element.addClass( 'tree-folder-select' ); this.$element.off( 'click.fu.tree', '.tree-branch-name' ); this.$element.on( 'click.fu.tree', '.icon-caret', $.proxy( function callToggle( ev ) { this.toggleFolder( $( ev.currentTarget ).parent() ); }, this ) ); this.$element.on( 'click.fu.tree', '.tree-branch-name', $.proxy( function callSelect( ev ) { this.selectFolder( $( ev.currentTarget ) ); }, this ) ); } this.$element.on( 'focus', function setFocusOnTab() { var $tree = $( this ); focusIn( $tree, $tree ); } ); this.$element.on( 'keydown', function processKeypress( e ) { return navigateTree( $( this ), e ); } ); this.render(); }
setValue() sets the Placard triggering DOM element's display value @param {String} the value to be displayed @param {Boolean} If you want to explicitly suppress the application of ellipsis, pass `true`. This would typically only be done from internal functions (like `applyEllipsis`) that want to avoid circular logic. Otherwise, the value of the option applyEllipsis will be used. @return {Object} jQuery object representing the DOM element whose value was set
Tree
javascript
ExactTarget/fuelux
dist/js/fuelux.js
https://github.com/ExactTarget/fuelux/blob/master/dist/js/fuelux.js
BSD-3-Clause
disclosedCompleted = function disclosedCompleted() { $tree.trigger( 'disclosedFolder.fu.tree', $branch.data() ); }
setValue() sets the Placard triggering DOM element's display value @param {String} the value to be displayed @param {Boolean} If you want to explicitly suppress the application of ellipsis, pass `true`. This would typically only be done from internal functions (like `applyEllipsis`) that want to avoid circular logic. Otherwise, the value of the option applyEllipsis will be used. @return {Object} jQuery object representing the DOM element whose value was set
disclosedCompleted
javascript
ExactTarget/fuelux
dist/js/fuelux.js
https://github.com/ExactTarget/fuelux/blob/master/dist/js/fuelux.js
BSD-3-Clause
closedReported = function closedReported( event, closed ) { reportedClosed.push( closed ); // jQuery deprecated hide in 3.0. Use hidden instead. Leaving hide here to support previous markup if ( self.$element.find( ".tree-branch.tree-open:not('.hidden, .hide')" ).length === 0 ) { self.$element.trigger( 'closedAll.fu.tree', { tree: self.$element, reportedClosed: reportedClosed } ); self.$element.off( 'loaded.fu.tree', self.$element, closedReported ); } }
setValue() sets the Placard triggering DOM element's display value @param {String} the value to be displayed @param {Boolean} If you want to explicitly suppress the application of ellipsis, pass `true`. This would typically only be done from internal functions (like `applyEllipsis`) that want to avoid circular logic. Otherwise, the value of the option applyEllipsis will be used. @return {Object} jQuery object representing the DOM element whose value was set
closedReported
javascript
ExactTarget/fuelux
dist/js/fuelux.js
https://github.com/ExactTarget/fuelux/blob/master/dist/js/fuelux.js
BSD-3-Clause
openReported = function openReported( event, opened ) { reportedOpened.push( opened ); if ( reportedOpened.length === $openableFolders.length ) { self.$element.trigger( 'disclosedVisible.fu.tree', { tree: self.$element, reportedOpened: reportedOpened } ); /* * Unbind the `openReported` event. `discloseAll` may be running and we want to reset this * method for the next iteration. */ self.$element.off( 'loaded.fu.tree', self.$element, openReported ); } }
setValue() sets the Placard triggering DOM element's display value @param {String} the value to be displayed @param {Boolean} If you want to explicitly suppress the application of ellipsis, pass `true`. This would typically only be done from internal functions (like `applyEllipsis`) that want to avoid circular logic. Otherwise, the value of the option applyEllipsis will be used. @return {Object} jQuery object representing the DOM element whose value was set
openReported
javascript
ExactTarget/fuelux
dist/js/fuelux.js
https://github.com/ExactTarget/fuelux/blob/master/dist/js/fuelux.js
BSD-3-Clause
fixFocusability = function fixFocusability( $tree, $branch ) { /* When tree initializes on page, the `<ul>` element should have tabindex=0 and all sub-elements should have tabindex=-1. When focus leaves the tree, whatever the last focused on element was will keep the tabindex=0. The tree itself will have a tabindex=-1. The reason for this is that if you are inside of the tree and press shift+tab, it will try and focus on the tree you are already in, which will cause focus to shift immediately back to the element you are already focused on. That will make it seem like the event is getting "Swallowed up" by an aggressive event listener trap. For this reason, only one element in the entire tree, including the tree itself, should ever have tabindex=0. If somewhere down the line problems are being caused by this, the only further potential improvement I can envision at this time is listening for the tree to lose focus and reseting the tabindexes of all children to -1 and setting the tabindex of the tree itself back to 0. This seems overly complicated with no benefit that I can imagine at this time, so instead I am leaving the last focused element with the tabindex of 0, even upon blur of the tree. One benefit to leaving the last focused element in a tree with a tabindex=0 is that if you accidentally tab out of the tree and then want to tab back in, you will be placed exactly where you left off instead of at the beginning of the tree. */ $tree.attr( 'tabindex', -1 ); $tree.find( 'li' ).attr( 'tabindex', -1 ); if ( $branch && $branch.length > 0 ) { $branch.attr( 'tabindex', 0 ); // if tabindex is not set to 0 (or greater), node is not able to receive focus } }
setValue() sets the Placard triggering DOM element's display value @param {String} the value to be displayed @param {Boolean} If you want to explicitly suppress the application of ellipsis, pass `true`. This would typically only be done from internal functions (like `applyEllipsis`) that want to avoid circular logic. Otherwise, the value of the option applyEllipsis will be used. @return {Object} jQuery object representing the DOM element whose value was set
fixFocusability
javascript
ExactTarget/fuelux
dist/js/fuelux.js
https://github.com/ExactTarget/fuelux/blob/master/dist/js/fuelux.js
BSD-3-Clause
focusIn = function focusIn( $tree, $branch ) { var $focusCandidate = $branch.find( '.tree-selected:first' ); // if no node is selected, set focus to first visible node if ( $focusCandidate.length <= 0 ) { $focusCandidate = $branch.find( 'li:not(".hidden"):first' ); } setFocus( $tree, $focusCandidate ); }
setValue() sets the Placard triggering DOM element's display value @param {String} the value to be displayed @param {Boolean} If you want to explicitly suppress the application of ellipsis, pass `true`. This would typically only be done from internal functions (like `applyEllipsis`) that want to avoid circular logic. Otherwise, the value of the option applyEllipsis will be used. @return {Object} jQuery object representing the DOM element whose value was set
focusIn
javascript
ExactTarget/fuelux
dist/js/fuelux.js
https://github.com/ExactTarget/fuelux/blob/master/dist/js/fuelux.js
BSD-3-Clause
setFocus = function setFocus( $tree, $branch ) { fixFocusability( $tree, $branch ); $tree.attr( 'aria-activedescendant', $branch.attr( 'id' ) ); $branch.focus(); $tree.trigger( 'setFocus.fu.tree', $branch ); }
setValue() sets the Placard triggering DOM element's display value @param {String} the value to be displayed @param {Boolean} If you want to explicitly suppress the application of ellipsis, pass `true`. This would typically only be done from internal functions (like `applyEllipsis`) that want to avoid circular logic. Otherwise, the value of the option applyEllipsis will be used. @return {Object} jQuery object representing the DOM element whose value was set
setFocus
javascript
ExactTarget/fuelux
dist/js/fuelux.js
https://github.com/ExactTarget/fuelux/blob/master/dist/js/fuelux.js
BSD-3-Clause
navigateTree = function navigateTree( $tree, e ) { if ( e.isDefaultPrevented() || e.isPropagationStopped() ) { return false; } var targetNode = e.originalEvent.target; var $targetNode = $( targetNode ); var isOpen = $targetNode.hasClass( 'tree-open' ); var handled = false; // because es5 lacks promises and fuelux has no polyfil (and I'm not adding one just for this change) // I am faking up promises here through callbacks and listeners. Done will be fired immediately at the end of // the navigateTree method if there is no (fake) promise, but will be fired by an event listener that will // be triggered by another function if necessary. This way when done runs, and fires keyboardNavigated.fu.tree // anything listening for that event can be sure that everything tied to that event is actually completed. var fireDoneImmediately = true; var done = function done() { $tree.trigger( 'keyboardNavigated.fu.tree', e, $targetNode ); }; switch ( e.which ) { case 13: // enter case 32: // space // activates a node, i.e., performs its default action. // For parent nodes, one possible default action is to open or close the node. // In single-select trees where selection does not follow focus, the default action is typically to select the focused node. var foldersSelectable = $tree.hasClass( 'tree-folder-select' ); var isFolder = $targetNode.hasClass( 'tree-branch' ); var isItem = $targetNode.hasClass( 'tree-item' ); // var isOverflow = $targetNode.hasClass('tree-overflow'); fireDoneImmediately = false; if ( isFolder ) { if ( foldersSelectable ) { $tree.one( 'selected.fu.tree deselected.fu.tree', done ); $tree.tree( 'selectFolder', $targetNode.find( '.tree-branch-header' )[ 0 ] ); } else { $tree.one( 'loaded.fu.tree closed.fu.tree', done ); $tree.tree( 'toggleFolder', $targetNode.find( '.tree-branch-header' )[ 0 ] ); } } else if ( isItem ) { $tree.one( 'selected.fu.tree', done ); $tree.tree( 'selectItem', $targetNode ); } else { // should be isOverflow... Try and click on it either way. $prev = $( $targetNode.prevAll().not( '.hidden' )[ 0 ] ); $targetNode.click(); $tree.one( 'loaded.fu.tree', function selectFirstNewlyLoadedNode() { $next = $( $prev.nextAll().not( '.hidden' )[ 0 ] ); setFocus( $tree, $next ); done(); } ); } handled = true; break; case 35: // end // Set focus to the last node in the tree that is focusable without opening a node. setFocus( $tree, $tree.find( 'li:not(".hidden"):last' ) ); handled = true; break; case 36: // home // set focus to the first node in the tree without opening or closing a node. setFocus( $tree, $tree.find( 'li:not(".hidden"):first' ) ); handled = true; break; case 37: // left if ( isOpen ) { fireDoneImmediately = false; $tree.one( 'closed.fu.tree', done ); $tree.tree( 'closeFolder', targetNode ); } else { setFocus( $tree, $( $targetNode.parents( 'li' )[ 0 ] ) ); } handled = true; break; case 38: // up // move focus to previous sibling var $prev = []; // move to previous li not hidden $prev = $( $targetNode.prevAll().not( '.hidden' )[ 0 ] ); // if the previous li is open, and has children, move selection to its last child so selection // appears to move to the next "thing" up if ( $prev.hasClass( 'tree-open' ) ) { var $prevChildren = $prev.find( 'li:not(".hidden"):last' ); if ( $prevChildren.length > 0 ) { $prev = $( $prevChildren[ 0 ] ); } } // if nothing has been selected, we are presumably at the top of an open li, select the immediate parent if ( $prev.length < 1 ) { $prev = $( $targetNode.parents( 'li' )[ 0 ] ); } setFocus( $tree, $prev ); handled = true; break; case 39: // right if ( isOpen ) { focusIn( $tree, $targetNode ); } else { fireDoneImmediately = false; $tree.one( 'disclosed.fu.tree', done ); $tree.tree( 'discloseFolder', targetNode ); } handled = true; break; case 40: // down // move focus to next selectable tree node var $next = $( $targetNode.find( 'li:not(".hidden"):first' )[ 0 ] ); if ( !isOpen || $next.length <= 0 ) { $next = $( $targetNode.nextAll().not( '.hidden' )[ 0 ] ); } if ( $next.length < 1 ) { $next = $( $( $targetNode.parents( 'li' )[ 0 ] ).nextAll().not( '.hidden' )[ 0 ] ); } setFocus( $tree, $next ); handled = true; break; default: // console.log(e.which); return true; // exit this handler for other keys } // if we didn't handle the event, allow propagation to continue so something else might. if ( handled ) { e.preventDefault(); e.stopPropagation(); if ( fireDoneImmediately ) { done(); } } return true; }
setValue() sets the Placard triggering DOM element's display value @param {String} the value to be displayed @param {Boolean} If you want to explicitly suppress the application of ellipsis, pass `true`. This would typically only be done from internal functions (like `applyEllipsis`) that want to avoid circular logic. Otherwise, the value of the option applyEllipsis will be used. @return {Object} jQuery object representing the DOM element whose value was set
navigateTree
javascript
ExactTarget/fuelux
dist/js/fuelux.js
https://github.com/ExactTarget/fuelux/blob/master/dist/js/fuelux.js
BSD-3-Clause
done = function done() { $tree.trigger( 'keyboardNavigated.fu.tree', e, $targetNode ); }
setValue() sets the Placard triggering DOM element's display value @param {String} the value to be displayed @param {Boolean} If you want to explicitly suppress the application of ellipsis, pass `true`. This would typically only be done from internal functions (like `applyEllipsis`) that want to avoid circular logic. Otherwise, the value of the option applyEllipsis will be used. @return {Object} jQuery object representing the DOM element whose value was set
done
javascript
ExactTarget/fuelux
dist/js/fuelux.js
https://github.com/ExactTarget/fuelux/blob/master/dist/js/fuelux.js
BSD-3-Clause
ariaSelect = function ariaSelect( $element ) { $element.attr( 'aria-selected', true ); }
setValue() sets the Placard triggering DOM element's display value @param {String} the value to be displayed @param {Boolean} If you want to explicitly suppress the application of ellipsis, pass `true`. This would typically only be done from internal functions (like `applyEllipsis`) that want to avoid circular logic. Otherwise, the value of the option applyEllipsis will be used. @return {Object} jQuery object representing the DOM element whose value was set
ariaSelect
javascript
ExactTarget/fuelux
dist/js/fuelux.js
https://github.com/ExactTarget/fuelux/blob/master/dist/js/fuelux.js
BSD-3-Clause
ariaDeselect = function ariaDeselect( $element ) { $element.attr( 'aria-selected', false ); }
setValue() sets the Placard triggering DOM element's display value @param {String} the value to be displayed @param {Boolean} If you want to explicitly suppress the application of ellipsis, pass `true`. This would typically only be done from internal functions (like `applyEllipsis`) that want to avoid circular logic. Otherwise, the value of the option applyEllipsis will be used. @return {Object} jQuery object representing the DOM element whose value was set
ariaDeselect
javascript
ExactTarget/fuelux
dist/js/fuelux.js
https://github.com/ExactTarget/fuelux/blob/master/dist/js/fuelux.js
BSD-3-Clause
function styleNodeSelected( $element, $icon ) { $element.addClass( 'tree-selected' ); if ( $element.data( 'type' ) === 'item' && $icon.hasClass( 'fueluxicon-bullet' ) ) { $icon.removeClass( 'fueluxicon-bullet' ).addClass( 'glyphicon-ok' ); // make checkmark } }
setValue() sets the Placard triggering DOM element's display value @param {String} the value to be displayed @param {Boolean} If you want to explicitly suppress the application of ellipsis, pass `true`. This would typically only be done from internal functions (like `applyEllipsis`) that want to avoid circular logic. Otherwise, the value of the option applyEllipsis will be used. @return {Object} jQuery object representing the DOM element whose value was set
styleNodeSelected
javascript
ExactTarget/fuelux
dist/js/fuelux.js
https://github.com/ExactTarget/fuelux/blob/master/dist/js/fuelux.js
BSD-3-Clause
function styleNodeDeselected( $element, $icon ) { $element.removeClass( 'tree-selected' ); if ( $element.data( 'type' ) === 'item' && $icon.hasClass( 'glyphicon-ok' ) ) { $icon.removeClass( 'glyphicon-ok' ).addClass( 'fueluxicon-bullet' ); // make bullet } }
setValue() sets the Placard triggering DOM element's display value @param {String} the value to be displayed @param {Boolean} If you want to explicitly suppress the application of ellipsis, pass `true`. This would typically only be done from internal functions (like `applyEllipsis`) that want to avoid circular logic. Otherwise, the value of the option applyEllipsis will be used. @return {Object} jQuery object representing the DOM element whose value was set
styleNodeDeselected
javascript
ExactTarget/fuelux
dist/js/fuelux.js
https://github.com/ExactTarget/fuelux/blob/master/dist/js/fuelux.js
BSD-3-Clause
function multiSelectSyncNodes( self, clicked, selected ) { // search for currently selected and add to selected data list if needed $.each( selected.$elements, function findCurrentlySelected( index, element ) { var $element = $( element ); if ( $element[ 0 ] !== clicked.$element[ 0 ] ) { selected.dataForEvent.push( $( $element ).data() ); } } ); if ( clicked.$element.hasClass( 'tree-selected' ) ) { styleNodeDeselected( clicked.$element, clicked.$icon ); // set event data selected.eventType = 'deselected'; } else { styleNodeSelected( clicked.$element, clicked.$icon ); // set event data selected.eventType = 'selected'; selected.dataForEvent.push( clicked.elementData ); } return selected; }
setValue() sets the Placard triggering DOM element's display value @param {String} the value to be displayed @param {Boolean} If you want to explicitly suppress the application of ellipsis, pass `true`. This would typically only be done from internal functions (like `applyEllipsis`) that want to avoid circular logic. Otherwise, the value of the option applyEllipsis will be used. @return {Object} jQuery object representing the DOM element whose value was set
multiSelectSyncNodes
javascript
ExactTarget/fuelux
dist/js/fuelux.js
https://github.com/ExactTarget/fuelux/blob/master/dist/js/fuelux.js
BSD-3-Clause
function singleSelectSyncNodes( self, clicked, selected ) { // element is not currently selected if ( selected.$elements[ 0 ] !== clicked.$element[ 0 ] ) { self.deselectAll( self.$element ); styleNodeSelected( clicked.$element, clicked.$icon ); // set event data selected.eventType = 'selected'; selected.dataForEvent = [ clicked.elementData ]; } else { styleNodeDeselected( clicked.$element, clicked.$icon ); // set event data selected.eventType = 'deselected'; selected.dataForEvent = []; } return selected; }
setValue() sets the Placard triggering DOM element's display value @param {String} the value to be displayed @param {Boolean} If you want to explicitly suppress the application of ellipsis, pass `true`. This would typically only be done from internal functions (like `applyEllipsis`) that want to avoid circular logic. Otherwise, the value of the option applyEllipsis will be used. @return {Object} jQuery object representing the DOM element whose value was set
singleSelectSyncNodes
javascript
ExactTarget/fuelux
dist/js/fuelux.js
https://github.com/ExactTarget/fuelux/blob/master/dist/js/fuelux.js
BSD-3-Clause