-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathPinker.js
More file actions
3703 lines (3598 loc) · 127 KB
/
Pinker.js
File metadata and controls
3703 lines (3598 loc) · 127 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Pinker: A standalone JavaScript library for rendering code dependency diagrams on your web page.
* Github: https://github.com/WithoutHaste/Pinker
*/
var pinker = pinker || {};
pinker.testMode = true;
pinker.version = '1.4.0';
pinker.config = {
fontSize: 14 //font size in pixels
,fontFamily: "Georgia"
,scopeMargin: 30 //minimum space around each scope
,scopePadding: 15 //minimum space between scope boundary and nested scopes
,labelPadding: 10 //minimum space between scope boundary and text areas
,canvasPadding: 15 //minimum space between canvas boundary and scopes
,backgroundColor: "#FFFFFF" //white
,shadeColor: "#EEEEEE" //pale gray
,lineColor: "#000000" //black
,lineWeight: 1 //line weight in pixels
,lineDashLength: 6 //length of a dash in pixels
,lineDashSpacing: 4 //length of space between dashes in pixels
,arrowHeadArea: 50 //pixels-squared area of an arrow head
,font: function() {
return this.fontSize + "px " + this.fontFamily;
}
,estimateFontHeight: function() {
return this.fontSize;
}
,lineSpacing: function() {
return this.estimateFontHeight() * 0.4;
}
,favorGoldenRatioLabelSize: true
,favorUniformNodeSizes: true
,useSmartArrows: true
,keepSource: false
};
/*private scope*/
(function() {
//render all sources onto new canvases
pinker.render = function(options={}) {
let pinkerElements = document.getElementsByClassName("pinker");
for(let i = 0; i < pinkerElements.length; i++)
{
let pinkerElement = pinkerElements[i];
switch(pinkerElement.tagName)
{
case "PRE": renderFromPre(pinkerElement, options); break;
default: displayError("unknown tag skipped (id:"+pinkerElement.id+")"); break;
}
}
};
function renderFromPre(preElement, options={}) {
Object.assign(pinker.config, options);
const sourceText = preElement.innerHTML;
const canvasElement = document.createElement("canvas");
if(preElement.id != null)
canvasElement.id = "canvas-" + preElement.id;
if(pinker.config.keepSource)
{
//insert canvas after pre element
preElement.parentNode.insertBefore(canvasElement, preElement.nextSibling); //verified nextSibling doesn't have to exist
}
else
{
//insert canvas into pre element
preElement.innerHTML = null;
preElement.appendChild(canvasElement);
}
pinker.draw(canvasElement, sourceText);
}
//works in FireFox but fails in Chrome due to CORS (cross-site data access rules)
function renderFromObject(objectElement, options={}) {
Object.assign(pinker.config, options);
const sourceDocument = objectElement.contentDocument || objectElement.contentWindow.document;
let container = sourceDocument.getElementsByTagName('body')[0];
while(container.children.length > 0)
{
container = container.children[0];
}
const sourceText = container.innerHTML;
const canvasElement = document.createElement("canvas");
if(objectElement.id != null)
canvasElement.id = "canvas-" + objectElement.id;
if(pinker.config.keepSource)
{
//insert canvas after object element
objectElement.parentNode.insertBefore(canvasElement, objectElement.nextSibling); //verified nextSibling doesn't have to exist
}
else
{
//replace object element with canvas
objectElement.parentNode.insertBefore(canvasElement, objectElement);
objectElement.parentNode.removeChild(objectElement);
}
pinker.draw(canvasElement, sourceText);
}
//draw on provided canvas with provided source
pinker.draw = function(canvasElement, sourceText, options={}) {
Object.assign(pinker.config, options);
sourceText = Source.decodeHtml(sourceText);
const source = parseSource(sourceText);
if(source.hasErrors)
{
source.errorMessages.forEach(function(errorMessage) {
console.log(`Pinker Error on canvas '${canvasElement.id}': ${errorMessage}`);
});
}
//displays what it can, despite errors
updateCanvas(canvasElement, source);
};
function displayError(message) {
console.log("Pinker Error: " + message);
}
const Text = {
//returns true for empty string, null, or undefined
isBlank: function(text) {
return (text == undefined || text == null || text.length == 0);
},
reverse: function(text) {
if(text == null)
return null;
return text.split("").reverse().join("");
},
removeFromStart: function(text, start) {
if(text.startsWith(start))
return text.substring(start.length);
return text;
},
removeEnclosingCharacters: function(text, startChar, endChar=null) {
if(endChar == null)
endChar = startChar;
if(text == null || text.length == 0)
return text;
if(text[0] == startChar)
text = text.substring(1);
if(text.length == 0)
return text;
if(text[text.length-1] == endChar)
text = text.substring(0, text.length-1);
return text;
}
};
const Source = {
//returns the text, with all HTML character encodings converted to plain text
decodeHtml: function(text) {
var element = document.createElement("textarea");
element.innerHTML = text;
return element.value;
},
//returns the text, with all leading and trailing whitespace characters removed from each line
trim: function(text) {
let result = Source.removeLeadingWhitespace(text);
result = Source.removeTrailingWhitespace(result);
return result;
},
//returns the text, with all leading whitespace characters removed from each line
removeLeadingWhitespace: function(text) {
return text.replace(/^\s+/mg,"");
},
//returns the text, with all trailing whitespace characters removed from each line
removeTrailingWhitespace: function(text) {
return text.replace(/\s+$/mg,"");
},
//returns true if this is a section header
isSectionHeader: function(term) {
if(term == null)
return false;
return ((term.match(/^.+\:$/) != null) && !RelateRecord.isRelateRowEndingInColon(term));
},
//returns true if term is a scope
isScope: function(term) {
if(term == null)
return false;
return (term.match(/^\[.+\]$/) != null);
},
//returns true if term is an alias
isAlias: function(term) {
if(term == null)
return false;
return(term.match(/^\{.+\}$/) != null);
},
//returns true if term is a path that starts with an alias
isAliasPath: function(term) {
if(term == null)
return false;
return (this.isAlias(term) || term.match(/^\{.+\}\./) != null);
},
//extracts the header from a section header
parseHeader: function(line) {
const matches = line.match(/^(.+)\:$/);
if(matches == null)
return line;
return matches[1].trim();
},
//returns a scope without the enclosing [], if they exist
openScope: function(scope) {
const matches = scope.match(/^\[(.+)\]$/);
if(matches == null)
return scope;
return matches[1].trim();
},
//returns true if the first term in the path is an alias
//returns false if the entire path is one alias
pathStartsWithAlias: function(path) {
return (path.match(/^\{.+?\}\./) != null);
},
//returns [alias, remainingPath]
splitAliasFromPath: function(path) {
if(!this.pathStartsWithAlias(path))
return path;
let matches = path.match(/^(\{.+?\})\.(.*)$/);
return [matches[1], matches[2]];
},
//returns a new source object
create: function(label=null) {
return {
label: label, //Level 1 has no label
alias: null,
hasErrors: false,
errorMessages: [],
define: null,
layout: null,
relate: null,
nestedSources: [],
getPathSegment: function() {
return (this.alias == null) ? this.label : this.alias;
},
appendToPath: function(prefix=null) {
if(prefix == null)
return this.getPathSegment();
if(this.alias != null)
return this.getPathSegment();
return prefix + "." + this.getPathSegment();
},
validate: function() {
if(this.layout == null && this.define == null)
{
this.hasErrors = true;
this.errorMessages.push("No layout OR define section.");
}
let self = this;
this.nestedSources.forEach(function(nestedSource) {
nestedSource.validate();
if(nestedSource.hasErrors)
{
self.hasErrors = true;
nestedSource.errorMessages.forEach(function(errorMessage) {
self.errorMessages.push(`${errorMessage} Section: '${nestedSource.label}'.`);
});
}
});
},
addSections: function(sections) {
let self = this;
sections.forEach(function(section) {
if(section.isReferenceSection)
{
if(Source.isAlias(section.reference))
{
let success = self.addAliasedNestedSource(section.reference, section.sections);
if(!success)
{
self.hasErrors = true;
self.errorMessages.push(`Cannot find alias '${section.reference}'.`);
}
}
else if(Source.pathStartsWithAlias(section.reference))
{
let [alias, label] = Source.splitAliasFromPath(section.reference);
let aliasedSource = self.findAliasedSource(alias);
if(aliasedSource == null)
{
self.hasErrors = true;
self.errorMessages.push(`Cannot find alias '${alias}'.`);
}
else
{
section.reference = Source.openScope(label);
aliasedSource.addSections([section]);
}
}
else
{
self.addNestedSource(section.reference, section.sections);
}
}
else
{
self.addSection(section);
}
});
},
addSection: function(section) {
switch(section.header)
{
case "define":
case "Define":
case "DEFINE":
if(this.define != null)
return;
this.define = parseDefineSection(section);
break;
case "layout":
case "Layout":
case "LAYOUT":
if(this.layout != null)
return;
this.layout = parseLayoutSection(section);
break;
case "relate":
case "Relate":
case "RELATE":
if(this.relate != null)
return;
this.relate = parseRelateSection(section);
break;
}
},
addNestedSource: function(label, sections) {
if(label.length == 0)
return; //invalid label
const isAlias = (label.match(/^\{.+\}$/) != null);
for(let i=0; i < this.nestedSources.length; i++)
{
let nestedSource = this.nestedSources[i];
if(nestedSource.label == label)
return; //skip it, it belongs here but we already have one
let labelStart = nestedSource.label + ".";
if(label.startsWith(labelStart))
{
let subLabel = label.substring(labelStart.length);
nestedSource.addNestedSource(subLabel, sections);
return;
}
}
let nestedSource = Source.create(label);
nestedSource.addSections(sections);
this.nestedSources.push(nestedSource);
},
//returns true when alias is found
addAliasedNestedSource: function(alias, sections) {
if(this.alias == alias)
return true; //skip it, we already have one
let layoutRecord = this.layout.findAlias(alias);
if(layoutRecord != null)
{
let nestedSource = Source.create(layoutRecord.label);
nestedSource.alias = alias;
nestedSource.addSections(sections);
this.nestedSources.push(nestedSource);
return true;
}
for(let i=0; i<this.nestedSources.length; i++)
{
let nestedSource = this.nestedSources[i];
let result = nestedSource.addAliasedNestedSource(alias, sections);
if(result)
return true;
}
return false;
},
//returns the nested source with alias or label
findSource: function(label, alias=null) {
if(alias == null)
return this.findLabeledSource(label);
return this.findAliasedSource(alias);
},
//returns the nested source with this alias
findAliasedSource: function(alias) {
if(this.alias == alias)
return this;
for(let i=0; i<this.nestedSources.length; i++)
{
let nestedSource = this.nestedSources[i];
let result = nestedSource.findAliasedSource(alias);
if(result != null)
return result;
}
return null;
},
//returns the nested source with this label (searches current level only)
findLabeledSource: function(label) {
for(let i=0; i<this.nestedSources.length; i++)
{
let nestedSource = this.nestedSources[i];
if(nestedSource.label == label)
{
return nestedSource;
}
}
return null;
}
};
}
};
const Section = {
//returns normal section object
create: function(header) {
return {
header: header,
body: [],
isReferenceSection: false
};
},
//returns reference section object
createReference: function(reference) {
return {
reference: reference,
sections: [],
isReferenceSection: true
};
},
//returns define section object
createDefine: function() {
return {
pipe: "|",
lines: [],
//append line, do not allow two pipes in a row
addLine: function(line) {
if(line == null || line.length == 0)
return;
if(line == this.pipe && this.lines.length > 0 && this.lines[this.lines.length-1] == this.pipe)
return;
this.lines.push(line);
}
};
},
//returns layout section object
createLayout: function() {
return {
rows: [],
//returns the matching LayoutRecord, or null
findAlias: function(alias) {
for(let i=0; i<this.rows.length; i++)
{
let row = this.rows[i];
let result = row.findAlias(alias);
if(result != null)
return result;
}
return null;
}
};
},
//returns relate section object
createRelate: function() {
return {
records: []
};
}
};
const LayoutRow = {
//returns array of opened-scopes or closed-aliases from source layout row
parseScopes: function(line) {
if(line == null || line.length == 0)
return [];
let results = [];
while(line.length > 0)
{
let matches = line.match(/^\[.+?\]/);
if(matches != null)
{
let scope = matches[0];
line = line.substring(scope.length);
results.push(Source.openScope(scope));
continue;
}
matches = line.match(/^\{.+?\}/);
if(matches != null)
{
let alias = matches[0];
line = line.substring(alias.length);
results.push(alias);
continue;
}
break; //unknown term found
}
return results;
},
//returns layout row object
create: function() {
return {
leftAlign: [], //arrays of LayoutRecords
rightAlign: [],
//returns both left and right aligned LayoutRecords
all: function() {
return this.leftAlign.concat(this.rightAlign);
},
//returns the matching LayoutRecord, or null
findAlias: function(alias) {
let layoutRecords = this.all();
for(let i=0; i<layoutRecords.length; i++)
{
let layoutRecord = layoutRecords[i];
if(layoutRecord.alias == alias)
return layoutRecord;
}
return null;
}
};
}
};
const LayoutRecord = {
//returns true if a source layout label has an alias
hasAlias: function(label) {
return (label.match(/^\{.+\}/) != null);
},
//returns [alias, label], alias may be null
parseAliasFromLabel: function(label) {
if(!this.hasAlias(label))
return [null, label];
const matches = label.match(/^(\{.+\})(.*)$/);
return [matches[1], matches[2].trim()];
},
//returns parsed layout record
parse: function(fullLabel) {
if(Source.isAlias(fullLabel))
{
return this.create(null, fullLabel);
}
fullLabel = Source.openScope(fullLabel);
const [alias, label] = this.parseAliasFromLabel(fullLabel);
return this.create(label, alias);
},
//returns a layout record
create: function(label, alias=null) {
return {
label: label,
alias: alias
};
}
};
const RelateRecord = {
//returns true for a line generally formatted like a Relate row with labels
//main intention is to differentiate a Section Header from a Relate row that ends in a colon
//ex [B1]->[B2] :"middle label":
isRelateRowEndingInColon: function(line) {
return (line.match(/\[.*\].*":/) != null || line.match(/\{.*\}.*":/) != null);
},
//returns true if source relate line starts with a scope
startIsScope: function(line) {
return (line.match(/^\[.+?\]/) != null);
},
//returns true if source relate line starts with an alias
startIsAlias: function(line) {
return (!this.startIsAliasPath(line) && line.match(/^\{.+?\}/) != null);
},
//returns true if source relate line starts with an alias path
startIsAliasPath: function(line) {
let matches = line.match(/^(\{.+?\})/);
if(matches == null)
return false;
line = line.substring(matches[1].length);
return line.match(/^\.\[.+?\]/);
},
trimSpacesAndCommas: function(line) {
line = line.trim();
while(line.length > 0 && line[0] == ',')
line = line.substring(1).trim();
return line;
},
//returns [[terms], remaining line]
//returns array of comma-separated scopes or alias paths
//stops when it hits something it doesn't recognize
parseListOfTerms: function(partialLine) {
let terms = [];
partialLine = this.trimSpacesAndCommas(partialLine);
while(partialLine.length > 0)
{
if(this.startIsAliasPath(partialLine))
{
let match = partialLine.match(/^\{.+?\}\.\[.+?\]/);
terms.push(match[0]);
partialLine = partialLine.substring(match[0].length);
}
else if(this.startIsAlias(partialLine))
{
let match = partialLine.match(/^\{.+?\}/);
terms.push(match[0]);
partialLine = partialLine.substring(match[0].length);
}
else if(this.startIsScope(partialLine))
{
let match = partialLine.match(/^\[.+?\]/);
terms.push(match[0]);
partialLine = partialLine.substring(match[0].length);
}
else
{
break;
}
partialLine = this.trimSpacesAndCommas(partialLine);
}
return [terms, partialLine];
},
//returns [lineLabelStart, lineLabelMiddle, lineLabelEnd] from the label section of a Relate line
parseLabels: function(line) {
line = line.trim();
let match = null;
match = line.match(/^\s*"(.+?)"\s*:\s*"(.+?)"\s*:\s*"(.+?)"\s*$/); //start:middle:end
if(match != null)
return [match[1].trim(), match[2].trim(), match[3].trim()];
match = line.match(/^\s*"(.+?)"\s*:\s*:\s*"(.+?)"\s*$/); //start::end
if(match != null)
return [match[1].trim(), null, match[2].trim()];
match = line.match(/^\s*"(.+?)"\s*:\s*"(.+?)"\s*$/); //start:end
if(match != null)
return [match[1].trim(), null, match[2].trim()];
match = line.match(/^\s*:\s*"(.+?)"\s*:\s*"(.+?)"\s*$/); //:middle:end
if(match != null)
return [null, match[1].trim(), match[2].trim()];
match = line.match(/^\s*:\s*"(.+?)"\s*:\s*$/); //:middle:
if(match != null)
return [null, match[1].trim(), null];
match = line.match(/^\s*"(.+?)"\s*:\s*"(.+?)"\s*:\s*$/); //start:middle:
if(match != null)
return [match[1].trim(), match[2].trim(), null];
match = line.match(/^\s*"(.+?)"\s*:\s*(:\s*)?$/); //start:: or start:
if(match != null)
return [match[1].trim(), null, null];
match = line.match(/^(\s*:)?\s*:\s*"(.+?)"\s*$/); //::end or :end
if(match != null)
return [null, null, match[2].trim()];
match = line.match(/^\s*"(.+?)"\s*$/); //middle
if(match != null)
return [null, match[1].trim(), null];
return [null, null, null];
},
//returns [[startTerms], arrowType, [endTerms], remainingLine] from full Relate row
parseRelation: function(line) {
let startTerms = [];
let arrowTerm = null;
let endTerms = [];
[startTerms, line] = this.parseListOfTerms(line);
if(line != null)
{
let matches = line.match(/^(.+?)(\[|\{)/);
if(matches == null)
{
arrowTerm = line;
line = "";
}
else
{
arrowTerm = matches[1].trim();
if(arrowTerm != null)
{
line = Text.removeFromStart(line, arrowTerm).trim();
}
[endTerms, line] = this.parseListOfTerms(line);
}
}
return [startTerms, arrowTerm, endTerms, line];
},
//returns an array of Relate Record objects
parseLine: function(line) {
let [startTerms, arrowTerm, endTerms, lineB] = this.parseRelation(line);
if(startTerms.length == 0 || arrowTerm == null || endTerms.length == 0)
return [];
let [lineLabelStart, lineLabelMiddle, lineLabelEnd] = this.parseLabels(lineB);
let results = [];
startTerms.forEach(function(startTerm) {
endTerms.forEach(function(endTerm) {
results.push(RelateRecord.create(Source.openScope(startTerm), arrowTerm, Source.openScope(endTerm), lineLabelStart, lineLabelMiddle, lineLabelEnd));
});
});
return results;
},
//returns a relate record
create: function(startLabel, arrowType, endLabel, lineLabelStart=null, lineLabelMiddle=null, lineLabelEnd=null) {
return {
startLabel: startLabel,
arrowType: arrowType,
endLabel: endLabel,
lineLabelStart: lineLabelStart,
lineLabelMiddle: lineLabelMiddle,
lineLabelEnd, lineLabelEnd
};
}
};
//returns a "source" object
function parseSource(sourceText) {
const source = Source.create();
sourceText = Source.trim(sourceText);
const sections = parseSections(sourceText);
source.addSections(sections);
source.validate();
return source;
}
//breaks text into sections, keeping all section headers
//returns an array of "section" objects
function parseSections(sourceText) {
const lines = sourceText.split("\n");
let sections = [];
let inSection = false;
let currentSection = null;
//find all sections
for(let i=0; i<lines.length; i++)
{
let line = lines[i];
if(line.length == 0)
continue;
if(Source.isSectionHeader(line))
{
const header = Source.parseHeader(line);
currentSection = Section.create(header);
sections.push(currentSection);
inSection = true;
}
else
{
if(inSection)
{
currentSection.body.push(line);
}
}
}
//collapse reference sections
let collapsedSections = [];
let inReferenceSection = false;
let currentReferenceSection = null;
sections.forEach(function(section) {
if(Source.isScope(section.header))
{
let header = Source.openScope(section.header);
currentReferenceSection = Section.createReference(header);
collapsedSections.push(currentReferenceSection);
inReferenceSection = true;
}
else if(Source.isAlias(section.header) || Source.pathStartsWithAlias(section.header))
{
currentReferenceSection = Section.createReference(section.header);
collapsedSections.push(currentReferenceSection);
inReferenceSection = true;
}
else
{
if(inReferenceSection)
currentReferenceSection.sections.push(section);
else
collapsedSections.push(section);
}
});
return collapsedSections;
}
function parseDefineSection(section) {
let defineSection = Section.createDefine();
const pipe = defineSection.pipe;
section.body.forEach(function(line) {
line = line.trim();
if(line == null || line.length == 0)
return;
if(line.startsWith(pipe))
{
defineSection.addLine(pipe);
line = line.substring(pipe.length).trim();
}
if(line.endsWith(pipe))
{
line = line.substring(0, line.length - pipe.length).trim();
defineSection.addLine(line);
defineSection.addLine(pipe);
}
else
{
defineSection.addLine(line);
}
});
return defineSection;
}
function parseLayoutSection(section) {
let layoutSection = Section.createLayout();
section.body.forEach(function(line) {
if(line.length == 0)
return;
layoutSection.rows.push(parseLayoutRow(line));
});
return layoutSection;
}
function parseLayoutRow(line) {
let layoutRow = LayoutRow.create();
let leftRight = line.split("...");
let left = LayoutRow.parseScopes(leftRight[0]);
left.forEach(function(label) {
layoutRow.leftAlign.push(LayoutRecord.parse(label));
});
if(leftRight.length > 1)
{
let right = LayoutRow.parseScopes(leftRight[1]);
right.forEach(function(label) {
layoutRow.rightAlign.push(LayoutRecord.parse(label));
});
}
return layoutRow;
}
function parseRelateSection(section) {
let relateSection = Section.createRelate();
section.body.forEach(function(line) {
let results = RelateRecord.parseLine(line);
relateSection.records = relateSection.records.concat(results);
});
return relateSection;
}
const Node = {
//returns node object
create: function(label, alias=null, path=null, isRightAlign=false) {
return {
relativeArea: null, //location and dimensions relative to parent node
absoluteArea: null, //location and dimensions on canvas
label: label, //simple label of node within scope
alias: alias,
path: path, //full path from root to parent scope
labelLayout: null,
labelArea: null, //location and dimensions relative to this node
defineLayout: null,
defineArea: null, //location and dimensions relative to this node
nodeArea: null, //location and dimensions relative to this node
nodes: [],
isRightAlign: isRightAlign, //TODO this temporary data should not be stored here
setRelativeArea: function(x, y, width, height) {
this.relativeArea = Area.create(x, y, width, height);
},
//expand node width as needed to fit content
//expands all areas as needed, too
//returns the delta
updateWidth(newWidth) {
if(this.relativeArea.width >= newWidth)
return 0;
const delta = newWidth - this.relativeArea.width;
this.relativeArea.width = newWidth;
if(this.labelArea != null)
this.labelArea.width = newWidth;
if(this.defineArea != null)
this.defineArea.width = newWidth;
if(this.nodeArea != null)
{
let nodeAreaDelta = newWidth - this.nodeArea.width;
this.nodeArea.width = newWidth;
this.nodeArea.paddingLeft += (nodeAreaDelta/2);
this.nodeArea.paddingRight += (nodeAreaDelta/2);
}
return delta;
},
//expand node height as needed to fit content
//expands all areas as needed, too
//returns the delta
updateHeight(newHeight) {
if(this.relativeHeight >= newHeight)
return 0;
const delta = newHeight - this.relativeArea.height;
this.relativeArea.height = newHeight;
if(this.nodeArea != null)
{
this.nodeArea.height += delta;
this.nodeArea.paddingTop += (delta/2);
this.nodeArea.paddingBottom += (delta/2);
}
else if(this.defineArea != null)
this.defineArea.height += delta;
else if(this.labelArea != null)
this.labelArea.height += delta;
return delta;
},
pathLabel: function() {
if(path == null || path.length == 0)
return label;
return path + "." + label;
},
setAbsoluteAreas: function(deltaX=0, deltaY=0) {
this.absoluteArea = Area.create(this.relativeArea.x + deltaX, this.relativeArea.y + deltaY, this.relativeArea.width, this.relativeArea.height);
let self = this;
this.nodes.forEach(function(nestedNode) {
nestedNode.setAbsoluteAreas(self.absoluteArea.x + self.nodeArea.x + self.nodeArea.paddingLeft, self.absoluteArea.y + self.nodeArea.y + self.nodeArea.paddingTop);
});
},
pathPrefix: function() {
return this.label + ".";
},
findPath: function(path) {
if(path == null)
return null;
if(Source.isAlias(path))
return this.findAlias(path);
if(Source.isAliasPath(path))
{
let [alias, label] = Source.splitAliasFromPath(path);
let node = this.findAlias(alias);
if(node == null)
return null;
if(label == null)
return node;
return node.findNestedLabel(Source.openScope(label));
}
return this.findLabel(Source.openScope(path));
},
findNestedLabel: function(label) {
for(let i=0; i<this.nodes.length; i++)
{
let result = this.nodes[i].findLabel(label);
if(result != null)
return result;
}
return null
},
//returns label based on next part of path matching this
findLabel: function(label) {
if(label == null)
return null;
if(this.label == label)
return this;
if(!label.startsWith(this.pathPrefix()))
return null;
label = label.substring(this.pathPrefix().length);
for(let i=0; i<this.nodes.length;i++)
{
let node = this.nodes[i];
let result = node.findLabel(label);
if(result != null)
return result;
}
return null;
},
findAlias: function(alias) {
if(alias == null)
return null;
if(this.alias == alias)
return this;
for(let i=0; i<this.nodes.length;i++)
{
let node = this.nodes[i];
let result = node.findAlias(alias);
if(result != null)
return result;
}
return null;
},
//returns depth of nested diagrams
//default of 1, for no nested diagrams
getMaxDepth: function() {
let maxDepth = 1;
this.nodes.forEach(function(node) {
maxDepth = Math.max(maxDepth, node.getMaxDepth() + 1);
});
return maxDepth;
}
};
}
};
const FindNode = {
//label = fully qualified alias/label/path being searched for from current node
//labelPath = the path from root node to current node
findNode: function(nodes, label, labelPath) {
if(Source.isAliasPath(label))
return FindNode.findNodeAliasPath(nodes, label);
if(Source.pathStartsWithAlias(label))
{
let [alias, remainingPath] = Source.splitAliasFromPath(label);
let node = FindNode.findNodeAlias(nodes, alias);
if(node == null)
return null;
return node.findLabel(node.pathPrefix() + Source.openScope(remainingPath));
}
let node = FindNode.findNodeRelative(nodes, label, labelPath);
if(node != null)
return node;
return FindNode.findNodeAbsolute(nodes, label);
},
findNodeRelative: function(nodes, label, path) {
let startingNode = FindNode.findNodeAbsolute(nodes, path);
if(startingNode == null)
return null;
return FindNode.findNodeAbsolute(startingNode.nodes, label);
},
findNodeAbsolute: function(nodes, labelOrPath) {
for(let i=0; i<nodes.length; i++)
{
let node = nodes[i];
let result = node.findPath(labelOrPath);