/
canvaslister.js
1858 lines (1535 loc) · 70.1 KB
/
canvaslister.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//'use strict';
function canvasLister(canvasItemId, sourceFile, fontDefaultFamily, fontDefaultSize, fontDefaultWeight, fontDefaultShape, defaultLineSpacingPercentage, textAlignment, backgroundColor, fontDefaultColor, sourceText) {
var canvasPages = [];
// If layouting is not in progress anymore, do the actual image loading
var inLayoutProcess = false;
var escapeLayoutProcess = false;
var hasConsole = typeof (window.console) !== undefined ? true : false;
window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.oRequestAnimationFrame;
function lg(msg) {
if (hasConsole) {
window.console.log(msg);
}
}
// The allowed attributes and there types
// (0 = Num, 1 = Hex, 2 = Tag, 3 = True text)
var textAttributes = {
'size': 0,
'color': 1
};
var imageAttributes = {
'title': 3,
'description': 3,
'src': 3,
'height': 0,
'width': 0,
'borderwidth': 0,
'bordercolor': 1,
'margin': 0,
'align': 2,
'fg': 1,
'bg': 1
};
var validTags = ['left', 'right', 'center'];
var validUnits = ['px', "%"];
var matchHex = /#[0-9a-f]*/gi;
// Performs checks if a given keyValuePair is valid to some ruleset
// returns false if something is wrong or missing
function checkKeyValuePair(type, keyValuePair) {
// Skip keys without a value
if (keyValuePair[1] === undefined) {
return false;
}
var key = keyValuePair[0].toLowerCase();
var value = keyValuePair[1].toLowerCase();
if (type === "text") {
var attribute = textAttributes[key];
if (attribute === undefined) {
return false;
}
} else if (type === "image") {
var attribute = imageAttributes[key];
if (attribute === undefined) {
return false;
}
}
switch (attribute) {
case 0:
if (isValidNum(value)) {
if (isValidUnit(value)) {
return true;
}
}
break;
case 1:
if (isValidHex(value)) {
return true;
}
break;
case 2:
if (isValidText(value)) {
return true;
}
break;
case 3:
// This is the override for values, we cant check
// like the image title and description
return true;
break;
}
return false;
}
// Helper functions to check if userinput is valid
function isValidNum(input) {
if (parseFloat(input) === NaN) {
return false;
}
return true;
}
function isValidHex(input) {
if (input[0] !== '#') {
return false;
}
var hexMatch = input.match(matchHex)[0];
if (hexMatch.length > 7) {
return false;
}
if (hexMatch.length < 4) {
return false;
}
return true;
}
function isValidText(input) {
if (validTags.indexOf(input) !== -1) {
return true;
}
return false;
}
function isValidUnit(input) {
if (input.length < 2) {
return false;
}
for (var unit = 0; unit < validUnits.length; unit++) {
if (input.indexOf(validUnits[unit]) !== -1) {
return true;
}
}
return false;
}
var canvas = document.getElementById(canvasItemId);
// Checking canvas presence
if (canvas === null) {
lg('Canvas item "' + canvasItemId + '" cannot be found, doing nothing.');
return;
}
// Get 2d context when present and measurements
var ci = canvas.getContext('2d');
var offsetX = 10;
var offsetY = 10;
var sizeX = canvas.width - (offsetX * 2);
var sizeY = canvas.height - (offsetY * 2);
var lineSpacingPercentage = 0.3;
// Reset any positiong
ci.translate(0, 0);
ci.translate(offsetX, offsetY);
// Check whether a sourcefile is given and if sourceText then is provided which is required
if (sourceFile === null) {
if (typeof (sourceText) === undefined) {
lg('Source file is not provided, but no sourceText either, canvas item id "' + canvasItemId + '"');
return;
}
}
// Setting default values for background color, font family, size, color and if not set in init
if (backgroundColor !== null) {
canvas.style.setProperty("background-color", backgroundColor);
} else {
backgroundColor = '#fff';
}
if (fontDefaultFamily === null) {
fontDefaultFamily = 'sans-serif';
}
if (fontDefaultSize === null) {
fontDefaultSize = '11px';
}
var fontDefaultLineHeight = parseFloat(fontDefaultSize) + (parseFloat(fontDefaultSize) * lineSpacingPercentage);
if (fontDefaultWeight === null) {
fontDefaultWeight = 'normal';
}
if (fontDefaultColor === null) {
fontDefaultColor = '#000';
}
if (fontDefaultShape === null) {
fontDefaultShape = 'normal';
}
if (defaultLineSpacingPercentage !== null) {
if (isValidNum(defaultLineSpacingPercentage)) {
lineSpacingPercentage = defaultLineSpacingPercentage;
}
}
if (textAlignment === null || textAlignment !== 'justified') {
textAlignment = "left";
}
ci.font = fontDefaultShape + ' normal ' + fontDefaultWeight + ' ' + fontDefaultSize + ' ' + fontDefaultFamily;
ci.fillStyle = fontDefaultColor;
ci.textAlign = 'left';
var markupData = '';
// Textloader using ajax
function loadText(sourceFile) {
if (typeof (ActiveXObject) !== "undefined") {
var dataLoader = new ActiveXObject("MSXML2.XMLHTTP.6.0");
} else {
var dataLoader = new XMLHttpRequest();
}
dataLoader.onreadystatechange = function () {
if (dataLoader.readyState === 4) {
// Clear the error message from canvas
ci.clearRect(0, 0, 300, 100);
// Continue with markup processing
markupData = dataLoader.responseText;
processMarkup(markupData);
}
};
// Prepare error message if the source could not be loaded
var stepY = 20;
ci.fillStyle = fontDefaultColor;
ci.fillText("If you see this message,", 10, stepY);
stepY += fontDefaultLineHeight;
ci.fillText('the source file "' + sourceFile + '"', 10, stepY);
stepY += fontDefaultLineHeight;
ci.fillText("could not be loaded !", 10, stepY);
dataLoader.open('GET', sourceFile);
dataLoader.send();
}
// Clear and fill for pagination
var previousFill = "";
function clearAndFill() {
previousFill = ci.fillStyle;
var canvasItem = document.getElementById(canvasItemId);
ci.clearRect(-10, -10, canvasItem.width + 20, canvasItem.height + 20);
ci.fillStyle = backgroundColor;
ci.fillRect(-10, -10, canvasItem.width + 20, canvasItem.height + 20);
ci.fillStyle = previousFill;
}
// Matching tags and imageTagStore for parser
var formatTagMatch = /<[^\/][\w\d\s\=\"\#\'\*\%]*>/g;
var imgMatch = /<[^\s]{0,}img\b[^\<]*/gi;
var imgReplace = /\bimg\b/g;
var imgTitleMatch = /title=[\"\'][^\"]*[\"\']{1,2}/gi;
var imgDescriptionMatch = /description=[\"\'][^\"]*[\"\']{1,2}/gi;
var imgkeyValueMatch = /[^<\"\'\s]{1,}[\w\d\#]*[^\"\'\=\>\s]/g;
var triggerMatch = /[^_][\w\d\.\,\;\:\_\'\"\#\+\*\=\(\)\[\]\-\&\`\!\%\\$\?]*[\.\,\;\:\_\'\"\#\+\*\=\(\)\[\]\-\&\`\!\%\\$\?]{0,}/g;
var spaceCorrection = /[\s]{2,}/g;
var parserObject = {};
var imageData = [];
var imageOrder = -3;
var keyValues = [];
var imageObject = {};
var imageTag = [];
var imgTitle = [];
var imgDescription = [];
function simpleParse(formatData) {
//lg('---parser data------------------');
parserObject = {}; // The parserObject contains the formatter data
parserObject.data = []; // Contains the data of the tag
parserObject.tags = []; // The tags as defined
parserObject.imageStore = []; // Image elements
parserObject.imageTagStore = []; // Image keyvalue store
parserObject.orders = []; // The tag order levels for formatting
parserObject.tagStore = {}; // The simple tags listed like b, bi, i
parserObject.tagKeyValues = {}; // The key values store of tags
parserObject.triggers = []; // Word boundaries which trigger formatting
parserObject.dataPoints = []; // The approximate indexes of the triggers
parserObject.orderNestedTags = []; // Information of tags nested into each other
// Preprocess and remove image tag from formatting data, prepare image data
// for display on the canvas, using parameters
imageData = formatData.match(imgMatch);
imageOrder = -3;
keyValues = [];
if (imageData !== null) {
parserObject.imageTagStore = imageData;
imageTag = [];
imgTitle = [];
imgDescription = [];
for (var img = 0; img < imageData.length; img++) {
imageTag = imageData[img];
// Create the general image object
imageObject = {};
imageObject.title = '';
imageObject.description = '';
imageObject.fg = '#000000';
imageObject.bg = '#ffffff';
imageObject.src = 'none';
imageObject.height = '0px';
imageObject.width = '0px';
imageObject.margin = '5px';
imageObject.align = "center";
imageObject.borderwidth = "0px";
imageObject.bordercolor = "#000000";
imageObject.id = imageOrder;
// Clean imageTag from format data
formatData = formatData.replace(imageTag, '');
// Clean imageTag from format data
imageTag = imageTag.replace(imgReplace, '');
// Check if we can get a title and remove it from the imageTag
imgTitle = imageTag.match(imgTitleMatch);
if (imgTitle !== null) {
var imgTitleString = imgTitle[0].split('=', 2)[1];
imageObject.title = imgTitleString.substr(1, imgTitleString.length - 2);
imageTag = imageTag.replace(imgTitleMatch, '');
}
// Check if we can get a description and remove it from imageTag
imgDescription = imageTag.match(imgDescriptionMatch);
if (imgDescription !== null) {
var imgDescriptionString = imgDescription[0].split('=', 2)[1];
imageObject.description = imgDescriptionString.substr(1, imgDescriptionString.length - 2);
imageTag = imageTag.replace(imgDescriptionMatch, '');
}
keyValues = imageTag.match(imgkeyValueMatch);
if (keyValues !== null) {
for (var keyValue = 0; keyValue < keyValues.length; keyValue += 2) {
if (checkKeyValuePair("image", [keyValues[keyValue], keyValues[keyValue + 1]])) {
imageObject[keyValues[keyValue].toLowerCase()] = keyValues[keyValue + 1].toLowerCase();
}
}
}
parserObject.orders.push(imageOrder);
parserObject.imageStore.push(imageObject);
imageOrder--;
}
}
// Start of actual parser code which generates the corner data
// for the formatter engine
var parserData = '';
var tagLength = 0;
var currentIndex = 0;
var nextIndex = 0;
var closingIndex = 0;
var currentTag = '';
var nextTag = '';
var openTags = [];
var processedTags = 0;
var dataPoint = 0;
parserObject.tags = formatData.match(formatTagMatch);
if (parserObject.tags !== null) {
tagLength = parserObject.tags.length;
} else {
parserObject.tags = [];
}
for (var tag = 0; tag < tagLength; tag++) {
currentTag = parserObject.tags[tag];
nextTag = parserObject.tags[tag + 1];
currentIndex = formatData.indexOf(currentTag);
nextIndex = formatData.indexOf(nextTag);
closingIndex = formatData.indexOf('</>');
if (closingIndex === 0) {
for (var openItem = 0; openItem < openTags.length - 1; openItem++) {
formatData = formatData.substr(closingIndex + 3);
currentIndex = formatData.indexOf(currentTag);
nextIndex = formatData.indexOf(nextTag);
closingIndex = formatData.indexOf('</>');
if (closingIndex !== 0) {
break;
}
}
}
//lg('tag: '+currentTag);
//lg('current: '+currentIndex+' -- next: '+nextIndex+' -- close: '+closingIndex);
// Escape from formatting because there was a parsing error
if (currentIndex === -1 && nextIndex === -1) {
break;
}
// Check the case if we have a tag followed by the same tag
if (currentIndex === 0 && nextIndex === 0) {
parserData = formatData.substring(currentIndex + currentTag.length, closingIndex).trim();
parserObject.data.push(parserData);
parserObject.orders.push(tag);
formatData = formatData.substr(closingIndex + 3);
parserObject.dataPoints.push(dataPoint);
dataPoint += parserData.length;
continue;
}
// Handle the case that a tag is open and data left to format
if (currentIndex > closingIndex) {
parserData = formatData.substring(0, closingIndex).trim();
parserObject.data.push(parserData);
parserObject.orders.push(0);
formatData = formatData.substr(closingIndex + 3);
parserObject.dataPoints.push(dataPoint);
processedTags++;
if (openTags.length !== 0) {
openTags = [];
}
dataPoint += parserData.length;
tag--;
continue;
}
// Handle a tag starting inside this tag or no tag following directly
if (nextIndex !== -1 && nextIndex < closingIndex && currentIndex !== nextIndex) {
// lg("closing tag or tag in tag
if (currentIndex === 0) {
parserData = formatData.substring(currentTag.length, nextIndex).trim();
parserObject.data.push(parserData);
parserObject.orders.push(tag);
formatData = formatData.substr(nextIndex);
} else {
parserData = formatData.substring(0, currentIndex).trim();
parserObject.data.push(parserData);
parserObject.orders.push(-1);
formatData = formatData.substr(currentIndex + currentTag.length);
}
parserObject.dataPoints.push(dataPoint);
openTags.push(tag);
processedTags++;
dataPoint += parserData.length;
continue;
}
// Handle the case that we have data from an opnened tag, within another one
// This part fetches the data for the embedded as well as the ending of that data
if (nextIndex === -1 && closingIndex !== -1 && tag === tagLength - 1 && openTags.length !== 0 && currentIndex === 0) {
parserData = formatData.substring(currentTag.length, closingIndex).trim();
parserObject.data.push(parserData);
parserObject.orders.push(tag);
parserObject.dataPoints.push(dataPoint);
formatData = formatData.substr(closingIndex + 3);
parserData = formatData.substring(0, formatData.length - 3).trim();
parserObject.data.push(parserData);
parserObject.orders.push(0);
parserObject.dataPoints.push(dataPoint);
dataPoint += parserData.length;
openTags = [];
continue;
}
// Case of non tagged data before last tag
if (currentIndex !== 0 && nextIndex === -1) {
parserData = formatData.substring(0, currentIndex).trim();
parserObject.data.push(parserData);
parserObject.orders.push(-1);
formatData = formatData.substr(currentIndex);
parserObject.dataPoints.push(dataPoint);
dataPoint += parserData.length;
openTags = [];
tag--;
continue;
}
// If the tag start not a zero, we have non-tagged data
if (currentIndex !== 0) {
//lg("in non tagged data");
if (openTags.length === 0) {
parserData = formatData.substring(0, currentIndex).trim();
parserObject.data.push(parserData);
parserObject.orders.push(-1);
formatData = formatData.substr(currentIndex).trim();
parserObject.dataPoints.push(dataPoint);
} else {
parserData = formatData.substring(0, currentIndex).trim();
parserObject.data.push(parserData);
parserObject.orders.push(openTags[0]);
formatData = formatData.substr(currentIndex).trim();
/*
parserData = formatData.substring(0, closingIndex).trim();
parserObject.data.push(parserData);
parserObject.orders.push(openTags[0]);
formatData = formatData.substr(closingIndex + 3);
*/
parserObject.dataPoints.push(dataPoint);
}
dataPoint += parserData.length;
tag--;
continue;
}
// Last tag processing
if (nextIndex === -1 && currentIndex === 0) {
parserData = formatData.substring(currentTag.length, closingIndex).trim();
formatData = formatData.substr(closingIndex + 3).trim();
parserObject.data.push(parserData);
parserObject.orders.push(tag);
processedTags++;
parserObject.dataPoints.push(dataPoint);
dataPoint += parserData.length;
continue;
}
// Assume non nested tag
if (nextIndex > closingIndex && currentIndex === 0) {
//lg("in non nested");
if (openTags.length === 0) {
parserData = formatData.substring(currentTag.length, closingIndex).trim();
formatData = formatData.substr(closingIndex + 3).trim();
parserObject.data.push(parserData);
parserObject.orders.push(tag);
} else {
parserData = formatData.substring(currentTag.length, closingIndex).trim();
formatData = formatData.substr(closingIndex + 3).trim();
parserObject.data.push(parserData);
parserObject.orders.push(tag);
formatData = formatData.substr((openTags.length - 1) * 3);
openTags = [openTags[0]];
}
parserObject.dataPoints.push(dataPoint);
dataPoint += parserData.length;
processedTags++;
continue;
}
// Assume nested tag
if (nextIndex < closingIndex && currentIndex === 0) {
//lg("in nested tag");
parserData = formatData.substring(currentTag.length, nextIndex).trim();
formatData = formatData.substr(nextIndex).trim();
parserObject.data.push(parserData);
parserObject.orders.push(tag);
openTags.push(tag);
processedTags++;
parserObject.dataPoints.push(dataPoint);
dataPoint += parserData.length;
continue;
}
}
// Create key value store for formatting after parsing the data
//var parserObject.tagKeyValues = {};
var keyValues = [];
var singleKey = [];
var keyValueMatch = /[^<\"\'\s]{1,}[\w\d\#]*[^\"\'\=\>\s]/g;
var singleValueMatch = /\b[b|i|bi]{1,2}\b/gi;
var permittedKeyValues = [];
for (var tag = 0; tag < parserObject.tags.length; tag++) {
singleKey = parserObject.tags[tag].match(singleValueMatch);
keyValues = parserObject.tags[tag].match(keyValueMatch);
if (singleKey !== null) {
// Only the first matched singleKey is used for formatting
parserObject.tagStore[tag] = singleKey[0].toLowerCase();
} else {
// Push an empty string to tell that we have no simple tag value
parserObject.tagStore[tag] = '';
}
if (keyValues !== null) {
permittedKeyValues = [];
// If we have one or more single key values, remove those to
// build up the keyValue pairs list
var keyValuesSize = keyValues.length;
if (singleKey !== null) {
for (var keyValue = 0; keyValue < keyValuesSize; keyValue++) {
for (var singleTag = 0; singleTag < singleKey.length; singleTag++) {
if (singleKey[singleTag] === keyValues[keyValue]) {
keyValues.splice(keyValue, 1);
keyValuesSize--;
}
}
}
}
for (var keyValue = 0; keyValue < keyValues.length; keyValue += 2) {
if (checkKeyValuePair("text", [keyValues[keyValue], keyValues[keyValue + 1]])) {
permittedKeyValues.push([keyValues[keyValue].toLowerCase(), keyValues[keyValue + 1].toLowerCase()]);
}
}
parserObject.tagKeyValues[tag] = permittedKeyValues;
} else {
parserObject.tagKeyValues[tag] = [];
}
}
// Create the triggers for the formatter from the parserObject.data
// for a particular tag
// Triggers are cleared of some special characters, to
// avoid that we cant trigger from "merged" data once the markup
// has been cleared from tag separators and line endings, line separators
// become merged during the clearing.
// var parserObject.triggers = [];
var triggers = [];
var parserData = '';
var triggerOne = '';
var triggerTwo = '';
for (var data = 0; data < parserObject.data.length; data++) {
parserData = parserObject.data[data].trim();
// Use whole word as trigger if we have no spaces inside
if (parserData.indexOf(" ") === -1 && parserData.length !== 0) {
triggerOne = parserData.match(triggerMatch)[0].trim();
if (triggerOne === "") {
parserObject.triggers.push([[0, parserData], [0, parserData]]);
} else {
parserObject.triggers.push([[0, triggerOne], [0, triggerOne]]);
}
continue;
}
triggers = parserData.match(triggerMatch);
if (triggers !== null) {
triggerOne = triggers[0].trim();
if (triggerOne.length === 0) {
parserData = parserData.replace(triggerOne, '');
triggerTwo = parserData.trim();
parserObject.triggers.push([[0, triggerOne], [parserData.indexOf(triggerTwo), triggerTwo]]);
} else {
triggerTwo = triggers[triggers.length - 1].trim();
if (triggerTwo.length === 0) {
parserObject.triggers.push([[0, triggerOne], [0, triggerOne]]);
} else {
parserObject.triggers.push([[parserData.indexOf(triggerOne), triggerOne], [parserData.indexOf(triggerTwo, triggerOne.length), triggerTwo]]);
}
}
} else {
parserObject.triggers.push(false);
}
}
// Get the information on how many tags are nested into one tag order
// based on the order list
parserObject.orderNestedTags = [];
var orderLevel = 0;
var tagSteps = 0;
var processedOrders = [];
var nestedTagCount = 0;
for (var order = 0; order < parserObject.orders.length; order++) {
orderLevel = parserObject.orders[order];
// If we have an image, simply add it as single item
if (orderLevel < -1) {
parserObject.orderNestedTags.push(0);
continue;
}
// If we have no open tag, dont push anything
if (orderLevel === -1) {
parserObject.orderNestedTags.push(-1);
continue;
}
tagSteps = 0;
previousTags = 0;
nestedTagCount = 0;
// Check that we process every order level only once
if (processedOrders.indexOf(orderLevel) === -1) {
var previousTags = 0;
for (var index = order + 1; index < parserObject.orders.length; index++) {
// If the index is not the same, assume a previous tag
if (parserObject.orders[index] !== orderLevel) {
previousTags++;
}
tagSteps++;
// If we reached the the same order level, the tag/orderLevel count is closed
// else
// if the index hits -1 or lower, the tag can be assumend to be closed
if (parserObject.orders[index] === orderLevel) {
break;
} else if (parserObject.orders[index] <= -1) {
break;
}
}
// Add the order to the processed order list
processedOrders.push(orderLevel);
// Push the amount of included tags
nestedTagCount = tagSteps - previousTags;
parserObject.orderNestedTags.push(nestedTagCount);
}
}
// After figuring out the how the tags are nested in orderNestedTags
// lets get the indexes for the data right, so we can start formatting
// not only by triggerwords, but also based on the position
// in the sourceText to avoid triggering on triggerwords before the acutal tag
// has started
return parserObject;
}
// Helper functions to set the font styles to
// default, a particular level or reset to previous levels
// Init values with defaults
var fontWeight = fontDefaultWeight;
var fontSize = fontDefaultSize;
var fontColor = fontDefaultColor;
var fontFamily = fontDefaultFamily;
var fontShape = fontDefaultShape;
var lineHeightHint = fontDefaultLineHeight;
var fontStyle = [fontShape, 'normal', fontWeight, fontSize, fontFamily];
// Simple tag and key value storage
var simpleTag = '';
var keyValues = [];
// Shorthands for the parserObject data
// also used by the styling functions
var tagStore = {};
var tagKeyValues = {};
var triggers = [];
var orders = [];
var dataPoints = [];
var imageStore = [];
var orderNestedTags = [];
function setDefaultStyle() {
fontWeight = fontDefaultWeight;
fontSize = fontDefaultSize;
fontColor = fontDefaultColor;
fontFamily = fontDefaultFamily;
fontShape = fontDefaultShape;
ci.fillStyle = fontDefaultColor;
fontStyle = [fontDefaultShape, 'normal', fontDefaultWeight, fontDefaultSize, fontDefaultFamily];
ci.font = fontStyle.join(' ');
}
function setStyle(setFormatLevel) {
// Get key value formatting or empty array
keyValues = [];
if (tagKeyValues.hasOwnProperty(setFormatLevel)) {
keyValues = tagKeyValues[setFormatLevel];
}
simpleTag = tagStore[setFormatLevel];
// Check if we have a simple tag to start with
if (simpleTag !== '') {
switch (simpleTag) {
case 'b':
fontWeight = 'bold';
break;
case 'i':
fontShape = 'italic';
break;
case 'bi':
fontWeight = 'bold';
fontShape = 'italic';
break;
}
fontStyle = [fontShape, 'normal', fontWeight, fontSize, fontDefaultFamily];
ci.font = fontStyle.join(' ');
}
if (keyValues.length !== 0) {
for (var keyItem = 0; keyItem < keyValues.length; keyItem++) {
switch (keyValues[keyItem][0]) {
case "size":
if (keyValues[keyItem][1].indexOf("%") !== -1) {
fontSize = (parseFloat(fontDefaultSize) * (parseFloat(keyValues[keyItem][1]) / 100)).toString() + "px";
} else {
fontSize = keyValues[keyItem][1];
}
var newHeight = parseFloat(fontSize) + (parseFloat(fontSize) * lineSpacingPercentage);
if (lineHeightHint < newHeight) {
lineHeightHint = newHeight;
}
break;
case "color":
fontColor = keyValues[keyItem][1];
ci.fillStyle = fontColor;
break;
}
}
fontStyle = [fontShape, 'normal', fontWeight, fontSize, fontDefaultFamily];
ci.font = fontStyle.join(' ');
}
}
function resetStyle(resetLevel, openTagCount) {
// Get key value formatting or empty array
keyValues = [];
if (tagKeyValues.hasOwnProperty(resetLevel)) {
keyValues = tagKeyValues[resetLevel];
}
simpleTag = tagStore[resetLevel];
// Check if we have a simple tag to start with
if (simpleTag !== '') {
switch (simpleTag) {
case 'b':
fontWeight = fontDefaultWeight;
break;
case 'i':
fontShape = fontDefaultShape;
break;
case 'bi':
fontWeight = fontDefaultWeight;
fontShape = fontDefaultShape;
break;
}
fontStyle = [fontShape, 'normal', fontWeight, fontSize, fontDefaultFamily];
ci.font = fontStyle.join(' ');
}
if (keyValues.length !== 0) {
for (var keyItem = 0; keyItem < keyValues.length; keyItem++) {
switch (keyValues[keyItem][0]) {
case "size":
fontSize = fontDefaultSize;
break;
case "color":
ci.fillStyle = fontDefaultColor;
break;
}
}
fontStyle = [fontShape, 'normal', fontWeight, fontSize, fontDefaultFamily];
ci.font = fontStyle.join(' ');
}
// If we have open tags, dont reset to defaults but previous tag values
if (openTagCount > 0) {
//lg("setting style to: " + (resetLevel - 1) + ", from openTag: " + openTags);
setStyle(resetLevel - 1);
} else {
//lg("setting style to: default, from openTag: " + openTags);
setDefaultStyle();
}
}
// This function stores img data as well as coordinates and size
// from the markup, and draws the images once they are ready onto
// the canvas
var phantomImages = [];
var imgCounter = 0;
function drawImages() {
if (inLayoutProcess || escapeLayoutProcess) {
return;
}
if (imgCounter >= phantomImages.length) {
if (canvasPages.length > 0) {
ci.putImageData(canvasPages[0], 0, 0);
}
activePage = 0;
return;
}
var phantomImg = phantomImages[imgCounter];
if (phantomImg[1].width === 0 || phantomImg[1].height === 0 || phantomImg[1].complete !== true) {
window.requestAnimationFrame(drawImages);
return;
} else {
if (canvasPages.length > 0) {
clearAndFill();
ci.putImageData(canvasPages[phantomImg[6]], 0, 0);
}
ci.drawImage(phantomImg[1], phantomImg[2], phantomImg[3], phantomImg[4], phantomImg[5]);
if (canvasPages.length > 0) {
canvasPages[phantomImg[6]] = ci.getImageData(0, 0, canvas.width, canvas.height);
}
imgCounter++;
}
}
// Markup processor
var hasFormatCheck = /<[^/]*>.*<\/>/;
var tagMatchPattern = /<[^<\s]{0,}.*[<\/>]+/g;
var closingMatch = /<\/>/g;
function processMarkup(markupData) {
var markupParts = markupData.trim().split('\n');
var line = 0;
var lines = markupParts.length;
var stepY = 0;
var stepX = 0;
var spacerSize = 0;
var hasFormat = false;
var parserObjectStore = [];
// The current line we are working with
var activeLine = '';
// The cleaned up alternative text array
var altTextArray = [];
// Define if we make use of phantom mode to align text if required
// in example for justified spaced text
var usePhantom = false;
var hadPhantom = false;
var phantomLines = [];
var lastItem = 0;
var optimalY = 0;
var subItem = [];
var itemSpace = 0;
if (textAlignment === "justified") {
usePhantom = true;
hadPhantom = false;
}
var currentWord = 0;
var currentSize = 0;
var word = '';
var wordSize = 0;
var wordIndex = 0;
var words = [];
var wordCount = 0;
var triggerWord = "";
var matchedTrigger = [];
var phantomIndex = 0;
// The formatter level and formatter switch