-
Notifications
You must be signed in to change notification settings - Fork 0
/
inset.js
636 lines (563 loc) · 16.1 KB
/
inset.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
/**
Author: Alex Lam
Application: Text Generator
Email: [email protected]
V2.0 Updated at Jan 05, 2019
V2.1 Updated at Mar 22, 2022
V2.2 Updated at Aug 15, 2023
V2.3 Updated at Feb 2, 2024
V3.0 Updated at Feb 10, 2024
V3.1 Updated at Feb 17, 2024
*/
"use strict";
//Define maximum number of parameter
var iMax = 26; //1..26
function resizeText() {
// const textElement = $("#txtpara").get(0);
// const windowHeight = window.innerHeight;
// console.log(windowHeight);
// // $("#txtParam1").height(windowHeight+"px");
// $("#txxtCodeArea").style.height = windowHeight - 300;
// $("#txtCodeResult").style.height =
// windowHeight - $("#txxtCodeArea").style.height;
// style.height = newHeight + "px";
// const padding = 20; // Adjust this value for top and bottom padding
// const maxHeight = windowHeight - padding;
// textElement.style.height = `${maxHeight}px`;
}
window.addEventListener("resize", resizeText);
// Call the function initially to set the height
resizeText();
/**
* @description Insert img to txtCodeArea
* @param {string} sHtml
* @returns {string}
*
*/
function pasteHtmlAtCaret(html) {
var sel, range;
if (window.getSelection) {
// IE9 and non-IE
sel = window.getSelection();
if (sel.getRangeAt && sel.rangeCount) {
range = sel.getRangeAt(0);
range.deleteContents();
// Range.createContextualFragment() would be useful here but is
// non-standard and not supported in all browsers (IE9, for one)
var el = document.createElement("div");
el.innerHTML = html;
var frag = document.createDocumentFragment(),
node,
lastNode;
while ((node = el.firstChild)) {
lastNode = frag.appendChild(node);
}
range.insertNode(frag);
// Preserve the selection
if (lastNode) {
range = range.cloneRange();
range.setStartAfter(lastNode);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
}
}
} else if (document.selection && document.selection.type != "Control") {
// IE < 9
document.selection.createRange().pasteHTML(html);
}
}
/**
* Add tab and empty content
* @param {*} iID
*/
function addTab(iID) {
//Add Tab Title
$("#tab-list").append(
$(
'<li class="nav-item"><a class="nav-link" id="ValTab' +
iID +
'" href="#tab' +
iID +
'" role="tab" data-toggle="tab"><span class="var">Var[' +
iID +
"]</span> " +
'<span class="glyphicon glyphicon-pencil text-muted edit"></span>' +
'<button class="close" type="button" onclick="btnDelV_OnClick(' +
iID +
')" title="Remove this page">×</button></a></li>'
)
);
//Add Tab Content
$("#tab-content").append(
$(
'<div class="tab-pane fade" id="tab' +
iID +
'" role="tabpanel"' +
iID +
'"><div class="txtNote">One parameter per line</div><dt class="txtParam" id="txtParam' +
iID +
'" contenteditable="plaintext-only"></dt>'
)
);
}
/**
* @description when the number [insert] button press, add tab and number
* @param {*} iID new tab id
*/
function btnAddV_OnClick(iID) {
//Add or show exist tab of variable
if ($("#tab" + iID).length <= 0) {
addTab(iID);
}
$('#tab-list a[href="#tab' + iID + '"]').tab("show");
$("#txtCodeArea").focus();
$("#txtCodeArea").text(
pasteHtmlAtCaret(
'<img src="blue/' + iID + '.png" width="16px" height="16px">'
)
);
}
/**
* @description when the number [delete] button press, delete the tab and content
* @param {*} iID
*/
function btnDelV_OnClick(iID) {
if ($("#tab" + iID).length > 0) {
if (confirm("Do you want to delete the parameter?") == true) {
let sText = $("#txtCodeArea").html();
if (sText.includes('<img src="blue/' + iID + '.png"')) {
alert(
"The parameter is used in the template! \nPlease delete it in template first!"
);
} else {
console.log($("#txtCodeArea").html());
//delete tab and content
$("#ValTab" + iID).remove();
$("#tab" + iID).remove();
$('#tab-list a[href="#tab1').tab("show");
}
}
}
}
/**
* Add the parameters from the 2-d array which includes csv data to the tabs
* @param {} csvData 2-d array of csv data
* @returns
*/
function addParamsFromArray(csvData) {
let lastNode = -1;
for (let i = 1; i <= iMax; i++) {
if ($("#txtParam" + i).length > 0) {
lastNode = i;
if ($("#txtParam" + i).html().length > 0) {
lastNode++;
}
}
}
let cols = csvData[0].length;
if (lastNode + cols <= iMax) {
for (let i = 0; i < cols; i++) {
let sRtn = "";
for (let j = 0; j < csvData.length; j++) {
sRtn += "<div>" + csvData[j][i].trim() + "</div>";
}
if ($("#txtParam" + (lastNode + i)).length <= 0) {
addTab(lastNode + i);
}
$("#txtParam" + (lastNode + i)).html(sRtn);
}
$('#tab-list a[href="#tab' + lastNode + '"]').tab("show");
} else {
alert(
"The number of columns in the CSV file exceeds the maximum number of parameters allowed"
);
return;
}
}
/**
* @description Get the id from the string which includes Var[ID]
* @param {} inputString
* @returns
*/
function get_ID(inputString) {
const regex = /\[(.*?)\]/;
const matches = regex.exec(inputString);
if (matches && matches.length > 1) {
return matches[1];
} else {
return "";
}
}
/**
* @description when the run button press, output the result
* @param {*} iID new tab id
*/
function btnGenerateResult_OnClick() {
$("#footer").text("Processing.....");
let sText = $("#txtCodeArea").html();
console.log(sText);
$("#txtCodeResult").html(makeString(sText));
let myDate = new Date();
$("#footer").text(
"Finished at " +
myDate.toLocaleString() +
". Result copied to Clipboard!! Text Generator by Alex. Email: [email protected]"
);
copyToClipboard();
}
/**
* @description when the copy button press, copy the result to clipboard
*/
function btnCopy_OnClick() {
copyToClipboard();
alert("The result has been copied to the clipboard");
}
function copyToClipboard() {
let tt = "";
const formattedContents = $("#txtCodeResult")
.find("div")
.map(function () {
tt += $(this).text().trim() + "\n";
});
navigator.clipboard.writeText(tt);
}
/**
* @description when the number [insert] button press, add tab and number
* Button [Generate Parameters] is pressed
*/
function btnGenerateParameters_OnClick() {
let sNav = $(".nav-tabs .active").text();
let s = sNav.split(" ");
let sID = get_ID(s[0].toString());
let sRtn = "";
var iFirst = +$("#txtFnum").val();
var iLast = +$("#txtLnum").val();
var iStep = +$("#txtStep").val();
for (let i = iFirst; i <= iLast; i += iStep) {
sRtn += "<div>" + i + "</div>";
}
$("#txtParam" + sID).html(sRtn);
}
/**
* @description Making string function
* Button [Generate the result below] is pressed
* @param {*} sSrc - the html source in txtCodeArea
*/
function makeString(sSrc) {
//Define variable
let sRtn = "";
let iParmLineCount = 0;
let bParmDiff = false;
let slParam = new Array();
if (sSrc == "") {
alert("No Content!");
return "There is no content exist!";
}
// count parameter;
for (let j = 0; j <= iMax; j++) {
slParam[j] = new Array();
if ($("#txtParam" + j).length <= 0) {
continue;
}
let sHtml = $("#txtParam" + j).html();
if (sHtml.slice(0, 5) == "<div>") {
sHtml = sHtml.slice(5, sHtml.length - 6);
}
if (sHtml != "") {
sHtml = sHtml.replace(/<\/div>/g, "");
sHtml = sHtml.replace(/<br>/g, "");
if (sHtml.includes("\r")) {
sHtml = sHtml.replace(/<div>/g, "");
slParam[j] = sHtml.split("\r");
} else if (sHtml.includes("\n")) {
sHtml = sHtml.replace(/<div>/g, "");
slParam[j] = sHtml.split("\n");
} else if (sHtml.includes("<div>")) {
slParam[j] = sHtml.split("<div>");
}
//delete the blank
for (let i = slParam[j].length - 1; i >= 0; i--) {
if (slParam[j][i] == "") {
slParam[j].splice(i, 1);
} else {
break;
}
}
//count the max length of parameters
if (slParam[j].length > iParmLineCount) {
if (iParmLineCount > 0) {
bParmDiff = true;
}
iParmLineCount = slParam[j].length;
}
} else {
if (iParmLineCount > 0) {
bParmDiff = true;
}
}
}
// check if the lines of parameters are different
if (bParmDiff) {
let bAnswer = confirm(
"The the lines of parameters are not equal, do you want to continue?"
);
if (bAnswer) {
} else {
return "The the lines of parameters are not equal!";
}
}
if (iParmLineCount == 0) {
alert("No Parameter exist!");
return "There is no parameter exist!";
}
//replace the parameter
for (let k = 0; k < iParmLineCount; k++) {
let sTemp = sSrc;
for (let i = 0; i <= iMax; i++) {
let sKey;
if (k >= slParam[i].length) {
sKey = "";
} else {
sKey = slParam[i][k];
}
let sRp = '<img src="blue/' + i + '.png" width="16px" height="16px">';
sTemp = sTemp.replace(new RegExp(sRp, "g"), sKey);
}
sRtn += "<div>" + sTemp + "</div>";
}
return sRtn;
}
/**
* @description csv text to 2-d array
* @param {} csvText
* @returns
*/
function parseCSV(csvText) {
if (csvText.trim() === "") {
return null;
}
const rows = csvText.trim().split("\n");
const csvData = [];
rows.forEach((row) => {
row = row.trim();
while (row.endsWith(",")) {
row = row.slice(0, -1);
}
const columns = row
.replace("\r", "")
.replace("\t", "")
.split(",")
.map((col) => col.trim());
csvData.push(columns);
});
return csvData;
}
/**
* @description when the example button press, add the example parameters to the tabs
* @returns
*/
function btnExample_OnClick() {
const contents = "John, male, 18\nGeen, female, 20\nLily, female, 21";
const csvData = parseCSV(contents);
if (csvData === null) {
alert("Invalid CSV file");
return;
}
addParamsFromArray(csvData);
let sText =
'Name: <img src="blue/1.png" width="16px" height="16px">, Gender: <img src="blue/2.png" width="16px" height="16px">, Age:<img src="blue/3.png" width="16px" height="16px">';
$("#txtCodeArea").html(sText);
btnGenerateResult_OnClick(); //Generate the result
}
/**
* @description when the clear button press, clear the content
*/
function btnClear_OnClick() {
window.location.reload();
}
/**
* @description when the button press, call the related file input to select the file
*/
function btnImportCSV_OnClick() {
btnImportCSV_file.click();
}
/**
* @description clear the parameters
*/
function btnClearParameters_OnClick() {
console.log("btnClearParameters_OnClick");
for (let i = 1; i <= iMax; i++) {
if ($("#txtParam" + i).length > 0) {
$("#txtParam" + i).html("");
}
}
}
/**
* @description call importTemplate file input to select the file
*/
function btnImportTemplate_OnClick() {
btnImportTemplate_file.click();
}
/**
* @description export the template and parameters to a file
*/
function btnExportTemplate_OnClick() {
let tpl_content = $("#txtCodeArea").html();
let csv_content = preCSV();
let content =
"[startTemplate.]" +
tpl_content +
"[endTemplate.]\n[startParameters.]" +
csv_content +
"[endParameters.]";
let filename = "template.tpl";
saveToFile(content, filename);
}
/**
* @description when the csv file is selected, read the file and add the parameters to the tabs
* @param {*} event
*/
function btnImportCSV_file_OnChange(event) {
const file = event.target.files[0];
const reader = new FileReader();
reader.onload = function (e) {
const contents = e.target.result;
const csvData = parseCSV(contents);
if (csvData === null) {
alert("Invalid CSV file");
return;
}
addParamsFromArray(csvData);
};
reader.readAsText(file);
}
/**
* @description when the template file is selected, read the file and add the content to the txtCodeArea
* @param {} event
*/
function btnImportTemplate_file_OnChange(event) {
const file = event.target.files[0];
const reader = new FileReader();
reader.onload = function (e) {
const contents = e.target.result;
console.log(contents);
if (contents === null) {
alert("Invalid template file");
return;
}
let tpl_content = getSubstring(
contents,
"[startTemplate.]",
"[endTemplate.]"
);
let csv_content = getSubstring(
contents,
"[startParameters.]",
"[endParameters.]"
);
$("#txtCodeArea").html(tpl_content);
const csvData = parseCSV(csv_content);
addParamsFromArray(csvData);
};
reader.readAsText(file);
}
/**
* @description Getting the substring between startMarker and endMarker
* @param {*} str
* @param {*} startMarker
* @param {*} endMarker
* @returns
*/
function getSubstring(str, startMarker, endMarker) {
const startIndex = str.indexOf(startMarker) + startMarker.length;
const endIndex = str.indexOf(endMarker);
// Check if markers are found and endIndex is after startIndex
if (startIndex !== -1 && endIndex !== -1 && endIndex > startIndex) {
return str.substring(startIndex, endIndex);
} else {
return ""; // Return empty string if markers not found or invalid position
}
}
/**
* @description Save the content to a file
* @param {*} content
* @param {*} filename
*/
function saveToFile(content, filename) {
let stringData = content;
const dataURL = `data:text/plain;base64,${btoa(stringData)}`;
const downloadLink = document.createElement("a");
downloadLink.href = dataURL;
downloadLink.download = filename;
downloadLink.target = "_blank";
downloadLink.click();
}
/**
* @description convert the 2-d array to csv
* @returns
*/
function preCSV() {
//Define variable
let sRtn = "";
let iParmLineCount = 0;
let bParmDiff = false;
let slParam = new Array();
// count parameter;
for (let j = 0; j <= iMax; j++) {
slParam[j] = new Array();
if ($("#txtParam" + j).length <= 0) {
continue;
}
let sHtml = $("#txtParam" + j).html();
if (sHtml.slice(0, 5) == "<div>") {
sHtml = sHtml.slice(5, sHtml.length - 6);
}
if (sHtml != "") {
sHtml = sHtml.replace(/<\/div>/g, "");
sHtml = sHtml.replace(/<br>/g, "");
if (sHtml.includes("\r")) {
sHtml = sHtml.replace(/<div>/g, "");
slParam[j] = sHtml.split("\r");
} else if (sHtml.includes("\n")) {
sHtml = sHtml.replace(/<div>/g, "");
slParam[j] = sHtml.split("\n");
} else if (sHtml.includes("<div>")) {
slParam[j] = sHtml.split("<div>");
}
//delete the blank
for (let i = slParam[j].length - 1; i >= 0; i--) {
if (slParam[j][i] == "") {
slParam[j].splice(i, 1);
} else {
break;
}
}
//count the max length of parameters
if (slParam[j].length > iParmLineCount) {
if (iParmLineCount > 0) {
bParmDiff = true;
}
iParmLineCount = slParam[j].length;
}
} else {
if (iParmLineCount > 0) {
bParmDiff = true;
}
}
}
// 2-D array to csv
for (let k = 0; k < iParmLineCount; k++) {
for (let i = 1; i <= iMax; i++) {
let sKey;
if (k >= slParam[i].length) {
sKey = "";
} else {
sKey = slParam[i][k];
}
sRtn += sKey + ",";
}
sRtn = sRtn.slice(0, -1) + "\n";
}
return sRtn;
}