-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathmarkdeep-diagram.js
1582 lines (1376 loc) · 65.9 KB
/
markdeep-diagram.js
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
/**
Markdeep diagrams; extracted from Markdeep.js Version 1.13
Refined for use with nodejs
Copyright 2015-2021, Morgan McGuire, https://casual-effects.com
All rights reserved.
-------------------------------------------------------------
You may use, extend, and redistribute this code under the terms of
the BSD license at https://opensource.org/licenses/BSD-2-Clause.
*/
'use strict';
// Mappings and constants used by markdeep.
const STROKE_WIDTH = 2;
const ARROW_COLOR = ' fill="black"'; // + ' stroke="none"', but xml2rfc doesn't like that.
const STROKE_COLOR = ' fill="none" stroke="black"';
const TEXT_COLOR = ' stroke="black"';
['min', 'max', 'abs', 'sign'].forEach(f => {
global[f] = Math[f];
});
String.prototype.ss = String.prototype.substring;
String.prototype.rp = String.prototype.replace;
function escapeHTMLEntities(str) {
return String(str).rp(/&/g, '&').rp(/</g, '<').rp(/>/g, '>').rp(/"/g, '"');
}
function strToArray(s) {
return Array.from(s);
}
/**
Adds whitespace at the end of each line of str, so that all lines have equal length in
unicode characters (which is not the same as JavaScript characters when high-index/escape
characters are present).
*/
function equalizeLineLengths(str) {
var lineArray = str.split('\n');
if ((lineArray.length > 0) && (lineArray[lineArray.length - 1] === '')) {
// Remove the empty last line generated by split on a trailing newline
lineArray.pop();
}
var longest = 0;
lineArray.forEach(function (line) {
longest = max(longest, strToArray(line).length);
});
// Worst case spaces needed for equalizing lengths
// http://stackoverflow.com/questions/1877475/repeat-character-n-times
var spaces = Array(longest + 1).join(' ');
var result = '';
lineArray.forEach(function (line) {
// Append the needed number of spaces onto each line, and
// reconstruct the output with newlines
result += line + spaces.ss(strToArray(line).length) + '\n';
});
return result;
}
/** Finds the longest common whitespace prefix of all non-empty lines
and then removes it */
function removeLeadingSpace(str) {
var lineArray = str.split('\n');
var minimum = Infinity;
lineArray.forEach(function (line) {
if (line.trim() !== '') {
// This is a non-empty line
var spaceArray = line.match(/^([ \t]*)/);
if (spaceArray) {
minimum = min(minimum, spaceArray[0].length);
}
}
});
if (minimum === 0) {
// No leading space
return str;
}
var result = '';
lineArray.forEach(function (line) {
// Strip the common spaces
result += line.ss(minimum) + '\n';
});
return result;
}
/** Returns true if this character is a "letter" under the ASCII definition */
function isASCIILetter(c) {
var code = c.charCodeAt(0);
return ((code >= 65) && (code <= 90)) || ((code >= 97) && (code <= 122));
}
const MARKERS = { 'o': '\ue004', 'v': '\ue005', 'V': '\ue006' };
function hideChar(s, i) {
let r = new Array(3);
r.fill('[a-zA-Z' + Object.values(MARKERS).join('') + ']');
r[i] = '[' + Object.keys(MARKERS).join('') + ']';
return s.replace(new RegExp(r.join(''), 'g'),
v => v.substring(0, i) + MARKERS[v.charAt(i)] + v.substring(i + 1));
}
function unhideMarkers(s) {
Object.keys(MARKERS).forEach(k => {
s = s.rp(new RegExp(MARKERS[k], 'g'), k);
});
return s;
}
function hideMarkers(s) {
s = hideChar(s, 0);
s = hideChar(s, 1);
s = hideChar(s, 2);
// Unhide strings that only contain 'o' or 'v'.
// Note: Using \B as \ue00? is a non-word character.
const allHidden = '\\B[' + Object.values(MARKERS).join('') + ']{3,}\\B';
return s.replace(new RegExp(allHidden, 'g'), unhideMarkers);
}
/** Converts diagramString, which is a Markdeep diagram without the surrounding asterisks, to
SVG (HTML). Lines may have ragged lengths.
`options` is a dictionary with the following keys:
backdrop (default: false) will add a white <rect> element as a backdrop so that
the background of the image is not transparent
disableText (default: false) will disable passing text
showGrid (default: false) will display a debug grid
spaces (default: 2) the number of spaces between different strings
style (default: {}) a dictionary of attributes to attach to the <svg> element
*/
function diagramToSVG(diagramString, options) {
// Clean up diagramString
diagramString = equalizeLineLengths(removeLeadingSpace(diagramString));
options = options || {};
if (!Number.isInteger(options.spaces)) { options.spaces = 2; } // 0 is valid so falsy tests fail.
// Temporarily replace 'o', 'v', and 'V' if they are surrounded by other
// text. Use another character to avoid processing them as decorations.
// These will be swapped back in the final SVG.
diagramString = hideMarkers(diagramString);
/** Pixels per character */
var SCALE = 8;
/** Multiply Y coordinates by this when generating the final SVG
result to account for the aspect ratio of text files. */
var ASPECT = 2;
var DIAGONAL_ANGLE = Math.atan(1.0 / ASPECT) * 180 / Math.PI;
var EPSILON = 1e-6;
// The order of the following is based on rotation angles
// and is used for ArrowSet.toSVG
var ARROW_HEAD_CHARACTERS = '>v<^';
var POINT_CHARACTERS = 'o*◌○◍●⊕';
var JUMP_CHARACTERS = '()';
var UNDIRECTED_VERTEX_CHARACTERS = "+";
var VERTEX_CHARACTERS = UNDIRECTED_VERTEX_CHARACTERS + ".',`";
// GRAY[i] is the Unicode block character for (i+1)/4 level gray
var GRAY_CHARACTERS = '\u2591\u2592\u2593\u2588';
// TRI[i] is a right-triangle rotated by 90*i
var TRI_CHARACTERS = '\u25E2\u25E3\u25E4\u25E5';
var DECORATION_CHARACTERS = ARROW_HEAD_CHARACTERS + POINT_CHARACTERS + JUMP_CHARACTERS + GRAY_CHARACTERS + TRI_CHARACTERS;
function isUndirectedVertex(c) { return UNDIRECTED_VERTEX_CHARACTERS.indexOf(c) !== -1; }
function isVertex(c) { return VERTEX_CHARACTERS.indexOf(c) !== -1; }
function isTopVertex(c) { return isUndirectedVertex(c) || (c === '.') || (c === ','); }
function isTopVertexOrDecoration(c) { return isTopVertex(c) || (c === '^'); }
function isBottomVertex(c) { return isUndirectedVertex(c) || (c === "'") || (c === '`'); }
function isVertexOrLeftDecoration(c) { return isVertex(c) || (c === '<') || isPoint(c); }
function isVertexOrRightDecoration(c) { return isVertex(c) || (c === '>') || isPoint(c); }
function isGray(c) { return GRAY_CHARACTERS.indexOf(c) + 1; }
function isTri(c) { return TRI_CHARACTERS.indexOf(c) + 1; }
// "D" = Diagonal slash (/), "B" = diagonal Backslash (\)
// Characters that may appear anywhere on a solid line
function isSolidHLine(c) { return (c === '-') || (c === '\u2501') || isUndirectedVertex(c) || isJump(c); }
function isSquiggleHLine(c) { return (c === '~') || isUndirectedVertex(c) || isJump(c); }
function isDoubleHLine(c) { return (c === '=') || (c === '\u2550') || isUndirectedVertex(c) || isJump(c); }
function isSolidVLineOrJumpOrPoint(c) { return isSolidVLine(c) || isJump(c) || isPoint(c); }
function isSolidVLine(c) { return (c === '|') || (c === '\u2503') || isUndirectedVertex(c); }
function isDoubleVLine(c) { return (c === '\u2551') || isUndirectedVertex(c); }
function isSolidDLine(c) { return (c === '/') || isUndirectedVertex(c) }
function isSolidBLine(c) { return (c === '\\') || isUndirectedVertex(c); }
function isJump(c) { return JUMP_CHARACTERS.indexOf(c) + 1; }
function isPoint(c) { return POINT_CHARACTERS.indexOf(c) + 1; }
function isDecoration(c) { return DECORATION_CHARACTERS.indexOf(c) + 1; }
///////////////////////////////////////////////////////////////////////////////
// Math library
/** Invoke as new Vec2(v) to clone or new Vec2(x, y) to create from coordinates.
Can also invoke without new for brevity. */
function Vec2(x, y) {
// Detect when being run without new
if (!(this instanceof Vec2)) { return new Vec2(x, y); }
if (y === undefined) {
if (x === undefined) { x = y = 0; }
else if (x instanceof Vec2) { y = x.y; x = x.x; }
else { throw new Error("Vec2 requires one Vec2 or (x, y) as an argument"); }
}
this.x = x;
this.y = y;
Object.seal(this);
}
/** Returns coordinates */
Vec2.prototype.coords = function () {
function s(x) { return x.toFixed(5).replace(/\.?0*$/, ''); }
return s((this.x + 1) * SCALE) + ',' + s((this.y + 1) * SCALE * ASPECT);
}
/** Returns an SVG representation, with a trailing space */
Vec2.prototype.toString = Vec2.prototype.toSVG =
function () { return this.coords() + ' '; };
/** Return an offset Vec2 */
Vec2.prototype.offset = function (dx, dy) { return Vec2(this.x + dx, this.y + dy); }
/** Converts a "rectangular" string defined by newlines into 2D
array of characters. Grids are immutable. */
function makeGrid(str) {
/** Returns ' ' for out of bounds values */
var grid = function (x, y) {
if (y === undefined) {
if (x instanceof Vec2) { y = x.y; x = x.x; }
else { throw new Error('grid requires either a Vec2 or (x, y)'); }
}
return ((x >= 0) && (x < grid.width) && (y >= 0) && (y < grid.height)) ?
str[y * (grid.width + 1) + x] : ' ';
};
// Elements are true when consumed
grid._used = [];
grid.height = str.split('\n').length;
if (str[str.length - 1] === '\n') { --grid.height; }
// Convert the string to an array to better handle greater-than 16-bit unicode
// characters, which JavaScript does not process correctly with indices. Do this after
// the above string processing.
str = strToArray(str);
grid.width = str.indexOf('\n');
grid.v = function (x, y) {
return ((x >= 0) && (x < grid.width) && (y >= 0) && (y < grid.height)) ?
str[y * (grid.width + 1) + x] : ' ';
};
/** Mark this location. Takes a Vec2 or (x, y) */
grid.setUsed = function (x, y) {
if (y === undefined) {
if (x instanceof Vec2) { y = x.y; x = x.x; }
else { throw new Error('grid requires either a Vec2 or (x, y)'); }
}
if ((x >= 0) && (x < grid.width) && (y >= 0) && (y < grid.height)) {
// Match the source string indexing
grid._used[y * (grid.width + 1) + x] = true;
}
};
grid.isUsed = function (x, y) {
if (y === undefined) {
if (x instanceof Vec2) { y = x.y; x = x.x; }
else { throw new Error('grid requires either a Vec2 or (x, y)'); }
}
return (this._used[y * (this.width + 1) + x] === true);
};
/** Returns the x offset of the next run of text on the line;
returns this.width if there is no text. */
grid.textStart = function (x, y) {
for (; x < this.width; ++x) {
if (this.isUsed(x, y)) { continue; }
if (this(x, y) !== ' ') { break; }
}
return x;
}
/** Returns the text at the given location, marking these locations as used. */
grid.text = function (x, y) {
let spaces = 0;
let end = x;
for (; end < this.width; ++end) {
if (this.isUsed(end, y)) {
break;
}
if (this(end, y) === ' ') {
spaces++;
} else {
spaces = 0;
}
if (spaces >= options.spaces) {
end++;
break;
}
}
end -= spaces;
for (let i = x; i < end; ++i) {
this._used[y * (this.width + 1) + i] = true;
}
return str.slice(y * (this.width + 1) + x, y * (this.width + 1) + end);
}
/** Returns true if there is a solid vertical line passing through (x, y) */
grid.isVLineAt = function (x, y, f, short) {
if (y === undefined) { y = x.x; x = x.x; }
var up = grid(x, y - 1);
var c = grid(x, y);
var dn = grid(x, y + 1);
var uprt = grid(x + 1, y - 1);
var uplt = grid(x - 1, y - 1);
if (f(c)) {
// Looks like a vertical line...does it continue?
return (isTopVertexOrDecoration(up) || f(up) || isJump(up) ||
isBottomVertex(dn) || (dn === 'v') || f(dn) || isJump(dn) ||
isPoint(up) || isPoint(dn) || (up === '_') || (uplt === '_') ||
(uprt === '_') ||
// Special case of 1-high vertical on two curved corners
((isTopVertex(uplt) || isTopVertex(uprt)) &&
(isBottomVertex(grid(x - 1, y + 1)) || isBottomVertex(grid(x + 1, y + 1)))));
} else if (isTopVertex(c) || (c === '^')) {
// May be the top of a vertical line
return f(dn) || (isJump(dn) && (c !== '.'));
} else if (isBottomVertex(c) || (c === 'v' || c === 'V')) {
return f(up) || (isJump(up) && (c !== "'"));
} else if (isPoint(c)) {
return f(up) || f(dn);
}
return false;
};
grid.isSolidVLineAt = function (x, y) {
return grid.isVLineAt(x, y, isSolidVLine, true);
};
grid.isDoubleVLineAt = function (x, y) {
return grid.isVLineAt(x, y, isDoubleVLine, false);
};
/** Returns true if there is a solid middle (---) horizontal line
passing through (x, y). Ignores underscores. */
grid.isHLineAt = function (x, y, f) {
if (y === undefined) { y = x.x; x = x.x; }
var ltlt = grid(x - 2, y);
var lt = grid(x - 1, y);
var c = grid(x + 0, y);
var rt = grid(x + 1, y);
var rtrt = grid(x + 2, y);
if (f(c) || (f(lt) && isJump(c))) {
// Looks like a horizontal line...does it continue? We need three in a row.
if (f(lt)) {
return f(rt) || isVertexOrRightDecoration(rt) || f(ltlt) || isVertexOrLeftDecoration(ltlt);
} else if (isVertexOrLeftDecoration(lt)) {
return f(rt);
} else {
return f(rt) && (f(rtrt) || isVertexOrRightDecoration(rtrt));
}
} else if (c === '<') {
return f(rt) && f(rtrt);
} else if (c === '>') {
return f(lt) && f(ltlt);
} else if (isVertex(c)) {
return ((f(lt) && f(ltlt)) || (f(rt) && f(rtrt)));
}
return false;
};
grid.isSolidHLineAt = function (x, y) {
return this.isHLineAt(x, y, isSolidHLine);
};
grid.isSquiggleHLineAt = function (x, y) {
return this.isHLineAt(x, y, isSquiggleHLine);
};
grid.isDoubleHLineAt = function (x, y) {
return this.isHLineAt(x, y, isDoubleHLine);
};
grid.isAnyHLineAt = function (x, y) {
return this.isHLineAt(x, y, isSolidHLine) || this.isHLineAt(x, y, isSquiggleHLine) || this.isHLineAt(x, y, isDoubleHLine);
};
/** Returns true if there is a solid backslash line passing through (x, y) */
grid.isSolidBLineAt = function (x, y) {
if (y === undefined) { y = x.x; x = x.x; }
var c = grid(x, y);
var lt = grid(x - 1, y - 1);
var rt = grid(x + 1, y + 1);
if (c === '\\') {
// Looks like a diagonal line...does it continue? We need two in a row.
return (isSolidBLine(rt) || isBottomVertex(rt) || isPoint(rt) || (rt === 'v' || rt === 'V') ||
isSolidBLine(lt) || isTopVertex(lt) || isPoint(lt) || (lt === '^') ||
(grid(x, y - 1) === '/') || (grid(x, y + 1) === '/') || (rt === '_') || (lt === '_') ||
(grid(x + 1, y) === '/' && grid(x - 1, y - 1) === '_') ||
(grid(x - 1, y) === '/' && grid(x + 1, y) === '_'));
} else if (c === '.') {
return (rt === '\\');
} else if (c === "'") {
return (lt === '\\');
} else if (c === '^') {
return rt === '\\';
} else if (c === 'v' || c === 'V') {
return lt === '\\';
} else if (isVertex(c) || isPoint(c) || (c === '|')) {
return isSolidBLine(lt) || isSolidBLine(rt);
}
};
/** Returns true if there is a solid diagonal line passing through (x, y) */
grid.isSolidDLineAt = function (x, y) {
if (y === undefined) { y = x.x; x = x.x; }
var c = grid(x, y);
var lt = grid(x - 1, y + 1);
var rt = grid(x + 1, y - 1);
if (c === '/' && ((grid(x, y - 1) === '\\') || (grid(x, y + 1) === '\\'))) {
// Special case of tiny hexagon corner
return true;
} else if (c === '/' && ((grid(x + 1, y) === '\\' && grid(x - 1, y) === '_') ||
(grid(x - 1, y) === '\\' && grid(x + 1, y - 1) === '_'))) {
// _/\ or _
// \/
return true;
} else if (isSolidDLine(c)) {
// Looks like a diagonal line...does it continue? We need two in a row.
return (isSolidDLine(rt) || isTopVertex(rt) || isPoint(rt) || (rt === '^') || (rt === '_') ||
isSolidDLine(lt) || isBottomVertex(lt) || isPoint(lt) || (lt === 'v' || lt === 'V') || (lt === '_'));
} else if (c === '.' || c === ',') {
return (lt === '/');
} else if (c === "'") {
return (rt === '/');
} else if (c === '^') {
return lt === '/';
} else if (c === 'v' || c === 'V') {
return rt === '/';
} else if (isVertex(c) || isPoint(c) || (c === '|')) {
return isSolidDLine(lt) || isSolidDLine(rt);
}
return false;
};
grid.toString = function () { return str; };
return Object.freeze(grid);
}
/** A 1D curve. If C is specified, the result is a bezier with
that as the tangent control point */
function Path(A, B, C, D, style) {
if (!((A instanceof Vec2) && (B instanceof Vec2))) {
throw new Error('Path constructor requires at least two Vec2s');
}
this.A = A;
this.B = B;
if (C) {
this.C = C;
if (D) {
this.D = D;
} else {
this.D = C;
}
}
this.dashed = style === 'dashed' || false;
this.double = style === 'double' || false;
this.squiggle = style === 'squiggle' || false;
Object.freeze(this);
}
var _ = Path.prototype;
_.isVertical = function () {
return this.B.x === this.A.x;
};
_.isHorizontal = function () {
return this.B.y === this.A.y;
};
/** Diagonal lines look like: / See also backDiagonal */
_.isDiagonal = function () {
var dx = this.B.x - this.A.x;
var dy = this.B.y - this.A.y;
return (abs(dy + dx) < EPSILON);
};
_.isBackDiagonal = function () {
var dx = this.B.x - this.A.x;
var dy = this.B.y - this.A.y;
return (abs(dy - dx) < EPSILON);
};
_.isCurved = function () {
return this.C !== undefined;
};
/** Does this path have any end at (x, y) */
_.endsAt = function (x, y) {
if (y === undefined) { y = x.y; x = x.x; }
return ((this.A.x === x) && (this.A.y === y)) ||
((this.B.x === x) && (this.B.y === y));
};
/** Does this path have an up end at (x, y) */
_.upEndsAt = function (x, y) {
if (y === undefined) { y = x.y; x = x.x; }
return this.isVertical() && (this.A.x === x) && (min(this.A.y, this.B.y) === y);
};
/** Does this path have an up end at (x, y) */
_.diagonalUpEndsAt = function (x, y) {
if (!this.isDiagonal()) { return false; }
if (y === undefined) { y = x.y; x = x.x; }
if (this.A.y < this.B.y) {
return (this.A.x === x) && (this.A.y === y);
} else {
return (this.B.x === x) && (this.B.y === y);
}
};
/** Does this path have a down end at (x, y) */
_.diagonalDownEndsAt = function (x, y) {
if (!this.isDiagonal()) { return false; }
if (y === undefined) { y = x.y; x = x.x; }
if (this.B.y < this.A.y) {
return (this.A.x === x) && (this.A.y === y);
} else {
return (this.B.x === x) && (this.B.y === y);
}
};
/** Does this path have an up end at (x, y) */
_.backDiagonalUpEndsAt = function (x, y) {
if (!this.isBackDiagonal()) { return false; }
if (y === undefined) { y = x.y; x = x.x; }
if (this.A.y < this.B.y) {
return (this.A.x === x) && (this.A.y === y);
} else {
return (this.B.x === x) && (this.B.y === y);
}
};
/** Does this path have a down end at (x, y) */
_.backDiagonalDownEndsAt = function (x, y) {
if (!this.isBackDiagonal()) { return false; }
if (y === undefined) { y = x.y; x = x.x; }
if (this.B.y < this.A.y) {
return (this.A.x === x) && (this.A.y === y);
} else {
return (this.B.x === x) && (this.B.y === y);
}
};
/** Does this path have a down end at (x, y) */
_.downEndsAt = function (x, y) {
if (y === undefined) { y = x.y; x = x.x; }
return this.isVertical() && (this.A.x === x) && (max(this.A.y, this.B.y) === y);
};
/** Does this path have a left end at (x, y) */
_.leftEndsAt = function (x, y) {
if (y === undefined) { y = x.y; x = x.x; }
return this.isHorizontal() && (this.A.y === y) && (min(this.A.x, this.B.x) === x);
};
/** Does this path have a right end at (x, y) */
_.rightEndsAt = function (x, y) {
if (y === undefined) { y = x.y; x = x.x; }
return this.isHorizontal() && (this.A.y === y) && (max(this.A.x, this.B.x) === x);
};
_.verticalPassesThrough = function (x, y) {
if (y === undefined) { y = x.y; x = x.x; }
return this.isVertical() &&
(this.A.x === x) &&
(min(this.A.y, this.B.y) <= y) &&
(max(this.A.y, this.B.y) >= y);
}
_.horizontalPassesThrough = function (x, y) {
if (y === undefined) { y = x.y; x = x.x; }
return this.isHorizontal() &&
(this.A.y === y) &&
(min(this.A.x, this.B.x) <= x) &&
(max(this.A.x, this.B.x) >= x);
}
_.offsetLine = function (dx, dy) {
let svg = '<path d="M ' + this.A.offset(dx, dy);
if (this.isCurved()) {
let c =
svg += 'C ' + this.C.offset(dx, dy) + this.D.offset(dx, dy);
} else {
svg += 'L ';
}
svg += this.B.offset(dx, dy).coords() + '"' + STROKE_COLOR;
if (this.dashed) {
svg += ' stroke-dasharray="3,6"';
}
svg += '/>';
return svg;
}
_.horizontalSquiggle = function (x0, x1, y) {
const SQUIGGLE_AMPLITUDE = 0.2;
let svg = '<path d="M ' + this.A.coords() + ' ';
let start = this.A.offset(0, 0);
for (let x = x0; x < x1; x++) {
let up = start.offset(0.25, -SQUIGGLE_AMPLITUDE);
let mid = up.offset(0.25, SQUIGGLE_AMPLITUDE);
let down = mid.offset(0.25, SQUIGGLE_AMPLITUDE);
start = down.offset(0.25, -SQUIGGLE_AMPLITUDE);
svg += 'Q ' + up + mid;
svg += 'Q ' + down + start;
}
svg += '"' + STROKE_COLOR + '/>';
return svg;
}
/** Returns a string suitable for inclusion in an SVG tag */
_.toSVG = function () {
let svg = '';
if (this.double) {
let vx = this.B.x - this.A.x;
let vy = this.B.y - this.A.y;
let s = Math.sqrt(vx * vx + vy * vy);
vx /= s * SCALE;
vy /= s * SCALE / ASPECT;
svg += this.offsetLine(vy, -vx);
svg += this.offsetLine(-vy, vx);
} else if (this.squiggle) {
if (this.B.y !== this.A.y) {
console.warn("warning: squiggle requested for non-horizontal line");
}
svg = this.horizontalSquiggle(this.A.x, this.B.x, this.A.y);
} else {
svg = this.offsetLine(0, 0);
}
return svg;
};
/** A group of 1D curves. This was designed so that all of the
methods can later be implemented in O(1) time, but it
currently uses O(n) implementations for source code
simplicity. */
function PathSet() {
this._pathArray = [];
}
var PS = PathSet.prototype;
PS.insert = function (path) {
this._pathArray.push(path);
};
/** Returns a new method that returns true if method(x, y)
returns true on any element of _pathAray */
function makeFilterAny(method) {
return function (x, y) {
for (var i = 0; i < this._pathArray.length; ++i) {
if (method.call(this._pathArray[i], x, y)) { return true; }
}
// Fall through: return undefined == false
}
}
// True if an up line ends at these coordinates. Recall that the
// variable _ is bound to the Path prototype still.
PS.upEndsAt = makeFilterAny(_.upEndsAt);
PS.diagonalUpEndsAt = makeFilterAny(_.diagonalUpEndsAt);
PS.backDiagonalUpEndsAt = makeFilterAny(_.backDiagonalUpEndsAt);
PS.diagonalDownEndsAt = makeFilterAny(_.diagonalDownEndsAt);
PS.backDiagonalDownEndsAt = makeFilterAny(_.backDiagonalDownEndsAt);
PS.downEndsAt = makeFilterAny(_.downEndsAt);
PS.leftEndsAt = makeFilterAny(_.leftEndsAt);
PS.rightEndsAt = makeFilterAny(_.rightEndsAt);
PS.endsAt = makeFilterAny(_.endsAt);
PS.verticalPassesThrough = makeFilterAny(_.verticalPassesThrough);
PS.horizontalPassesThrough = makeFilterAny(_.horizontalPassesThrough);
/** Returns an SVG string */
PS.toSVG = function () {
var svg = '';
for (var i = 0; i < this._pathArray.length; ++i) {
svg += this._pathArray[i].toSVG() + '\n';
}
return svg;
};
function DecorationSet() {
this._decorationArray = [];
}
var DS = DecorationSet.prototype;
/** insert(x, y, type, <angle>)
insert(vec, type, <angle>)
angle is the angle in degrees to rotate the result */
DS.insert = function (x, y, type, angle) {
if (type === undefined) { type = y; y = x.y; x = x.x; }
if (!isDecoration(type)) {
throw new Error('Illegal decoration character: ' + type);
}
var d = { C: Vec2(x, y), type: type, angle: angle || 0 };
// Put arrows at the front and points at the back so that
// arrows always draw under points
if (isPoint(type)) {
this._decorationArray.push(d);
} else {
this._decorationArray.unshift(d);
}
};
DS.toSVG = function () {
var svg = '';
for (var i = 0; i < this._decorationArray.length; ++i) {
var decoration = this._decorationArray[i];
var C = decoration.C;
if (isJump(decoration.type)) {
// Slide jumps
var dx = (decoration.type === ')') ? +0.75 : -0.75;
var up = Vec2(C.x, C.y - 0.5);
var dn = Vec2(C.x, C.y + 0.5);
var cup = Vec2(C.x + dx, C.y - 0.5);
var cdn = Vec2(C.x + dx, C.y + 0.5);
svg += '<path class="jump" d="M ' + dn + 'C ' + cdn + cup + up.coords() + '"' + STROKE_COLOR + '/>';
} else if (isPoint(decoration.type)) {
const CLASSES = { '*': 'closed', 'o': 'open', '◌': 'dotted', '○': 'open', '◍': 'shaded', '●': 'closed', '⊕': 'xor' };
const FILL = { 'closed': 'black', 'open': 'white', 'dotted': 'white', 'shaded': '#666', 'xor': 'white' };
const STROKE = {
'closed': '',
'open': ' stroke="black"',
'dotted': ' stroke="black" stroke-dasharray="0,1.8"',
'shaded': ' stroke="black"',
'xor': ' stroke="black"',
};
var cls = CLASSES[decoration.type];
svg += '<circle cx="' + ((C.x + 1) * SCALE) + '" cy="' + ((C.y + 1) * SCALE * ASPECT) +
'" r="' + (SCALE - STROKE_WIDTH) + '" class="' + cls + 'dot"' +
' fill="' + FILL[cls] + '"' + STROKE[cls] + '/>\n';
if (decoration.type === '⊕') {
svg += '<line x1="' + ((C.x) * SCALE + STROKE_WIDTH) +
'" y1="' + ((C.y + 1) * SCALE * ASPECT) +
'" x2="' + ((C.x + 2) * SCALE - STROKE_WIDTH) +
'" y2="' + ((C.y + 1) * SCALE * ASPECT) +
'" stroke="black"/>';
svg += '<line x1="' + ((C.x + 1) * SCALE) +
'" y1="' + ((C.y + 1) * SCALE * ASPECT - SCALE + STROKE_WIDTH) +
'" x2="' + ((C.x + 1) * SCALE) +
'" y2="' + ((C.y + 1) * SCALE * ASPECT + SCALE - STROKE_WIDTH) +
'" stroke="black"/>';
}
} else if (isGray(decoration.type)) {
var shade = Math.round((3 - GRAY_CHARACTERS.indexOf(decoration.type)) * 63.75);
svg += '<rect class="gray" x="' + ((C.x + 0.5) * SCALE) + '" y="' + ((C.y + 0.5) * SCALE * ASPECT) +
'" width="' + SCALE + '" height="' + (SCALE * ASPECT) +
'" fill="rgb(' + shade + ',' + shade + ',' + shade + ')"/>\n';
} else if (isTri(decoration.type)) {
// 30-60-90 triangle
var index = TRI_CHARACTERS.indexOf(decoration.type);
var xs = 0.5 - (index & 1);
var ys = 0.5 - (index >> 1);
xs *= sign(ys);
var tip = Vec2(C.x + xs, C.y - ys);
var up = Vec2(C.x + xs, C.y + ys);
var dn = Vec2(C.x - xs, C.y + ys);
svg += '<polygon class="triangle" points="' + tip + up + dn.coords(4) + '"' + ARROW_COLOR + '/>\n';
} else { // Arrow head
var tip = Vec2(C.x + 1, C.y);
var up = Vec2(C.x - 0.5, C.y - 0.35);
var dn = Vec2(C.x - 0.5, C.y + 0.35);
svg += '<polygon class="arrowhead" points="' + tip + up + dn.coords() + '"' + ARROW_COLOR +
' transform="rotate(' + decoration.angle + ',' + C.coords() + ')"/>\n';
}
}
return svg;
};
////////////////////////////////////////////////////////////////////////////
function findPaths(grid, pathSet) {
// Does the line from A to B contain at least one c?
function lineContains(A, B, c) {
var dx = sign(B.x - A.x);
var dy = sign(B.y - A.y);
var x, y;
for (x = A.x, y = A.y; (x !== B.x) || (y !== B.y); x += dx, y += dy) {
if (grid(x, y) === c) { return true; }
}
// Last point
return (grid(x, y) === c);
}
// Find all solid vertical lines. Iterate horizontally
// so that we never hit the same line twice
for (var x = 0; x < grid.width; ++x) {
for (var y = 0; y < grid.height; ++y) {
function vline(p, alt, boxt, boxb, style) {
if (grid[p](x, y)) {
// This character begins a vertical line...now, find the end
var A = Vec2(x, y);
do { grid.setUsed(x, y); ++y; } while (grid[p](x, y));
var B = Vec2(x, y - 1);
var up = grid(A);
var upup = grid(A.x, A.y - 1);
if (!isVertex(up) && ((upup === '-') || (upup === '_') ||
(boxt.indexOf(upup) >= 0) ||
(grid(A.x - 1, A.y - 1) === '_') ||
(grid(A.x + 1, A.y - 1) === '_') ||
isBottomVertex(upup)) || isJump(upup) ||
(grid[alt](A.x, A.y - 1) && !isVertex(upup))) {
// Stretch up to almost reach the line above (if there is a decoration,
// it will finish the gap)
A.y -= (isVertex(upup) && grid[alt](A.x, A.y - 2) && !isTopVertexOrDecoration(up)) ? 1 : 0.5;
}
var dn = grid(B);
var dndn = grid(B.x, B.y + 1);
if (!isVertex(dn) && ((dndn === '-') || (boxb.indexOf(dndn) >= 0) || isTopVertex(dndn)) || isJump(dndn) ||
(grid(B.x - 1, B.y) === '_') || (grid(B.x + 1, B.y) === '_') ||
(grid[alt](B.x, B.y + 1) && !isVertex(dn))) {
// Stretch down to almost reach the line below
B.y += 0.5;
}
// Don't insert degenerate lines
if ((A.x !== B.x) || (A.y !== B.y)) {
pathSet.insert(new Path(A, B, null, null, style));
// Re-evaluate the character we just rejected.
--y;
return true;
}
// Continue the search from y+1.
}
return false;
}
if (vline("isSolidVLineAt", "isDoubleVLineAt", '\u2564', '\u2567') ||
vline("isDoubleVLineAt", "isSolidVLineAt", '\u2565\u2566', '\u2568\u2569', "double")) {
continue;
}
// Some very special patterns for the short lines needed on
// circuit diagrams. Only invoke these if not also on a curve
// _ _
// -' '- -'
if ((grid(x, y) === "'") &&
(((grid(x - 1, y) === '-') && (grid(x + 1, y - 1) === '_') &&
!isSolidVLineOrJumpOrPoint(grid(x - 1, y - 1))) ||
((grid(x - 1, y - 1) === '_') && (grid(x + 1, y) === '-') &&
!isSolidVLineOrJumpOrPoint(grid(x + 1, y - 1))))) {
pathSet.insert(new Path(Vec2(x, y - 0.5), Vec2(x, y)));
}
// _.- -._
else if ((grid(x, y) === '.') &&
(((grid(x - 1, y) === '_') && (grid(x + 1, y) === '-') &&
!isSolidVLineOrJumpOrPoint(grid(x + 1, y + 1))) ||
((grid(x - 1, y) === '-') && (grid(x + 1, y) === '_') &&
!isSolidVLineOrJumpOrPoint(grid(x - 1, y + 1))))) {
pathSet.insert(new Path(Vec2(x, y), Vec2(x, y + 0.5)));
}
// For drawing resistors: -.╱
else if ((grid(x, y) === '.') &&
(grid(x - 1, y) === '-') &&
(grid(x + 1, y) === '\u2571')) {
pathSet.insert(new Path(Vec2(x, y), Vec2(x + 0.5, y + 0.5)));
}
// For drawing resistors: ╱'-
else if ((grid(x, y) === "'") &&
(grid(x + 1, y) === '-') &&
(grid(x - 1, y) === '\u2571')) {
pathSet.insert(new Path(Vec2(x, y), Vec2(x - 0.5, y - 0.5)));
}
} // y
} // x
// Find all solid horizontal lines
for (var y = 0; y < grid.height; ++y) {
for (var x = 0; x < grid.width; ++x) {
function hline(p, boxl, boxr, style) {
if (grid[p](x, y)) {
// Begins a line...find the end
var A = Vec2(x, y);
do { grid.setUsed(x, y); ++x; } while (grid[p](x, y));
var B = Vec2(x - 1, y);
// Detect adjacent box-drawing characters and lengthen the edge
if (boxr.indexOf(grid(B.x + 1, B.y)) >= 0) { B.x += 0.5; }
if (boxl.indexOf(grid(A.x - 1, A.y)) >= 0) { A.x -= 0.5; }
// Detect curves and shorten the edge
if (!isVertex(grid(A.x - 1, A.y)) &&
((isTopVertex(grid(A)) && isSolidVLineOrJumpOrPoint(grid(A.x - 1, A.y + 1))) ||
(isBottomVertex(grid(A)) && isSolidVLineOrJumpOrPoint(grid(A.x - 1, A.y - 1))))) {
++A.x;
} else if (!isVertexOrLeftDecoration(grid(A)) &&
isVertex(grid(A.x - 1, A.y)) &&
grid.isAnyHLineAt(A.x - 2, A.y)) {
// Line continuation, changing type.
--A.x;
} else if (grid.isAnyHLineAt(A.x - 1, A.y) &&
!isVertexOrRightDecoration(grid(A.x - 1, A.y)) &&
!isVertex(grid(A))) {
A.x -= 0.5;
}
if (!isVertex(grid(B.x + 1, B.y)) &&
((isTopVertex(grid(B)) && isSolidVLineOrJumpOrPoint(grid(B.x + 1, B.y + 1))) ||
(isBottomVertex(grid(B)) && isSolidVLineOrJumpOrPoint(grid(B.x + 1, B.y - 1))))) {
--B.x;
} else if (grid.isAnyHLineAt(B.x + 1, B.y) &&
!isVertexOrLeftDecoration(grid(B.x + 1, B.y)) &&
!isVertex(grid(B))) {
B.x += 0.5;
}
// Only insert non-degenerate lines
if ((A.x !== B.x) || (A.y !== B.y)) {
pathSet.insert(new Path(A, B, null, null, style));
// Re-evaluate the character we just rejected.
--x;
return true;
}
// Continue the search from x+1.
}
return false;
}
hline("isSolidHLineAt", '\u2523', '\u252b', null) ||
hline("isSquiggleHLineAt", '\u2523', '\u252b', "squiggle") ||
hline("isDoubleHLineAt", '\u255E', '\u2561', "double");
}
} // y
// Find all solid left-to-right downward diagonal lines (BACK DIAGONAL)
for (var i = -grid.height; i < grid.width; ++i) {
for (var x = i, y = 0; y < grid.height; ++y, ++x) {
if (grid.isSolidBLineAt(x, y)) {
// Begins a line...find the end
var A = Vec2(x, y);
do { ++x; ++y; } while (grid.isSolidBLineAt(x, y));
var B = Vec2(x - 1, y - 1);
// Ensure that the entire line wasn't just vertices
if (lineContains(A, B, '\\')) {
for (var j = A.x; j <= B.x; ++j) {
grid.setUsed(j, A.y + (j - A.x));
}
var top = grid(A);
var up = grid(A.x, A.y - 1);
var uplt = grid(A.x - 1, A.y - 1);