1 | 'use strict';
|
2 |
|
3 | var eventCodes = {
|
4 | 8: 'backspace'
|
5 | };
|
6 |
|
7 | function addTextEvent(eventList, text) {
|
8 | if(text.length > 0){
|
9 | eventList.push({
|
10 | type: 'text',
|
11 | data: text
|
12 | });
|
13 | }
|
14 | }
|
15 |
|
16 | function addEvent(eventList, type, data) {
|
17 | eventList.push({
|
18 | type: type,
|
19 | data: data
|
20 | });
|
21 | }
|
22 |
|
23 | function combineLinefeed(lastCode, code){
|
24 | return (lastCode === 10 && code === 13) || (lastCode === 13 && code === 10);
|
25 | }
|
26 |
|
27 | function StreamParser(){
|
28 | this.lastCode = null;
|
29 | }
|
30 |
|
31 | StreamParser.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 |
|
39 | continue;
|
40 | } else if(char === 10 || char === 13){
|
41 | str += '\n';
|
42 | } else if(eventCodes[char] != null){
|
43 |
|
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 |
|
55 | addTextEvent(events, str);
|
56 | return events;
|
57 | };
|
58 |
|
59 | module.exports = StreamParser;
|