UNPKG

1.36 kBJavaScriptView Raw
1'use strict';
2
3var eventCodes = {
4 8: 'backspace'
5};
6
7function addTextEvent(eventList, text) {
8 if(text.length > 0){
9 eventList.push({
10 type: 'text',
11 data: text
12 });
13 }
14}
15
16function addEvent(eventList, type, data) {
17 eventList.push({
18 type: type,
19 data: data
20 });
21}
22
23function combineLinefeed(lastCode, code){
24 return (lastCode === 10 && code === 13) || (lastCode === 13 && code === 10);
25}
26
27function StreamParser(){
28 this.lastCode = null;
29}
30
31StreamParser.prototype.parseStreamChunk = function(chunk){
32 var events = [];
33 var str = '';
34 for(var idx = 0; idx < chunk.length; idx++){
35 var char = chunk[idx];
36 if(combineLinefeed(this.lastCode, char)){
37 this.lastCode = char;
38 //do nothing, allow previous linefeed event to handle this
39 continue;
40 } else if(char === 10 || char === 13){
41 str += '\n';
42 } else if(eventCodes[char] != null){
43 // finalize the current text event before we create the special event
44 addTextEvent(events, str);
45 str = '';
46 addEvent(events, eventCodes[char]);
47 } else if(char <= 31 || (char >= 128 && char <= 159)){
48 str += ' ';
49 } else {
50 str += String.fromCharCode(char);
51 }
52 this.lastCode = char;
53 }
54 // finalize any trailing text into an event
55 addTextEvent(events, str);
56 return events;
57};
58
59module.exports = StreamParser;