-
Notifications
You must be signed in to change notification settings - Fork 1
/
tidpaste.js
executable file
·1730 lines (1585 loc) · 52 KB
/
tidpaste.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
tiddlyclip={hello:"hello"};
(function(){
tiddlyclip.modules={};
var log = function (x) {
//alert(x);
}
function status (param) {
//console.log(param);
}
if (true) {
tiddlyclip.modules.tPaste = (function () {
var api =
{
onLoad:onLoad, paste:paste,
hasMode:hasMode, setconfig:setconfig,
getconfig:getconfig, dodock:dodock,
hasModeBegining:hasModeBegining,setopts:setopts,
getopts:getopts, getconfigStatus:getconfigStatus
};
var tiddlerObj, twobj, defaults;
//** guru meditaion - maybe tiddlerObj can be moved inside paste as a step to make tc ri-entrant
function onLoad() {
tiddlerAPI = tiddlyclip.modules.tiddlerAPI;
twobj = tiddlyclip.modules.twobj;
defaults = tiddlyclip.modules.defaults;
}
/////////////////////////////////////////////////////////////////////////////
function dodock(text,aux,extra) {
var message = document.createElement("div") ,messageBox = document.getElementById("tiddlyclip-message-box");
if(messageBox) {
message.setAttribute("data-action","dock");
message.setAttribute("data-text",text||"");
message.setAttribute("data-aux",aux||"");
message.setAttribute("data-extra",extra||document.title);
//add in the version - thru tcadapter
var tidops = getopts();
var noshowtids = tidops && tidops.noshowtids && tidops.noshowtids === "yes";
if (tiddlyclip.version && !noshowtids) {
message.setAttribute("data-version",tiddlyclip.version());
}
messageBox.appendChild(message);
// Create and dispatch the custom event to the extension
var event = document.createEvent("Events");
event.initEvent("tc-send-event",true,false);
message.dispatchEvent(event);
return "docked";
} else {
return "error no extension found";
}
};
var configName="", config="",optsName="", opts="", optsEnable=false;
function findDefaultRule(rule) {
return (rule.substring(0,7)==='default') ? defaults.getDefaultRule(rule):null;
}
function findCategory (tableOfCats, category) {
var categoryRows = tableOfCats.split("\n");
var cat = {}, tagsAndModes, pieces, catFound=false;
var hasExt = false;
for (var i=0; i<categoryRows.length; i++) {
pieces = categoryRows[i].split("|");// row is = |Category|Tip|Tags|Rules Tid|Modes|
if (pieces.length==1) continue; //ingore blanklines
if (pieces.length < 7) {
alert('config table format error no of row incorrect '+categoryRows[i]);
return {valid:false};
}
if (pieces[1].substring(0,1)==='!') continue; //first row is column headings
if (category == pieces[1]) {
catFound = true;
break;
}
} //loop end
if (!catFound) {status ("not found cat: "+category);return {valid:false};}
var ruleDefs = twobj.getTidContents(pieces[4].replace(/^\[\[([\s\S]*)\]\]/,"$1"));//remove wikiword parens if present
//if rule is not found use the default rules
if (!ruleDefs) {
status ("rules not found for cat: "+category+" was "+pieces[4]);
ruleDefs = findDefaultRule(pieces[4]);
}
if (!!ruleDefs) {
try {
cat = {rules:null,valid:false};
cat.rules=addSequenceOfRules(ruleDefs,category);//one or more
cat.modes= extractModes(pieces[5]);
cat.tags = pieces[3];
cat.tip = pieces[2];
cat.valid= true;
status("found cat: "+category)
return cat;
} catch(e) {
status("caught error while adding rules for cat: " + category);
return {valid:false};
}
}
status ("rules not found for cat: "+category);
return {valid:false};
}
function setRules(cat)
{
var ruleDefs;
if (!cat.title) {
return setSingleRule(cat);
}
ruleDefs = twobj.getTidContents(cat.title);
//if rule is not found use the default rules
if (!ruleDefs) {
status ("rules not found for cat: "+category+" was "+cat.title);
ruleDefs = findDefaultRule(cat.title);//BJ tile is not correct
}
if (!!ruleDefs) {
try {
cat.rules=addSequenceOfRules(ruleDefs);//one or more
status("found cat: ");
cat.valid =true;
return cat;
} catch(e) {
status("caught error while adding rules for cat: ");
return {valid:false};
}
}
status ("rules not found for cat: "+category);
return {valid:false};
}
function setSingleRule(def) {
try {
var rule = new Rule ({title:def.tidtitle,fields:def.doz,modes:(def.rulemodes||"append")});//bj modes should be from cat??
cat = {rules:[rule],modes:def.modes};
status("dofalse cat: ");
cat.valid =true;
return cat;
} catch(e) {
status("caught error while adding rules for cat: ");
return {valid:false};
}
status ("rules not found for cat: "+category);
return {valid:false};
}
function findSection(activeSection,configTable) {
var sectionStrgs;
var content = configTable;
if (content != null) {
sectionStrgs = content.split(defaults.getDefs().FOLDSTART+'['); //sections begin with a title, , followed by a table of categories
if(sectionStrgs.length>1) {
status("found clip list format config")
sectionStrgs.shift();
//only load active categories
return (sectionStrgs[activeSection].split('!/%%/\n')[1]);//strip of section name from first line
} else {
status("found straight config format");
sectionStrgs = content.split('\n!'); //sections begin with a title, eg !mysection, followed by a table of categories
for (var j = activeSection; j < sectionStrgs.length; j++) {
if ( sectionStrgs[j].indexOf('|') !== -1) {
// assumes that '|' means there is a def table otherwise move to next sections def table
//only load active categories
return (sectionStrgs[j].replace(/(^\|)*\n/,''));//strip of section name from first line
}
}
status("config tiddler missing table");
return ([]);//not found
}
}else {
status("config tiddler not found try with default values");
return defaults.getDefaultCategories().join("\n");
}
}
//////////////////////////////////////////////////////////
function extractModes(tagString) {
var modes =[], tList = tagString.split(' ');
for (var i=0; i< tList.length; i++) {
modes[i] = tList[i].trim();
}
return modes;
}
function hasMode (cat,mode) {
if (!cat.modes) return false;
for (var i=0; i< cat.modes.length;i++)
if (mode === cat.modes[i]) return true;
return false;
}
function hasModeBegining (cat,mode) {
if (!cat.modes) return false;
for (var i=0; i< cat.modes.length;i++)
if (mode === cat.modes[i].substr(0,mode.length)) return true;
return false;
}
//////////////////////////////////////
function addSequenceOfRules(tiddler,cat) {
var ruleDefs = tiddler.trim().split("\n");
var arrayOfRules =[];
var firstRow=0,firstrule=0;
/*
if (ruleDefs[firstRow].substring(0,2)==='|!') firstRow += 1;// row maybe column titles, ie the string |!Title|!Body|!Tags|!Modes|
for (var i=firstrule,j=firstRow; j<ruleDefs.length; i++,j++) {
arrayOfRules[i]=new Rule(ruleDefs[j]);
}
*/
var j = 0;
for (var i = 0;i < ruleDefs.length;i++) {
if (ruleDefs[i].charAt(0) !== "|" || ruleDefs[i].charAt(1) === "!") continue;//row maybe column titles, ie the string |!Title|!Body|!Tags|!Modes| or a comment
arrayOfRules[j]=new Rule(ruleDefs[i]);
j++;
}
return arrayOfRules;
}
function Rule(defRule, modes) {
//INPUT DEF:
//defRule is a string of the form '|Title|Body|Tags|Fields|Init values|Modes|' or a struture { title:'..', body:'..', tags:'..'}
//extracts subst patterns for title, body, tags. Also extracts modes
var Tid;
var tList;
var modes="";
var whiteSpace = /^\s+|\s+$/g;//use trim
var isLinked = /^\[\[([\s|\S]*)\]\]$/;
if ((typeof defRule) =='string' ) { //we has a row definition
//remove triple quotes around any | - these were needed to stop TW thinking they were table elements
var pieces = defRule.replace(/\"\"\"\|\"\"\"/g,"&bar;").split("|");
if (pieces.length <7) {error('short:'+defRule);throw new Error('Invalid Rule');} //error malformeed TODO: inform the user
var tidops = getopts();
modes = pieces[6];//raw modes
for (var i=1;i<7;i++) {
pieces[i]= pieces[i].replace("&bar;","|");
if (pieces[i] == null && i !==1) {
} else if (i!=3 && isLinked.test(pieces[i])) { // -there is a definition in a seperated tiddler - go get it
var temp=pieces[i].replace (/^\[\[([\s|\S]*)\]\]$/,"$1"); //remove brackets
temp =twobj.getTidrules(temp); //this.body contains the name of the tiddler
if (temp != null) pieces[i] = temp;
} else{
if (i==6) pieces[i] = '[{"#newdata":"'+pieces[i]+'"}]';//modes
else if (i==4||i==5) pieces[i] = '['+pieces[i]+']';
else if (i==3) {
if (tidops && tidops.noautoextratags && tidops.noautoextratags === "yes") {
if (pieces[i]) pieces[i] = '[{"#space":" "},{"$tags":"((*@exists($tags)*??*$tags*))((*@exists($tags)*??*#space*))'+pieces[i]+'"}]';
else pieces[i] ='[]'; // don't modify/create
} else {
if (pieces[i]) pieces[i] = '[{"#space":" "},{"$tags":"((*@exists($tags)*??*$tags*))((*@exists($tags)*??*#space*))((*@exists(@extraTags)*??*@extraTags*)) '+pieces[i]+'"}]';
else pieces[i] ='[{"$tags":"((*@exists(@extraTags)*??*@extraTags*)) ((*@abort(@extraTags)*)) ((*@exists($tags)*??*$tags*))"}]';
}
}
else if (i==2) {
if (tidops && tidops.legacybody && tidops.legacybody === "yes")
pieces[i] = '[{"#newdata":"'+pieces[i]+'"}]';//text
else
pieces[i] = JSON.stringify([{"#newdata":pieces[i].replaceAll("\\n","\n")}]);//text
}
else if (i==1){
if (pieces[i]) pieces[i] = '[{"$title":"'+pieces[i]+'"}]';
else pieces[i] ='[{"$title":""}]'; // don't modify/create
}
}
}
this.title =pieces[1];
this.body =pieces[2];
this.tags = pieces[3];
this.fields =pieces[4];
this.InitVals=pieces[5];
this.modes =pieces[6];
if (!isLinked.test(modes)) { //modes must be simple values for final and oneshot
tList = modes.split(' ');//raw modes
for (var i=0; i< tList.length; i++) {
if (tList[i].trim()==="final") {this.final = "final"} //used with filterlist
if (tList[i].trim()==="oneshot") {this.oneshot = "oneshot"}//used with filterlist
}
}
}
else { // we are passed a structure
this.title ='[{"$title":"'+defRule.title+'"}]';
this.body = '[{"#newdata":""}]';
this.tags ='[]';
this.InitVals ='[]';//bj this look wrong - initvals are used next??
this.fields=twobj.getTidrules(defRule.fields);
this.modes = '[{"#newdata":"'+defRule.modes+'"}]';
}
}
function userInput(source){ //replace % delimited strings with user input
return source.replace(/%\[\$(.*?)\]%/g,function(m,key,offset,str){
var parts=key.split("::");
var userString={value:" "};
//alert(parts[0]+"::"+parts[1]);
if (parts.length !==2) {
//use as a single field
return m;
}
//tcBrowser.UserInputDialog(parts[1],userString);
return (userString.value);
}
)};
function decodeutf8(source) {
var chr1,chr2,chr3,result="",i=0;
while (i <source.length){
chr1= source.charCodeAt(i);
if (chr1<128) {result+= String.fromCharCode(chr1);i++;}
else {
chr2=source.charCodeAt(i+1);
if ((chr1 > 191) && (chr1 < 224)){result+= String.fromCharCode(((chr1 & 31) << 6) | (chr2 & 63));i+=2;}
else {
chr3=source.charCodeAt(i+2);
result+= String.fromCharCode(((chr1 & 15) << 12) | ((chr2 & 63) << 6) | (chr3 & 63));
i+=3;
}
}
}
return result;
}
function firstRemoteTid(pageData) {
pageData.remoteTidIndex = 0;
return pageData.remoteTidArr[0];
}
function hasNextRemoteTid(pageData) {//alert(api.remoteTidArr.length + " len "+api.remoteTidIndex );
return (pageData.remoteTidIndex < pageData.remoteTidArr.length);
}
function nextRemoteTid(pageData) {
pageData.remoteTidIndex += 1;
if (pageData.remoteTidIndex === pageData.remoteTidArr.length) return null;
return pageData.remoteTidArr[pageData.remoteTidIndex];
}
// BJ! TODO ADD A LOG THAT IS ONLY WRITTEN WHEN SAVING THE TW - this needs to be done in the finish() function of the shim
function performAction(cat,pageData) {
defaults.defaultCommands[cat].command(pageData);
}
function getconfig() {
if (config) return config;
if (!configName) return twobj.getTidContents("TiddlyClipConfig");
return twobj.getTidContents(configName)||null;
}
function getconfigStatus() {
if (config) return true;
return false;
}
function setconfig (text,name) {
config = text;
configName = name;
}
function loadOpts(ClipOpts) {
//load additional prefs from targetTW
var pieces =ClipOpts, opts={};
if (!pieces) {
return;
}
pieces.split(/\r?\n/mg).forEach(function(line) {
if(line.charAt(0) !== "#") {
var p = line.indexOf(":");
if(p !== -1) {
var field = line.substr(0, p).trim(),
value = line.substr(p+1).trim();
opts[field] = value;
}
}
});
return opts;
};
function getopts() {
if (!optsEnable) return {noautoextratags:"yes"};
if (opts) return opts;
if (!optsName) return twobj.getTiddlerData("TiddlyClipOpts");
return twobj.getTiddlerData(optsName)||null;
}
function setopts (op,name) {
opts = loadOpts(op);
optsName = name;
}
function enableOpts() {//opts only valid for docked addon
optsEnable = true;
}
function disableOpts() {
optsEnable = false;
}
// This is the function called when clicking the context menu item.
function paste(catName,pageData, section, substitutionTiddler ,setCat)
{
var cat, save = false, fromaddon = false;
if (tiddlyclip.disabled) return;
disableOpts();
try{
tiddlyclip.caller = this;
tiddlyclip.lastevent = pageData.e||null;
twobj.tiddlers = [];//list of tids to store
status ("paste enter");
if (!setCat) {
if (substitutionTiddler) {
cat = findCategory (twobj.getTidContents(substitutionTiddler), catName);
} else if (pageData.data.section === "__sys__") { //from addon - change of focused tw
cat = findCategory (findSection(section,twobj.getTidContents("TiddlyClipSys")), catName);
} else if (pageData.data.section === "__sysdock__") {//from addon to solicite dock
var tidclipconfigtext = twobj.getTidContents("TiddlyClipConfig");// bj if empty then filter on tag tcconfigfiles
var tcconf = JSON.stringify({text:tidclipconfigtext,title:'TiddlyClipConfig'});
var tidclipconfigopts = twobj.getTidContents("TiddlyClipOpts");
var tcopts = JSON.stringify({text:tidclipconfigopts,title:'TiddlyClipOpts'});
setconfig(tidclipconfigtext,'TiddlyClipConfig');
setopts(tidclipconfigopts,'TiddlyClipOpts');
status (dodock(tcconf,tcopts));
return;
} else {//from addon
fromaddon = true;
enableOpts();
cat = findCategory (findSection(section,getconfig()), catName);
}
//find the table denoted by the section (a header in the TiddlyClipConfig ), then find the row (cat)
if (!cat.valid) {
cat = findCategory (findSection(section), catName);//look for default rule
}
}else {
cat = setRules(setCat);
}
if (!cat.valid) {
status("not valid category");
return;
}
status ("valid category");
//could check for type of cat.rules if function then run -- allows module plugin with Tw5
var cancelled = {val:false};
var catTags = cat.tags;//main config tags
var rules = cat.rules;
var startrule=0;
if(hasMode(cat,"nosub")) return;
//now loop over each tiddler to be created(defined in the category's extension entry)
//if a list of tiddlers are to be copied from a page then we will have to loop over them as well
tiddlerAPI.parserReset(true); //and expose %$hasGlobalSaver
//console.log("nosave",cat.modes)
status ("before subst loop");
if (!hasModeBegining(cat,"tiddler")) { //user has not selected tiddler mode
for(var i=startrule; i<rules.length; i++) {
var tiddlerObj, writeMode;
tiddlerObj = new tiddlerAPI.Tiddler();
status ("before subst");
tiddlerObj.copyCatModes(cat.modes);
tiddlerObj.setPageVars(pageData);
tiddlerObj.setNormal(rules[i],fromaddon);
tiddlerObj.subst(rules[i]);
status ("after subst");
//tiddlerObj.text=userInput(tiddlerObj.text); //not used at present
tiddlerObj.addTags(catTags);
status ("after addTags");
if (cancelled.val==true) {return;}
//if (pageData.data.WriteMode !="none") writeMode=pageData.data.WriteMode;
//add tiddlers one by one to our list of edits
twobj.pushTiddler(tiddlerObj);
status ("after push to list");
}
} else {
var tid, hasfinalrule=-1;
for (tid=firstRemoteTid(pageData); hasNextRemoteTid(pageData);tid=nextRemoteTid(pageData)){
if (!hasMode(cat,"tiddlerscopy")) {
var filterMode = hasModeBegining(cat,"tiddlerFilter"), filterMakeMode = hasMode(cat,"tiddlerFilterMake")
for(var i=startrule; i<rules.length; i++) {
var tiddlerObj,existingTid = true;
if (rules[i].ignore) continue;
if (rules[i].final) {
hasfinalrule=i;
rules[i].ignore=true;
continue;
}
if (rules[i].oneshot) {
rules[i].ignore=true;
}
//** guru meditaion
if (filterMode) {// we have the name of a tid
existingTid = twobj.getTiddler(tid,!hasMode(cat,'nocache'));
if (existingTid) {
tiddlerObj = new tiddlerAPI.Tiddler(existingTid,true);
} else { // create missing tid
if (filterMakeMode) {
tiddlerObj = new tiddlerAPI.Tiddler({fields:{title:tid,text:""}},true);
}
else throw ('non-existant tid');
}
} else {
tiddlerObj = new tiddlerAPI.Tiddler(tid);//from browser addon etc
}
status ("before subst");
tiddlerObj.copyCatModes(cat.modes);
tiddlerObj.setPageVars(pageData);
tiddlerObj.setTids(rules[i],{"externalTid":fromaddon,"newTid":!existingTid});
//guru meditation we can check mode on 'pattern' and so put this at the begining of loop
//and not create tiddlerObj un-neccessarily
//guru meditation we can check mode on 'pattern' and so put this at the begining of loop
//and not create tiddlerObj un-neccessarily -but what about 'calcuated modes?' - what are they used for??
//The 'modes' are cacluated in the 'setTids' so we cannot move this before that call.
if (tiddlerObj.hasMode("oneshot") ) {
//console.log("oneshot second call is good "+i);
}
if (tiddlerObj.hasMode("final") ) {
//console.log("final again second call is bad "+i);
}
if (tiddlerObj.hasMode("normal")||tiddlerObj.hasMode("oneshot")) {
tiddlerObj = new tiddlerAPI.Tiddler();
status ("reset for normal");
tiddlerObj.copyCatModes(cat.modes);
tiddlerObj.setPageVars(pageData);
tiddlerObj.setNormal(rules[i],fromaddon);
} else if (tiddlerObj.hasMode("nontid")) {
tiddlerObj.fields={};
tiddlerObj.setPageVars(pageData);
tiddlerObj.setNormal(rules[i],fromaddon);
}
tiddlerObj.subst(rules[i]);
status ("after subst");
//tiddlerObj.text=userInput(tiddlerObj.text); //not used at present
tiddlerObj.addTags(catTags);
status ("after addTags");
if (cancelled.val==true) {return;}
//if (pageData.data.WriteMode !="none") writeMode=pageData.data.WriteMode;
//add tiddlers one by one to our list of edits
twobj.pushTiddler(tiddlerObj);
status ("after push to list");
}
}
else {
tiddlerObj=new tiddlerAPI.Tiddler(tid);
tiddlerObj.addTags(catTags);
twobj.pushTiddler(tiddlerObj);
}
}
if (hasfinalrule>-1) {
var tiddlerObj, writeMode ,i=hasfinalrule;
tiddlerObj = new tiddlerAPI.Tiddler();
status ("final before subst");
tiddlerObj.copyCatModes(cat.modes);
tiddlerObj.setPageVars(pageData);
tiddlerObj.setNormal(rules[i],fromaddon);
tiddlerObj.subst(rules[i]);
status ("final after subst");
//tiddlerObj.text=userInput(tiddlerObj.text); //not used at present
tiddlerObj.addTags(catTags);
status ("final after addTags");
if (cancelled.val==true) {return;}
//if (pageData.data.WriteMode !="none") writeMode=pageData.data.WriteMode;
//add tiddlers one by one to our list of edits
twobj.pushTiddler(tiddlerObj);
status ("final after push to list");
}
}
if(hasMode(cat,"immediate")) {
status ("before immediate tids to tw");
var tidimmdiate=[];
for (var i =0; i< twobj.tiddlers.length; i++) {
tidimmdiate.push(twobj.immediatetids(twobj.tiddlers[i]));
}
return tidimmdiate;
}
if(hasMode(cat,"nosave")) return;
status ("before adding to tw");
var tidnames=[];
for (var i =0; i< twobj.tiddlers.length; i++) {
if (!twobj.tiddlers[i].noSave()){
twobj.tiddlers[i].deHydrate();
addTiddlerToTW(twobj.tiddlers[i]);
save = true;
}
if(twobj.tiddlers[i].hasMode("open")) tidnames.push(twobj.tiddlers[i].fields.title);
}
if(hasMode(cat,"nofin")) return;
if(hasMode(cat,"noautosave")) save = false;
twobj.finish(tidnames,save);
}catch (e) {console.log(e)}
}
function save(tiddlerObj) {
switch (tiddlerObj.getSaveMode()) {
case 'add/import':
if (twobj.tiddlerExists(tiddlerObj.fields.title)) twobj.importtids(tiddlerObj);
else twobj.modifyTW(tiddlerObj);
break;
case 'add':
twobj.modifyTW(tiddlerObj);
break;
default: //import
twobj.importtids(tiddlerObj);
}
}
function addTiddlerToTW( tiddlerObj) {
switch (tiddlerObj.getWriteMode()) {
case 'once':
var oldtid = tiddlyclip.getTiddler(tiddlerObj.fields.title);//retrieve existing version
if (!!oldtid) break;
save(tiddlerObj);
break;
case 'move':
var oldtid = tiddlyclip.getTiddler(tiddlerObj.fields.title);//retrieve existing version
if (!!oldtid) {
oldtid.fields.title =oldtid.fields.title +'/'+ new Date();//move old tid by appending the date to its title
oldtid.modes = tiddlerObj.modes //need to know the save mode
save(oldtid);//move out the way//BJ this is a bug - save expects a tiddlerObj
}
save(tiddlerObj);
break;
case 'inc':
tiddlerObj.fields.title = twobj.getNewTitle(tiddlerObj.fields.title);
save(tiddlerObj);
break;
case 'delete':
tiddlerObj.fields.title = twobj.deleteTiddler(tiddlerObj.fields.title);
break;
default: //import
save(tiddlerObj);
}
}
return api;
}());
///end tPaste ///
tiddlyclip.modules.twobj = (function () {
var api =
{
onLoad:onLoad, tiddlerExists:tiddlerExists,
modifyTW:modifyTW, getTiddler:getTiddler,
getTidContents:getTidContents,finish:finish,
importtids:importtids, getNewTitle:getNewTitle,
getTidrules:getTidrules, getTiddlerData:getTiddlerData,
immediatetids:immediatetids,deleteTiddler:deleteTiddler,
tiddlers:null, pushTiddler:pushTiddler,
inCache:inCache
}
var tiddlerAPI;
function onLoad () {
tiddlerAPI = tiddlyclip.modules.tiddlerAPI;
}
var tw =null;
var storeStart;
function getTidContents(tidname) {
return tiddlyclip.getTidContents(tidname);
}
function getTiddlerData(tid) {
return tiddlyclip.getTiddlerData(tid);
}
function deleteTiddler(tid) {
return tiddlyclip.deleteTiddler(tid);
}
function getTidrules(tidname) {
return tiddlyclip.getTidrules(tidname);
}
function getNewTitle(tidname) {
return tiddlyclip.getNewTitle(tidname);
}
function getTiddler(tidRefName,usecache) {
var storedTid, found=false, tidname = tidRefName, tid, simple = true, subtid = null;
var tiddler = tiddlyclip.getMultiTidTitle(tidname);
if(tiddler.container) {
tidname = tiddler.container;
subtid = tiddler.title;
simple = false;
}
//console.log("tids no is "+api.tiddlers.length);
if (!!usecache) {
for (var i = 0; i < api.tiddlers.length; i++){
if (api.tiddlers[i].fields.title === tidname) {
status("found in cache " +tidname);
if (simple) return api.tiddlers[i];
//// look for subtid
tid = api.tiddlers[i].getSubTid(subtid);
if (tid) {
//put text ref as name
tid.fields.title = tidRefName;
status("subtid found in cache " +tidRefName);
return tid;
}
break; //subtid not found in cached parent tiddler
}
}
}
status("not found in cache " + tidRefName);
storedTid=tiddlyclip.getTiddler(tidRefName);//get external tid
if (storedTid) {
var tid;
if (!subtid) return (new tiddlerAPI.Tiddler(storedTid,true));//make internal version
tid= new tiddlerAPI.Tiddler(storedTid,true);
tid.fields.title = tidRefName;
return tid;
}
return null;
}
function pushTiddler(tid) {
var tiddlerMultiTitle, storedTid, found=false, tidname=tid.fields.title, simple = true, subtid = null;
if (!tidname) return;
tiddlerMultiTitle = tiddlyclip.getMultiTidTitle(tidname);
if(tiddlerMultiTitle.container) {
tidname = tiddlerMultiTitle.container;
subtid = tiddlerMultiTitle.title;
simple = false;
}
for (var i = 0; i < api.tiddlers.length; i++){
if (api.tiddlers[i].fields.title === tidname) {
status("foundpush "+tidname);
if (simple) {// but could be a plugin
// check to see if it has modified sub tids
var theSubTids = api.tiddlers[i].tiddlers;
api.tiddlers[i]=tid;
if (!!theSubTids) api.tiddlers[i].tiddlers = theSubTids
return;
}
else {
//bj gurumeditaion - if inc mode we should create a new tid with inc'd title here???
tid.fields.title = subtid;
api.tiddlers[i].putSubTid(tid);
return;
}
}
}
//not in cache - add
if (simple) {
api.tiddlers.push(tid);
return
}
//the 'plugin' (parent) of the tiddler is not in cache then load it!
storedTid = tiddlyclip.getSimpleTiddler(tidname);
if (storedTid) tiddler = new tiddlerAPI.Tiddler(storedTid,true);
else {//create new parent tid
var initVals = {text:{tiddlers:{}}, title:tidname, "plugin-type":""};
tiddler = new tiddlerAPI.Tiddler(initVals,true);
}
status("subpush " + subtid + " parent " +tidname);
tid.fields.title = subtid;
tiddler.putSubTid(tid);
api.tiddlers.push(tiddler);
}
function inCache(tidRefName) {
var storedTid, tiddler, found=false, tidname = tidRefName, tid, simple = true, subtid = null;
if (!tidRefName) return false;
tiddler = tiddlyclip.getMultiTidTitle(tidname);
if(tiddler.container) {
tidname = tiddler.container;
subtid = tiddler.title;
simple = false;
}
//console.log("tids no is "+api.tiddlers.length);
for (var i = 0; i < api.tiddlers.length; i++){
if (api.tiddlers[i].fields.title === tidname) {
status("found in cache " +tidname);
if (simple) return true;
//// look for subtid
tid = api.tiddlers[i].getSubTid(subtid);
if (tid) {
return true;
}
break; //subtid not found in cached parent tiddler
}
}
status("not found in cache SEARCH " + tidRefName);
return false;
}
function modifyTW(t)
{
var fields={};
for (var i in t.fields) {
fields[i]=t.fields[i];
}
tiddlyclip.modifyTW(fields);
}
function importtids(t){
var fields={};
for (var i in t.fields) {
fields[i]=t.fields[i];
}
tiddlyclip.importTids(fields);
}
function immediatetids(t){
var fields={};
for (var i in t.fields) {
fields[i]=t.fields[i];
}
return fields;
}
function tiddlerExists(title) {
return tiddlyclip.tiddlerExists(title);
}
function finish(tids,save)
{
tiddlyclip.finish(tids,save);
}
return api;
}());
///end twobj///
tiddlyclip.modules.tiddlerAPI = (function () {
var api =
{
onLoad:onLoad, Tiddler:Tiddler, parserReset:parserReset, initJSinterface:initJSinterface
}
var tcBrowser, twobj,pref, util, table;
function onLoad(doc) {
tcBrowser = tiddlyclip.modules.tcBrowser;
twobj = tiddlyclip.modules.twobj;
defaults = tiddlyclip.modules.defaults;
}
function parserReset(globsaver) {
table=globsaver?{'%':{"$hasGlobalSaver":"true"}}:{'%':{"$hasGlobalSaver":"false"}};
}
function createDiv(){
return document.createElement("div");
}
// Static method to bracket a string with double square brackets if it contains a space
function encodeTiddlyLink(title)
{
return title.indexOf(" ") == -1 ? title : "[[" + title + "]]";
};
// Static method to encodeTiddlyLink for every item in an array and join them with spaces
function encodeTiddlyLinkList(list)
{
if(list) {
var t,results = [];
for(t=0; t<list.length; t++)
results.push(encodeTiddlyLink(list[t]));
return results.join(" ");
} else {
return "";
}
};
function removeDuplicates(names) {
var i,j,dup,nams = [];
nlist = tiddlyclip.parseStringArray(names);
/*
for ( i=0; i < nlist.length; i++)
nlist[i] = nlist[i].trim();
for ( i=0; i < nlist.length; i++){
dup = false;
for ( j = i ; j > 0; j--) {
if (nlist[i] === nlist[j-1]){
dup = true;// alert("dup");
break;
}
}
if (!dup) nams.push(nlist[i]);
}
*/
return encodeTiddlyLinkList(nlist);
}
function initJSinterface(callback) {
callback ({
_encodeTiddlyLinkList:encodeTiddlyLinkList,
_sAll :updateTables,
_gAll :cloneTables,
_s :setVar,
_g :getVar
});
}
function getVar(x){return valOf(x,true);}
function setVar (x,y,z){table[x][y]=toString(z);}
function Tiddler(el,truetid) {
this.toRemove =[];
var current = this,el = el;
current.fields = {};
current.fields.text ="";
//current.fields.title ="";
function convertedFromJSON(el) {
try {
var tid =JSON.parse(el);
for (var atr in tid){
current.fields[atr]=tid[atr];
}
return true;
} catch(e){
return false;
}
}
if (!el) {
el = tiddlyclip.newProtoTiddler();
for (var atr in el.fields){
current.fields[atr]=el.fields[atr];
}
this.fields.tags="";//BJ FIX remove or move to adapter
} else if (!truetid) {
if((typeof el) ==="string"){
if (convertedFromJSON(el)) return this; //conversion complete
//convert html to dom ;
var wrapper= createDiv();
wrapper.innerHTML= el;
el= wrapper.firstChild;
wrapper = {};//release div
}
this.fields.text = undoHtmlEncode(el.innerHTML.
replace(/\n<pre xmlns="http:\/\/www.w3.org\/1999\/xhtml">([\s|\S]*)<\/pre>\n/mg,"$1").
replace(/\n<pre>([\s|\S]*)<\/pre>\n/mg,"$1"));
var j = el.attributes, m, extraTags='';
for (var i = j.length; i!== 0; i--) {
m=j[i-1].nodeName;
v=j[i-1].value;
this.fields[m] = undoHtmlEncode(v) ;
}
} else {
//if((typeof el) ==="string") {var name = el; el = $tw.wiki.getTiddler(el);}//passed in name of tiddler -BJ change $tw to tiddlyclip
//if (!el) console.log ("notid with name "+name);
for (var atr in el.fields){
current.fields[atr]=el.fields[atr];
}
if (!!this.fields.tags) this.fields.tags = (this.fields.tags instanceof Array)?this.fields.tags.join(' '):this.fields.tags;
else this.fields.tags="";
//this.body = this.text;
}
return this;
}
Tiddler.prototype.getSubTid=function(subtidTitle) {
if (this.tiddlers && this.tiddlers[subtidTitle]) return this.tiddlers[subtidTitle];
try {
var subtid = (JSON.parse(this.fields.text)).tiddlers[subtidTitle];
if (!!subtid) return new Tiddler(subtid);
return null;
} catch (e) {
return null;
}
}
Tiddler.prototype.putSubTid=function(subtid) {
status("putSubTid "+subtid.fields.title);
if (!this.tiddlers) this.tiddlers = {};
this.tiddlers[subtid.fields.title] = subtid;
}
Tiddler.prototype.deHydrate=function() {
var oldtids,tid;
if (this.tiddlers) {
try {oldtids = (JSON.parse(this.fields.text)).tiddlers;}
catch (e){
oldtids = {}
}
} else {
return;//no new or updated subtids