forked from mathjax/MathJax
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MathJax.js
3107 lines (2923 loc) · 115 KB
/
MathJax.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
/* -*- Mode: Javascript; indent-tabs-mode:nil; js-indent-level: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/*************************************************************
*
* MathJax.js
*
* The main support code for the MathJax Hub, including the
* Ajax, Callback, Messaging, and Object-Oriented Programming
* libraries, as well as the base Jax classes, and startup
* processing code.
*
* ---------------------------------------------------------------------
*
* Copyright (c) 2009-2013 The MathJax Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//
// Check if browser can support MathJax (no one fails this nowadays)
//
if (document.getElementById && document.childNodes && document.createElement) {
//
// Skip if MathJax is already loaded
//
if (!(window.MathJax && MathJax.Hub)) {
//
// Get author configuration from MathJax variable, if any
//
if (window.MathJax) {window.MathJax = {AuthorConfig: window.MathJax}}
else {window.MathJax = {}}
// MathJax.isPacked = true; // This line is uncommented by the packer.
MathJax.version = "2.3";
MathJax.fileversion = "2.3.1";
/**********************************************************/
(function (BASENAME) {
var BASE = window[BASENAME];
if (!BASE) {BASE = window[BASENAME] = {}}
var PROTO = []; // a static object used to indicate when a prototype is being created
var OBJECT = function (def) {
var obj = def.constructor; if (!obj) {obj = new Function("")}
for (var id in def) {if (id !== 'constructor' && def.hasOwnProperty(id)) {obj[id] = def[id]}}
return obj;
};
var CONSTRUCTOR = function () {
return new Function ("return arguments.callee.Init.call(this,arguments)");
};
//
// Test for Safari 2.x bug (can't replace prototype for result of new Function()).
// (We don't use this version for everyone since it is a closure and we don't need that).
//
var BUGTEST = CONSTRUCTOR(); BUGTEST.prototype = {bug_test: 1};
if (!BUGTEST.prototype.bug_test) {
CONSTRUCTOR = function () {
return function () {return arguments.callee.Init.call(this,arguments)};
};
};
BASE.Object = OBJECT({
constructor: CONSTRUCTOR(),
Subclass: function (def,classdef) {
var obj = CONSTRUCTOR();
obj.SUPER = this; obj.Init = this.Init;
obj.Subclass = this.Subclass; obj.Augment = this.Augment;
obj.protoFunction = this.protoFunction;
obj.can = this.can; obj.has = this.has; obj.isa = this.isa;
obj.prototype = new this(PROTO);
obj.prototype.constructor = obj; // the real constructor
obj.Augment(def,classdef);
return obj;
},
Init: function (args) {
var obj = this;
if (args.length === 1 && args[0] === PROTO) {return obj}
if (!(obj instanceof args.callee)) {obj = new args.callee(PROTO)}
return obj.Init.apply(obj,args) || obj;
},
Augment: function (def,classdef) {
var id;
if (def != null) {
for (id in def) {if (def.hasOwnProperty(id)) {this.protoFunction(id,def[id])}}
// MSIE doesn't list toString even if it is not native so handle it separately
if (def.toString !== this.prototype.toString && def.toString !== {}.toString)
{this.protoFunction('toString',def.toString)}
}
if (classdef != null) {
for (id in classdef) {if (classdef.hasOwnProperty(id)) {this[id] = classdef[id]}}
}
return this;
},
protoFunction: function (id,def) {
this.prototype[id] = def;
if (typeof def === "function") {def.SUPER = this.SUPER.prototype}
},
prototype: {
Init: function () {},
SUPER: function (fn) {return fn.callee.SUPER},
can: function (method) {return typeof(this[method]) === "function"},
has: function (property) {return typeof(this[property]) !== "undefined"},
isa: function (obj) {return (obj instanceof Object) && (this instanceof obj)}
},
can: function (method) {return this.prototype.can.call(this,method)},
has: function (property) {return this.prototype.has.call(this,property)},
isa: function (obj) {
var constructor = this;
while (constructor) {
if (constructor === obj) {return true} else {constructor = constructor.SUPER}
}
return false;
},
SimpleSUPER: OBJECT({
constructor: function (def) {return this.SimpleSUPER.define(def)},
define: function (src) {
var dst = {};
if (src != null) {
for (var id in src) {if (src.hasOwnProperty(id)) {dst[id] = this.wrap(id,src[id])}}
// MSIE doesn't list toString even if it is not native so handle it separately
if (src.toString !== this.prototype.toString && src.toString !== {}.toString)
{dst.toString = this.wrap('toString',src.toString)}
}
return dst;
},
wrap: function (id,f) {
if (typeof(f) === 'function' && f.toString().match(/\.\s*SUPER\s*\(/)) {
var fn = new Function(this.wrapper);
fn.label = id; fn.original = f; f = fn;
fn.toString = this.stringify;
}
return f;
},
wrapper: function () {
var fn = arguments.callee;
this.SUPER = fn.SUPER[fn.label];
try {var result = fn.original.apply(this,arguments)}
catch (err) {delete this.SUPER; throw err}
delete this.SUPER;
return result;
}.toString().replace(/^\s*function\s*\(\)\s*\{\s*/i,"").replace(/\s*\}\s*$/i,""),
toString: function () {
return this.original.toString.apply(this.original,arguments);
}
})
});
})("MathJax");
/**********************************************************/
/*
* Create a callback function from various forms of data:
*
* MathJax.Callback(fn) -- callback to a function
*
* MathJax.Callback([fn]) -- callback to function
* MathJax.Callback([fn,data...])
* -- callback to function with given data as arguments
* MathJax.Callback([object,fn])
* -- call fn with object as "this"
* MathJax.Callback([object,fn,data...])
* -- call fn with object as "this" and data as arguments
* MathJax.Callback(["method",object])
* -- call method of object wth object as "this"
* MathJax.Callback(["method",object,data...])
* -- as above, but with data as arguments to method
*
* MathJax.Callback({hook: fn, data: [...], object: this})
* -- give function, data, and object to act as "this" explicitly
*
* MathJax.Callback("code") -- callback that compiles and executes a string
*
* MathJax.Callback([...],i)
* -- use slice of array starting at i and interpret
* result as above. (Used for passing "arguments" array
* and trimming initial arguments, if any.)
*/
/*
* MathJax.Callback.After([...],cb1,cb2,...)
* -- make a callback that isn't called until all the other
* ones are called first. I.e., wait for a union of
* callbacks to occur before making the given callback.
*/
/*
* MathJax.Callback.Queue([callback,...])
* -- make a synchronized queue of commands that process
* sequentially, waiting for those that return uncalled
* callbacks.
*/
/*
* MathJax.Callback.Signal(name)
* -- finds or creates a names signal, to which listeners
* can be attached and are signaled by messages posted
* to the signal. Responses can be asynchronous.
*/
(function (BASENAME) {
var BASE = window[BASENAME];
if (!BASE) {BASE = window[BASENAME] = {}}
//
// Create a callback from an associative array
//
var CALLBACK = function (data) {
var cb = new Function("return arguments.callee.execute.apply(arguments.callee,arguments)");
for (var id in CALLBACK.prototype) {
if (CALLBACK.prototype.hasOwnProperty(id)) {
if (typeof(data[id]) !== 'undefined') {cb[id] = data[id]}
else {cb[id] = CALLBACK.prototype[id]}
}
}
cb.toString = CALLBACK.prototype.toString;
return cb;
};
CALLBACK.prototype = {
isCallback: true,
hook: function () {},
data: [],
object: window,
execute: function () {
if (!this.called || this.autoReset) {
this.called = !this.autoReset;
return this.hook.apply(this.object,this.data.concat([].slice.call(arguments,0)));
}
},
reset: function () {delete this.called},
toString: function () {return this.hook.toString.apply(this.hook,arguments)}
};
var ISCALLBACK = function (f) {
return (typeof(f) === "function" && f.isCallback);
}
//
// Evaluate a string in global context
//
var EVAL = function (code) {return eval.call(window,code)}
EVAL("var __TeSt_VaR__ = 1"); // check if it works in global context
if (window.__TeSt_VaR__) {
try { delete window.__TeSt_VaR__; } // NOTE IE9 throws when in IE7 mode
catch (error) { window.__TeSt_VaR__ = null; }
} else {
if (window.execScript) {
// IE
EVAL = function (code) {
BASE.__code = code;
code = "try {"+BASENAME+".__result = eval("+BASENAME+".__code)} catch(err) {"+BASENAME+".__result = err}";
window.execScript(code);
var result = BASE.__result; delete BASE.__result; delete BASE.__code;
if (result instanceof Error) {throw result}
return result;
}
} else {
// Safari2
EVAL = function (code) {
BASE.__code = code;
code = "try {"+BASENAME+".__result = eval("+BASENAME+".__code)} catch(err) {"+BASENAME+".__result = err}";
var head = (document.getElementsByTagName("head"))[0]; if (!head) {head = document.body}
var script = document.createElement("script");
script.appendChild(document.createTextNode(code));
head.appendChild(script); head.removeChild(script);
var result = BASE.__result; delete BASE.__result; delete BASE.__code;
if (result instanceof Error) {throw result}
return result;
}
}
}
//
// Create a callback from various types of data
//
var USING = function (args,i) {
if (arguments.length > 1) {
if (arguments.length === 2 && !(typeof arguments[0] === 'function') &&
arguments[0] instanceof Object && typeof arguments[1] === 'number')
{args = [].slice.call(args,i)}
else {args = [].slice.call(arguments,0)}
}
if (args instanceof Array && args.length === 1) {args = args[0]}
if (typeof args === 'function') {
if (args.execute === CALLBACK.prototype.execute) {return args}
return CALLBACK({hook: args});
} else if (args instanceof Array) {
if (typeof(args[0]) === 'string' && args[1] instanceof Object &&
typeof args[1][args[0]] === 'function') {
return CALLBACK({hook: args[1][args[0]], object: args[1], data: args.slice(2)});
} else if (typeof args[0] === 'function') {
return CALLBACK({hook: args[0], data: args.slice(1)});
} else if (typeof args[1] === 'function') {
return CALLBACK({hook: args[1], object: args[0], data: args.slice(2)});
}
} else if (typeof(args) === 'string') {
return CALLBACK({hook: EVAL, data: [args]});
} else if (args instanceof Object) {
return CALLBACK(args);
} else if (typeof(args) === 'undefined') {
return CALLBACK({});
}
throw Error("Can't make callback from given data");
};
//
// Wait for a given time to elapse and then perform the callback
//
var DELAY = function (time,callback) {
callback = USING(callback);
callback.timeout = setTimeout(callback,time);
return callback;
};
//
// Callback used by AFTER, QUEUE, and SIGNAL to check if calls have completed
//
var WAITFOR = function (callback,signal) {
callback = USING(callback);
if (!callback.called) {WAITSIGNAL(callback,signal); signal.pending++}
};
var WAITEXECUTE = function () {
var signals = this.signal; delete this.signal;
this.execute = this.oldExecute; delete this.oldExecute;
var result = this.execute.apply(this,arguments);
if (ISCALLBACK(result) && !result.called) {WAITSIGNAL(result,signals)} else {
for (var i = 0, m = signals.length; i < m; i++) {
signals[i].pending--;
if (signals[i].pending <= 0) {signals[i].call()}
}
}
};
var WAITSIGNAL = function (callback,signals) {
if (!(signals instanceof Array)) {signals = [signals]}
if (!callback.signal) {
callback.oldExecute = callback.execute;
callback.execute = WAITEXECUTE;
callback.signal = signals;
} else if (signals.length === 1) {callback.signal.push(signals[0])}
else {callback.signal = callback.signal.concat(signals)}
};
//
// Create a callback that is called when a collection of other callbacks have
// all been executed. If the callback gets called immediately (i.e., the
// others are all already called), check if it returns another callback
// and return that instead.
//
var AFTER = function (callback) {
callback = USING(callback);
callback.pending = 0;
for (var i = 1, m = arguments.length; i < m; i++)
{if (arguments[i]) {WAITFOR(arguments[i],callback)}}
if (callback.pending === 0) {
var result = callback();
if (ISCALLBACK(result)) {callback = result}
}
return callback;
};
//
// An array of prioritized hooks that are executed sequentially
// with a given set of data.
//
var HOOKS = MathJax.Object.Subclass({
//
// Initialize the array and the auto-reset status
//
Init: function (reset) {
this.hooks = [];
this.reset = reset;
},
//
// Add a callback to the list, in priority order (default priority is 10)
//
Add: function (hook,priority) {
if (priority == null) {priority = 10}
if (!ISCALLBACK(hook)) {hook = USING(hook)}
hook.priority = priority;
var i = this.hooks.length;
while (i > 0 && priority < this.hooks[i-1].priority) {i--}
this.hooks.splice(i,0,hook);
return hook;
},
Remove: function (hook) {
for (var i = 0, m = this.hooks.length; i < m; i++) {
if (this.hooks[i] === hook) {this.hooks.splice(i,1); return}
}
},
//
// Execute the list of callbacks, resetting them if requested.
// If any return callbacks, return a callback that will be
// executed when they all have completed.
//
Execute: function () {
var callbacks = [{}];
for (var i = 0, m = this.hooks.length; i < m; i++) {
if (this.reset) {this.hooks[i].reset()}
var result = this.hooks[i].apply(window,arguments);
if (ISCALLBACK(result) && !result.called) {callbacks.push(result)}
}
if (callbacks.length === 1) {return null}
if (callbacks.length === 2) {return callbacks[1]}
return AFTER.apply({},callbacks);
}
});
//
// Run an array of callbacks passing them the given data.
// (Legacy function, since this has been replaced by the HOOKS object).
//
var EXECUTEHOOKS = function (hooks,data,reset) {
if (!hooks) {return null}
if (!(hooks instanceof Array)) {hooks = [hooks]}
if (!(data instanceof Array)) {data = (data == null ? [] : [data])}
var handler = HOOKS(reset);
for (var i = 0, m = hooks.length; i < m; i++) {handler.Add(hooks[i])}
return handler.Execute.apply(handler,data);
};
//
// Command queue that performs commands in order, waiting when
// necessary for commands to complete asynchronousely
//
var QUEUE = BASE.Object.Subclass({
//
// Create the queue and push any commands that are specified
//
Init: function () {
this.pending = 0; this.running = 0;
this.queue = [];
this.Push.apply(this,arguments);
},
//
// Add commands to the queue and run them. Adding a callback object
// (rather than a callback specification) queues a wait for that callback.
// Return the final callback for synchronization purposes.
//
Push: function () {
var callback;
for (var i = 0, m = arguments.length; i < m; i++) {
callback = USING(arguments[i]);
if (callback === arguments[i] && !callback.called)
{callback = USING(["wait",this,callback])}
this.queue.push(callback);
}
if (!this.running && !this.pending) {this.Process()}
return callback;
},
//
// Process the command queue if we aren't waiting on another command
//
Process: function (queue) {
while (!this.running && !this.pending && this.queue.length) {
var callback = this.queue[0];
queue = this.queue.slice(1); this.queue = [];
this.Suspend(); var result = callback(); this.Resume();
if (queue.length) {this.queue = queue.concat(this.queue)}
if (ISCALLBACK(result) && !result.called) {WAITFOR(result,this)}
}
},
//
// Suspend/Resume command processing on this queue
//
Suspend: function () {this.running++},
Resume: function () {if (this.running) {this.running--}},
//
// Used by WAITFOR to restart the queue when an action completes
//
call: function () {this.Process.apply(this,arguments)},
wait: function (callback) {return callback}
});
//
// Create a named signal that listeners can attach to, to be signaled by
// postings made to the signal. Posts are queued if they occur while one
// is already in process.
//
var SIGNAL = QUEUE.Subclass({
Init: function (name) {
QUEUE.prototype.Init.call(this);
this.name = name;
this.posted = []; // the messages posted so far
this.listeners = HOOKS(true); // those with interest in this signal
},
//
// Post a message to the signal listeners, with callback for when complete
//
Post: function (message,callback,forget) {
callback = USING(callback);
if (this.posting || this.pending) {
this.Push(["Post",this,message,callback,forget]);
} else {
this.callback = callback; callback.reset();
if (!forget) {this.posted.push(message)}
this.Suspend(); this.posting = true;
var result = this.listeners.Execute(message);
if (ISCALLBACK(result) && !result.called) {WAITFOR(result,this)}
this.Resume(); delete this.posting;
if (!this.pending) {this.call()}
}
return callback;
},
//
// Clear the post history (so new listeners won't get old messages)
//
Clear: function (callback) {
callback = USING(callback);
if (this.posting || this.pending) {
callback = this.Push(["Clear",this,callback]);
} else {
this.posted = [];
callback();
}
return callback;
},
//
// Call the callback (all replies are in) and process the command queue
//
call: function () {this.callback(this); this.Process()},
//
// A listener calls this to register intrest in the signal (so it will be called
// when posts occur). If ignorePast is true, it will not be sent the post history.
//
Interest: function (callback,ignorePast,priority) {
callback = USING(callback);
this.listeners.Add(callback,priority);
if (!ignorePast) {
for (var i = 0, m = this.posted.length; i < m; i++) {
callback.reset();
var result = callback(this.posted[i]);
if (ISCALLBACK(result) && i === this.posted.length-1) {WAITFOR(result,this)}
}
}
return callback;
},
//
// A listener calls this to remove itself from a signal
//
NoInterest: function (callback) {
this.listeners.Remove(callback);
},
//
// Hook a callback to a particular message on this signal
//
MessageHook: function (msg,callback,priority) {
callback = USING(callback);
if (!this.hooks) {this.hooks = {}; this.Interest(["ExecuteHooks",this])}
if (!this.hooks[msg]) {this.hooks[msg] = HOOKS(true)}
this.hooks[msg].Add(callback,priority);
for (var i = 0, m = this.posted.length; i < m; i++)
{if (this.posted[i] == msg) {callback.reset(); callback(this.posted[i])}}
return callback;
},
//
// Execute the message hooks for the given message
//
ExecuteHooks: function (msg,more) {
var type = ((msg instanceof Array) ? msg[0] : msg);
if (!this.hooks[type]) {return null}
return this.hooks[type].Execute(msg);
}
},{
signals: {}, // the named signals
find: function (name) {
if (!SIGNAL.signals[name]) {SIGNAL.signals[name] = new SIGNAL(name)}
return SIGNAL.signals[name];
}
});
//
// The main entry-points
//
BASE.Callback = BASE.CallBack = USING;
BASE.Callback.Delay = DELAY;
BASE.Callback.After = AFTER;
BASE.Callback.Queue = QUEUE;
BASE.Callback.Signal = SIGNAL.find;
BASE.Callback.Hooks = HOOKS;
BASE.Callback.ExecuteHooks = EXECUTEHOOKS;
})("MathJax");
/**********************************************************/
(function (BASENAME) {
var BASE = window[BASENAME];
if (!BASE) {BASE = window[BASENAME] = {}}
var isSafari2 = (navigator.vendor === "Apple Computer, Inc." &&
typeof navigator.vendorSub === "undefined");
var sheets = 0; // used by Safari2
//
// Update sheets count and look up the head object
//
var HEAD = function (head) {
if (document.styleSheets && document.styleSheets.length > sheets)
{sheets = document.styleSheets.length}
if (!head) {
head = (document.getElementsByTagName("head"))[0];
if (!head) {head = document.body}
}
return head;
};
//
// Remove scripts that are completed so they don't clutter up the HEAD.
// This runs via setTimeout since IE7 can't remove the script while it is running.
//
var SCRIPTS = []; // stores scripts to be removed after a delay
var REMOVESCRIPTS = function () {
for (var i = 0, m = SCRIPTS.length; i < m; i++) {BASE.Ajax.head.removeChild(SCRIPTS[i])}
SCRIPTS = [];
};
BASE.Ajax = {
loaded: {}, // files already loaded
loading: {}, // files currently in process of loading
loadHooks: {}, // hooks to call when files are loaded
timeout: 15*1000, // timeout for loading of files (15 seconds)
styleDelay: 1, // delay to use before styles are available
config: {root: ""}, // URL of root directory to load from
STATUS: {
OK: 1, // file is loading or did load OK
ERROR: -1 // file timed out during load
},
rootPattern: new RegExp("^\\["+BASENAME+"\\]"),
//
// Return a complete URL to a file (replacing the root pattern)
//
fileURL: function (file) {return file.replace(this.rootPattern,this.config.root)},
//
// Load a file if it hasn't been already.
// Make sure the file URL is "safe"?
//
Require: function (file,callback) {
callback = BASE.Callback(callback); var type;
if (file instanceof Object) {
for (var i in file)
{if (file.hasOwnProperty(i)) {type = i.toUpperCase(); file = file[i]}}
} else {type = file.split(/\./).pop().toUpperCase()}
file = this.fileURL(file);
// FIXME: check that URL is OK
if (this.loaded[file]) {
callback(this.loaded[file]);
} else {
var FILE = {}; FILE[type] = file;
this.Load(FILE,callback);
}
return callback;
},
//
// Load a file regardless of where it is and whether it has
// already been loaded.
//
Load: function (file,callback) {
callback = BASE.Callback(callback); var type;
if (file instanceof Object) {
for (var i in file)
{if (file.hasOwnProperty(i)) {type = i.toUpperCase(); file = file[i]}}
} else {type = file.split(/\./).pop().toUpperCase()}
file = this.fileURL(file);
if (this.loading[file]) {
this.addHook(file,callback);
} else {
this.head = HEAD(this.head);
if (this.loader[type]) {this.loader[type].call(this,file,callback)}
else {throw Error("Can't load files of type "+type)}
}
return callback;
},
//
// Register a load hook for a particular file (it will be called when
// loadComplete() is called for that file)
//
LoadHook: function (file,callback,priority) {
callback = BASE.Callback(callback);
if (file instanceof Object)
{for (var i in file) {if (file.hasOwnProperty(i)) {file = file[i]}}}
file = this.fileURL(file);
if (this.loaded[file]) {callback(this.loaded[file])}
else {this.addHook(file,callback,priority)}
return callback;
},
addHook: function (file,callback,priority) {
if (!this.loadHooks[file]) {this.loadHooks[file] = MathJax.Callback.Hooks()}
this.loadHooks[file].Add(callback,priority);
},
//
// Used when files are combined in a preloading configuration file
//
Preloading: function () {
for (var i = 0, m = arguments.length; i < m; i++) {
var file = this.fileURL(arguments[i]);
if (!this.loading[file]) {this.loading[file] = {preloaded: true}}
}
},
//
// Code used to load the various types of files
// (JS for JavaScript, CSS for style sheets)
//
loader: {
//
// Create a SCRIPT tag to load the file
//
JS: function (file,callback) {
var script = document.createElement("script");
var timeout = BASE.Callback(["loadTimeout",this,file]);
this.loading[file] = {
callback: callback,
timeout: setTimeout(timeout,this.timeout),
status: this.STATUS.OK,
script: script
};
// Add this to the structure above after it is created to prevent recursion
// when loading the initial localization file (before loading messsage is available)
this.loading[file].message = BASE.Message.File(file);
script.onerror = timeout; // doesn't work in IE and no apparent substitute
script.type = "text/javascript";
script.src = file;
this.head.appendChild(script);
},
//
// Create a LINK tag to load the style sheet
//
CSS: function (file,callback) {
var link = document.createElement("link");
link.rel = "stylesheet"; link.type = "text/css"; link.href = file;
this.loading[file] = {
callback: callback,
message: BASE.Message.File(file),
status: this.STATUS.OK
};
this.head.appendChild(link);
this.timer.create.call(this,[this.timer.file,file],link);
}
},
//
// Timing code for checking when style sheets are available.
//
timer: {
//
// Create the timing callback and start the timing loop.
// We use a delay because some browsers need it to allow the styles
// to be processed.
//
create: function (callback,node) {
callback = BASE.Callback(callback);
if (node.nodeName === "STYLE" && node.styleSheet &&
typeof(node.styleSheet.cssText) !== 'undefined') {
callback(this.STATUS.OK); // MSIE processes style immediately, but doesn't set its styleSheet!
} else if (window.chrome && node.nodeName === "LINK") {
callback(this.STATUS.OK); // Chrome doesn't give access to cssRules for stylesheet in
// a link node, so we can't detect when it is loaded.
} else if (isSafari2) {
this.timer.start(this,[this.timer.checkSafari2,sheets++,callback],this.styleDelay);
} else {
this.timer.start(this,[this.timer.checkLength,node,callback],this.styleDelay);
}
return callback;
},
//
// Start the timer for the given callback checker
//
start: function (AJAX,check,delay,timeout) {
check = BASE.Callback(check);
check.execute = this.execute; check.time = this.time;
check.STATUS = AJAX.STATUS; check.timeout = timeout || AJAX.timeout;
check.delay = check.total = delay || 0;
if (delay) {setTimeout(check,delay)} else {check()}
},
//
// Increment the time total, increase the delay
// and test if we are past the timeout time.
//
time: function (callback) {
this.total += this.delay;
this.delay = Math.floor(this.delay * 1.05 + 5);
if (this.total >= this.timeout) {callback(this.STATUS.ERROR); return 1}
return 0;
},
//
// For JS file loads, call the proper routine according to status
//
file: function (file,status) {
if (status < 0) {BASE.Ajax.loadTimeout(file)} else {BASE.Ajax.loadComplete(file)}
},
//
// Call the hook with the required data
//
execute: function () {this.hook.call(this.object,this,this.data[0],this.data[1])},
//
// Safari2 doesn't set the link's stylesheet, so we need to look in the
// document.styleSheets array for the new sheet when it is created
//
checkSafari2: function (check,length,callback) {
if (check.time(callback)) return;
if (document.styleSheets.length > length &&
document.styleSheets[length].cssRules &&
document.styleSheets[length].cssRules.length)
{callback(check.STATUS.OK)} else {setTimeout(check,check.delay)}
},
//
// Look for the stylesheets rules and check when they are defined
// and no longer of length zero. (This assumes there actually ARE
// some rules in the stylesheet.)
//
checkLength: function (check,node,callback) {
if (check.time(callback)) return;
var isStyle = 0; var sheet = (node.sheet || node.styleSheet);
try {if ((sheet.cssRules||sheet.rules||[]).length > 0) {isStyle = 1}} catch(err) {
if (err.message.match(/protected variable|restricted URI/)) {isStyle = 1}
else if (err.message.match(/Security error/)) {
// Firefox3 gives "Security error" for missing files, so
// can't distinguish that from OK files on remote servers.
// or OK files in different directory from local files.
isStyle = 1; // just say it is OK (can't really tell)
}
}
if (isStyle) {
// Opera 9.6 requires this setTimeout
setTimeout(BASE.Callback([callback,check.STATUS.OK]),0);
} else {
setTimeout(check,check.delay);
}
}
},
//
// JavaScript code must call this when they are completely initialized
// (this allows them to perform asynchronous actions before indicating
// that they are complete).
//
loadComplete: function (file) {
file = this.fileURL(file);
var loading = this.loading[file];
if (loading && !loading.preloaded) {
BASE.Message.Clear(loading.message);
clearTimeout(loading.timeout);
if (loading.script) {
if (SCRIPTS.length === 0) {setTimeout(REMOVESCRIPTS,0)}
SCRIPTS.push(loading.script);
}
this.loaded[file] = loading.status; delete this.loading[file];
this.addHook(file,loading.callback);
} else {
if (loading) {delete this.loading[file]}
this.loaded[file] = this.STATUS.OK;
loading = {status: this.STATUS.OK}
}
if (!this.loadHooks[file]) {return null}
return this.loadHooks[file].Execute(loading.status);
},
//
// If a file fails to load within the timeout period (or the onerror handler
// is called), this routine runs to signal the error condition.
//
loadTimeout: function (file) {
if (this.loading[file].timeout) {clearTimeout(this.loading[file].timeout)}
this.loading[file].status = this.STATUS.ERROR;
this.loadError(file);
this.loadComplete(file);
},
//
// The default error hook for file load failures
//
loadError: function (file) {
BASE.Message.Set(["LoadFailed","File failed to load: %1",file],null,2000);
BASE.Hub.signal.Post(["file load error",file]);
},
//
// Defines a style sheet from a hash of style declarations (key:value pairs
// where the key is the style selector and the value is a hash of CSS attributes
// and values).
//
Styles: function (styles,callback) {
var styleString = this.StyleString(styles);
if (styleString === "") {
callback = BASE.Callback(callback);
callback();
} else {
var style = document.createElement("style"); style.type = "text/css";
this.head = HEAD(this.head);
this.head.appendChild(style);
if (style.styleSheet && typeof(style.styleSheet.cssText) !== 'undefined') {
style.styleSheet.cssText = styleString;
} else {
style.appendChild(document.createTextNode(styleString));
}
callback = this.timer.create.call(this,callback,style);
}
return callback;
},
//
// Create a stylesheet string from a style declaration object
//
StyleString: function (styles) {
if (typeof(styles) === 'string') {return styles}
var string = "", id, style;
for (id in styles) {if (styles.hasOwnProperty(id)) {
if (typeof styles[id] === 'string') {
string += id + " {"+styles[id]+"}\n";
} else if (styles[id] instanceof Array) {
for (var i = 0; i < styles[id].length; i++) {
style = {}; style[id] = styles[id][i];
string += this.StyleString(style);
}
} else if (id.substr(0,6) === '@media') {
string += id + " {"+this.StyleString(styles[id])+"}\n";
} else if (styles[id] != null) {
style = [];
for (var name in styles[id]) {if (styles[id].hasOwnProperty(name)) {
if (styles[id][name] != null)
{style[style.length] = name + ': ' + styles[id][name]}
}}
string += id +" {"+style.join('; ')+"}\n";
}
}}
return string;
}
};
})("MathJax");
/**********************************************************/
MathJax.HTML = {
//
// Create an HTML element with given attributes and content.
// The def parameter is an (optional) object containing key:value pairs
// of the attributes and their values, and contents is an (optional)
// array of strings to be inserted as text, or arrays of the form
// [type,def,contents] that describes an HTML element to be inserted
// into the current element. Thus the contents can describe a complete
// HTML snippet of arbitrary complexity. E.g.:
//
// MathJax.HTML.Element("span",{id:"mySpan",style{"font-style":"italic"}},[
// "(See the ",["a",{href:"http://www.mathjax.org"},["MathJax home page"]],
// " for more details.)"]);
//
Element: function (type,def,contents) {
var obj = document.createElement(type);
if (def) {
if (def.style) {
var style = def.style; def.style = {};
for (var id in style) {if (style.hasOwnProperty(id))
{def.style[id.replace(/-([a-z])/g,this.ucMatch)] = style[id]}}
}
MathJax.Hub.Insert(obj,def);
}
if (contents) {
if (!(contents instanceof Array)) {contents = [contents]}
for (var i = 0; i < contents.length; i++) {
if (contents[i] instanceof Array) {
obj.appendChild(this.Element(contents[i][0],contents[i][1],contents[i][2]));
} else if (type === "script") { // IE throws an error if script is added as a text node
this.setScript(obj, contents[i]);
} else {
obj.appendChild(document.createTextNode(contents[i]));
}