-
-
Notifications
You must be signed in to change notification settings - Fork 11.2k
/
Copy pathutils.js
1238 lines (1034 loc) · 37.9 KB
/
utils.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
/*
* Copyright Adam Pritchard 2015
* MIT License : https://adampritchard.mit-license.org/
*/
/*
* Utilities and helpers that are needed in multiple places.
*
* This module assumes that a global `window` is available.
*/
;(function() {
"use strict";
/*global module:false, chrome:false, safari:false*/
function consoleLog(logString) {
if (typeof(console) !== 'undefined') {
console.log(logString);
}
else {
var consoleService = Components.classes['@mozilla.org/consoleservice;1']
.getService(Components.interfaces.nsIConsoleService);
consoleService.logStringMessage(String(logString));
}
}
// TODO: Try to use `insertAdjacentHTML` for the inner and outer HTML functions.
// https://developer.mozilla.org/en-US/docs/Web/API/Element.insertAdjacentHTML
// Assigning a string directly to `element.innerHTML` is potentially dangerous:
// e.g., the string can contain harmful script elements. (Additionally, Mozilla
// won't let us pass validation with `innerHTML` assignments in place.)
// This function provides a safer way to append a HTML string into an element.
function saferSetInnerHTML(parentElem, htmlString) {
// Jump through some hoops to avoid using innerHTML...
var range = parentElem.ownerDocument.createRange();
range.selectNodeContents(parentElem);
var docFrag = range.createContextualFragment(htmlString);
docFrag = sanitizeDocumentFragment(docFrag);
range.deleteContents();
range.insertNode(docFrag);
range.detach();
}
// Approximating equivalent to assigning to `outerHTML` -- completely replaces
// the target element with `htmlString`.
// Note that some caveats apply that also apply to `outerHTML`:
// - The element must be in the DOM. Otherwise an exception will be thrown.
// - The original element has been removed from the DOM, but continues to exist.
// Any references to it (such as the one passed into this function) will be
// references to the original.
function saferSetOuterHTML(elem, htmlString) {
if (!isElementinDocument(elem)) {
throw new Error('Element must be in document');
}
var range = elem.ownerDocument.createRange();
range.selectNode(elem);
var docFrag = range.createContextualFragment(htmlString);
docFrag = sanitizeDocumentFragment(docFrag);
range.deleteContents();
range.insertNode(docFrag);
range.detach();
}
// Removes potentially harmful elements and attributes from `docFrag`.
// Returns a santized copy.
function sanitizeDocumentFragment(docFrag) {
var i;
// Don't modify the original
docFrag = docFrag.cloneNode(true);
var scriptTagElems = docFrag.querySelectorAll('script');
for (i = 0; i < scriptTagElems.length; i++) {
scriptTagElems[i].parentNode.removeChild(scriptTagElems[i]);
}
function cleanAttributes(node) {
var i;
if (typeof(node.removeAttribute) === 'undefined') {
// We can't operate on this node
return;
}
// Remove event handler attributes
for (i = node.attributes.length-1; i >= 0; i--) {
if (node.attributes[i].name.match(/^on/)) {
node.removeAttribute(node.attributes[i].name);
}
}
}
walkDOM(docFrag.firstChild, cleanAttributes);
return docFrag;
}
// Walk the DOM, executing `func` on each element.
// From Crockford.
function walkDOM(node, func) {
func(node);
node = node.firstChild;
while(node) {
walkDOM(node, func);
node = node.nextSibling;
}
}
// Next three functions from: https://stackoverflow.com/a/1483487/729729
// Returns true if `node` is in `range`.
function rangeIntersectsNode(range, node) {
var nodeRange;
// adam-p: I have found that Range.intersectsNode gives incorrect results in
// Chrome (but not Firefox). So we're going to use the fail-back code always,
// regardless of whether the current platform implements Range.intersectsNode.
/*
if (range.intersectsNode) {
return range.intersectsNode(node);
}
else {
...
*/
nodeRange = node.ownerDocument.createRange();
try {
nodeRange.selectNode(node);
}
catch (e) {
nodeRange.selectNodeContents(node);
}
// Workaround for this old Mozilla bug, which is still present in Postbox:
// https://bugzilla.mozilla.org/show_bug.cgi?id=665279
var END_TO_START = node.ownerDocument.defaultView.Range.END_TO_START || window.Range.END_TO_START;
var START_TO_END = node.ownerDocument.defaultView.Range.START_TO_END || window.Range.START_TO_END;
return range.compareBoundaryPoints(
END_TO_START,
nodeRange) === -1 &&
range.compareBoundaryPoints(
START_TO_END,
nodeRange) === 1;
}
// Returns array of elements in selection.
function getSelectedElementsInDocument(doc) {
var range, sel, containerElement;
sel = doc.getSelection();
if (sel.rangeCount > 0) {
range = sel.getRangeAt(0);
}
if (!range) {
return [];
}
return getSelectedElementsInRange(range);
}
// Returns array of elements in range
function getSelectedElementsInRange(range) {
var elems = [], treeWalker, containerElement;
if (range) {
containerElement = range.commonAncestorContainer;
if (containerElement.nodeType != 1) {
containerElement = containerElement.parentNode;
}
elems = [treeWalker.currentNode];
walkDOM(
containerElement,
function(node) {
if (rangeIntersectsNode(range, node)) {
elems.push(node);
}
});
/*? if(platform!=='firefox' && platform!=='thunderbird'){ */
/*
// This code is probably superior, but TreeWalker is not supported by Postbox.
// If this ends up getting used, it should probably be moved into walkDOM
// (or walkDOM should be removed).
treeWalker = doc.createTreeWalker(
containerElement,
range.commonAncestorContainerownerDocument.defaultView.NodeFilter.SHOW_ELEMENT,
function(node) { return rangeIntersectsNode(range, node) ? range.commonAncestorContainerownerDocument.defaultView.NodeFilter.FILTER_ACCEPT : range.commonAncestorContainerownerDocument.defaultView.NodeFilter.FILTER_REJECT; },
false
);
elems = [treeWalker.currentNode];
while (treeWalker.nextNode()) {
elems.push(treeWalker.currentNode);
}
*/
/*? } */
}
return elems;
}
function isElementinDocument(element) {
var doc = element.ownerDocument;
while (!!(element = element.parentNode)) {
if (element === doc) {
return true;
}
}
return false;
}
// From: https://stackoverflow.com/a/3819589/729729
// Postbox doesn't support `node.outerHTML`.
function outerHTML(node, doc) {
// if IE, Chrome take the internal method otherwise build one
return node.outerHTML || (
function(n){
var div = doc.createElement('div'), h;
div.appendChild(n.cloneNode(true));
h = div.innerHTML;
div = null;
return h;
})(node);
}
// From: https://stackoverflow.com/a/5499821/729729
var charsToReplace = {
'&': '&',
'<': '<',
'>': '>'
};
function replaceChar(char) {
return charsToReplace[char] || char;
}
// An approximate equivalent to outerHTML for document fragments.
function getDocumentFragmentHTML(docFrag) {
var html = '', i;
for (i = 0; i < docFrag.childNodes.length; i++) {
var node = docFrag.childNodes[i];
if (node.nodeType === node.TEXT_NODE) {
html += node.nodeValue.replace(/[&<>]/g, replaceChar);
}
else { // going to assume ELEMENT_NODE
html += outerHTML(node, docFrag.ownerDocument);
}
}
return html;
}
function isElementDescendant(parent, descendant) {
var ancestor = descendant;
while (!!(ancestor = ancestor.parentNode)) {
if (ancestor === parent) {
return true;
}
}
return false;
}
// Take a URL that refers to a file in this extension and makes it absolute.
// Note that the URL *must not* be relative to the current path position (i.e.,
// no "./blah" or "../blah"). So `url` must start with `/`.
function getLocalURL(url) {
if (url[0] !== '/') {
throw 'relative url not allowed: ' + url;
}
if (url.indexOf('://') >= 0) {
// already absolute
return url;
}
// (This if-structure is ugly to work around the preprocessor logic.)
var matched = false;
/*? if (platform==='chrome' || platform==='firefox') { */
if (typeof(chrome) !== 'undefined') {
matched = true;
return chrome.runtime.getURL(url);
}
/*? } */
/*? if (platform==='safari') { */
if (!matched && typeof(safari) !== 'undefined') {
matched = true;
return safari.extension.baseURI + 'markdown-here/src' + url;
}
/*? } */
/*? if(platform==='thunderbird'){ */
if (!matched) {
matched = true;
// Mozilla platform.
// HACK: The proper URL depends on values in `chrome.manifest`. But we "know"
// that there are only a couple of locations we request from, so we're going
// to branch depending on the presence of "common".
var COMMON = '/common/';
var CONTENT = '/firefox/chrome/';
if (url.indexOf(COMMON) === 0) {
return 'resource://markdown_here_common/' + url.slice(COMMON.length);
}
else if (url.indexOf(CONTENT) === 0) {
return 'chrome://markdown_here/' + url.slice(CONTENT.length);
}
}
/*? } */
throw 'unknown url type: ' + url;
}
// Makes an asynchrous XHR request for a local file (basically a thin wrapper).
// `dataType` must be one of 'text', 'json', or 'base64'.
// `callback` will be called with the response value, of a type depending on `dataType`.
// Errors are not expected for local files, and will result in an exception being thrown asynchrously.
// TODO: Return a promise instead of using a callback. This will allow returning an error
// properly, and then this can be used in options.js when checking for the existence of
// the test file.
function getLocalFile(url, dataType, callback) {
fetch(url)
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error status: ${response.status}`);
}
switch (dataType) {
case 'text':
return response.text();
case 'json':
return response.json();
case 'base64':
return response.blob();
default:
throw new Error(`Unknown dataType: ${dataType}`);
}
})
.then(data => {
switch (dataType) {
case 'text':
case 'json':
callback(data);
break;
case 'base64':
data.arrayBuffer().then(function(buffer) {
var uInt8Array = new Uint8Array(buffer);
var base64Data = base64EncArr(uInt8Array);
callback(base64Data);
});
}
})
.catch(err => {
throw new Error(`Error fetching local file: ${url}: ${err}`);
});
}
// Events fired by Markdown Here will have this property set to true.
var MARKDOWN_HERE_EVENT = 'markdown-here-event';
// Fire a mouse event on the given element. (Note: not super robust.)
function fireMouseClick(elem) {
var clickEvent = elem.ownerDocument.createEvent('MouseEvent');
clickEvent.initMouseEvent(
'click',
true, // bubbles: We want the event to bubble.
true, // cancelable
elem.ownerDocument.defaultView, // view,
1, // detail,
0, // screenX
0, // screenY
0, // clientX
0, // clientY
false, // ctrlKey
false, // altKey
false, // shiftKey
false, // metaKey
0, // button
null); // relatedTarget
clickEvent[MARKDOWN_HERE_EVENT] = true;
elem.dispatchEvent(clickEvent);
}
var PRIVILEGED_REQUEST_EVENT_NAME = 'markdown-here-request-event';
function makeRequestToPrivilegedScript(doc, requestObj, callback) {
// (This if-structure is ugly to work around the preprocessor logic.)
var matched = false;
/*? if(platform==='chrome' || platform==='firefox'){ */
if (typeof(chrome) !== 'undefined') {
matched = true;
// If `callback` is undefined and we pass it anyway, Chrome complains with this:
// Uncaught Error: Invocation of form extension.sendMessage(object, undefined, null) doesn't match definition extension.sendMessage(optional string extensionId, any message, optional function responseCallback)
if (callback) {
chrome.runtime.sendMessage(requestObj, callback);
}
else {
chrome.runtime.sendMessage(requestObj);
}
}
/*? } */
/*? if(platform==='safari'){ */
if (!matched && typeof(safari) !== 'undefined') {
matched = true;
/*
Unlike Chrome, Safari doesn't provide a way to pass a callback to a background-
script request. Instead the background script sends a separate message to
the content script. We'll keep a set of outstanding callbacks to process as
the responses come in.
*/
// If this is the first call, do some initialization.
if (typeof(makeRequestToPrivilegedScript.requestCallbacks) === 'undefined') {
makeRequestToPrivilegedScript.requestCallbacks = {};
// Handle messages received from the background script.
var backgroundMessageHandler = function(event) {
// Note that this message handler will get triggered by any request sent
// from the background script to the content script for a page, and
// it'll get triggered once for each frame in the page. So we need to
// make very sure that we should be acting on the message.
if (event.name === 'request-response') {
var responseObj = window.JSON.parse(event.message);
if (responseObj.requestID &&
makeRequestToPrivilegedScript.requestCallbacks[responseObj.requestID]) {
// Call the stored callback.
makeRequestToPrivilegedScript.requestCallbacks[responseObj.requestID](responseObj.response);
// And remove the stored callback.
delete makeRequestToPrivilegedScript.requestCallbacks[responseObj.requestID];
}
}
};
safari.self.addEventListener('message', backgroundMessageHandler, false);
}
// Store the callback for later use in the response handler.
if (callback) {
var reqID = Math.random();
makeRequestToPrivilegedScript.requestCallbacks[reqID] = callback;
requestObj.requestID = reqID;
}
safari.self.tab.dispatchMessage('request', window.JSON.stringify(requestObj));
}
/*? } */
/*? if(platform==='thunderbird'){ */
if (!matched) { // Mozilla/XUL
matched = true;
// See: https://developer.mozilla.org/en-US/docs/Code_snippets/Interaction_between_privileged_and_non-privileged_pages#Chromium-like_messaging.3A_json_request_with_json_callback
// Make a unique event name to use. (Bad style to modify the input like this...)
requestObj.responseEventName = 'markdown-here-response-event-' + Math.floor(Math.random()*1000000);
var request = doc.createTextNode(JSON.stringify(requestObj));
var responseHandler = function(event) {
var response = null;
// There may be no response data.
if (request.nodeValue) {
response = JSON.parse(request.nodeValue);
}
request.parentNode.removeChild(request);
if (callback) {
callback(response);
}
};
request.addEventListener(requestObj.responseEventName, responseHandler, false);
(doc.head || doc.body).appendChild(request);
var event = doc.createEvent('HTMLEvents');
event.initEvent(PRIVILEGED_REQUEST_EVENT_NAME, true, false);
request.dispatchEvent(event);
}
/*? } */
}
// Gives focus to the element.
// Setting focus into elements inside iframes is not simple.
function setFocus(elem) {
// We need to do some tail-recursion focus setting up through the iframes.
if (elem.document) {
// This is a window
if (elem.frameElement) {
// This is the window of an iframe. Set focus to the parent window.
setFocus(elem.frameElement.ownerDocument.defaultView);
}
}
else if (elem.ownerDocument.defaultView.frameElement) {
// This element is in an iframe. Set focus to its owner window.
setFocus(elem.ownerDocument.defaultView);
}
elem.focus();
}
// Gets the URL of the top window that elem belongs to.
// May recurse up through iframes.
function getTopURL(win, justHostname) {
if (win.frameElement) {
// This is the window of an iframe
return getTopURL(win.frameElement.ownerDocument.defaultView);
}
var url;
// We still want a useful value if we're in Thunderbird, etc.
if (!win.location.href || win.location.href === 'about:blank') {
url = win.navigator.userAgent.match(/Thunderbird'/);
if (url) {
url = url[0];
}
}
else if (justHostname) {
url = win.location.hostname;
}
else {
url = win.location.href;
}
return url;
}
// Regarding methods for `nextTick` and related:
// For ordinary browser use, setTimeout() is throttled to 1000ms for inactive
// tabs. This doesn't seem to affect extensions, except... Chrome Canary is
// currently doing this for the extension background scripts. This causes
// horribly slow rendering. For info see:
// https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout#Inactive_tabs
// As an alternative, we can use a local XHR request/response.
// This function just does a simple, local async request and then calls the callback.
function asyncCallbackXHR(callback) {
fetch(getLocalURL('/common/CHANGES.md'), {method: 'HEAD'})
.then(callback)
.catch(callback);
}
function asyncCallbackTimeout(callback) {
setTimeout(callback, 0);
}
// We prefer to use the setTimeout approach.
var asyncCallback = asyncCallbackTimeout;
// Sets a short timeout and then calls callback
function nextTick(callback, context) {
nextTickFn(callback, context)();
}
// `context` is optional. Will be `this` when `callback` is called.
function nextTickFn(callback, context) {
var start = new Date();
return function nextTickFnInner() {
var args = arguments;
var runner = function() {
// Detect a whether the async callback was super slow
var end = new Date() - start;
if (end > 200) {
// setTimeout is too slow -- switch to the XHR approach.
asyncCallback = asyncCallbackXHR;
}
callback.apply(context, args);
};
asyncCallback(runner);
};
}
/*? if(platform==='thunderbird'){ */
/**
* Returns the stored preference string for the given key.
* Must only be called from a privileged Mozilla script.
* @param {nsIPrefBranch} prefsBranch
* @param {string} key
* @returns {?string} The preference value. May be null if the preference is not set
* or is null.
*/
function getMozStringPref(prefsBranch, key) {
try {
if (Services.vc.compare(Services.appinfo.platformVersion, '58') < 0) {
return prefsBranch.getComplexValue(
key,
Components.interfaces.nsISupportsString).data;
}
return prefsBranch.getStringPref(key, null);
}
catch(e) {
// getComplexValue could have thrown an exception because it didn't find the key. As
// with getStringPref, we will default to null.
return null;
}
}
/**
* Get the stored preference object, JSON-parsed, for the given key.
* Must only be called from a privileged Mozilla script.
* @param {nsIPrefBranch} prefsBranch
* @param {string} key
* @returns {?(object|number|boolean|string)} The preference object (any valid JSON
* type). May be null if the preference is not set or is null.
*/
function getMozJsonPref(prefsBranch, key) {
try {
return JSON.parse(getMozStringPref(prefsBranch, key));
}
catch(e) {
return null;
}
}
/**
* Store the preference string for the given key.
* Must only be called from a privileged Mozilla script.
* @param {nsIPrefBranch} prefsBranch
* @param {string} key
* @param {string} value
*/
function setMozStringPref(prefsBranch, key, value) {
var supportString = Components.classes['@mozilla.org/supports-string;1']
.createInstance(Components.interfaces.nsISupportsString);
if (Services.vc.compare(Services.appinfo.platformVersion, '58') < 0) {
supportString.data = value;
prefsBranch.setComplexValue(
key,
Components.interfaces.nsISupportsString,
supportString);
}
else {
prefsBranch.setStringPref(key, value);
}
}
/**
* Store the given object in preferences under the given key.
* Must only be called from a privileged Mozilla script.
* @param {nsIPrefBranch} prefsBranch
* @param {string} key
* @param {?(object|number|boolean|string)} value
*/
function setMozJsonPref(prefsBranch, key, value) {
setMozStringPref(prefsBranch, key, JSON.stringify(value));
}
/*? } */
/*
* i18n/l10n
*/
/*
This is a much bigger hassle than it should be. i18n support is great on Chrome
(and Opera, and Firefox+WebExtensions), a bit of a hassle on Thunderbird/XUL,
and basically nonexistent on Safari.
In Chrome, we can use `chrome.i18n.getMessage` to just get the string we want,
in either content or background scripts, synchronously and with no extra prep
work.
In Thunderbird, we need to load the `strings.properties` string bundle for both the
current locale and English (our fallback language) and combine them. This can
only be done from a privileged script. Then we can use the strings. The loading
is synchronous for the privileged script, but asynchronous for the unprivileged
script (because it needs to make a request to the privileged script).
In Safari, we need to read in the JSON files for the current locale and English
(our fallback language) and combine them. This can only be done from a privileged
script. Then we can use the strings. The loading is asynchronous for both
privileged and unprivileged scripts (because async XHR is used for the former
and a request is made to the privileged script for the latter).
It can happen that attempts to access the strings are made before the loading
has actually occurred. This has been observed on Safari in the MDH Options page.
This necessitated the addition of `registerStringBundleLoadListener` and
`triggerStringBundleLoadListeners`, which may be used to ensure that `getMessage`
calls wait until the loading is complete.
*/
var g_stringBundleLoadListeners = [];
function registerStringBundleLoadListener(callback) {
// (This if-structure is ugly to work around the preprocessor logic.)
var matched = false;
/*? if(platform==='chrome' || platform==='firefox'){ */
if (typeof(chrome) !== 'undefined') {
matched = true;
// Already loaded
Utils.nextTick(callback);
return;
}
/*? } */
/*? if(platform==='safari'){ */
if (!matched
&& typeof(g_safariStringBundle) === 'object'
&& Object.keys(g_safariStringBundle).length > 0) {
matched = true;
// Already loaded
Utils.nextTick(callback);
return;
}
/*? } */
/*? if(platform==='thunderbird'){ */
if (!matched
&& typeof(g_mozStringBundle) === 'object'
&& Object.keys(g_mozStringBundle).length > 0) {
matched = true;
// Already loaded
Utils.nextTick(callback);
return;
}
/*? } */
g_stringBundleLoadListeners.push(callback);
}
function triggerStringBundleLoadListeners() {
var listener;
while (g_stringBundleLoadListeners.length > 0) {
listener = g_stringBundleLoadListeners.pop();
listener();
}
}
// Must only be called from a privileged Mozilla script
function getMozStringBundle() {
if (typeof(Components) === 'undefined' || typeof(Components.classes) === 'undefined') {
return false;
}
// Return a cached bundle, if we have one
if (typeof(g_mozStringBundle) !== 'undefined' &&
Object.keys(g_mozStringBundle).length > 0) {
return g_mozStringBundle;
}
// Adapted from: https://developer.mozilla.org/en-US/docs/Code_snippets/Miscellaneous#Using_string_bundles_from_JavaScript
// and: https://developer.mozilla.org/en-US/docs/Using_nsISimpleEnumerator
var stringBundleObj = {}, stringBundle, stringBundleEnum, property;
// First load the English fallback strings
stringBundle = Components.classes["@mozilla.org/intl/stringbundle;1"]
.getService(Components.interfaces.nsIStringBundleService)
// Notice the explicit locale in this path:
.createBundle("resource://markdown_here_locale/en/strings.properties");
stringBundleEnum = stringBundle.getSimpleEnumeration();
while (stringBundleEnum.hasMoreElements()) {
property = stringBundleEnum.getNext().QueryInterface(Components.interfaces.nsIPropertyElement);
stringBundleObj[property.key] = property.value;
}
// Then load the strings that are overridden for the current locale
stringBundle = Components.classes["@mozilla.org/intl/stringbundle;1"]
.getService(Components.interfaces.nsIStringBundleService)
.createBundle("chrome://markdown_here/locale/strings.properties");
stringBundleEnum = stringBundle.getSimpleEnumeration();
while (stringBundleEnum.hasMoreElements()) {
property = stringBundleEnum.getNext().QueryInterface(Components.interfaces.nsIPropertyElement);
stringBundleObj[property.key] = property.value;
}
return stringBundleObj;
}
/*? if(platform==='thunderbird'){ */
// Load the Mozilla string bundle
if (typeof(chrome) === 'undefined' && typeof(safari) === 'undefined') {
var g_mozStringBundle = getMozStringBundle();
if (!g_mozStringBundle || Object.keys(g_mozStringBundle).length === 0) {
window.setTimeout(function requestMozStringBundle() {
makeRequestToPrivilegedScript(window.document, {action: 'get-string-bundle'}, function(response) {
g_mozStringBundle = response;
triggerStringBundleLoadListeners();
});
}, 0);
}
else {
// g_mozStringBundle is filled in
triggerStringBundleLoadListeners();
}
}
/*? } */
/*? if(platform==='safari'){ */
// Will only succeed when called from a privileged Safari script.
// `callback(data, err)` is passed a non-null value for err in case of total
// failure, which should be interpreted as being called from a non-privileged
// (content) script.
// Otherwise `data` will contain the string bundle object.
function getSafariStringBundle(callback) {
// Can't use Utils.functionname in this function, since the exports haven't
// been set up at the time it's called.
var stringBundle = {};
// Return a cached bundle, if we have one
if (typeof(g_safariStringBundle) !== 'undefined' &&
Object.keys(g_safariStringBundle).length > 0) {
nextTickFn(callback)(g_safariStringBundle);
return;
}
// Get the English fallback
getStringBundle('en', function(data, err) {
if (err) {
consoleLog('Error getting English string bundle:');
consoleLog(err);
return callback(null, err);
}
extendBundle(stringBundle, data);
var locale = window.navigator.language;
if (locale.indexOf('en') === 0) {
// The locale is English, nothing more to do
return callback(stringBundle, null);
}
// Get the actual locale string bundle
getStringBundle(locale, function(data, err) {
if (err) {
// The locale in navigator.language typically looks like "ja-JP", but
// MDH's locale typically looks like "ja".
locale = locale.split('-')[0];
getStringBundle(locale, function(data, err) {
if (err) {
// Couldn't find it. We'll just have to use the fallback.
consoleLog('Markdown Here has no language support for: ' + locale);
return callback(stringBundle);
}
extendBundle(stringBundle, data);
return callback(stringBundle);
});
}
extendBundle(stringBundle, data);
return callback(stringBundle);
});
});
function getStringBundle(locale, callback) {
var url = getLocalURL('/_locales/' + locale + '/messages.json');
getLocalFile(url, 'json', function(data, err) {
if (err) {
return callback(null, err);
}
// Chrome's messages.json uses "$" as placeholders and "$$" as an explicit
// "$". We're not yet using placeholders, so we'll just convert double to singles.
data = data.replace(/\$\$/g, '$');
return callback(JSON.parse(data));
});
}
function extendBundle(intoBundle, fromObj) {
var key;
for (key in fromObj) {
intoBundle[key] = fromObj[key].message;
}
}
}
/*? } */
/*? if(platform==='safari'){ */
// Load the Safari string bundle
if (typeof(safari) !== 'undefined') {
var g_safariStringBundle = {};
// This is effectively checking if we're calling from a privileged script.
// We could instead just try getSafariStringBundle() and check the error, but
// that's surely less efficient.
if (typeof(safari.application) !== 'undefined') {
// calling from a privileged script
getSafariStringBundle(function(data, err) {
if (err) {
consoleLog('Markdown Here: privileged script failed to load string bundle: ' + err);
return;
}
g_safariStringBundle = data;
triggerStringBundleLoadListeners();
});
}
else {
// Call from the privileged script
makeRequestToPrivilegedScript(window.document, {action: 'get-string-bundle'}, function(response) {
if (response) {
g_safariStringBundle = response;
triggerStringBundleLoadListeners();
}
else {
consoleLog('Markdown Here: content script failed to get string bundle from privileged script');
}
});
}
}
/*? } */
// Get the translated string indicated by `messageID`.
// Note that there's no support for placeholders as yet.
// Throws exception if message is not found or if the platform doesn't support
// internationalization (yet).
function getMessage(messageID) {
var message = '';
// (This if-structure is ugly to work around the preprocessor logic.)
var matched = false;
/*? if (platform==='chrome' || platform==='firefox') { */
if (typeof(chrome) !== 'undefined') {
matched = true;
message = chrome.i18n.getMessage(messageID);
}
/*? } */
/*? if (platform==='safari') { */
if (!matched && typeof(safari) !== 'undefined') {
matched = true;
if (g_safariStringBundle) {
message = g_safariStringBundle[messageID];
}
else {
// We don't yet have the string bundle available
return '';
}
}
/*? } */
/*? if (platform==='thunderbird') { */
if (!matched) { // Mozilla
matched = true;
if (g_mozStringBundle) {
message = g_mozStringBundle[messageID];
}
else {
// We don't yet have the string bundle available
return '';
}
}
/*? } */
if (!message) {
throw new Error('Could not find message ID: ' + messageID);
}
return message;
}
// Returns true if the semver version string in a is greater than the one in b.
// If a or b isn't a version string, a simple string comparison is returned.
// If a or b is falsy, false is returned.
// From https://stackoverflow.com/a/55466325
function semverGreaterThan(a, b) {