Debian Codegraph @

railroad.js

raw symbols SCIP
1 "use strict";
2 /*
3 Railroad Diagrams
4 by Tab Atkins Jr. (and others)
5 http://xanthir.com
6 http://twitter.com/tabatkins
7 http://github.com/tabatkins/railroad-diagrams
8
9 This document and all associated files in the github project are licensed under CC0: http://creativecommons.org/publicdomain/zero/1.0/
10 This means you can reuse, remix, or otherwise appropriate this project for your own use WITHOUT RESTRICTION.
11 (The actual legal meaning can be found at the above link.)
12 Don't ask me for permission to use any part of this project, JUST USE IT.
13 I would appreciate attribution, but that is not required by the license.
14 */
15
16 // Export function versions of all the constructors.
17 // Each class will add itself to this object.
18 const funcs = {};
19 export default funcs;
20
21 export const Options = {
22 DEBUG: false, // if true, writes some debug information into attributes
23 VS: 8, // minimum vertical separation between things. For a 3px stroke, must be at least 4
24 AR: 10, // radius of arcs
25 DIAGRAM_CLASS: 'railroad-diagram', // class to put on the root <svg>
26 STROKE_ODD_PIXEL_LENGTH: true, // is the stroke width an odd (1px, 3px, etc) pixel length?
27 INTERNAL_ALIGNMENT: 'center', // how to align items when they have extra space. left/right/center
28 CHAR_WIDTH: 8.5, // width of each monospace character. play until you find the right value for your font
29 COMMENT_CHAR_WIDTH: 7, // comments are in smaller text by default
30 ESCAPE_HTML: true, // Should Diagram.toText() produce HTML-escaped text, or raw?
31 };
32
33 export const defaultCSS = `
34 svg {
35 background-color: hsl(30,20%,95%);
36 }
37 path {
38 stroke-width: 3;
39 stroke: black;
40 fill: rgba(0,0,0,0);
41 }
42 text {
43 font: bold 14px monospace;
44 text-anchor: middle;
45 white-space: pre;
46 }
47 text.diagram-text {
48 font-size: 12px;
49 }
50 text.diagram-arrow {
51 font-size: 16px;
52 }
53 text.label {
54 text-anchor: start;
55 }
56 text.comment {
57 font: italic 12px monospace;
58 }
59 g.non-terminal text {
60 /*font-style: italic;*/
61 }
62 rect {
63 stroke-width: 3;
64 stroke: black;
65 fill: hsl(120,100%,90%);
66 }
67 rect.group-box {
68 stroke: gray;
69 stroke-dasharray: 10 5;
70 fill: none;
71 }
72 path.diagram-text {
73 stroke-width: 3;
74 stroke: black;
75 fill: white;
76 cursor: help;
77 }
78 g.diagram-text:hover path.diagram-text {
79 fill: #eee;
80 }`;
81
82
83 export class FakeSVG {
84 constructor(tagName, attrs, text) {
85 if(text) this.children = text;
86 else this.children = [];
87 this.tagName = tagName;
88 this.attrs = unnull(attrs, {});
89 }
90 format(x, y, width) {
91 // Virtual
92 }
93 addTo(parent) {
94 if(parent instanceof FakeSVG) {
95 parent.children.push(this);
96 return this;
97 } else {
98 var svg = this.toSVG();
99 parent.appendChild(svg);
100 return svg;
101 }
102 }
103 toSVG() {
104 var el = SVG(this.tagName, this.attrs);
105 if(typeof this.children == 'string') {
106 el.textContent = this.children;
107 } else {
108 this.children.forEach(function(e) {
109 el.appendChild(e.toSVG());
110 });
111 }
112 return el;
113 }
114 toString() {
115 var str = '<' + this.tagName;
116 var group = this.tagName == "g" || this.tagName == "svg";
117 for(var attr in this.attrs) {
118 str += ' ' + attr + '="' + (this.attrs[attr]+'').replace(/&/g, '&amp;').replace(/"/g, '&quot;') + '"';
119 }
120 str += '>';
121 if(group) str += "\n";
122 if(typeof this.children == 'string') {
123 str += escapeString(this.children);
124 } else {
125 this.children.forEach(function(e) {
126 str += e;
127 });
128 }
129 str += '</' + this.tagName + '>\n';
130 return str;
131 }
132 toTextDiagram() {
133 return new TextDiagram(0, 0, []);
134 }
135 toText() {
136 var outputTD = this.toTextDiagram();
137 var output = outputTD+"";
138 if(Options.ESCAPE_HTML) {
139 output = output.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace('"', "&quot;").replace("'", "&apos;");
140 }
141 return output;
142 }
143 walk(cb) {
144 cb(this);
145 }
146 }
147
148
149 export class Path extends FakeSVG {
150 constructor(x,y) {
151 super('path');
152 this.attrs.d = "M"+x+' '+y;
153 }
154 m(x,y) {
155 this.attrs.d += 'm'+x+' '+y;
156 return this;
157 }
158 h(val) {
159 this.attrs.d += 'h'+val;
160 return this;
161 }
162 right(val) { return this.h(Math.max(0, val)); }
163 left(val) { return this.h(-Math.max(0, val)); }
164 v(val) {
165 this.attrs.d += 'v'+val;
166 return this;
167 }
168 down(val) { return this.v(Math.max(0, val)); }
169 up(val) { return this.v(-Math.max(0, val)); }
170 arc(sweep){
171 // 1/4 of a circle
172 var x = Options.AR;
173 var y = Options.AR;
174 if(sweep[0] == 'e' || sweep[1] == 'w') {
175 x *= -1;
176 }
177 if(sweep[0] == 's' || sweep[1] == 'n') {
178 y *= -1;
179 }
180 var cw;
181 if(sweep == 'ne' || sweep == 'es' || sweep == 'sw' || sweep == 'wn') {
182 cw = 1;
183 } else {
184 cw = 0;
185 }
186 this.attrs.d += "a"+Options.AR+" "+Options.AR+" 0 0 "+cw+' '+x+' '+y;
187 return this;
188 }
189 arc_8(start, dir) {
190 // 1/8 of a circle
191 const arc = Options.AR;
192 const s2 = 1/Math.sqrt(2) * arc;
193 const s2inv = (arc - s2);
194 let path = "a " + arc + " " + arc + " 0 0 " + (dir=='cw' ? "1" : "0") + " ";
195 const sd = start+dir;
196 const offset =
197 sd == 'ncw' ? [s2, s2inv] :
198 sd == 'necw' ? [s2inv, s2] :
199 sd == 'ecw' ? [-s2inv, s2] :
200 sd == 'secw' ? [-s2, s2inv] :
201 sd == 'scw' ? [-s2, -s2inv] :
202 sd == 'swcw' ? [-s2inv, -s2] :
203 sd == 'wcw' ? [s2inv, -s2] :
204 sd == 'nwcw' ? [s2, -s2inv] :
205 sd == 'nccw' ? [-s2, s2inv] :
206 sd == 'nwccw' ? [-s2inv, s2] :
207 sd == 'wccw' ? [s2inv, s2] :
208 sd == 'swccw' ? [s2, s2inv] :
209 sd == 'sccw' ? [s2, -s2inv] :
210 sd == 'seccw' ? [s2inv, -s2] :
211 sd == 'eccw' ? [-s2inv, -s2] :
212 sd == 'neccw' ? [-s2, -s2inv] : null
213 ;
214 path += offset.join(" ");
215 this.attrs.d += path;
216 return this;
217 }
218 l(x, y) {
219 this.attrs.d += 'l'+x+' '+y;
220 return this;
221 }
222 format() {
223 // All paths in this library start/end horizontally.
224 // The extra .5 ensures a minor overlap, so there's no seams in bad rasterizers.
225 this.attrs.d += 'h.5';
226 return this;
227 }
228 toTextDiagram() {
229 return new TextDiagram(0, 0, []);
230 }
231 }
232
233
234 export class DiagramMultiContainer extends FakeSVG {
235 constructor(tagName, items, attrs, text) {
236 super(tagName, attrs, text);
237 this.items = items.map(wrapString);
238 }
239 walk(cb) {
240 cb(this);
241 this.items.forEach(x=>x.walk(cb));
242 }
243 }
244
245
246 export class Diagram extends DiagramMultiContainer {
247 constructor(...items) {
248 super('svg', items, {class: Options.DIAGRAM_CLASS});
249 if(!(this.items[0] instanceof Start)) {
250 this.items.unshift(new Start());
251 }
252 if(!(this.items[this.items.length-1] instanceof End)) {
253 this.items.push(new End());
254 }
255 this.up = this.down = this.height = this.width = 0;
256 for(const item of this.items) {
257 this.width += item.width + (item.needsSpace?20:0);
258 this.up = Math.max(this.up, item.up - this.height);
259 this.height += item.height;
260 this.down = Math.max(this.down - item.height, item.down);
261 }
262 this.formatted = false;
263 }
264 format(paddingt, paddingr, paddingb, paddingl) {
265 paddingt = unnull(paddingt, 20);
266 paddingr = unnull(paddingr, paddingt, 20);
267 paddingb = unnull(paddingb, paddingt, 20);
268 paddingl = unnull(paddingl, paddingr, 20);
269 var x = paddingl;
270 var y = paddingt;
271 y += this.up;
272 var g = new FakeSVG('g', Options.STROKE_ODD_PIXEL_LENGTH ? {transform:'translate(.5 .5)'} : {});
273 for(var i = 0; i < this.items.length; i++) {
274 var item = this.items[i];
275 if(item.needsSpace) {
276 new Path(x,y).h(10).addTo(g);
277 x += 10;
278 }
279 item.format(x, y, item.width).addTo(g);
280 x += item.width;
281 y += item.height;
282 if(item.needsSpace) {
283 new Path(x,y).h(10).addTo(g);
284 x += 10;
285 }
286 }
287 this.attrs.width = this.width + paddingl + paddingr;
288 this.attrs.height = this.up + this.height + this.down + paddingt + paddingb;
289 this.attrs.viewBox = "0 0 " + this.attrs.width + " " + this.attrs.height;
290 g.addTo(this);
291 this.formatted = true;
292 return this;
293 }
294 addTo(parent) {
295 if(!parent) {
296 var scriptTag = document.getElementsByTagName('script');
297 scriptTag = scriptTag[scriptTag.length - 1];
298 parent = scriptTag.parentNode;
299 }
300 return super.addTo.call(this, parent);
301 }
302 toSVG() {
303 if(!this.formatted) {
304 this.format();
305 }
306 return super.toSVG.call(this);
307 }
308 toString() {
309 if(!this.formatted) {
310 this.format();
311 }
312 return super.toString.call(this);
313 }
314 toStandalone(style) {
315 if(!this.formatted) {
316 this.format();
317 }
318 const s = new FakeSVG('style', {}, style || defaultCSS);
319 this.children.push(s);
320 this.attrs.xmlns = "http://www.w3.org/2000/svg";
321 this.attrs['xmlns:xlink'] = "http://www.w3.org/1999/xlink";
322 const result = super.toString.call(this);
323 this.children.pop();
324 delete this.attrs.xmlns;
325 return result;
326 }
327 toTextDiagram() {
328 var [separator] = TextDiagram._getParts(["separator"])
329 var diagramTD = this.items[0].toTextDiagram();
330 for(const item of this.items.slice(1)) {
331 var itemTD = item.toTextDiagram();
332 if(item.needsSpace) {
333 itemTD = itemTD.expand(1, 1, 0, 0);
334 }
335 diagramTD = diagramTD.appendRight(itemTD, separator);
336 }
337 return diagramTD;
338 }
339 }
340 funcs.Diagram = (...args)=>new Diagram(...args);
341
342
343 export class ComplexDiagram extends FakeSVG {
344 constructor(...items) {
345 var diagram = new Diagram(...items);
346 diagram.items[0] = new Start({type:"complex"});
347 diagram.items[diagram.items.length-1] = new End({type:"complex"});
348 return diagram;
349 }
350 }
351 funcs.ComplexDiagram = (...args)=>new ComplexDiagram(...args);
352
353
354 export class Sequence extends DiagramMultiContainer {
355 constructor(...items) {
356 super('g', items);
357 var numberOfItems = this.items.length;
358 this.needsSpace = true;
359 this.up = this.down = this.height = this.width = 0;
360 for(var i = 0; i < this.items.length; i++) {
361 var item = this.items[i];
362 this.width += item.width + (item.needsSpace?20:0);
363 this.up = Math.max(this.up, item.up - this.height);
364 this.height += item.height;
365 this.down = Math.max(this.down - item.height, item.down);
366 }
367 if(this.items[0].needsSpace) this.width -= 10;
368 if(this.items[this.items.length-1].needsSpace) this.width -= 10;
369 if(Options.DEBUG) {
370 this.attrs['data-updown'] = this.up + " " + this.height + " " + this.down;
371 this.attrs['data-type'] = "sequence";
372 }
373 }
374 format(x,y,width) {
375 // Hook up the two sides if this is narrower than its stated width.
376 var gaps = determineGaps(width, this.width);
377 new Path(x,y).h(gaps[0]).addTo(this);
378 new Path(x+gaps[0]+this.width,y+this.height).h(gaps[1]).addTo(this);
379 x += gaps[0];
380
381 for(var i = 0; i < this.items.length; i++) {
382 var item = this.items[i];
383 if(item.needsSpace && i > 0) {
384 new Path(x,y).h(10).addTo(this);
385 x += 10;
386 }
387 item.format(x, y, item.width).addTo(this);
388 x += item.width;
389 y += item.height;
390 if(item.needsSpace && i < this.items.length-1) {
391 new Path(x,y).h(10).addTo(this);
392 x += 10;
393 }
394 }
395 return this;
396 }
397 toTextDiagram() {
398 var [separator] = TextDiagram._getParts(["separator"])
399 var diagramTD = new TextDiagram(0, 0, [""])
400 for(const item of this.items) {
401 var itemTD = item.toTextDiagram();
402 if(item.needsSpace) {
403 itemTD = itemTD.expand(1, 1, 0, 0);
404 }
405 diagramTD = diagramTD.appendRight(itemTD, separator);
406 }
407 return diagramTD;
408 }
409 }
410 funcs.Sequence = (...args)=>new Sequence(...args);
411
412
413 export class Stack extends DiagramMultiContainer {
414 constructor(...items) {
415 super('g', items);
416 if( items.length === 0 ) {
417 throw new RangeError("Stack() must have at least one child.");
418 }
419 this.width = Math.max.apply(null, this.items.map(function(e) { return e.width + (e.needsSpace?20:0); }));
420 //if(this.items[0].needsSpace) this.width -= 10;
421 //if(this.items[this.items.length-1].needsSpace) this.width -= 10;
422 if(this.items.length > 1){
423 this.width += Options.AR*2;
424 }
425 this.needsSpace = true;
426 this.up = this.items[0].up;
427 this.down = this.items[this.items.length-1].down;
428
429 this.height = 0;
430 var last = this.items.length - 1;
431 for(var i = 0; i < this.items.length; i++) {
432 var item = this.items[i];
433 this.height += item.height;
434 if(i > 0) {
435 this.height += Math.max(Options.AR*2, item.up + Options.VS);
436 }
437 if(i < last) {
438 this.height += Math.max(Options.AR*2, item.down + Options.VS);
439 }
440 }
441 if(Options.DEBUG) {
442 this.attrs['data-updown'] = this.up + " " + this.height + " " + this.down;
443 this.attrs['data-type'] = "stack";
444 }
445 }
446 format(x,y,width) {
447 var gaps = determineGaps(width, this.width);
448 new Path(x,y).h(gaps[0]).addTo(this);
449 x += gaps[0];
450 var xInitial = x;
451 if(this.items.length > 1) {
452 new Path(x, y).h(Options.AR).addTo(this);
453 x += Options.AR;
454 }
455
456 for(var i = 0; i < this.items.length; i++) {
457 var item = this.items[i];
458 var innerWidth = this.width - (this.items.length>1 ? Options.AR*2 : 0);
459 item.format(x, y, innerWidth).addTo(this);
460 x += innerWidth;
461 y += item.height;
462
463 if(i !== this.items.length-1) {
464 new Path(x, y)
465 .arc('ne').down(Math.max(0, item.down + Options.VS - Options.AR*2))
466 .arc('es').left(innerWidth)
467 .arc('nw').down(Math.max(0, this.items[i+1].up + Options.VS - Options.AR*2))
468 .arc('ws').addTo(this);
469 y += Math.max(item.down + Options.VS, Options.AR*2) + Math.max(this.items[i+1].up + Options.VS, Options.AR*2);
470 //y += Math.max(Options.AR*4, item.down + Options.VS*2 + this.items[i+1].up)
471 x = xInitial+Options.AR;
472 }
473
474 }
475
476 if(this.items.length > 1) {
477 new Path(x,y).h(Options.AR).addTo(this);
478 x += Options.AR;
479 }
480 new Path(x,y).h(gaps[1]).addTo(this);
481
482 return this;
483 }
484 toTextDiagram() {
485 var [corner_bot_left, corner_bot_right, corner_top_left, corner_top_right, line, line_vertical] = TextDiagram._getParts(["corner_bot_left", "corner_bot_right", "corner_top_left", "corner_top_right", "line", "line_vertical"]);
486
487 // Format all the child items, so we can know the maximum width.
488 var itemTDs = [];
489 for(const item of this.items) {
490 itemTDs.push(item.toTextDiagram());
491 }
492 var maxWidth = Math.max(...(itemTDs.map(function(itemTD) {return itemTD.width;})));
493
494 var leftLines = [];
495 var rightLines = [];
496 var separatorTD = new TextDiagram(0, 0, [line.repeat(maxWidth)]);
497 var diagramTD = null; // Top item will replace it
498
499 for(var [itemNum, itemTD] of enumerate(itemTDs)) {
500 if(itemNum == 0) {
501 // The top item enters directly from its left.
502 leftLines.push(line + line);
503 for(var i = 0; i < (itemTD.height - itemTD.entry - 1); i++) {
504 leftLines.push(" ");
505 }
506 } else {
507 // All items below the top enter from a snake-line from the previous item's exit.
508 // Here, we resume that line, already having descended from above on the right.
509 diagramTD = diagramTD.appendBelow(separatorTD, []);
510 leftLines.push(corner_top_left + line);
511 for(i = 0; i < itemTD.entry; i++) {
512 leftLines.push(line_vertical + " ")
513 }
514 leftLines.push(corner_bot_left + line);
515 for(i = 0; i < (itemTD.height - itemTD.entry - 1); i++) {
516 leftLines.push(" ");
517 }
518 for(i = 0; i < itemTD.exit; i++) {
519 rightLines.push(" ");
520 }
521 }
522 if(itemNum < itemTDs.length - 1) {
523 // All items above the bottom exit via a snake-line to the next item's entry.
524 // Here, we start that line on the right.
525 rightLines.push(line + corner_top_right);
526 for(i = 0; i < (itemTD.height - itemTD.exit - 1); i++) {
527 rightLines.push(" " + line_vertical);
528 }
529 rightLines.push(line + corner_bot_right);
530 } else {
531 // The bottom item exits directly to its right.
532 rightLines.push(line + line);
533 }
534 var [leftPad, rightPad] = TextDiagram._gaps(maxWidth, itemTD.width);
535 itemTD = itemTD.expand(leftPad, rightPad, 0, 0);
536 if(itemNum == 0) {
537 diagramTD = itemTD;
538 } else {
539 diagramTD = diagramTD.appendBelow(itemTD, []);
540 }
541 }
542
543 var leftTD = new TextDiagram(0, 0, leftLines);
544 diagramTD = leftTD.appendRight(diagramTD, "");
545 var rightTD = new TextDiagram(0, rightLines.length - 1, rightLines);
546 diagramTD = diagramTD.appendRight(rightTD, "");
547 return diagramTD;
548 }
549 }
550 funcs.Stack = (...args)=>new Stack(...args);
551
552
553 export class OptionalSequence extends DiagramMultiContainer {
554 constructor(...items) {
555 super('g', items);
556 if( items.length === 0 ) {
557 throw new RangeError("OptionalSequence() must have at least one child.");
558 }
559 if( items.length === 1 ) {
560 return new Sequence(items);
561 }
562 var arc = Options.AR;
563 this.needsSpace = false;
564 this.width = 0;
565 this.up = 0;
566 this.height = sum(this.items, function(x){return x.height});
567 this.down = this.items[0].down;
568 var heightSoFar = 0;
569 for(var i = 0; i < this.items.length; i++) {
570 var item = this.items[i];
571 this.up = Math.max(this.up, Math.max(arc*2, item.up + Options.VS) - heightSoFar);
572 heightSoFar += item.height;
573 if(i > 0) {
574 this.down = Math.max(this.height + this.down, heightSoFar + Math.max(arc*2, item.down + Options.VS)) - this.height;
575 }
576 var itemWidth = (item.needsSpace?10:0) + item.width;
577 if(i === 0) {
578 this.width += arc + Math.max(itemWidth, arc);
579 } else {
580 this.width += arc*2 + Math.max(itemWidth, arc) + arc;
581 }
582 }
583 if(Options.DEBUG) {
584 this.attrs['data-updown'] = this.up + " " + this.height + " " + this.down;
585 this.attrs['data-type'] = "optseq";
586 }
587 }
588 format(x, y, width) {
589 var arc = Options.AR;
590 var gaps = determineGaps(width, this.width);
591 new Path(x, y).right(gaps[0]).addTo(this);
592 new Path(x + gaps[0] + this.width, y + this.height).right(gaps[1]).addTo(this);
593 x += gaps[0];
594 var upperLineY = y - this.up;
595 var last = this.items.length - 1;
596 for(var i = 0; i < this.items.length; i++) {
597 var item = this.items[i];
598 var itemSpace = (item.needsSpace?10:0);
599 var itemWidth = item.width + itemSpace;
600 if(i === 0) {
601 // Upper skip
602 new Path(x,y)
603 .arc('se')
604 .up(y - upperLineY - arc*2)
605 .arc('wn')
606 .right(itemWidth - arc)
607 .arc('ne')
608 .down(y + item.height - upperLineY - arc*2)
609 .arc('ws')
610 .addTo(this);
611 // Straight line
612 new Path(x, y)
613 .right(itemSpace + arc)
614 .addTo(this);
615 item.format(x + itemSpace + arc, y, item.width).addTo(this);
616 x += itemWidth + arc;
617 y += item.height;
618 // x ends on the far side of the first element,
619 // where the next element's skip needs to begin
620 } else if(i < last) {
621 // Upper skip
622 new Path(x, upperLineY)
623 .right(arc*2 + Math.max(itemWidth, arc) + arc)
624 .arc('ne')
625 .down(y - upperLineY + item.height - arc*2)
626 .arc('ws')
627 .addTo(this);
628 // Straight line
629 new Path(x,y)
630 .right(arc*2)
631 .addTo(this);
632 item.format(x + arc*2, y, item.width).addTo(this);
633 new Path(x + item.width + arc*2, y + item.height)
634 .right(itemSpace + arc)
635 .addTo(this);
636 // Lower skip
637 new Path(x,y)
638 .arc('ne')
639 .down(item.height + Math.max(item.down + Options.VS, arc*2) - arc*2)
640 .arc('ws')
641 .right(itemWidth - arc)
642 .arc('se')
643 .up(item.down + Options.VS - arc*2)
644 .arc('wn')
645 .addTo(this);
646 x += arc*2 + Math.max(itemWidth, arc) + arc;
647 y += item.height;
648 } else {
649 // Straight line
650 new Path(x, y)
651 .right(arc*2)
652 .addTo(this);
653 item.format(x + arc*2, y, item.width).addTo(this);
654 new Path(x + arc*2 + item.width, y + item.height)
655 .right(itemSpace + arc)
656 .addTo(this);
657 // Lower skip
658 new Path(x,y)
659 .arc('ne')
660 .down(item.height + Math.max(item.down + Options.VS, arc*2) - arc*2)
661 .arc('ws')
662 .right(itemWidth - arc)
663 .arc('se')
664 .up(item.down + Options.VS - arc*2)
665 .arc('wn')
666 .addTo(this);
667 }
668 }
669 return this;
670 }
671 toTextDiagram() {
672 var [line, line_vertical, roundcorner_bot_left, roundcorner_bot_right, roundcorner_top_left, roundcorner_top_right] = TextDiagram._getParts(["line", "line_vertical", "roundcorner_bot_left", "roundcorner_bot_right", "roundcorner_top_left", "roundcorner_top_right"]);
673
674 // Format all the child items, so we can know the maximum entry.
675 var itemTDs = [];
676 for(const item of this.items) {
677 itemTDs.push(item.toTextDiagram());
678 }
679 // diagramEntry: distance from top to lowest entry, aka distance from top to diagram entry, aka final diagram entry and exit.
680 var diagramEntry = Math.max(...(itemTDs.map(function(itemTD) {return itemTD.entry})));
681 // SOILHeight: distance from top to lowest entry before rightmost item, aka distance from skip-over-items line to rightmost entry, aka SOIL height.
682 var SOILHeight = Math.max(...(itemTDs.slice(0,-1).map(function(itemTD) {return itemTD.entry;})));
683 // topToSOIL: distance from top to skip-over-items line.
684 var topToSOIL = diagramEntry - SOILHeight;
685
686 // The diagram starts with a line from its entry up to the skip-over-items line {
687 var lines = [];
688 for(var i = 0; i < topToSOIL; i++) {
689 lines.push(" ");
690 }
691 lines.push(roundcorner_top_left + line);
692 for(i = 0; i < SOILHeight; i++) {
693 lines.push(line_vertical + " ");
694 }
695 lines.push(roundcorner_bot_right + line);
696 var diagramTD = new TextDiagram(lines.length - 1, lines.length - 1, lines);
697 for(const [itemNum, itemTD] of enumerate(itemTDs)) {
698 if(itemNum > 0) {
699 // All items except the leftmost start with a line from their entry down to their skip-under-item line,
700 // with a joining-line across at the skip-over-items line
701 lines = [];
702 for(i = 0; i < topToSOIL; i++) {
703 lines.push(" ");
704 }
705 lines.push(line + line);
706 for(i = 0; i < (diagramTD.exit - topToSOIL - 1); i++) {
707 lines.push(" ");
708 }
709 lines.push(line + roundcorner_top_right);
710 for(i = 0; i < (itemTD.height - itemTD.entry - 1); i++) {
711 lines.push(" " + line_vertical);
712 }
713 lines.push(" " + roundcorner_bot_left);
714 var skipDownTD = new TextDiagram(diagramTD.exit, diagramTD.exit, lines);
715 diagramTD = diagramTD.appendRight(skipDownTD, "");
716 // All items except the leftmost next have a line from skip-over-items line down to their entry,
717 // with joining-lines at their entry and at their skip-under-item line
718 lines = [];
719 for(i = 0; i < topToSOIL; i++) {
720 lines.push(" ");
721 }
722 // All such items except the rightmost also have a continuation of the skip-over-items line
723 var lineToNextItem = itemNum < itemTDs.length - 1 ? line : " ";
724 lines.push(line + roundcorner_top_right + lineToNextItem);
725 for(i = 0; i < (diagramTD.exit - topToSOIL - 1); i++) {
726 lines.push(" " + line_vertical + " ");
727 }
728 lines.push(line + roundcorner_bot_left + line);
729 for(i = 0; i < (itemTD.height - itemTD.entry - 1); i++) {
730 lines.push(" ");
731 }
732 lines.push(line + line + line);
733 var entryTD = new TextDiagram(diagramTD.exit, diagramTD.exit, lines);
734 diagramTD = diagramTD.appendRight(entryTD, "");
735 }
736 var partTD = new TextDiagram(0, 0, []);
737 if(itemNum < itemTDs.length - 1) {
738 // All items except the rightmost have a segment of the skip-over-items line at the top,
739 // followed by enough blank lines to push their entry down to the previous item's exit
740 lines = [];
741 lines.push(line.repeat(itemTD.width));
742 for(i = 0; i < (SOILHeight - itemTD.entry); i++) {
743 lines.push(" ".repeat(itemTD.width));
744 }
745 var SOILSegment = new TextDiagram(0, 0, lines);
746 partTD = partTD.appendBelow(SOILSegment, []);
747 }
748 partTD = partTD.appendBelow(itemTD, [], true, true);
749 if (itemNum > 0) {
750 // All items except the leftmost have their skip-under-item line at the bottom.
751 var SUILSegment = new TextDiagram(0, 0, [line.repeat(itemTD.width)]);
752 partTD = partTD.appendBelow(SUILSegment, []);
753 }
754 diagramTD = diagramTD.appendRight(partTD, "");
755 if(0 < itemNum) {
756 // All items except the leftmost have a line from their skip-under-item line to their exit
757 lines = [];
758 for(i = 0; i < topToSOIL; i++) {
759 lines.push(" ");
760 }
761 // All such items except the rightmost also have a joining-line across at the skip-over-items line
762 var skipOverChar = itemNum < itemTDs.length - 1 ? line : " ";
763 lines.push(skipOverChar.repeat(2));
764 for(i = 0; i < (diagramTD.exit - topToSOIL - 1); i++) {
765 lines.push(" ");
766 }
767 lines.push(line + roundcorner_top_left);
768 for(i = 0; i < (partTD.height - partTD.exit - 2); i++) {
769 lines.push(" " + line_vertical);
770 }
771 lines.push(line + roundcorner_bot_right);
772 var skipUpTD = new TextDiagram(diagramTD.exit, diagramTD.exit, lines);
773 diagramTD = diagramTD.appendRight(skipUpTD, "");
774 }
775 }
776 return diagramTD;
777 }
778 }
779 funcs.OptionalSequence = (...args)=>new OptionalSequence(...args);
780
781
782 export class AlternatingSequence extends DiagramMultiContainer {
783 constructor(...items) {
784 super('g', items);
785 if( items.length === 1 ) {
786 return new Sequence(items);
787 }
788 if( items.length !== 2 ) {
789 throw new RangeError("AlternatingSequence() must have one or two children.");
790 }
791 this.needsSpace = false;
792
793 const arc = Options.AR;
794 const vert = Options.VS;
795 const max = Math.max;
796 const first = this.items[0];
797 const second = this.items[1];
798
799 const arcX = 1 / Math.sqrt(2) * arc * 2;
800 const arcY = (1 - 1 / Math.sqrt(2)) * arc * 2;
801 const crossY = Math.max(arc, Options.VS);
802 const crossX = (crossY - arcY) + arcX;
803
804 const firstOut = max(arc + arc, crossY/2 + arc + arc, crossY/2 + vert + first.down);
805 this.up = firstOut + first.height + first.up;
806
807 const secondIn = max(arc + arc, crossY/2 + arc + arc, crossY/2 + vert + second.up);
808 this.down = secondIn + second.height + second.down;
809
810 this.height = 0;
811
812 const firstWidth = 2*(first.needsSpace?10:0) + first.width;
813 const secondWidth = 2*(second.needsSpace?10:0) + second.width;
814 this.width = 2*arc + max(firstWidth, crossX, secondWidth) + 2*arc;
815
816 if(Options.DEBUG) {
817 this.attrs['data-updown'] = this.up + " " + this.height + " " + this.down;
818 this.attrs['data-type'] = "altseq";
819 }
820 }
821 format(x, y, width) {
822 const arc = Options.AR;
823 const gaps = determineGaps(width, this.width);
824 new Path(x,y).right(gaps[0]).addTo(this);
825 x += gaps[0];
826 new Path(x+this.width, y).right(gaps[1]).addTo(this);
827 // bounding box
828 //new Path(x+gaps[0], y).up(this.up).right(this.width).down(this.up+this.down).left(this.width).up(this.down).addTo(this);
829 const first = this.items[0];
830 const second = this.items[1];
831
832 // top
833 const firstIn = this.up - first.up;
834 const firstOut = this.up - first.up - first.height;
835 new Path(x,y).arc('se').up(firstIn-2*arc).arc('wn').addTo(this);
836 first.format(x + 2*arc, y - firstIn, this.width - 4*arc).addTo(this);
837 new Path(x + this.width - 2*arc, y - firstOut).arc('ne').down(firstOut - 2*arc).arc('ws').addTo(this);
838
839 // bottom
840 const secondIn = this.down - second.down - second.height;
841 const secondOut = this.down - second.down;
842 new Path(x,y).arc('ne').down(secondIn - 2*arc).arc('ws').addTo(this);
843 second.format(x + 2*arc, y + secondIn, this.width - 4*arc).addTo(this);
844 new Path(x + this.width - 2*arc, y + secondOut).arc('se').up(secondOut - 2*arc).arc('wn').addTo(this);
845
846 // crossover
847 const arcX = 1 / Math.sqrt(2) * arc * 2;
848 const arcY = (1 - 1 / Math.sqrt(2)) * arc * 2;
849 const crossY = Math.max(arc, Options.VS);
850 const crossX = (crossY - arcY) + arcX;
851 const crossBar = (this.width - 4*arc - crossX)/2;
852 new Path(x+arc, y - crossY/2 - arc).arc('ws').right(crossBar)
853 .arc_8('n', 'cw').l(crossX - arcX, crossY - arcY).arc_8('sw', 'ccw')
854 .right(crossBar).arc('ne').addTo(this);
855 new Path(x+arc, y + crossY/2 + arc).arc('wn').right(crossBar)
856 .arc_8('s', 'ccw').l(crossX - arcX, -(crossY - arcY)).arc_8('nw', 'cw')
857 .right(crossBar).arc('se').addTo(this);
858
859 return this;
860 }
861 toTextDiagram() {
862 var [cross_diag, corner_bot_left, corner_bot_right, corner_top_left, corner_top_right, line, line_vertical, tee_left, tee_right] = TextDiagram._getParts(["cross_diag", "roundcorner_bot_left", "roundcorner_bot_right", "roundcorner_top_left", "roundcorner_top_right", "line", "line_vertical", "tee_left", "tee_right"]);
863
864 var firstTD = this.items[0].toTextDiagram();
865 var secondTD = this.items[1].toTextDiagram();
866 var maxWidth = TextDiagram._maxWidth(firstTD, secondTD);
867 var leftLines = [];
868 var rightLines = [];
869 var separator = [];
870 var [leftGap, rightGap] = TextDiagram._gaps(maxWidth, firstTD.width);
871 var diagramTD = firstTD.expand(leftGap, rightGap, 0, 0);
872 for(var i = 0; i < diagramTD.entry; i++) {
873 leftLines.push(" ");
874 }
875 leftLines.push(corner_top_left + line);
876 for(i = 0; i < (diagramTD.height - diagramTD.entry - 1); i++) {
877 leftLines.push(line_vertical + " ");
878 }
879 leftLines.push(corner_bot_left + line);
880 for(i = 0; i < diagramTD.exit; i++) {
881 rightLines.push(" ");
882 }
883 rightLines.push(line + corner_top_right);
884 for(i = 0; i < (diagramTD.height - diagramTD.exit - 1); i++) {
885 rightLines.push(" " + line_vertical);
886 }
887 rightLines.push(line + corner_bot_right);
888
889 var [leftSepWidth, rightSepWidth] = TextDiagram._gaps(maxWidth, 3, "center")
890 separator.push((line.repeat(leftSepWidth)) + corner_top_right + " " + corner_top_left + (line.repeat(rightSepWidth)));
891 separator.push((" ".repeat(leftSepWidth)) + " " + cross_diag + " " + (" ".repeat(rightSepWidth)));
892 separator.push((line.repeat(leftSepWidth)) + corner_bot_right + " " + corner_bot_left + (line.repeat(rightSepWidth)));
893 leftLines.push(" ");
894 rightLines.push(" ");
895
896 [leftGap, rightGap] = TextDiagram._gaps(maxWidth, secondTD.width);
897 secondTD = secondTD.expand(leftGap, rightGap, 0, 0);
898 diagramTD = diagramTD.appendBelow(secondTD, separator, true, true);
899 leftLines.push(corner_top_left + line);
900 for(i = 0; i < secondTD.entry; i++) {
901 leftLines.push(line_vertical + " ");
902 }
903 leftLines.push(corner_bot_left + line);
904 rightLines.push(line + corner_top_right);
905 for(i = 0; i < secondTD.exit; i++) {
906 rightLines.push(" " + line_vertical);
907 }
908 rightLines.push(line + corner_bot_right);
909
910 diagramTD = diagramTD.alter({entry:firstTD.height + Math.trunc(separator.length / 2), exit:firstTD.height + Math.trunc(separator.length / 2)});
911 var leftTD = new TextDiagram(firstTD.height + Math.trunc(separator.length / 2), firstTD.height + Math.trunc(separator.length / 2), leftLines);
912 var rightTD = new TextDiagram(firstTD.height + Math.trunc(separator.length / 2), firstTD.height + Math.trunc(separator.length / 2), rightLines);
913 diagramTD = leftTD.appendRight(diagramTD, "").appendRight(rightTD, "");
914 diagramTD = new TextDiagram(1, 1, [corner_top_left, tee_left, corner_bot_left]).appendRight(diagramTD, "").appendRight(new TextDiagram(1, 1, [corner_top_right, tee_right, corner_bot_right]), "");
915 return diagramTD;
916 }
917 }
918 funcs.AlternatingSequence = (...args)=>new AlternatingSequence(...args);
919
920
921 export class Choice extends DiagramMultiContainer {
922 constructor(normal, ...items) {
923 super('g', items);
924 if( typeof normal !== "number" || normal !== Math.floor(normal) ) {
925 throw new TypeError("The first argument of Choice() must be an integer.");
926 } else if(normal < 0 || normal >= items.length) {
927 throw new RangeError("The first argument of Choice() must be an index for one of the items.");
928 } else {
929 this.normal = normal;
930 }
931 this.width = max(this.items, el=>el.width) + Options.AR*4;
932 var firstItem = this.items[0];
933 var lastItem = this.items[items.length - 1];
934 var normalItem = this.items[normal];
935
936 // The size of the vertical separation between an item
937 // and the following item.
938 // The calcs are non-trivial and need to be done both here
939 // and in .format(), so no reason to do it twice.
940 this.separators = Array.from({length:items.length-1}, x=>0);
941
942 // If the entry or exit lines would be too close together
943 // to accommodate the arcs,
944 // bump up the vertical separation to compensate.
945 this.up = 0
946 var arcs;
947 for(var i = normal - 1; i >= 0; i--) {
948 if(i == normal-1) arcs = Options.AR * 2;
949 else arcs = Options.AR;
950
951 let item = this.items[i];
952 let lowerItem = this.items[i+1];
953
954 let entryDelta = lowerItem.up + Options.VS + item.down + item.height;
955 let exitDelta = lowerItem.height + lowerItem.up + Options.VS + item.down;
956
957 let separator = Options.VS;
958 if(exitDelta < arcs || entryDelta < arcs) {
959 separator += Math.max(arcs - entryDelta, arcs - exitDelta)
960 }
961 this.separators[i] = separator
962 this.up += lowerItem.up + separator + item.down + item.height
963 }
964 this.up += firstItem.up;
965
966 this.height = normalItem.height;
967
968 this.down = 0;
969 for(var i = normal+1; i < this.items.length; i++) {
970 if(i == normal+1) arcs = Options.AR * 2;
971 else arcs = Options.AR;
972
973 let item = this.items[i];
974 let upperItem = this.items[i-1];
975
976 let entryDelta = upperItem.height + upperItem.down + Options.VS + item.up;
977 let exitDelta = upperItem.down + Options.VS + item.up + item.height;
978
979 let separator = Options.VS;
980 if(entryDelta < arcs || exitDelta < arcs) {
981 separator += Math.max(arcs - entryDelta, arcs - exitDelta)
982 }
983 this.separators[i-1] = separator;
984 this.down += upperItem.down + separator + item.up + item.height;
985 }
986 this.down += lastItem.down;
987
988 if(Options.DEBUG) {
989 this.attrs['data-updown'] = this.up + " " + this.height + " " + this.down;
990 this.attrs['data-type'] = "choice";
991 }
992 }
993 format(x,y,width) {
994 // Hook up the two sides if this is narrower than its stated width.
995 var gaps = determineGaps(width, this.width);
996 new Path(x,y).h(gaps[0]).addTo(this);
997 new Path(x+gaps[0]+this.width,y+this.height).h(gaps[1]).addTo(this);
998 x += gaps[0];
999
1000 var last = this.items.length -1;
1001 var innerWidth = this.width - Options.AR*4;
1002
1003 // Do the elements that curve above
1004 var distanceFromY = 0;
1005 for(var i = this.normal - 1; i >= 0; i--) {
1006 let item = this.items[i];
1007 let lowerItem = this.items[i+1];
1008 distanceFromY += lowerItem.up + this.separators[i] + item.down + item.height;
1009 new Path(x,y)
1010 .arc('se')
1011 .up(distanceFromY - Options.AR*2)
1012 .arc('wn').addTo(this);
1013 item.format(x+Options.AR*2,y - distanceFromY,innerWidth).addTo(this);
1014 new Path(x+Options.AR*2+innerWidth, y-distanceFromY+item.height)
1015 .arc('ne')
1016 .down(distanceFromY - item.height + this.height - Options.AR*2)
1017 .arc('ws').addTo(this);
1018 }
1019
1020 // Do the straight-line path.
1021 new Path(x,y).right(Options.AR*2).addTo(this);
1022 this.items[this.normal].format(x+Options.AR*2, y, innerWidth).addTo(this);
1023 new Path(x+Options.AR*2+innerWidth, y+this.height).right(Options.AR*2).addTo(this);
1024
1025 // Do the elements that curve below
1026 var distanceFromY = 0;
1027 for(var i = this.normal+1; i <= last; i++) {
1028 let item = this.items[i];
1029 let upperItem = this.items[i-1];
1030 distanceFromY += upperItem.height + upperItem.down + this.separators[i-1] + item.up;
1031 new Path(x,y)
1032 .arc('ne')
1033 .down(distanceFromY - Options.AR*2)
1034 .arc('ws').addTo(this);
1035 if(!item.format) console.log(item);
1036 item.format(x+Options.AR*2, y+distanceFromY, innerWidth).addTo(this);
1037 new Path(x+Options.AR*2+innerWidth, y+distanceFromY+item.height)
1038 .arc('se')
1039 .up(distanceFromY - Options.AR*2 + item.height - this.height)
1040 .arc('wn').addTo(this);
1041 }
1042
1043 return this;
1044 }
1045 toTextDiagram() {
1046 var [cross, line, line_vertical, roundcorner_bot_left, roundcorner_bot_right, roundcorner_top_left, roundcorner_top_right] = TextDiagram._getParts(["cross", "line", "line_vertical", "roundcorner_bot_left", "roundcorner_bot_right", "roundcorner_top_left", "roundcorner_top_right"]);
1047 // Format all the child items, so we can know the maximum width.
1048 var itemTDs = [];
1049 for(const item of this.items) {
1050 itemTDs.push(item.toTextDiagram().expand(1, 1, 0, 0));
1051 }
1052 var max_item_width = Math.max(...(itemTDs.map(function(itemTD) {return itemTD.width})));
1053 var diagramTD = new TextDiagram(0, 0, []);
1054 // Format the choice collection.
1055 for(var [itemNum, itemTD] of enumerate(itemTDs)) {
1056 var [leftPad, rightPad] = TextDiagram._gaps(max_item_width, itemTD.width);
1057 itemTD = itemTD.expand(leftPad, rightPad, 0, 0);
1058 var hasSeparator = true;
1059 var leftLines = [];
1060 var rightLines = [];
1061 for (var i = 0; i < itemTD.height; i++) {
1062 leftLines.push(line_vertical);
1063 rightLines.push(line_vertical);
1064 }
1065 var moveEntry = false;
1066 var moveExit = false;
1067 if(itemNum <= this.normal) {
1068 // Item above the line: round off the entry/exit lines upwards.
1069 leftLines[itemTD.entry] = roundcorner_top_left;
1070 rightLines[itemTD.exit] = roundcorner_top_right;
1071 if(itemNum == 0) {
1072 // First item and above the line: also remove ascenders above the item's entry and exit, suppress the separator above it.
1073 hasSeparator = false;
1074 for(i = 0; i < itemTD.entry; i++) {
1075 leftLines[i] = " ";
1076 }
1077 for(i = 0; i < itemTD.exit; i++) {
1078 rightLines[i] = " ";
1079 }
1080 }
1081 }
1082 if(itemNum >= this.normal) {
1083 // Item below the line: round off the entry/exit lines downwards.
1084 leftLines[itemTD.entry] = roundcorner_bot_left;
1085 rightLines[itemTD.exit] = roundcorner_bot_right;
1086 if(itemNum == 0) {
1087 // First item and below the line: also suppress the separator above it.
1088 hasSeparator = false;
1089 }
1090 if(itemNum == (this.items.length - 1)) {
1091 // Last item and below the line: also remove descenders below the item's entry and exit
1092 for(i = itemTD.entry + 1; i < itemTD.height; i++) {
1093 leftLines[i] = " ";
1094 }
1095 for(i = itemTD.exit + 1; i < itemTD.height; i++) {
1096 rightLines[i] = " ";
1097 }
1098 }
1099 }
1100 if(itemNum == this.normal) {
1101 // Item on the line: entry/exit are horizontal, and sets the outer entry/exit.
1102 leftLines[itemTD.entry] = cross;
1103 rightLines[itemTD.exit] = cross;
1104 moveEntry = true;
1105 moveExit = true;
1106 if(itemNum == 0 && itemNum == (this.items.length - 1)) {
1107 // Only item and on the line: set entry/exit for straight through.
1108 leftLines[itemTD.entry] = line;
1109 rightLines[itemTD.exit] = line;
1110 } else if(itemNum == 0) {
1111 // First item and on the line: set entry/exit for no ascenders.
1112 leftLines[itemTD.entry] = roundcorner_top_right;
1113 rightLines[itemTD.exit] = roundcorner_top_left;
1114 } else if(itemNum == (this.items.length - 1)) {
1115 // Last item and on the line: set entry/exit for no descenders.
1116 leftLines[itemTD.entry] = roundcorner_bot_right;
1117 rightLines[itemTD.exit] = roundcorner_bot_left;
1118 }
1119 }
1120 var leftJointTD = new TextDiagram(itemTD.entry, itemTD.entry, leftLines);
1121 var rightJointTD = new TextDiagram(itemTD.exit, itemTD.exit, rightLines);
1122 itemTD = leftJointTD.appendRight(itemTD, "").appendRight(rightJointTD, "");
1123 var separator = hasSeparator ? [line_vertical + (" ".repeat(TextDiagram._maxWidth(diagramTD, itemTD) - 2)) + line_vertical] : [];
1124 diagramTD = diagramTD.appendBelow(itemTD, separator, moveEntry, moveExit);
1125 }
1126 return diagramTD;
1127 }
1128 }
1129 funcs.Choice = (...args)=>new Choice(...args);
1130
1131
1132 export class HorizontalChoice extends DiagramMultiContainer {
1133 constructor(...items) {
1134 super('g', items);
1135 if( items.length === 0 ) {
1136 throw new RangeError("HorizontalChoice() must have at least one child.");
1137 }
1138 if( items.length === 1) {
1139 return new Sequence(items);
1140 }
1141 const allButLast = this.items.slice(0, -1);
1142 const middles = this.items.slice(1, -1);
1143 const first = this.items[0];
1144 const last = this.items[this.items.length - 1];
1145 this.needsSpace = false;
1146
1147 this.width = Options.AR; // starting track
1148 this.width += Options.AR*2 * (this.items.length-1); // inbetween tracks
1149 this.width += sum(this.items, x=>x.width + (x.needsSpace?20:0)); // items
1150 this.width += (last.height > 0 ? Options.AR : 0); // needs space to curve up
1151 this.width += Options.AR; //ending track
1152
1153 // Always exits at entrance height
1154 this.height = 0;
1155
1156 // All but the last have a track running above them
1157 this._upperTrack = Math.max(
1158 Options.AR*2,
1159 Options.VS,
1160 max(allButLast, x=>x.up) + Options.VS
1161 );
1162 this.up = Math.max(this._upperTrack, last.up);
1163
1164 // All but the first have a track running below them
1165 // Last either straight-lines or curves up, so has different calculation
1166 this._lowerTrack = Math.max(
1167 Options.VS,
1168 max(middles, x=>x.height+Math.max(x.down+Options.VS, Options.AR*2)),
1169 last.height + last.down + Options.VS
1170 );
1171 if(first.height < this._lowerTrack) {
1172 // Make sure there's at least 2*AR room between first exit and lower track
1173 this._lowerTrack = Math.max(this._lowerTrack, first.height + Options.AR*2);
1174 }
1175 this.down = Math.max(this._lowerTrack, first.height + first.down);
1176
1177
1178 if(Options.DEBUG) {
1179 this.attrs['data-updown'] = this.up + " " + this.height + " " + this.down;
1180 this.attrs['data-type'] = "horizontalchoice";
1181 }
1182 }
1183 format(x,y,width) {
1184 // Hook up the two sides if this is narrower than its stated width.
1185 var gaps = determineGaps(width, this.width);
1186 new Path(x,y).h(gaps[0]).addTo(this);
1187 new Path(x+gaps[0]+this.width,y+this.height).h(gaps[1]).addTo(this);
1188 x += gaps[0];
1189
1190 const first = this.items[0];
1191 const last = this.items[this.items.length-1];
1192 const allButFirst = this.items.slice(1);
1193 const allButLast = this.items.slice(0, -1);
1194
1195 // upper track
1196 var upperSpan = (sum(allButLast, x=>x.width+(x.needsSpace?20:0))
1197 + (this.items.length - 2) * Options.AR*2
1198 - Options.AR
1199 );
1200 new Path(x,y)
1201 .arc('se')
1202 .v(-(this._upperTrack - Options.AR*2))
1203 .arc('wn')
1204 .h(upperSpan)
1205 .addTo(this);
1206
1207 // lower track
1208 var lowerSpan = (sum(allButFirst, x=>x.width+(x.needsSpace?20:0))
1209 + (this.items.length - 2) * Options.AR*2
1210 + (last.height > 0 ? Options.AR : 0)
1211 - Options.AR
1212 );
1213 var lowerStart = x + Options.AR + first.width+(first.needsSpace?20:0) + Options.AR*2;
1214 new Path(lowerStart, y+this._lowerTrack)
1215 .h(lowerSpan)
1216 .arc('se')
1217 .v(-(this._lowerTrack - Options.AR*2))
1218 .arc('wn')
1219 .addTo(this);
1220
1221 // Items
1222 for(const [i, item] of enumerate(this.items)) {
1223 // input track
1224 if(i === 0) {
1225 new Path(x,y)
1226 .h(Options.AR)
1227 .addTo(this);
1228 x += Options.AR;
1229 } else {
1230 new Path(x, y - this._upperTrack)
1231 .arc('ne')
1232 .v(this._upperTrack - Options.AR*2)
1233 .arc('ws')
1234 .addTo(this);
1235 x += Options.AR*2;
1236 }
1237
1238 // item
1239 var itemWidth = item.width + (item.needsSpace?20:0);
1240 item.format(x, y, itemWidth).addTo(this);
1241 x += itemWidth;
1242
1243 // output track
1244 if(i === this.items.length-1) {
1245 if(item.height === 0) {
1246 new Path(x,y)
1247 .h(Options.AR)
1248 .addTo(this);
1249 } else {
1250 new Path(x,y+item.height)
1251 .arc('se')
1252 .addTo(this);
1253 }
1254 } else if(i === 0 && item.height > this._lowerTrack) {
1255 // Needs to arc up to meet the lower track, not down.
1256 if(item.height - this._lowerTrack >= Options.AR*2) {
1257 new Path(x, y+item.height)
1258 .arc('se')
1259 .v(this._lowerTrack - item.height + Options.AR*2)
1260 .arc('wn')
1261 .addTo(this);
1262 } else {
1263 // Not enough space to fit two arcs
1264 // so just bail and draw a straight line for now.
1265 new Path(x, y+item.height)
1266 .l(Options.AR*2, this._lowerTrack - item.height)
1267 .addTo(this);
1268 }
1269 } else {
1270 new Path(x, y+item.height)
1271 .arc('ne')
1272 .v(this._lowerTrack - item.height - Options.AR*2)
1273 .arc('ws')
1274 .addTo(this);
1275 }
1276 }
1277 return this;
1278 }
1279 toTextDiagram() {
1280 var [line, line_vertical, roundcorner_bot_left, roundcorner_bot_right, roundcorner_top_left, roundcorner_top_right] = TextDiagram._getParts(["line", "line_vertical", "roundcorner_bot_left", "roundcorner_bot_right", "roundcorner_top_left", "roundcorner_top_right"]);
1281
1282 // Format all the child items, so we can know the maximum entry, exit, and height.
1283 var itemTDs = [];
1284 for(const item of this.items) {
1285 itemTDs.push(item.toTextDiagram());
1286 }
1287 // diagramEntry: distance from top to lowest entry, aka distance from top to diagram entry, aka final diagram entry and exit.
1288 var diagramEntry = Math.max(...(itemTDs.map(function(itemTD) {return itemTD.entry})));
1289 // SOILToBaseline: distance from top to lowest entry before rightmost item, aka distance from skip-over-items line to rightmost entry, aka SOIL height.
1290 var SOILToBaseline = Math.max(...(itemTDs.slice(0, -1).map(function(itemTD) {return itemTD.entry})));
1291 // topToSOIL: distance from top to skip-over-items line.
1292 var topToSOIL = diagramEntry - SOILToBaseline;
1293 // baselineToSUIL: distance from lowest entry or exit after leftmost item to bottom, aka distance from entry to skip-under-items line, aka SUIL height.
1294 var baselineToSUIL = Math.max(...(itemTDs.slice(1).map(function(itemTD) {return itemTD.height - Math.min(itemTD.entry, itemTD.exit) - 1;})));
1295
1296 // The diagram starts with a line from its entry up to skip-over-items line {
1297 var lines = [];
1298 for(var i = 0; i < topToSOIL; i++) {
1299 lines.push(" ");
1300 }
1301 lines.push(roundcorner_top_left + line);
1302 for(i = 0; i < SOILToBaseline; i++) {
1303 lines.push(line_vertical + " ");
1304 }
1305 lines.push(roundcorner_bot_right + line);
1306 var diagramTD = new TextDiagram(lines.length - 1, lines.length - 1, lines);
1307 for(const [itemNum, itemTD] of enumerate(itemTDs)) {
1308 if(itemNum > 0) {
1309 // All items except the leftmost start with a line from the skip-over-items line down to their entry,
1310 // with a joining-line across at the skip-under-items line {
1311 lines = [];
1312 for(i = 0; i < topToSOIL; i++) {
1313 lines.push(" ");
1314 }
1315 // All such items except the rightmost also have a continuation of the skip-over-items line {
1316 var lineToNextItem = itemNum == itemTDs.length - 1 ? " " : line;
1317 lines.push(roundcorner_top_right + lineToNextItem);
1318 for(i = 0; i < SOILToBaseline; i++) {
1319 lines.push(line_vertical + " ");
1320 }
1321 lines.push(roundcorner_bot_left + line);
1322 for(i = 0; i < baselineToSUIL; i++) {
1323 lines.push(" ");
1324 }
1325 lines.push(line + line);
1326 var entryTD = new TextDiagram(diagramTD.exit, diagramTD.exit, lines);
1327 diagramTD = diagramTD.appendRight(entryTD, "");
1328 }
1329 var partTD = new TextDiagram(0, 0, []);
1330 if(itemNum < itemTDs.length - 1) {
1331 // All items except the rightmost start with a segment of the skip-over-items line at the top.
1332 // followed by enough blank lines to push their entry down to the previous item's exit {
1333 lines = [];
1334 lines.push(line.repeat(itemTD.width));
1335 for(i = 0; i < (SOILToBaseline - itemTD.entry); i++) {
1336 lines.push(" ".repeat(itemTD.width));
1337 }
1338 var SOILSegment = new TextDiagram(0, 0, lines);
1339 partTD = partTD.appendBelow(SOILSegment, []);
1340 }
1341 partTD = partTD.appendBelow(itemTD, [], true, true);
1342 if(itemNum > 0) {
1343 // All items except the leftmost end with enough blank lines to pad down to the skip-under-items
1344 // line, followed by a segment of the skip-under-items line {
1345 lines = [];
1346 for(i = 0; i < (baselineToSUIL - (itemTD.height - itemTD.entry) + 1); i++) {
1347 lines.push(" ".repeat(itemTD.width));
1348 }
1349 lines.push(line.repeat(itemTD.width));
1350 var SUILSegment = new TextDiagram(0, 0, lines);
1351 partTD = partTD.appendBelow(SUILSegment, []);
1352 }
1353 diagramTD = diagramTD.appendRight(partTD, "");
1354 if(itemNum < itemTDs.length - 1) {
1355 // All items except the rightmost have a line from their exit down to the skip-under-items line,
1356 // with a joining-line across at the skip-over-items line {
1357 lines = [];
1358 for(i = 0; i < topToSOIL; i++) {
1359 lines.push(" ");
1360 }
1361 lines.push(line + line);
1362 for(i = 0; i < (diagramTD.exit - topToSOIL - 1); i++) {
1363 lines.push(" ");
1364 }
1365 lines.push(line + roundcorner_top_right);
1366 for(i = 0; i < (baselineToSUIL - (diagramTD.exit - diagramTD.entry)); i++) {
1367 lines.push(" " + line_vertical);
1368 }
1369 // All such items except the leftmost also have are continuing of the skip-under-items line from the previous item {
1370 var lineFromPrevItem = itemNum > 0 ? line : " ";
1371 lines.push(lineFromPrevItem + roundcorner_bot_left);
1372 var entry = diagramEntry + 1 + (diagramTD.exit - diagramTD.entry);
1373 var exitTD = new TextDiagram(entry, diagramEntry + 1, lines);
1374 diagramTD = diagramTD.appendRight(exitTD, "");
1375 } else {
1376 // The rightmost item has a line from the skip-under-items line and from its exit up to the diagram exit {
1377 lines = [];
1378 var lineFromExit = diagramTD.exit != diagramTD.entry ? " " : line;
1379 lines.push(lineFromExit + roundcorner_top_left);
1380 for(i = 0; i < (diagramTD.exit - diagramTD.entry - 1); i++) {
1381 lines.push(" " + line_vertical);
1382 }
1383 if(diagramTD.exit != diagramTD.entry) {
1384 lines.push(line + roundcorner_bot_right);
1385 }
1386 for(i = 0; i < (baselineToSUIL - (diagramTD.exit - diagramTD.entry)); i++) {
1387 lines.push(" " + line_vertical);
1388 }
1389 lines.push(line + roundcorner_bot_right);
1390 exitTD = new TextDiagram(diagramTD.exit - diagramTD.entry, 0, lines);
1391 diagramTD = diagramTD.appendRight(exitTD, "");
1392 }
1393 }
1394 return diagramTD;
1395 }
1396 }
1397 funcs.HorizontalChoice = (...args)=>new HorizontalChoice(...args);
1398
1399
1400 export class MultipleChoice extends DiagramMultiContainer {
1401 constructor(normal, type, ...items) {
1402 super('g', items);
1403 if( typeof normal !== "number" || normal !== Math.floor(normal) ) {
1404 throw new TypeError("The first argument of MultipleChoice() must be an integer.");
1405 } else if(normal < 0 || normal >= items.length) {
1406 throw new RangeError("The first argument of MultipleChoice() must be an index for one of the items.");
1407 } else {
1408 this.normal = normal;
1409 }
1410 if( type != "any" && type != "all" ) {
1411 throw new SyntaxError("The second argument of MultipleChoice must be 'any' or 'all'.");
1412 } else {
1413 this.type = type;
1414 }
1415 this.needsSpace = true;
1416 this.innerWidth = max(this.items, function(x){return x.width});
1417 this.width = 30 + Options.AR + this.innerWidth + Options.AR + 20;
1418 this.up = this.items[0].up;
1419 this.down = this.items[this.items.length-1].down;
1420 this.height = this.items[normal].height;
1421 for(var i = 0; i < this.items.length; i++) {
1422 let item = this.items[i];
1423 let minimum;
1424 if(i == normal - 1 || i == normal + 1) minimum = 10 + Options.AR;
1425 else minimum = Options.AR;
1426 if(i < normal) {
1427 this.up += Math.max(minimum, item.height + item.down + Options.VS + this.items[i+1].up);
1428 } else if(i > normal) {
1429 this.down += Math.max(minimum, item.up + Options.VS + this.items[i-1].down + this.items[i-1].height);
1430 }
1431 }
1432 this.down -= this.items[normal].height; // already counted in this.height
1433 if(Options.DEBUG) {
1434 this.attrs['data-updown'] = this.up + " " + this.height + " " + this.down;
1435 this.attrs['data-type'] = "multiplechoice";
1436 }
1437 }
1438 format(x, y, width) {
1439 var gaps = determineGaps(width, this.width);
1440 new Path(x, y).right(gaps[0]).addTo(this);
1441 new Path(x + gaps[0] + this.width, y + this.height).right(gaps[1]).addTo(this);
1442 x += gaps[0];
1443
1444 var normal = this.items[this.normal];
1445
1446 // Do the elements that curve above
1447 var distanceFromY;
1448 for(var i = this.normal - 1; i >= 0; i--) {
1449 var item = this.items[i];
1450 if( i == this.normal - 1 ) {
1451 distanceFromY = Math.max(10 + Options.AR, normal.up + Options.VS + item.down + item.height);
1452 }
1453 new Path(x + 30,y)
1454 .up(distanceFromY - Options.AR)
1455 .arc('wn').addTo(this);
1456 item.format(x + 30 + Options.AR, y - distanceFromY, this.innerWidth).addTo(this);
1457 new Path(x + 30 + Options.AR + this.innerWidth, y - distanceFromY + item.height)
1458 .arc('ne')
1459 .down(distanceFromY - item.height + this.height - Options.AR - 10)
1460 .addTo(this);
1461 if(i !== 0) {
1462 distanceFromY += Math.max(Options.AR, item.up + Options.VS + this.items[i-1].down + this.items[i-1].height);
1463 }
1464 }
1465
1466 new Path(x + 30, y).right(Options.AR).addTo(this);
1467 normal.format(x + 30 + Options.AR, y, this.innerWidth).addTo(this);
1468 new Path(x + 30 + Options.AR + this.innerWidth, y + this.height).right(Options.AR).addTo(this);
1469
1470 for(i = this.normal+1; i < this.items.length; i++) {
1471 let item = this.items[i];
1472 if(i == this.normal + 1) {
1473 distanceFromY = Math.max(10+Options.AR, normal.height + normal.down + Options.VS + item.up);
1474 }
1475 new Path(x + 30, y)
1476 .down(distanceFromY - Options.AR)
1477 .arc('ws')
1478 .addTo(this);
1479 item.format(x + 30 + Options.AR, y + distanceFromY, this.innerWidth).addTo(this);
1480 new Path(x + 30 + Options.AR + this.innerWidth, y + distanceFromY + item.height)
1481 .arc('se')
1482 .up(distanceFromY - Options.AR + item.height - normal.height)
1483 .addTo(this);
1484 if(i != this.items.length - 1) {
1485 distanceFromY += Math.max(Options.AR, item.height + item.down + Options.VS + this.items[i+1].up);
1486 }
1487 }
1488 var text = new FakeSVG('g', {"class": "diagram-text"}).addTo(this);
1489 new FakeSVG('title', {}, (this.type=="any"?"take one or more branches, once each, in any order":"take all branches, once each, in any order")).addTo(text);
1490 new FakeSVG('path', {
1491 "d": "M "+(x+30)+" "+(y-10)+" h -26 a 4 4 0 0 0 -4 4 v 12 a 4 4 0 0 0 4 4 h 26 z",
1492 "class": "diagram-text"
1493 }).addTo(text);
1494 new FakeSVG('text', {
1495 "x": x + 15,
1496 "y": y + 4,
1497 "class": "diagram-text"
1498 }, (this.type=="any"?"1+":"all")).addTo(text);
1499 new FakeSVG('path', {
1500 "d": "M "+(x+this.width-20)+" "+(y-10)+" h 16 a 4 4 0 0 1 4 4 v 12 a 4 4 0 0 1 -4 4 h -16 z",
1501 "class": "diagram-text"
1502 }).addTo(text);
1503 new FakeSVG('path', {
1504 "d": "M "+(x+this.width-13)+" "+(y-2)+" a 4 4 0 1 0 6 -1 m 2.75 -1 h -4 v 4 m 0 -3 h 2",
1505 "style": "stroke-width: 1.75"
1506 }).addTo(text);
1507 return this;
1508 }
1509 toTextDiagram() {
1510 var [multi_repeat] = TextDiagram._getParts(["multi_repeat"]);
1511 if(this.type == "any") {
1512 var anyAll = TextDiagram.rect("1+");
1513 } else {
1514 anyAll = TextDiagram.rect("all");
1515 }
1516 var diagramTD = Choice.prototype.toTextDiagram.call(this);
1517 var repeatTD = TextDiagram.rect(multi_repeat);
1518 diagramTD = anyAll.appendRight(diagramTD, "");
1519 diagramTD = diagramTD.appendRight(repeatTD, "");
1520 return diagramTD;
1521 }
1522 }
1523 funcs.MultipleChoice = (...args)=>new MultipleChoice(...args);
1524
1525
1526 export class Optional extends FakeSVG {
1527 constructor(item, skip) {
1528 if( skip === undefined )
1529 return new Choice(1, new Skip(), item);
1530 else if ( skip === "skip" )
1531 return new Choice(0, new Skip(), item);
1532 else
1533 throw "Unknown value for Optional()'s 'skip' argument.";
1534 }
1535 }
1536 funcs.Optional = (...args)=>new Optional(...args);
1537
1538
1539 export class OneOrMore extends FakeSVG {
1540 constructor(item, rep) {
1541 super('g');
1542 rep = rep || (new Skip());
1543 this.item = wrapString(item);
1544 this.rep = wrapString(rep);
1545 this.width = Math.max(this.item.width, this.rep.width) + Options.AR*2;
1546 this.height = this.item.height;
1547 this.up = this.item.up;
1548 this.down = Math.max(Options.AR*2, this.item.down + Options.VS + this.rep.up + this.rep.height + this.rep.down);
1549 this.needsSpace = true;
1550 if(Options.DEBUG) {
1551 this.attrs['data-updown'] = this.up + " " + this.height + " " + this.down;
1552 this.attrs['data-type'] = "oneormore";
1553 }
1554 }
1555 format(x,y,width) {
1556 // Hook up the two sides if this is narrower than its stated width.
1557 var gaps = determineGaps(width, this.width);
1558 new Path(x,y).h(gaps[0]).addTo(this);
1559 new Path(x+gaps[0]+this.width,y+this.height).h(gaps[1]).addTo(this);
1560 x += gaps[0];
1561
1562 // Draw item
1563 new Path(x,y).right(Options.AR).addTo(this);
1564 this.item.format(x+Options.AR,y,this.width-Options.AR*2).addTo(this);
1565 new Path(x+this.width-Options.AR,y+this.height).right(Options.AR).addTo(this);
1566
1567 // Draw repeat arc
1568 var distanceFromY = Math.max(Options.AR*2, this.item.height+this.item.down+Options.VS+this.rep.up);
1569 new Path(x+Options.AR,y).arc('nw').down(distanceFromY-Options.AR*2).arc('ws').addTo(this);
1570 this.rep.format(x+Options.AR, y+distanceFromY, this.width - Options.AR*2).addTo(this);
1571 new Path(x+this.width-Options.AR, y+distanceFromY+this.rep.height).arc('se').up(distanceFromY-Options.AR*2+this.rep.height-this.item.height).arc('en').addTo(this);
1572
1573 return this;
1574 }
1575 toTextDiagram() {
1576 var [line, repeat_top_left, repeat_left, repeat_bot_left, repeat_top_right, repeat_right, repeat_bot_right] = TextDiagram._getParts(["line", "repeat_top_left", "repeat_left", "repeat_bot_left", "repeat_top_right", "repeat_right", "repeat_bot_right"]);
1577 // Format the item and then format the repeat append it to tbe bottom, after a spacer.
1578 var itemTD = this.item.toTextDiagram();
1579 var repeatTD = this.rep.toTextDiagram();
1580 var itemAndRepeatTD = itemTD.appendBelow(repeatTD, []);
1581 // Build the left side of the repeat line and append the combined item and repeat to its right.
1582 var leftLines = [];
1583 leftLines.push(repeat_top_left + line);
1584 for(var i = 0; i < ((itemTD.height - itemTD.entry) + repeatTD.entry - 1); i++) {
1585 leftLines.push(repeat_left + " ");
1586 }
1587 leftLines.push(repeat_bot_left + line);
1588 var leftTD = new TextDiagram(0, 0, leftLines);
1589 leftTD = leftTD.appendRight(itemAndRepeatTD, "");
1590 // Build the right side of the repeat line and append it to the combined left side, item, and repeat's right.
1591 var rightLines = [];
1592 rightLines.push(line + repeat_top_right);
1593 for(i = 0; i < ((itemTD.height - itemTD.exit) + repeatTD.exit - 1); i++) {
1594 rightLines.push(" " + repeat_right);
1595 }
1596 rightLines.push(line + repeat_bot_right);
1597 var rightTD = new TextDiagram(0, 0, rightLines);
1598 var diagramTD = leftTD.appendRight(rightTD, "");
1599 return diagramTD;
1600 }
1601 walk(cb) {
1602 cb(this);
1603 this.item.walk(cb);
1604 this.rep.walk(cb);
1605 }
1606 }
1607 funcs.OneOrMore = (...args)=>new OneOrMore(...args);
1608
1609
1610 export class ZeroOrMore extends FakeSVG {
1611 constructor(item, rep, skip) {
1612 return new Optional(new OneOrMore(item, rep), skip);
1613 }
1614 }
1615 funcs.ZeroOrMore = (...args)=>new ZeroOrMore(...args);
1616
1617
1618 export class Group extends FakeSVG {
1619 constructor(item, label) {
1620 super('g');
1621 this.item = wrapString(item);
1622 this.label =
1623 label instanceof FakeSVG
1624 ? label
1625 : label
1626 ? new Comment(label)
1627 : undefined;
1628
1629 this.width = Math.max(
1630 this.item.width + (this.item.needsSpace?20:0),
1631 this.label ? this.label.width : 0,
1632 Options.AR*2);
1633 this.height = this.item.height;
1634 this.boxUp = this.up = Math.max(this.item.up + Options.VS, Options.AR);
1635 if(this.label) {
1636 this.up += this.label.up + this.label.height + this.label.down;
1637 }
1638 this.down = Math.max(this.item.down + Options.VS, Options.AR);
1639 this.needsSpace = true;
1640 if(Options.DEBUG) {
1641 this.attrs['data-updown'] = this.up + " " + this.height + " " + this.down;
1642 this.attrs['data-type'] = "group";
1643 }
1644 }
1645 format(x, y, width) {
1646 var gaps = determineGaps(width, this.width);
1647 new Path(x,y).h(gaps[0]).addTo(this);
1648 new Path(x+gaps[0]+this.width,y+this.height).h(gaps[1]).addTo(this);
1649 x += gaps[0];
1650
1651 new FakeSVG('rect', {
1652 x,
1653 y:y-this.boxUp,
1654 width:this.width,
1655 height:this.boxUp + this.height + this.down,
1656 rx: Options.AR,
1657 ry: Options.AR,
1658 'class':'group-box',
1659 }).addTo(this);
1660
1661 this.item.format(x,y,this.width).addTo(this);
1662 if(this.label) {
1663 this.label.format(
1664 x,
1665 y-(this.boxUp+this.label.down+this.label.height),
1666 this.label.width).addTo(this);
1667 }
1668
1669 return this;
1670 }
1671 toTextDiagram() {
1672 var diagramTD = TextDiagram.roundrect(this.item.toTextDiagram(), true);
1673 if(this.label != undefined) {
1674 var labelTD = this.label.toTextDiagram();
1675 diagramTD = labelTD.appendBelow(diagramTD, [], true, true).expand(0, 0, 1, 0);
1676 }
1677 return diagramTD
1678 }
1679 walk(cb) {
1680 cb(this);
1681 this.item.walk(cb);
1682 this.label.walk(cb);
1683 }
1684 }
1685 funcs.Group = (...args)=>new Group(...args);
1686
1687
1688 export class Start extends FakeSVG {
1689 constructor({type="simple", label}={}) {
1690 super('g');
1691 this.width = 20;
1692 this.height = 0;
1693 this.up = 10;
1694 this.down = 10;
1695 this.type = type;
1696 if(label) {
1697 this.label = ""+label;
1698 this.width = Math.max(20, this.label.length * Options.CHAR_WIDTH + 10);
1699 }
1700 if(Options.DEBUG) {
1701 this.attrs['data-updown'] = this.up + " " + this.height + " " + this.down;
1702 this.attrs['data-type'] = "start";
1703 }
1704 }
1705 format(x,y) {
1706 let path = new Path(x, y-10);
1707 if (this.type === "complex") {
1708 path.down(20)
1709 .m(0, -10)
1710 .right(this.width)
1711 .addTo(this);
1712 } else {
1713 path.down(20)
1714 .m(10, -20)
1715 .down(20)
1716 .m(-10, -10)
1717 .right(this.width)
1718 .addTo(this);
1719 }
1720 if(this.label) {
1721 new FakeSVG('text', {x:x, y:y-15, style:"text-anchor:start"}, this.label).addTo(this);
1722 }
1723 return this;
1724 }
1725 toTextDiagram() {
1726 var [cross, line, tee_right] = TextDiagram._getParts(["cross", "line", "tee_right"])
1727 if (this.type === "simple") {
1728 var start = tee_right + cross + line;
1729 } else {
1730 start = tee_right + line;
1731 }
1732 var labelTD = new TextDiagram(0, 0, []);
1733 if (this.label != undefined) {
1734 labelTD = new TextDiagram(0, 0, [this.label]);
1735 start = TextDiagram._padR(start, labelTD.width, line);
1736 }
1737 var startTD = new TextDiagram(0, 0, [start]);
1738 return labelTD.appendBelow(startTD, [], true, true);
1739 }
1740 }
1741 funcs.Start = (...args)=>new Start(...args);
1742
1743
1744 export class End extends FakeSVG {
1745 constructor({type="simple"}={}) {
1746 super('path');
1747 this.width = 20;
1748 this.height = 0;
1749 this.up = 10;
1750 this.down = 10;
1751 this.type = type;
1752 if(Options.DEBUG) {
1753 this.attrs['data-updown'] = this.up + " " + this.height + " " + this.down;
1754 this.attrs['data-type'] = "end";
1755 }
1756 }
1757 format(x,y) {
1758 if (this.type === "complex") {
1759 this.attrs.d = 'M '+x+' '+y+' h 20 m 0 -10 v 20';
1760 } else {
1761 this.attrs.d = 'M '+x+' '+y+' h 20 m -10 -10 v 20 m 10 -20 v 20';
1762 }
1763 return this;
1764 }
1765 toTextDiagram() {
1766 var [cross, line, tee_left] = TextDiagram._getParts(["cross", "line", "tee_left"]);
1767 if (this.type === "simple") {
1768 var end = line + cross + tee_left;
1769 } else {
1770 end = line + tee_left;
1771 }
1772 return new TextDiagram(0, 0, [end]);
1773 }
1774 }
1775 funcs.End = (...args)=>new End(...args);
1776
1777
1778 export class Terminal extends FakeSVG {
1779 constructor(text, {href, title, cls}={}) {
1780 super('g', {'class': ['terminal', cls].join(" ")});
1781 this.text = ""+text;
1782 this.href = href;
1783 this.title = title;
1784 this.cls = cls;
1785 this.width = this.text.length * Options.CHAR_WIDTH + 20; /* Assume that each char is .5em, and that the em is 16px */
1786 this.height = 0;
1787 this.up = 11;
1788 this.down = 11;
1789 this.needsSpace = true;
1790 if(Options.DEBUG) {
1791 this.attrs['data-updown'] = this.up + " " + this.height + " " + this.down;
1792 this.attrs['data-type'] = "terminal";
1793 }
1794 }
1795 format(x, y, width) {
1796 // Hook up the two sides if this is narrower than its stated width.
1797 var gaps = determineGaps(width, this.width);
1798 new Path(x,y).h(gaps[0]).addTo(this);
1799 new Path(x+gaps[0]+this.width,y).h(gaps[1]).addTo(this);
1800 x += gaps[0];
1801
1802 new FakeSVG('rect', {x:x, y:y-11, width:this.width, height:this.up+this.down, rx:10, ry:10}).addTo(this);
1803 var text = new FakeSVG('text', {x:x+this.width/2, y:y+4}, this.text);
1804 if(this.href)
1805 new FakeSVG('a', {'xlink:href': this.href}, [text]).addTo(this);
1806 else
1807 text.addTo(this);
1808 if(this.title)
1809 new FakeSVG('title', {}, [this.title]).addTo(this);
1810 return this;
1811 }
1812 toTextDiagram() {
1813 // Note: href, title, and cls are ignored for text diagrams.
1814 return TextDiagram.roundrect(this.text);
1815 }
1816 }
1817 funcs.Terminal = (...args)=>new Terminal(...args);
1818
1819
1820 export class NonTerminal extends FakeSVG {
1821 constructor(text, {href, title, cls=""}={}) {
1822 super('g', {'class': ['non-terminal', cls].join(" ")});
1823 this.text = ""+text;
1824 this.href = href;
1825 this.title = title;
1826 this.cls = cls;
1827 this.width = this.text.length * Options.CHAR_WIDTH + 20;
1828 this.height = 0;
1829 this.up = 11;
1830 this.down = 11;
1831 this.needsSpace = true;
1832 if(Options.DEBUG) {
1833 this.attrs['data-updown'] = this.up + " " + this.height + " " + this.down;
1834 this.attrs['data-type'] = "nonterminal";
1835 }
1836 }
1837 format(x, y, width) {
1838 // Hook up the two sides if this is narrower than its stated width.
1839 var gaps = determineGaps(width, this.width);
1840 new Path(x,y).h(gaps[0]).addTo(this);
1841 new Path(x+gaps[0]+this.width,y).h(gaps[1]).addTo(this);
1842 x += gaps[0];
1843
1844 new FakeSVG('rect', {x:x, y:y-11, width:this.width, height:this.up+this.down}).addTo(this);
1845 var text = new FakeSVG('text', {x:x+this.width/2, y:y+4}, this.text);
1846 if(this.href)
1847 new FakeSVG('a', {'xlink:href': this.href}, [text]).addTo(this);
1848 else
1849 text.addTo(this);
1850 if(this.title)
1851 new FakeSVG('title', {}, [this.title]).addTo(this);
1852 return this;
1853 }
1854 toTextDiagram() {
1855 // Note: href, title, and cls are ignored for text diagrams.
1856 return TextDiagram.rect(this.text);
1857 }
1858 }
1859 funcs.NonTerminal = (...args)=>new NonTerminal(...args);
1860
1861
1862 export class Comment extends FakeSVG {
1863 constructor(text, {href, title, cls=""}={}) {
1864 super('g', {'class': ['comment', cls].join(" ")});
1865 this.text = ""+text;
1866 this.href = href;
1867 this.title = title;
1868 this.cls = cls;
1869 this.width = this.text.length * Options.COMMENT_CHAR_WIDTH + 10;
1870 this.height = 0;
1871 this.up = 8;
1872 this.down = 8;
1873 this.needsSpace = true;
1874 if(Options.DEBUG) {
1875 this.attrs['data-updown'] = this.up + " " + this.height + " " + this.down;
1876 this.attrs['data-type'] = "comment";
1877 }
1878 }
1879 format(x, y, width) {
1880 // Hook up the two sides if this is narrower than its stated width.
1881 var gaps = determineGaps(width, this.width);
1882 new Path(x,y).h(gaps[0]).addTo(this);
1883 new Path(x+gaps[0]+this.width,y+this.height).h(gaps[1]).addTo(this);
1884 x += gaps[0];
1885
1886 var text = new FakeSVG('text', {x:x+this.width/2, y:y+5, class:'comment'}, this.text);
1887 if(this.href)
1888 new FakeSVG('a', {'xlink:href': this.href}, [text]).addTo(this);
1889 else
1890 text.addTo(this);
1891 if(this.title)
1892 new FakeSVG('title', {}, this.title).addTo(this);
1893 return this;
1894 }
1895 toTextDiagram() {
1896 // Note: href, title, and cls are ignored for text diagrams.
1897 return new TextDiagram(0, 0, [this.text]);
1898 }
1899 }
1900 funcs.Comment = (...args)=>new Comment(...args);
1901
1902
1903 export class Skip extends FakeSVG {
1904 constructor() {
1905 super('g');
1906 this.width = 0;
1907 this.height = 0;
1908 this.up = 0;
1909 this.down = 0;
1910 this.needsSpace = false;
1911 if(Options.DEBUG) {
1912 this.attrs['data-updown'] = this.up + " " + this.height + " " + this.down;
1913 this.attrs['data-type'] = "skip";
1914 }
1915 }
1916 format(x, y, width) {
1917 new Path(x,y).right(width).addTo(this);
1918 return this;
1919 }
1920 toTextDiagram() {
1921 var [line] = TextDiagram._getParts(["line"]);
1922 return new TextDiagram(0, 0, [line]);
1923 }
1924 }
1925 funcs.Skip = (...args)=>new Skip(...args);
1926
1927
1928 export class Block extends FakeSVG {
1929 constructor({width=50, up=15, height=25, down=15, needsSpace=true}={}) {
1930 super('g');
1931 this.width = width;
1932 this.height = height;
1933 this.up = up;
1934 this.down = down;
1935 this.needsSpace = true;
1936 if(Options.DEBUG) {
1937 this.attrs['data-updown'] = this.up + " " + this.height + " " + this.down;
1938 this.attrs['data-type'] = "block";
1939 }
1940 }
1941 format(x, y, width) {
1942 // Hook up the two sides if this is narrower than its stated width.
1943 var gaps = determineGaps(width, this.width);
1944 new Path(x,y).h(gaps[0]).addTo(this);
1945 new Path(x+gaps[0]+this.width,y).h(gaps[1]).addTo(this);
1946 x += gaps[0];
1947
1948 new FakeSVG('rect', {x:x, y:y-this.up, width:this.width, height:this.up+this.height+this.down}).addTo(this);
1949 return this;
1950 }
1951 toTextDiagram() {
1952 return TextDiagram.rect("");
1953 }
1954 }
1955 funcs.Block = (...args)=>new Block(...args);
1956
1957 export class TextDiagram {
1958 constructor(entry, exit, lines) {
1959 // entry: The entry line for this diagram-part.
1960 this.entry = entry;
1961 // exit: The exit line for this diagram-part.
1962 this.exit = exit;
1963 // height: The height of this diagram-part, in lines.
1964 this.height = lines.length;
1965 // lines[]: The visual data of this diagram-part. Each line must be the same length.
1966 this.lines = Array.from(lines);
1967 // width: The width of this diagram-part, in character cells.
1968 this.width = lines.length > 0 ? lines[0].length : 0;
1969 if(entry > lines.length) {
1970 throw new Error("Entry is not within diagram vertically:\n" + this._dump(false));
1971 }
1972 if(exit > lines.length) {
1973 throw new Error("Exit is not within diagram vertically:\n" + this._dump(false));
1974 }
1975 for(var i=0; i < lines.length; i++) {
1976 if(lines[0].length != lines[i].length) {
1977 throw new Error("Diagram data is not rectangular:\n" + this._dump(false));
1978 }
1979 }
1980 }
1981 toString() {
1982 return this.lines.join("\n")+"\n";
1983 }
1984 alter({entry, exit, lines}) {
1985 /*
1986 Create and return a new TextDiagram based on this instance, with the specified changes.
1987 */
1988 var newEntry = entry || this.entry;
1989 var newExit = exit || this.exit;
1990 var newLines = lines || this.lines;
1991 return new TextDiagram(newEntry, newExit, Array.from(newLines));
1992 }
1993 appendBelow(item, linesBetween, moveEntry=false, moveExit=false) {
1994 /*
1995 Create and return a new TextDiagram by appending the specified lines below this instance's data,
1996 and then appending the specified TextDiagram below those lines, possibly setting the resulting
1997 TextDiagram's entry and or exit indices to those of the appended item.
1998 */
1999 var newWidth = Math.max(this.width, item.width);
2000 var item1 = this.expandWidth(newWidth);
2001 var item2 = item.expandWidth(newWidth);
2002 var linesBetween = linesBetween.map(x=>TextDiagram._padR(x, newWidth, " "));
2003 var newLines = [...item1.lines, ...linesBetween, ...item2.lines];
2004
2005 var newEntry = moveEntry ? this.height + linesBetween.length + item.entry : this.entry;
2006 var newExit = moveExit ? this.height + linesBetween.length + item.exit : this.exit;
2007 return new TextDiagram(newEntry, newExit, newLines);
2008 }
2009 appendRight(item, charsBetween) {
2010 /*
2011 Create and return a new TextDiagram by appending the specified TextDiagram to the right of this instance's data,
2012 aligning the left-hand exit and the right-hand entry points. The charsBetween are inserted between the left-exit
2013 and right-entry, and equivalent spaces on all other lines.
2014 */
2015 var joinLine = Math.max(this.exit, item.entry);
2016 var newHeight = Math.max(this.height - this.exit, item.height - item.entry) + joinLine;
2017 var leftTopAdd = joinLine - this.exit;
2018 var leftBotAdd = newHeight - this.height - leftTopAdd;
2019 var rightTopAdd = joinLine - item.entry;
2020 var rightBotAdd = newHeight - item.height - rightTopAdd;
2021 var left = this.expand(0, 0, leftTopAdd, leftBotAdd);
2022 var right = item.expand(0, 0, rightTopAdd, rightBotAdd);
2023 var newLines = [];
2024 for(var i = 0; i < newHeight; i++) {
2025 var sep = i != joinLine ? " ".repeat(charsBetween.length) : charsBetween;
2026 newLines.push((left.lines[i] + sep + right.lines[i]));
2027 }
2028 var newEntry = this.entry + leftTopAdd;
2029 var newExit = item.exit + rightTopAdd;
2030 return new TextDiagram(newEntry, newExit, newLines);
2031 }
2032 expandWidth(newWidth) {
2033 if(newWidth < this.width) {
2034 throw new Error(`Cannot expandWidth() to a smaller width (changing ${this.width} to ${newWidth})`);
2035 }
2036 if(newWidth == this.width) {
2037 return this.copy();
2038 }
2039 var [leftGap, rightGap] = TextDiagram._gaps(newWidth, this.width);
2040 var line = TextDiagram.parts["line"];
2041 var lefts = [];
2042 var rights = [];
2043 for(var i = 0; i < this.height; i++) {
2044 var leftChar = (this.entry == i) ? line : " ";
2045 var rightChar = (this.exit == i) ? line : " ";
2046 lefts.push(leftChar.repeat(leftGap));
2047 rights.push(rightChar.repeat(rightGap));
2048 }
2049 return this.alter({lines:TextDiagram._encloseLines(this.lines, lefts, rights)});
2050
2051 }
2052 expandHeight(newHeight) {
2053 if(newHeight < this.height) {
2054 throw new Error(`Cannot expandHeight() to a smaller width (changing ${this.width} to ${newWidth})`);
2055 }
2056 if(newHeight == this.height) {
2057 return this.copy();
2058 }
2059 var [topGap, bottomGap] = TextDiagram._gaps(this.height, newHeight, "center");
2060 var newLines = [];
2061 for(var i = 0; i < topGap; i++) {
2062 newLines.push(" ".repeat(this.width));
2063 }
2064 newLines.extend(this.lines);
2065 for(var i = 0; i < bottomGap; i++) {
2066 newLines.push(" ".repeat(this.width));
2067 }
2068 return new TextDiagram(this.entry+topGap, this.exit+topGap, newLines);
2069
2070 }
2071 center(width, pad) {
2072 /*
2073 Create and return a new TextDiagram by centering the data of this instance within a new, equal or larger width.
2074 */
2075 if(width < this.width) {
2076 throw new Error("Cannot center into smaller width")
2077 }
2078 if(width === this.width) {
2079 return this.copy();
2080 }
2081 var [leftGap, rightGap] = TextDiagram._gaps(this.width, width);
2082 var lefts = [];
2083 var rights = [];
2084 for (var i = 0; i < this.height; i++) {
2085 lefts.push(pad.repeat(leftGap));
2086 rights.push(pad.repeat(rightGap));
2087 }
2088 for (i = 0; i < this.height; i++) {
2089 }
2090 return this.alter({lines:TextDiagram._encloseLines(this.lines, lefts, rights)});
2091 }
2092 copy() {
2093 /*
2094 Create and return a new TextDiagram by copying this instance's data.
2095 */
2096 return new TextDiagram(this.entry, this.exit, Array.from(this.lines));
2097 }
2098 expand(left, right, top, bottom) {
2099 /*
2100 Create and return a new TextDiagram by expanding this instance's data by the specified amount in the specified directions.
2101 */
2102 if(left < 0 || right < 0 || top < 0 || bottom < 0) {
2103 throw new Error("Expansion values cannot be negative");
2104 }
2105 if(left + right + top + bottom === 0) {
2106 return this.copy();
2107 }
2108 var line = TextDiagram.parts["line"];
2109 var newLines = [];
2110 for(var i = 0; i < top; i++) {
2111 newLines.push(" ".repeat(this.width + left + right));
2112 }
2113 for(i = 0; i < this.height; i++){
2114 var leftExpansion = i === this.entry ? line : " ";
2115 var rightExpansion = i === this.exit ? line : " ";
2116 newLines.push(leftExpansion.repeat(left) + this.lines[i] + rightExpansion.repeat(right));
2117 }
2118 for(i = 0; i < bottom; i++) {
2119 newLines.push(" ".repeat(this.width + left + right));
2120 }
2121 return new TextDiagram(this.entry + top, this.exit + top, newLines);
2122 }
2123 static rect(item, dashed=false) {
2124 /*
2125 Create and return a new TextDiagram for a rectangular box.
2126 */
2127 return TextDiagram._rectish("rect", item, dashed);
2128 }
2129 static roundrect(item, dashed=false) {
2130 /*
2131 Create and return a new TextDiagram for a rectangular box with rounded corners.
2132 */
2133 return TextDiagram._rectish("roundrect", item, dashed);
2134 }
2135 static setFormatting(characters = null, defaults = null) {
2136 /*
2137 Set the characters to use for drawing text diagrams.
2138 */
2139 if(characters !== null) {
2140 TextDiagram.parts = {}
2141 if(defaults !== null){
2142 TextDiagram.parts = {...TextDiagram.parts, ...defaults}
2143 }
2144 TextDiagram.parts = {...TextDiagram.parts, ...characters}
2145 }
2146 for(const [name, value] of TextDiagram.parts) {
2147 if(value.length != 1) {
2148 "Text part " + name + " is more than 1 character: " + value;
2149 }
2150 }
2151 }
2152 _dump(show=true) {
2153 /*
2154 Dump out the data of this instance for debugging, either displaying or returning it.
2155 DO NOT use this for actual work, only for debugging or in assertion output.
2156 */
2157 var nl = "\n" // f-strings can't contain \n until Python 3.12;
2158 var result = "height=" + this.height + " lines.length=" + this.lines.length;
2159 if(this.entry > this.lines.length) {
2160 result += "; entry outside diagram: entry=" + this.entry;
2161 }
2162 if(this.exit > this.lines.length) {
2163 result += "; exit outside diagram: exit=" + this.exit;
2164 }
2165 for(var y = 0; y < Math.max(this.lines.length, this.entry + 1, this.exit + 1); y++) {
2166 result = result + nl + "[" + ("00" + y).slice(-3) + "]";
2167 if(y < this.lines.length) {
2168 result += (" '" + this.lines[y] + "' len=" + this.lines[y].length);
2169 }
2170 if(y === this.entry && y === this.exit) {
2171 result += " <- entry, exit";
2172 } else if(y === this.entry) {
2173 result += " <- entry";
2174 } else if(y === this.exit) {
2175 result += " <- exit";
2176 }
2177 }
2178 if(show) {
2179 console.log(result);
2180 }
2181 return result;
2182 }
2183 static _encloseLines(lines, lefts, rights) {
2184 /*
2185 Join the lefts, lines, and rights arrays together, line-by-line, and return the result.
2186 */
2187 if(lines.length != lefts.length) {
2188 throw new Error("All arguments must be the same length");
2189 }
2190 if(lines.length != rights.length) {
2191 throw new Error("All arguments must be the same length");
2192 }
2193 var newLines = [];
2194 for(var i = 0; i < lines.length; i++) {
2195 newLines.push(lefts[i] + lines[i] + rights[i]);
2196 }
2197 return newLines;
2198 }
2199 static _gaps(outerWidth, innerWidth, alignment) {
2200 /*
2201 Return the left and right pad spacing based on the alignment configuration setting.
2202 */
2203 var diff = outerWidth - innerWidth;
2204 if(diff < 0) {
2205 console.error(`Larger innerWidth (${innerWidth}) than outerWidth (${outerWidth})`)
2206 }
2207 alignment = unnull(alignment, Options.INTERNAL_ALIGNMENT);
2208 if(alignment === "left") {
2209 return [0, diff];
2210 } else if(alignment === "right") {
2211 return [diff, 0];
2212 } else {
2213 var left = Math.trunc(diff / 2);
2214 var right = diff - left;
2215 return [left, right];
2216 }
2217 }
2218 static _getParts(partNames) {
2219 /*
2220 Return a list of text diagram drawing characters for the specified character names.
2221 */
2222 var result = [];
2223 for(const name of partNames) {
2224 if(TextDiagram.parts[name] == undefined) {
2225 throw new Error("Text diagram part " + name + "not found.")
2226 }
2227 result.push(TextDiagram.parts[name]);
2228 }
2229 return result;
2230 }
2231 static _maxWidth(...args) {
2232 /*
2233 Return the maximum width of all of the arguments.
2234 */
2235 var maxWidth = 0;
2236 for(const arg of args) {
2237 if(arg instanceof TextDiagram) {
2238 var width = arg.width;
2239 } else if(arg instanceof Array) {
2240 width = Math.max(arg.map(function(e) { return e.length;}));
2241 } else if(Number.isInteger(arg)) {
2242 width = Number.toString(arg).length;
2243 } else {
2244 width = arg.length;
2245 }
2246 maxWidth = width > maxWidth ? width : maxWidth;
2247 }
2248 return maxWidth;
2249 }
2250 static _padL(string, width, pad) {
2251 /*
2252 Pad the specified string on the left to the specified width with the specified pad string and return the result.
2253 */
2254 if((width - string.length) % pad.length != 0) {
2255 throw new Error("Gap " + (width - string.length) + " must be a multiple of pad string '" + pad + "'");
2256 }
2257 return pad.repeat(Math.trunc((width - string.length / pad.length))) + string;
2258 }
2259 static _padR(string, width, pad) {
2260 /*
2261 Pad the specified string on the right to the specified width with the specified pad string and return the result.
2262 */
2263 if((width - string.length) % pad.length != 0) {
2264 throw new Error("Gap " + (width - string.length) + " must be a multiple of pad string '" + pad + "'");
2265 }
2266 return string + pad.repeat(Math.trunc((width - string.length / pad.length)));
2267 }
2268 static _rectish(rectType, data, dashed=false) {
2269 /*
2270 Create and return a new TextDiagram for a rectangular box surrounding the specified TextDiagram, using the
2271 specified set of drawing characters (i.e., "rect" or "roundrect"), and possibly using dashed lines.
2272 */
2273 var lineType = dashed ? "_dashed" : "";
2274 var [topLeft, ctrLeft, botLeft, topRight, ctrRight, botRight, topHoriz, botHoriz, line, cross] = TextDiagram._getParts([rectType + "_top_left", rectType + "_left" + lineType, rectType + "_bot_left", rectType + "_top_right", rectType + "_right" + lineType, rectType + "_bot_right", rectType + "_top" + lineType, rectType + "_bot" + lineType, "line", "cross"]);
2275 var itemWasFormatted = data instanceof TextDiagram;
2276 if(itemWasFormatted) {
2277 var itemTD = data;
2278 } else {
2279 itemTD = new TextDiagram(0, 0, [data]);
2280 }
2281 // Create the rectangle and enclose the item in it.
2282 var lines = [];
2283 lines.push(topHoriz.repeat(itemTD.width + 2));
2284 if(itemWasFormatted) {
2285 lines += itemTD.expand(1, 1, 0, 0).lines;
2286 } else {
2287 for(var i = 0; i < itemTD.lines.length; i++) {
2288 lines.push(" " + itemTD.lines[i] + " ");
2289 }
2290 }
2291 lines.push(botHoriz.repeat(itemTD.width + 2));
2292 var entry = itemTD.entry + 1;
2293 var exit = itemTD.exit + 1;
2294 var leftMaxWidth = TextDiagram._maxWidth(topLeft, ctrLeft, botLeft);
2295 var lefts = [];
2296 lefts.push(TextDiagram._padR(topLeft, leftMaxWidth, topHoriz));
2297 for(i = 1; i < (lines.length - 1); i++) {
2298 lefts.push(TextDiagram._padR(ctrLeft, leftMaxWidth, " "));
2299 }
2300 lefts.push(TextDiagram._padR(botLeft, leftMaxWidth, botHoriz));
2301 if(itemWasFormatted) {
2302 lefts[entry] = cross;
2303 }
2304 var rightMaxWidth = TextDiagram._maxWidth(topRight, ctrRight, botRight);
2305 var rights = [];
2306 rights.push(TextDiagram._padL(topRight, rightMaxWidth, topHoriz));
2307 for(i = 1; i < (lines.length - 1); i++) {
2308 rights.push(TextDiagram._padL(ctrRight, rightMaxWidth, " "));
2309 }
2310 rights.push(TextDiagram._padL(botRight, rightMaxWidth, botHoriz));
2311 if(itemWasFormatted) {
2312 rights[exit] = cross;
2313 }
2314 // Build the entry and exit perimeter.
2315 lines = TextDiagram._encloseLines(lines, lefts, rights);
2316 lefts = [];
2317 for(i = 0; i < lines.length; i++) {
2318 lefts.push(" ");
2319 }
2320 lefts[entry] = line;
2321 rights = [];
2322 for(i = 0; i < lines.length; i++) {
2323 rights.push(" ");
2324 }
2325 rights[exit] = line;
2326 lines = TextDiagram._encloseLines(lines, lefts, rights);
2327 return new TextDiagram(entry, exit, lines);
2328 }
2329 // Note: All the drawing sequences below MUST be single characters. setFormatting() checks this.
2330 // Unicode 25xx box drawing characters, plus a few others.
2331 static PARTS_UNICODE = {
2332 "cross_diag" : "\u2573",
2333 "corner_bot_left" : "\u2514",
2334 "corner_bot_right" : "\u2518",
2335 "corner_top_left" : "\u250c",
2336 "corner_top_right" : "\u2510",
2337 "cross" : "\u253c",
2338 "left" : "\u2502",
2339 "line" : "\u2500",
2340 "line_vertical" : "\u2502",
2341 "multi_repeat" : "\u21ba",
2342 "rect_bot" : "\u2500",
2343 "rect_bot_dashed" : "\u2504",
2344 "rect_bot_left" : "\u2514",
2345 "rect_bot_right" : "\u2518",
2346 "rect_left" : "\u2502",
2347 "rect_left_dashed" : "\u2506",
2348 "rect_right" : "\u2502",
2349 "rect_right_dashed" : "\u2506",
2350 "rect_top" : "\u2500",
2351 "rect_top_dashed" : "\u2504",
2352 "rect_top_left" : "\u250c",
2353 "rect_top_right" : "\u2510",
2354 "repeat_bot_left" : "\u2570",
2355 "repeat_bot_right" : "\u256f",
2356 "repeat_left" : "\u2502",
2357 "repeat_right" : "\u2502",
2358 "repeat_top_left" : "\u256d",
2359 "repeat_top_right" : "\u256e",
2360 "right" : "\u2502",
2361 "roundcorner_bot_left" : "\u2570",
2362 "roundcorner_bot_right" : "\u256f",
2363 "roundcorner_top_left" : "\u256d",
2364 "roundcorner_top_right" : "\u256e",
2365 "roundrect_bot" : "\u2500",
2366 "roundrect_bot_dashed" : "\u2504",
2367 "roundrect_bot_left" : "\u2570",
2368 "roundrect_bot_right" : "\u256f",
2369 "roundrect_left" : "\u2502",
2370 "roundrect_left_dashed" : "\u2506",
2371 "roundrect_right" : "\u2502",
2372 "roundrect_right_dashed" : "\u2506",
2373 "roundrect_top" : "\u2500",
2374 "roundrect_top_dashed" : "\u2504",
2375 "roundrect_top_left" : "\u256d",
2376 "roundrect_top_right" : "\u256e",
2377 "separator" : "\u2500",
2378 "tee_left" : "\u2524",
2379 "tee_right" : "\u251c",
2380 };
2381 // Plain old ASCII characters.
2382 static PARTS_ASCII = {
2383 "cross_diag" : "X",
2384 "corner_bot_left" : "\\",
2385 "corner_bot_right" : "/",
2386 "corner_top_left" : "/",
2387 "corner_top_right" : "\\",
2388 "cross" : "+",
2389 "left" : "|",
2390 "line" : "-",
2391 "line_vertical" : "|",
2392 "multi_repeat" : "&",
2393 "rect_bot" : "-",
2394 "rect_bot_dashed" : "-",
2395 "rect_bot_left" : "+",
2396 "rect_bot_right" : "+",
2397 "rect_left" : "|",
2398 "rect_left_dashed" : "|",
2399 "rect_right" : "|",
2400 "rect_right_dashed" : "|",
2401 "rect_top_dashed" : "-",
2402 "rect_top" : "-",
2403 "rect_top_left" : "+",
2404 "rect_top_right" : "+",
2405 "repeat_bot_left" : "\\",
2406 "repeat_bot_right" : "/",
2407 "repeat_left" : "|",
2408 "repeat_right" : "|",
2409 "repeat_top_left" : "/",
2410 "repeat_top_right" : "\\",
2411 "right" : "|",
2412 "roundcorner_bot_left" : "\\",
2413 "roundcorner_bot_right" : "/",
2414 "roundcorner_top_left" : "/",
2415 "roundcorner_top_right" : "\\",
2416 "roundrect_bot" : "-",
2417 "roundrect_bot_dashed" : "-",
2418 "roundrect_bot_left" : "\\",
2419 "roundrect_bot_right" : "/",
2420 "roundrect_left" : "|",
2421 "roundrect_left_dashed" : "|",
2422 "roundrect_right" : "|",
2423 "roundrect_right_dashed" : "|",
2424 "roundrect_top" : "-",
2425 "roundrect_top_dashed" : "-",
2426 "roundrect_top_left" : "/",
2427 "roundrect_top_right" : "\\",
2428 "separator" : "-",
2429 "tee_left" : "|",
2430 "tee_right" : "|",
2431 };
2432
2433 // Characters to use in drawing diagrams. See setFormatting(), PARTS_ASCII, and PARTS_UNICODE.
2434 static parts = TextDiagram.PARTS_UNICODE;
2435
2436 }
2437
2438 function unnull(...args) {
2439 // Return the first value that isn't undefined.
2440 // More correct than `v1 || v2 || v3` because falsey values will be returned.
2441 return args.reduce(function(sofar, x) { return sofar !== undefined ? sofar : x; });
2442 }
2443
2444 function determineGaps(outer, inner) {
2445 var diff = outer - inner;
2446 switch(Options.INTERNAL_ALIGNMENT) {
2447 case 'left': return [0, diff];
2448 case 'right': return [diff, 0];
2449 default: return [diff/2, diff/2];
2450 }
2451 }
2452
2453 function wrapString(value) {
2454 return value instanceof FakeSVG ? value : new Terminal(""+value);
2455 }
2456
2457 function sum(iter, func) {
2458 if(!func) func = function(x) { return x; };
2459 return iter.map(func).reduce(function(a,b){return a+b}, 0);
2460 }
2461
2462 function max(iter, func=x=>x) {
2463 return Math.max.apply(null, iter.map(func));
2464 }
2465
2466 function SVG(name, attrs, text) {
2467 attrs = attrs || {};
2468 text = text || '';
2469 var el = document.createElementNS("http://www.w3.org/2000/svg",name);
2470 for(var attr in attrs) {
2471 if(attr === 'xlink:href')
2472 el.setAttributeNS("http://www.w3.org/1999/xlink", 'href', attrs[attr]);
2473 else
2474 el.setAttribute(attr, attrs[attr]);
2475 }
2476 el.textContent = text;
2477 return el;
2478 }
2479
2480 function escapeString(string) {
2481 // Escape markdown and HTML special characters
2482 return string.replace(/[*_\`\[\]<&]/g, function(charString) {
2483 return '&#' + charString.charCodeAt(0) + ';';
2484 });
2485 }
2486
2487 function* enumerate(iter) {
2488 var count = 0;
2489 for(const x of iter) {
2490 yield [count, x];
2491 count++;
2492 }
2493 }