aboutsummaryrefslogtreecommitdiff
path: root/src/index.js
blob: fc7a02a2ae2a880f4db0f7121f3e184638a756e4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
'use strict';

// A valid output which means nothing has been parsed.
// Used as error return / invalid output
const nothingHappend = {
  prop: {},
  eaten: '',
};

const defaultConfig = {
  defaultValue: () => undefined, // Its a function
};

// Main function
function parse(value, indexNext, userConfig) {
  let letsEat = '';
  let stopOnBrace = false;
  let errorDetected = false;
  const config = {...defaultConfig, ...userConfig};

  // Make defaultValue a function if it isn't
  if (typeof (config.defaultValue) !== 'function') {
    const {defaultValue} = config;
    config.defaultValue = () => defaultValue;
  }

  const prop = {};

  /* They are at least one label and at best two */
  /* ekqsdf <- one label
   * qsdfqsfd=qsdfqsdf <- two */
  let labelFirst = '';
  let labelSecond;

  if (indexNext === undefined) {
    indexNext = 0;
  }

  /* 3 types :
   * .azcv <- class
   * #poi <- id
   * dfgh=zert <- key
   * jkj <- this is also a key but with a user defined value (default is undefined)
   * jkj= <- this is also a key but with a empty value
   */
  let type;
  const forbidenCharacters = '\n\r{}';

  // A function that detect if it's time to end the parsing
  const shouldStop = function () {
    if (indexNext >= value.length || forbidenCharacters.indexOf(value[indexNext]) > -1) {
      if (stopOnBrace && value[indexNext] !== '}') {
        errorDetected = true;
      }
      return true;
    }
    return value[indexNext] === '}' && stopOnBrace;
  };

  let eaten = '';
  // Couple of functions that parse same kinds of characters
  // Used to parse spaces or identifiers
  const eat = chars => {
    eaten = '';

    while (indexNext < value.length &&
            forbidenCharacters.indexOf(value.charAt(indexNext)) < 0 &&
            chars.indexOf(value.charAt(indexNext)) >= 0) {
      letsEat += value.charAt(indexNext);
      eaten += value.charAt(indexNext);
      indexNext++;
    }

    return shouldStop();
  };
  const eatUntil = chars => {
    eaten = '';

    while (indexNext < value.length &&
            forbidenCharacters.indexOf(value.charAt(indexNext)) < 0 &&
            chars.indexOf(value.charAt(indexNext)) < 0) {
      letsEat += value.charAt(indexNext);
      eaten += value.charAt(indexNext);
      indexNext++;
    }

    // Ugly but keep the main loop readable
    // Set the label it should set
    if (labelFirst) {
      labelSecond = eaten;
    } else {
      labelFirst = eaten;
    }

    return shouldStop();
  };

  // In quote, every character is valid except the unescaped quotes and CR or LF
  // Same function for single and double quote
  const eatInQuote = quote => {
    eaten = '';
    // First check so value[indexNext-1] will always be valid
    if (value[indexNext] === quote) {
      return;
    }

    while (indexNext < value.length &&
          !(quote === value[indexNext] && value[indexNext - 1] !== '\\') &&
          value[indexNext] !== '\n' && value[indexNext] !== '\r') {
      letsEat += value.charAt(indexNext);
      eaten += value.charAt(indexNext);
      indexNext++;
    }
    // If we encounter an EOL, there is an error
    // We are waiting for a quote
    if (value[indexNext] === '\n' || value[indexNext] === '\r' || indexNext >= value.length) {
      errorDetected = true;
      return true;
    }

    // Ugly but keep the main loop readable
    if (labelFirst) {
      labelSecond = eaten.replace(/\\"/g, '"');
    } else {
      labelFirst = eaten.replace(/\\"/g, '"');
    }

    return shouldStop();
  };

  // It's really common to eat only one character so let's make it a function
  const eatOne = (c, skipStopCheck) => {
    // Miam !
    letsEat += c;
    indexNext++;

    return skipStopCheck ? false : shouldStop();
  };

  // Common parsing of quotes
  const eatQuote = q => {
    eatOne(q, true);
    eatInQuote(q, true);

    if (value.charAt(indexNext) !== q) {
      return nothingHappend;
    }
    if (eatOne(q)) {
      return -1;
    }
  };

  const addAttribute = () => {
    switch (type) {
      case 'id': // ID
        prop.id = prop.id || labelFirst;
        break;
      case 'class':
        if (!prop.class) {
          prop.class = [];
        }

        if (prop.class.indexOf(labelFirst) < 0) {
          prop.class.push(labelFirst);
        }

        break;
      case 'key':
        if (!labelFirst) {
          return nothingHappend;
        }
        if (!(labelFirst in prop)) {
          if (labelSecond === undefined) { // Here, we have an attribute without value
            // so it's user defined
            prop[labelFirst] = config.defaultValue(labelFirst);
          } else {
            prop[labelFirst] = labelFirst === 'class' ? [labelSecond] : labelSecond;
          }
        }
        break;
      default:
    }
    type = undefined;
    labelFirst = '';
    labelSecond = undefined;
  };

  /** *********************** Start parsing ************************ */

  // Let's check for leading spaces first
  eat(' \t\v');

  if (value[indexNext] === '{') {
    eatOne('{');
    stopOnBrace = true;
  }

  while (!shouldStop()) { // Main loop which extract attributes
    if (eat(' \t\v')) {
      break;
    }

    if (value.charAt(indexNext) === '.') { // Classes
      type = 'class';
      if (eatOne('.')) {
        errorDetected = true;
        break;
      }
    } else if (value.charAt(indexNext) === '#') { // ID
      type = 'id';
      if (eatOne('#')) {
        errorDetected = true;
        break;
      }
    } else { // Key
      type = 'key';
    }

    // Extract name
    if (eatUntil('=\t\b\v  ') || !labelFirst) {
      break;
    }
    if (value.charAt(indexNext) === '=' && type === 'key') { // Set labelSecond
      if (eatOne('=')) {
        break;
      }

      if (value.charAt(indexNext) === '"') {
        const ret = eatQuote('"');
        if (ret === -1) {
          break;
        } else if (ret === nothingHappend) {
          return nothingHappend;
        }
      } else if (value.charAt(indexNext) === '\'') {
        const ret = eatQuote('\'');
        if (ret === -1) {
          break;
        } else if (ret === nothingHappend) {
          return nothingHappend;
        }
      } else if (eatUntil(' \t\n\r\v=}')) {
        break;
      }
    }

    // Add the parsed attribute to the output prop with the ad hoc type
    addAttribute();
  }
  addAttribute();
  if (stopOnBrace) {
    if (indexNext < value.length && value[indexNext] === '}') {
      stopOnBrace = false;
      eatOne('}');
    } else {
      return nothingHappend;
    }
  }

  return errorDetected ? nothingHappend : {prop, eaten: letsEat};
}

module.exports = parse;