summaryrefslogtreecommitdiff
path: root/lib/hyphen/hyphen.js
blob: d5c2df35755988598910fc6b3b7fae97555d0a39 (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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
/** Text hyphenation in Javascript.
 *  Copyright (C) 2020 Yevhen Tiurin ([email protected])
 *  https://github.com/ytiurin/hyphen
 *
 *  Released under the ISC license
 *  https://github.com/ytiurin/hyphen/blob/master/LICENSE
 */
(function (root, factory) {
  if (typeof define === "function" && define.amd) {
    // AMD. Register as an anonymous module.
    define([], factory);
  } else if (typeof module === "object" && module.exports) {
    // Node. Does not work with strict CommonJS, but
    // only CommonJS-like environments that support module.exports,
    // like Node.
    module.exports = factory();
  } else {
    // Browser globals (root is window)
    root.createHyphenator = factory();
  }
})(this, function () {
  var MIN_WORD_LENGTH_BOUNDRY = 5;

  var SETTING_DEFAULT_ASYNC = false,
    SETTING_DEFAULT_DEBUG = false,
    SETTING_DEFAULT_HTML = false,
    SETTING_DEFAULT_HYPH_CHAR = "\u00AD",
    SETTING_NAME_ASYNC = "async",
    SETTING_NAME_DEBUG = "debug",
    SETTING_NAME_HTML = "html",
    SETTING_NAME_HYPH_CHAR = "hyphenChar",
    SETTING_NAME_MIN_WORD_LENGTH = "minWordLength";

  var _global =
    typeof global === "object"
      ? global
      : typeof window === "object"
      ? window
      : typeof this === "object"
      ? this
      : {};

  function cloneObj(source) {
    var target = {};
    for (var key in source) {
      target[key] = source[key];
    }
    return target;
  }

  function keyOrDefault(object, key, defaultValue) {
    if (key in object) {
      return object[key];
    }
    return defaultValue;
  }

  function exceptionsFromDefinition(patternsDefinition, hyphenChar) {
    return patternsDefinition.exceptions.reduce(function (
      exceptions,
      exception
    ) {
      exceptions[exception.replace(/\-/g, "")] = exception.replace(
        /\-/g,
        hyphenChar
      );
      return exceptions;
    },
    {});
  }

  function createHyphenator(patternsDefinition, options) {
    options = options || {};
    var //
      asyncMode = keyOrDefault(
        options,
        SETTING_NAME_ASYNC,
        SETTING_DEFAULT_ASYNC
      ),
      caches = {},
      debug = keyOrDefault(options, SETTING_NAME_DEBUG, SETTING_DEFAULT_DEBUG),
      exceptions = {},
      hyphenChar = keyOrDefault(
        options,
        SETTING_NAME_HYPH_CHAR,
        SETTING_DEFAULT_HYPH_CHAR
      ),
      patterns = patternsDefinition.patterns.map(preprocessPattern),
      minWordLength = Math.max(
        options[SETTING_NAME_MIN_WORD_LENGTH] >> 0,
        MIN_WORD_LENGTH_BOUNDRY
      ),
      skipHTML = keyOrDefault(options, SETTING_NAME_HTML, SETTING_DEFAULT_HTML);

    // Prepare cache
    var cacheKey = hyphenChar + minWordLength;
    exceptions[cacheKey] = exceptionsFromDefinition(
      patternsDefinition,
      hyphenChar
    );
    caches[cacheKey] = cloneObj(exceptions[cacheKey]);

    if (asyncMode && !("Promise" in _global)) {
      throw new Error(
        "Failed to create hyphenator: Could not find global Promise object, needed for hyphenator to work in async mode"
      );
    }

    return function (text, options) {
      options = options || {};

      var localDebug = keyOrDefault(options, SETTING_NAME_DEBUG, debug),
        localHyphenChar = keyOrDefault(
          options,
          SETTING_NAME_HYPH_CHAR,
          hyphenChar
        ),
        localMinWordLength = Math.max(
          options[SETTING_NAME_MIN_WORD_LENGTH] >> 0,
          minWordLength
        ),
        cacheKey = localHyphenChar + localMinWordLength;

      if (!exceptions[cacheKey]) {
        exceptions[cacheKey] = exceptionsFromDefinition(
          patternsDefinition,
          localHyphenChar
        );
      }

      if (!caches[cacheKey]) {
        caches[cacheKey] = cloneObj(exceptions[cacheKey]);
      }

      return start(
        text,
        patterns,
        caches[cacheKey],
        localDebug,
        localHyphenChar,
        skipHTML,
        localMinWordLength,
        asyncMode
      );
    };
  }
  function createTextChunkReader(text, hyphenChar, skipHTML, minWordLength) {
    function readNextTextChunk() {
      var nextTextChunk = "";

      shouldHyphenate = void 0;

      chunkReader: while (nextCharIndex <= text.length) {
        var //
          nextChar = text.charAt(nextCharIndex++),
          charIsLetter =
            !!nextChar && !/\s|[\!-\@\[-\`\{-\~\u2013-\u203C]/.test(nextChar),
          charIsAngleOpen = nextChar === "<",
          charIsAngleClose = nextChar === ">",
          charIsHyphen = nextChar === hyphenChar;

        do {
          if (state === STATE_READ_TAG) {
            if (charIsAngleClose) {
              state = STATE_RETURN_UNTOUCHED;
            }
            break;
          }

          if (charIsHyphen) {
            shouldHyphenate = SHOULD_SKIP;
            state = STATE_READ_WORD;
            break;
          }

          if (charIsLetter) {
            state = STATE_READ_WORD;
            break;
          }

          if (state === STATE_READ_WORD) {
            state = STATE_RETURN_WORD;
            shouldHyphenate =
              shouldHyphenate ||
              (nextTextChunk.length >= minWordLength && SHOULD_HYPHENATE);
            break;
          }

          shouldHyphenate = SHOULD_SKIP;
          state = STATE_RETURN_UNTOUCHED;
        } while (0);

        if (
          charIsAngleOpen &&
          state !== STATE_RETURN_WORD &&
          skipHTML &&
          !isSpacelike(text.charAt(nextCharIndex))
        ) {
          shouldHyphenate = SHOULD_SKIP;
          state = STATE_READ_TAG;
        }

        switch (state) {
          case STATE_READ_TAG:
            nextTextChunk += nextChar;
            break;

          case STATE_READ_WORD:
            nextTextChunk += nextChar;
            break;

          case STATE_RETURN_UNTOUCHED:
            nextTextChunk += nextChar;
            break chunkReader;

          case STATE_RETURN_WORD:
            nextCharIndex--;
            break chunkReader;
        }
      }
      return nextTextChunk || void 0;
    }

    function shouldNextHyphenate() {
      return shouldHyphenate === SHOULD_HYPHENATE;
    }

    var isSpacelike = RegExp.prototype.test.bind(/\s/);

    var //
      nextCharIndex = 0,
      SHOULD_HYPHENATE = 1,
      SHOULD_SKIP = 2,
      shouldHyphenate,
      STATE_READ_TAG = 1,
      STATE_READ_WORD = 2,
      STATE_RETURN_UNTOUCHED = 3,
      STATE_RETURN_WORD = 4,
      state;

    return [readNextTextChunk, shouldNextHyphenate];
  }
  function hyphenateWord(text, patterns, debug, hyphenChar) {
    var //
      levels = new Array(text.length + 1),
      loweredText = text.toLocaleLowerCase(),
      p = [],
      patternData,
      patternIndex = 0;

    for (var i = levels.length; i--; ) levels[i] = 0;

    while ((patternData = patterns[patternIndex++])) {
      var //
        fromChar = 0,
        endPattern = false;
      while (!endPattern) {
        var //
          patternEntityIndex = loweredText.indexOf(patternData.text, fromChar),
          patternFits =
            patternEntityIndex > -1 &&
            (patternData.stickToLeft ? patternEntityIndex === 0 : true) &&
            (patternData.stickToRight
              ? patternEntityIndex + patternData.text.length === text.length
              : true);

        if (patternFits) {
          p.push(patternData.pattern + ">" + patternData.levels.join(""));

          for (var i = 0; i < patternData.levels.length; i++)
            levels[patternEntityIndex + i] = Math.max(
              patternData.levels[i],
              levels[patternEntityIndex + i]
            );
        }
        if (patternEntityIndex > -1 && patternData.text.length > 0) {
          fromChar = patternEntityIndex + patternData.text.length + 1;
        } else {
          endPattern = true;
        }
      }
    }

    levels[0] = levels[1] = levels[levels.length - 1] = levels[
      levels.length - 2
    ] = 0;

    var //
      hyphenatedText = "",
      leveledText = "",
      debugHyphenatedText = "";

    for (var i = 0; i < levels.length; i++) {
      hyphenatedText +=
        (levels[i] % 2 === 1 ? hyphenChar : "") + text.charAt(i);
      debugHyphenatedText += (levels[i] % 2 === 1 ? "-" : "") + text.charAt(i);
      leveledText += (levels[i] > 0 ? levels[i] : "") + text.charAt(i);
    }

    if (debug)
      console.log.apply(
        console,
        [text, "->"]
          .concat(p)
          .concat(["->"])
          .concat(levels)
          .concat(["->", leveledText])
          .concat(["->", debugHyphenatedText])
      );

    return hyphenatedText;
  }
  function preprocessPattern(pattern) {
    var //
      patternCharIndex = 0,
      patternChar,
      patternData = {
        pattern: pattern,
        text: "",
        levels: [],
        stickToLeft: 0,
        stickToRight: 0
      },
      states = { alphabet: 1, level: 2, stickToLeft: 3, stickToRight: 4 };

    while ((patternChar = pattern.charAt(patternCharIndex++))) {
      var //
        charIsDot = patternChar === ".",
        charIsNumber = !charIsDot && /\d/.test(patternChar),
        state = charIsDot
          ? patternCharIndex - 1 === 0
            ? states.stickToLeft
            : states.stickToRight
          : charIsNumber
          ? states.level
          : states.alphabet;

      switch (state) {
        case states.alphabet:
          !prevCharIsNumber && patternData.levels.push(0);
          patternData.text += patternChar;
          break;

        case states.level:
          patternData.levels.push(parseInt(patternChar));
          break;

        case states.stickToLeft:
          patternData.stickToLeft = true;
          break;

        case states.stickToRight:
          patternData.stickToRight = true;
          break;
      }

      var prevCharIsNumber = charIsNumber;
    }

    return patternData;
  }
  function start(
    text,
    patterns,
    cache,
    debug,
    hyphenChar,
    skipHTML,
    minWordLength,
    isAsync
  ) {
    function done() {
      allTime = new Date() - allTime;
      resolveNewText(newText);

      if (debug) {
        console.log(
          "----------------\nHyphenation stats: " +
            processedN +
            " text chunks processed, " +
            hyphenatedN +
            " words hyphenated"
        );
        console.log("Work time: " + workTime / 1000);
        console.log("Wait time: " + (allTime - workTime) / 1000);
        console.log("All time: " + allTime / 1000);
      }
    }

    var //
      newText = "",
      nextTextChunk,
      reader = createTextChunkReader(text, hyphenChar, skipHTML, minWordLength),
      readNextTextChunk = reader[0],
      shouldNextHyphenate = reader[1],
      states = { hyphenateWord: 1, concatenate: 2 },
      processedN = 0,
      hyphenatedN = 0;

    var //
      allTime = new Date(),
      workTime = 0;

    var resolveNewText = function () {};

    function nextTick() {
      var loopStart = new Date();

      while (
        (!isAsync || new Date() - loopStart < 10) &&
        (nextTextChunk = readNextTextChunk())
      ) {
        var state = shouldNextHyphenate()
          ? states.hyphenateWord
          : states.concatenate;

        switch (state) {
          case states.hyphenateWord:
            if (!cache[nextTextChunk])
              cache[nextTextChunk] = hyphenateWord(
                nextTextChunk,
                patterns,
                debug,
                hyphenChar
              );

            if (nextTextChunk !== cache[nextTextChunk]) hyphenatedN++;

            nextTextChunk = cache[nextTextChunk];

          case states.concatenate:
            newText += nextTextChunk;
        }

        processedN++;
      }
      workTime += new Date() - loopStart;

      if (!nextTextChunk) {
        done();
      } else {
        setTimeout(nextTick);
      }
    }

    if (isAsync) {
      setTimeout(nextTick);
      return new Promise(function (resolve) {
        resolveNewText = resolve;
      });
    } else {
      nextTick();
      return newText;
    }
  }

  return createHyphenator;
});