-
Notifications
You must be signed in to change notification settings - Fork 187
Expand file tree
/
Copy pathfiglet.ts
More file actions
1670 lines (1538 loc) · 47.4 KB
/
Copy pathfiglet.ts
File metadata and controls
1670 lines (1538 loc) · 47.4 KB
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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
FIGlet.ts (a FIGDriver for FIGlet fonts)
Written by https://github.com/patorjk/figlet.js/graphs/contributors
Originally Written For: http://patorjk.com/software/taag/
License: MIT
This TypeScript code aims to fully implement the FIGlet spec.
Full FIGlet spec: http://patorjk.com/software/taag/docs/figfont.txt
FIGlet fonts are actually kind of complex, which is why you will see
a lot of code about parsing and interpreting rules. The actual generation
code is pretty simple and is done near the bottom of the code.
*/
import {
BreakWordResult,
CallbackFunction,
FigletDefaults,
FigCharsWithOverlap,
FigCharWithOverlap,
FigletModule,
FigletFont,
FittingRules,
FontName,
FontMetadata,
InternalOptions,
KerningMethods,
LAYOUT,
LayoutType,
FigletOptions,
PrintDirection,
} from "./figlet-types";
import { fontList } from "./font-list";
import { getFontName } from "./renamed-fonts.js";
// helper method
function escapeRegExpChar(char: string): string {
// Characters that have special meaning in regex and need escaping
const specialChars = /[.*+?^${}()|[\]\\]/;
return specialChars.test(char) ? "\\" + char : char;
}
const figlet: FigletModule = (() => {
// ---------------------------------------------------------------------
// Private static variables
const { FULL_WIDTH = 0, FITTING, SMUSHING, CONTROLLED_SMUSHING } = LAYOUT;
// ---------------------------------------------------------------------
// Variable that will hold information about the fonts
const figFonts: Record<string, FigletFont> = {}; // What stores all of the FIGlet font data
const figDefaults: FigletDefaults = {
font: "Standard",
fontPath: "./fonts",
fetchFontIfMissing: true,
};
// ---------------------------------------------------------------------
// Private static methods
/**
* Figures out the end char for a FIGlet line and removes it. Technically there aren't supposed to be white spaces
* after the end char, but certain TOIlet fonts have this. The FIGlet unix app handles this though so we handle it
* here too.
*
* @param line
* @param lineNum
* @param fontHeight
*/
function removeEndChar(line: string, lineNum: number, fontHeight: number) {
const endChar = escapeRegExpChar(line.trim().slice(-1)) || "@";
const endCharRegEx =
lineNum === fontHeight - 1
? new RegExp(endChar + endChar + "?\\s*$")
: new RegExp(endChar + "\\s*$");
return line.replace(endCharRegEx, "");
}
/**
* This method takes in the oldLayout and newLayout data from the FIGfont header file and returns
* the layout information.
*
*/
function getSmushingRules(
oldLayout: number = -1,
newLayout: number | null = null,
) {
let rules: Partial<FittingRules> = {};
let val;
let codes: Array<[number, keyof FittingRules, boolean | LayoutType]> = [
[16384, "vLayout", SMUSHING],
[8192, "vLayout", FITTING],
[4096, "vRule5", true],
[2048, "vRule4", true],
[1024, "vRule3", true],
[512, "vRule2", true],
[256, "vRule1", true],
[128, "hLayout", SMUSHING],
[64, "hLayout", FITTING],
[32, "hRule6", true],
[16, "hRule5", true],
[8, "hRule4", true],
[4, "hRule3", true],
[2, "hRule2", true],
[1, "hRule1", true],
];
val = newLayout !== null ? newLayout : oldLayout;
for (const [code, rule, value] of codes) {
if (val >= code) {
val -= code;
if (rules[rule] === undefined) {
rules[rule] = value as any;
}
} else if (rule !== "vLayout" && rule !== "hLayout") {
rules[rule] = false as any;
}
}
if (typeof rules["hLayout"] === "undefined") {
if (oldLayout === 0) {
rules["hLayout"] = FITTING;
} else if (oldLayout === -1) {
rules["hLayout"] = FULL_WIDTH;
} else {
if (
rules["hRule1"] ||
rules["hRule2"] ||
rules["hRule3"] ||
rules["hRule4"] ||
rules["hRule5"] ||
rules["hRule6"]
) {
rules["hLayout"] = CONTROLLED_SMUSHING;
} else {
rules["hLayout"] = SMUSHING;
}
}
} else if (rules["hLayout"] === SMUSHING) {
if (
rules["hRule1"] ||
rules["hRule2"] ||
rules["hRule3"] ||
rules["hRule4"] ||
rules["hRule5"] ||
rules["hRule6"]
) {
rules["hLayout"] = CONTROLLED_SMUSHING;
}
}
if (typeof rules["vLayout"] === "undefined") {
if (
rules["vRule1"] ||
rules["vRule2"] ||
rules["vRule3"] ||
rules["vRule4"] ||
rules["vRule5"]
) {
rules["vLayout"] = CONTROLLED_SMUSHING;
} else {
rules["vLayout"] = FULL_WIDTH;
}
} else if (rules["vLayout"] === SMUSHING) {
if (
rules["vRule1"] ||
rules["vRule2"] ||
rules["vRule3"] ||
rules["vRule4"] ||
rules["vRule5"]
) {
rules["vLayout"] = CONTROLLED_SMUSHING;
}
}
return rules as FittingRules;
}
/* The [vh]Rule[1-6]_Smush functions return the smushed character OR false if the two characters can't be smushed */
/**
* Rule 1: EQUAL CHARACTER SMUSHING (code value 1)
*
* Two sub-characters are smushed into a single sub-character
* if they are the same. This rule does not smush
* hardblanks. (See rule 6 on hardblanks below)
*/
function hRule1_Smush(
ch1: string,
ch2: string,
hardBlank: string = "",
): string | false {
if (ch1 === ch2 && ch1 !== hardBlank) {
return ch1;
}
return false;
}
/**
* Rule 2: UNDERSCORE SMUSHING (code value 2)
*
* An underscore ("_") will be replaced by any of: "|", "/",
* "\", "[", "]", "{", "}", "(", ")", "<" or ">".
*/
function hRule2_Smush(ch1: string, ch2: string): string | false {
let rule2Str = "|/\\[]{}()<>";
if (ch1 === "_") {
if (rule2Str.indexOf(ch2) !== -1) {
return ch2;
}
} else if (ch2 === "_") {
if (rule2Str.indexOf(ch1) !== -1) {
return ch1;
}
}
return false;
}
/**
* Rule 3: HIERARCHY SMUSHING (code value 4)
*
* A hierarchy of six classes is used: "|", "/\", "[]", "{}",
* "()", and "<>". When two smushing sub-characters are
* from different classes, the one from the latter class
* will be used.
*/
function hRule3_Smush(ch1: string, ch2: string): string | false {
let rule3Classes = "| /\\ [] {} () <>";
let r3_pos1 = rule3Classes.indexOf(ch1);
let r3_pos2 = rule3Classes.indexOf(ch2);
if (r3_pos1 !== -1 && r3_pos2 !== -1) {
if (r3_pos1 !== r3_pos2 && Math.abs(r3_pos1 - r3_pos2) !== 1) {
const startPos = Math.max(r3_pos1, r3_pos2);
const endPos = startPos + 1;
return rule3Classes.substring(startPos, endPos);
}
}
return false;
}
/**
* Rule 4: OPPOSITE PAIR SMUSHING (code value 8)
*
* Smushes opposing brackets ("[]" or "]["), braces ("{}" or
* "}{") and parentheses ("()" or ")(") together, replacing
* any such pair with a vertical bar ("|").
*/
function hRule4_Smush(ch1: string, ch2: string): string | false {
let rule4Str = "[] {} ()";
let r4_pos1 = rule4Str.indexOf(ch1);
let r4_pos2 = rule4Str.indexOf(ch2);
if (r4_pos1 !== -1 && r4_pos2 !== -1) {
if (Math.abs(r4_pos1 - r4_pos2) <= 1) {
return "|";
}
}
return false;
}
/**
* Rule 5: BIG X SMUSHING (code value 16)
*
* Smushes "/\" into "|", "\/" into "Y", and "><" into "X".
* Note that "<>" is not smushed in any way by this rule.
* The name "BIG X" is historical; originally all three pairs
* were smushed into "X".
*/
function hRule5_Smush(ch1: string, ch2: string): string | false {
const patterns: Record<string, string> = {
"/\\": "|",
"\\/": "Y",
"><": "X",
};
return patterns[ch1 + ch2] || false;
}
/**
* Rule 6: HARDBLANK SMUSHING (code value 32)
*
* Smushes two hardblanks together, replacing them with a
* single hardblank. (See "Hardblanks" below.)
*/
function hRule6_Smush(
ch1: string,
ch2: string,
hardBlank: string = "",
): string | false {
if (ch1 === hardBlank && ch2 === hardBlank) {
return hardBlank;
}
return false;
}
/**
* Rule 1: EQUAL CHARACTER SMUSHING (code value 256)
*
* Same as horizontal smushing rule 1.
*/
function vRule1_Smush(ch1: string, ch2: string): string | false {
if (ch1 === ch2) {
return ch1;
}
return false;
}
/**
* Rule 2: UNDERSCORE SMUSHING (code value 512)
*
* Same as horizontal smushing rule 2.
*/
function vRule2_Smush(ch1: string, ch2: string): string | false {
return hRule2_Smush(ch1, ch2);
}
/**
* Rule 3: HIERARCHY SMUSHING (code value 1024)
*
* Same as horizontal smushing rule 3.
*/
function vRule3_Smush(ch1: string, ch2: string): string | false {
return hRule3_Smush(ch1, ch2);
}
/**
* Rule 4: HORIZONTAL LINE SMUSHING (code value 2048)
*
* Smushes stacked pairs of "-" and "_", replacing them with
* a single "=" sub-character. It does not matter which is
* found above the other. Note that vertical smushing rule 1
* will smush IDENTICAL pairs of horizontal lines, while this
* rule smushes horizontal lines consisting of DIFFERENT
* sub-characters.
*/
function vRule4_Smush(ch1: string, ch2: string): string | false {
if ((ch1 === "-" && ch2 === "_") || (ch1 === "_" && ch2 === "-")) {
return "=";
}
return false;
}
/**
* Rule 5: VERTICAL LINE SUPERSMUSHING (code value 4096)
*
* This one rule is different from all others, in that it
* "supersmushes" vertical lines consisting of several
* vertical bars ("|"). This creates the illusion that
* FIGcharacters have slid vertically against each other.
* Supersmushing continues until any sub-characters other
* than "|" would have to be smushed. Supersmushing can
* produce impressive results, but it is seldom possible,
* since other sub-characters would usually have to be
* considered for smushing as soon as any such stacked
* vertical lines are encountered.
*/
function vRule5_Smush(ch1: string, ch2: string): string | false {
if (ch1 === "|" && ch2 === "|") {
return "|";
}
return false;
}
/**
* Universal smushing simply overrides the sub-character from the
* earlier FIGcharacter with the sub-character from the later
* FIGcharacter. This produces an "overlapping" effect with some
* FIGfonts, wherin the latter FIGcharacter may appear to be "in
* front".
*/
function uni_Smush(ch1: string, ch2: string, hardBlank?: string): string {
if (ch2 === " " || ch2 === "") {
return ch1;
} else if (ch2 === hardBlank && ch1 !== " ") {
return ch1;
} else {
return ch2;
}
}
// --------------------------------------------------------------------------
// main vertical smush routines (excluding rules)
/**
* This function takes in two lines of text and returns one of the following:
* "valid" - These liens can be smushed together given the current smushing rules.
* "end" - The lines can be smushed, but we're at a stopping point.
* "invalid" - The two liens cannot be smushed together.
*
* @param txt1 Line of text from a character
* @param txt2 Line of text from a character
* @param opts FIGlet options array
*/
function canVerticalSmush(
txt1: string,
txt2: string,
opts: InternalOptions,
): "valid" | "end" | "invalid" {
if (opts.fittingRules && opts.fittingRules.vLayout === FULL_WIDTH) {
return "invalid";
}
let ii,
len = Math.min(txt1.length, txt2.length),
ch1,
ch2,
endSmush = false,
validSmush;
if (len === 0) {
return "invalid";
}
for (ii = 0; ii < len; ii++) {
ch1 = txt1.substring(ii, ii + 1);
ch2 = txt2.substring(ii, ii + 1);
if (ch1 !== " " && ch2 !== " ") {
if (opts.fittingRules && opts.fittingRules.vLayout === FITTING) {
return "invalid";
} else if (
opts.fittingRules &&
opts.fittingRules.vLayout === SMUSHING
) {
return "end";
} else {
if (vRule5_Smush(ch1, ch2)) {
endSmush = endSmush || false;
continue;
} // rule 5 allow for "super" smushing, but only if we're not already ending this smush
validSmush = false;
validSmush =
opts.fittingRules && opts.fittingRules.vRule1
? vRule1_Smush(ch1, ch2)
: validSmush;
validSmush =
!validSmush && opts.fittingRules && opts.fittingRules.vRule2
? vRule2_Smush(ch1, ch2)
: validSmush;
validSmush =
!validSmush && opts.fittingRules && opts.fittingRules.vRule3
? vRule3_Smush(ch1, ch2)
: validSmush;
validSmush =
!validSmush && opts.fittingRules && opts.fittingRules.vRule4
? vRule4_Smush(ch1, ch2)
: validSmush;
endSmush = true;
if (!validSmush) {
return "invalid";
}
}
}
}
if (endSmush) {
return "end";
} else {
return "valid";
}
}
function getVerticalSmushDist(
lines1: string[],
lines2: string[],
opts: InternalOptions,
): number {
let maxDist = lines1.length;
let len1 = lines1.length;
let subLines1, subLines2, slen;
let curDist = 1;
let ii, ret, result;
while (curDist <= maxDist) {
subLines1 = lines1.slice(Math.max(0, len1 - curDist), len1);
subLines2 = lines2.slice(0, Math.min(maxDist, curDist));
slen = subLines2.length;
result = "";
for (ii = 0; ii < slen; ii++) {
ret = canVerticalSmush(subLines1[ii], subLines2[ii], opts);
if (ret === "end") {
result = ret;
} else if (ret === "invalid") {
result = ret;
break;
} else {
if (result === "") {
result = "valid";
}
}
}
if (result === "invalid") {
curDist--;
break;
}
if (result === "end") {
break;
}
if (result === "valid") {
curDist++;
}
}
return Math.min(maxDist, curDist);
}
function verticallySmushLines(
line1: string,
line2: string,
opts: InternalOptions,
): string {
let ii,
len = Math.min(line1.length, line2.length);
let ch1,
ch2,
result = "",
validSmush;
const fittingRules = opts.fittingRules || {};
for (ii = 0; ii < len; ii++) {
ch1 = line1.substring(ii, ii + 1);
ch2 = line2.substring(ii, ii + 1);
if (ch1 !== " " && ch2 !== " ") {
if (fittingRules.vLayout === FITTING) {
result += uni_Smush(ch1, ch2);
} else if (fittingRules.vLayout === SMUSHING) {
result += uni_Smush(ch1, ch2);
} else {
validSmush = false;
validSmush = fittingRules.vRule5
? vRule5_Smush(ch1, ch2)
: validSmush;
validSmush =
!validSmush && fittingRules.vRule1
? vRule1_Smush(ch1, ch2)
: validSmush;
validSmush =
!validSmush && fittingRules.vRule2
? vRule2_Smush(ch1, ch2)
: validSmush;
validSmush =
!validSmush && fittingRules.vRule3
? vRule3_Smush(ch1, ch2)
: validSmush;
validSmush =
!validSmush && fittingRules.vRule4
? vRule4_Smush(ch1, ch2)
: validSmush;
result += validSmush;
}
} else {
result += uni_Smush(ch1, ch2);
}
}
return result;
}
function verticalSmush(
lines1: string[],
lines2: string[],
overlap: number,
opts: InternalOptions,
): string[] {
let len1 = lines1.length;
let len2 = lines2.length;
let piece1 = lines1.slice(0, Math.max(0, len1 - overlap));
let piece2_1 = lines1.slice(Math.max(0, len1 - overlap), len1);
let piece2_2 = lines2.slice(0, Math.min(overlap, len2));
let ii,
len,
line,
piece2 = [],
piece3;
len = piece2_1.length;
for (ii = 0; ii < len; ii++) {
if (ii >= len2) {
line = piece2_1[ii];
} else {
line = verticallySmushLines(piece2_1[ii], piece2_2[ii], opts);
}
piece2.push(line);
}
piece3 = lines2.slice(Math.min(overlap, len2), len2);
return [...piece1, ...piece2, ...piece3];
}
function padLines(lines: string[], numSpaces: number): string[] {
const padding = " ".repeat(numSpaces);
return lines.map((line) => line + padding);
}
function smushVerticalFigLines(
output: string[],
lines: string[],
opts: InternalOptions,
): string[] {
let len1 = output[0].length;
let len2 = lines[0].length;
let overlap;
if (len1 > len2) {
lines = padLines(lines, len1 - len2);
} else if (len2 > len1) {
output = padLines(output, len2 - len1);
}
overlap = getVerticalSmushDist(output, lines, opts);
return verticalSmush(output, lines, overlap, opts);
}
// -------------------------------------------------------------------------
// Main horizontal smush routines (excluding rules)
function getHorizontalSmushLength(
txt1: string,
txt2: string,
opts: InternalOptions,
): number {
const fittingRules = opts.fittingRules || {};
if (fittingRules.hLayout === FULL_WIDTH) {
return 0;
}
let ii,
len1 = txt1.length,
len2 = txt2.length;
let maxDist = len1;
let curDist = 1;
let breakAfter = false;
let seg1, seg2, ch1, ch2;
if (len1 === 0) {
return 0;
}
distCal: while (curDist <= maxDist) {
const seg1StartPos = len1 - curDist;
seg1 = txt1.substring(seg1StartPos, seg1StartPos + curDist);
seg2 = txt2.substring(0, Math.min(curDist, len2));
for (ii = 0; ii < Math.min(curDist, len2); ii++) {
ch1 = seg1.substring(ii, ii + 1);
ch2 = seg2.substring(ii, ii + 1);
if (ch1 !== " " && ch2 !== " ") {
if (fittingRules.hLayout === FITTING) {
curDist = curDist - 1;
break distCal;
} else if (fittingRules.hLayout === SMUSHING) {
if (ch1 === opts.hardBlank || ch2 === opts.hardBlank) {
curDist = curDist - 1; // universal smushing does not smush hardblanks
}
break distCal;
} else {
breakAfter = true; // we know we need to break, but we need to check if our smushing rules will allow us to smush the overlapped characters
// the below checks will let us know if we can smush these characters
const validSmush =
(fittingRules.hRule1 && hRule1_Smush(ch1, ch2, opts.hardBlank)) ||
(fittingRules.hRule2 && hRule2_Smush(ch1, ch2)) ||
(fittingRules.hRule3 && hRule3_Smush(ch1, ch2)) ||
(fittingRules.hRule4 && hRule4_Smush(ch1, ch2)) ||
(fittingRules.hRule5 && hRule5_Smush(ch1, ch2)) ||
(fittingRules.hRule6 && hRule6_Smush(ch1, ch2, opts.hardBlank));
if (!validSmush) {
curDist = curDist - 1;
break distCal;
}
}
}
}
if (breakAfter) {
break;
}
curDist++;
}
return Math.min(maxDist, curDist);
}
function horizontalSmush(
textBlock1: string[],
textBlock2: string[],
overlap: number,
opts: InternalOptions,
): string[] {
let ii,
jj,
outputFig: string[] = [],
overlapStart,
piece1,
piece2,
piece3,
len1,
len2,
txt1,
txt2;
const fittingRules = opts.fittingRules || {};
if (typeof opts.height !== "number") {
throw new Error("height is not defined.");
}
for (ii = 0; ii < opts.height; ii++) {
txt1 = textBlock1[ii];
txt2 = textBlock2[ii];
len1 = txt1.length;
len2 = txt2.length;
overlapStart = len1 - overlap;
piece1 = txt1.slice(0, Math.max(0, overlapStart));
piece2 = "";
// determine overlap piece
const seg1StartPos = Math.max(0, len1 - overlap);
let seg1 = txt1.substring(seg1StartPos, seg1StartPos + overlap);
let seg2 = txt2.substring(0, Math.min(overlap, len2));
for (jj = 0; jj < overlap; jj++) {
let ch1 = jj < len1 ? seg1.substring(jj, jj + 1) : " ";
let ch2 = jj < len2 ? seg2.substring(jj, jj + 1) : " ";
if (ch1 !== " " && ch2 !== " ") {
if (
fittingRules.hLayout === FITTING ||
fittingRules.hLayout === SMUSHING
) {
piece2 += uni_Smush(ch1, ch2, opts.hardBlank);
} else {
// Controlled Smushing
const nextCh =
(fittingRules.hRule1 && hRule1_Smush(ch1, ch2, opts.hardBlank)) ||
(fittingRules.hRule2 && hRule2_Smush(ch1, ch2)) ||
(fittingRules.hRule3 && hRule3_Smush(ch1, ch2)) ||
(fittingRules.hRule4 && hRule4_Smush(ch1, ch2)) ||
(fittingRules.hRule5 && hRule5_Smush(ch1, ch2)) ||
(fittingRules.hRule6 && hRule6_Smush(ch1, ch2, opts.hardBlank)) ||
uni_Smush(ch1, ch2, opts.hardBlank);
piece2 += nextCh;
}
} else {
piece2 += uni_Smush(ch1, ch2, opts.hardBlank);
}
}
if (overlap >= len2) {
piece3 = "";
} else {
piece3 = txt2.substring(overlap, overlap + Math.max(0, len2 - overlap));
}
outputFig[ii] = piece1 + piece2 + piece3;
}
return outputFig;
}
/**
* Creates new empty ASCII placeholder of given length
*
* @param len
*/
function newFigChar(len: number): string[] {
return new Array(len).fill("");
}
/**
* Return max line of the ASCII Art
*
* @param textLines Lines for the text
*/
const figLinesWidth = function (textLines: string[]): number {
return Math.max(...textLines.map((line) => line.length));
};
/**
* Join words or single characters into a single Fig line
*
* @param array Array of ASCII words or single character: {fig: array, overlap: number}
* @param len Height of the characters (number of rows)
* @param opts
*/
function joinFigArray(
array: FigCharWithOverlap[],
len: number,
opts: InternalOptions,
): string[] {
return array.reduce(function (acc, data) {
return horizontalSmush(acc, data.fig, data.overlap || 0, opts);
}, newFigChar(len));
}
/**
* Break long words, return leftover characters and line before the break
*
* @param figChars List of single ASCII characters in form {fig, overlap}
* @param len
* @param opts
*/
function breakWord(
figChars: FigCharWithOverlap[],
len: number,
opts: InternalOptions,
): BreakWordResult {
for (let i = figChars.length - 1; i > 0; i--) {
const w = joinFigArray(figChars.slice(0, i), len, opts);
if (figLinesWidth(w) <= opts.width) {
return {
outputFigText: w,
chars: figChars.slice(i),
};
}
}
// No break point fits within opts.width, which happens when a single
// character is wider than the requested width. Emit the first character
// on its own line.
if (figChars.length > 0) {
return {
outputFigText: joinFigArray([figChars[0]], len, opts),
chars: figChars.slice(1),
};
}
return { outputFigText: newFigChar(len), chars: figChars };
}
function generateFigTextLines(
txt: string,
figChars: FigletFont,
opts: InternalOptions,
): string[][] {
let charIndex,
figChar: string[],
overlap = 0,
row,
outputFigText,
len,
height = opts.height,
outputFigLines: string[][] = [],
maxWidth,
nextFigChars: FigCharsWithOverlap = {
chars: [], // list of characters is used to break in the middle of the word when word is longer
overlap, // chars is array of characters with {fig, overlap} and overlap is for whole word
},
figWords = [],
char,
isSpace,
textFigWord,
textFigLine,
tmpBreak;
if (typeof height !== "number") {
throw new Error("height is not defined.");
}
outputFigText = newFigChar(height);
const fittingRules = opts.fittingRules || {};
// iterate code points rather than UTF-16 code units so characters outside
// the Basic Multilingual Plane (BMP), ex: emojis, aren't split into surrogate halves
const txtChars = [...txt];
if (opts.printDirection === 1) {
txtChars.reverse();
}
len = txtChars.length;
for (charIndex = 0; charIndex < len; charIndex++) {
char = txtChars[charIndex];
isSpace = char.match(/\s/);
// FIGcharacter 0 is the "missing character", the spec's fallback for
// characters the font doesn't define
figChar = figChars[char.codePointAt(0) as number] ?? figChars[0];
textFigLine = null;
if (figChar) {
if (fittingRules.hLayout !== FULL_WIDTH) {
overlap = 10000; // a value too high to be the overlap
for (row = 0; row < height; row++) {
overlap = Math.min(
overlap,
getHorizontalSmushLength(outputFigText[row], figChar[row], opts),
);
}
overlap = overlap === 10000 ? 0 : overlap;
}
if (opts.width > 0) {
if (opts.whitespaceBreak) {
// next character in last word (figChars have same data as words)
textFigWord = joinFigArray(
nextFigChars.chars.concat([
{
fig: figChar,
overlap,
},
]),
height,
opts,
);
textFigLine = joinFigArray(
figWords.concat([
{
fig: textFigWord,
overlap: nextFigChars.overlap,
},
]),
height,
opts,
);
maxWidth = figLinesWidth(textFigLine);
} else {
textFigLine = horizontalSmush(
outputFigText,
figChar,
overlap,
opts,
);
maxWidth = figLinesWidth(textFigLine);
}
if (maxWidth >= opts.width && charIndex > 0) {
if (opts.whitespaceBreak) {
outputFigText = joinFigArray(figWords.slice(0, -1), height, opts);
if (figWords.length > 1) {
outputFigLines.push(outputFigText);
outputFigText = newFigChar(height);
}
figWords = [];
} else {
outputFigLines.push(outputFigText);
outputFigText = newFigChar(height);
}
}
}
if (opts.width > 0 && opts.whitespaceBreak) {
if (!isSpace || charIndex === len - 1) {
nextFigChars.chars.push({ fig: figChar, overlap });
}
if (isSpace || charIndex === len - 1) {
// break long words
tmpBreak = null;
while (true) {
textFigLine = joinFigArray(nextFigChars.chars, height, opts);
maxWidth = figLinesWidth(textFigLine);
if (maxWidth >= opts.width) {
tmpBreak = breakWord(nextFigChars.chars, height, opts);
nextFigChars = { chars: tmpBreak.chars }; // TODO: does overlap actually need to be apart of FigCharsWithOverlap type?
outputFigLines.push(tmpBreak.outputFigText);
} else {
break;
}
}
// any leftovers
if (maxWidth > 0) {
if (tmpBreak) {
figWords.push({ fig: textFigLine, overlap: 1 });
} else {
figWords.push({
fig: textFigLine,
overlap: nextFigChars.overlap,
});
}
}
// save space character and current overlap for smush in joinFigWords
if (isSpace) {
figWords.push({ fig: figChar, overlap });
outputFigText = newFigChar(height);
}
if (charIndex === len - 1) {
// last line
outputFigText = joinFigArray(figWords, height, opts);
}
nextFigChars = {
chars: [],
overlap: overlap,
};
continue;
}
}
outputFigText = horizontalSmush(outputFigText, figChar, overlap, opts);
}
}
// special case when last line would be empty
// this may happen if text fit exactly opt.width
if (figLinesWidth(outputFigText) > 0) {
outputFigLines.push(outputFigText);
}
// remove hardblanks
if (!opts.showHardBlanks) {
outputFigLines.forEach(function (outputFigText) {
len = outputFigText.length;
for (row = 0; row < len; row++) {
outputFigText[row] = outputFigText[row].replace(
new RegExp("\\" + opts.hardBlank, "g"),
" ",
);
}
});
}
// special case where the line is just an empty line
if (txt === "" && outputFigLines.length === 0) {
outputFigLines.push(new Array(height).fill(""));
}
return outputFigLines;
}
// -------------------------------------------------------------------------
// Parsing and Generation methods
const getHorizontalFittingRules = function (
layout: KerningMethods,
options: FontMetadata,