forked from jbt/markdown-editor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
399 lines (349 loc) · 12.3 KB
/
index.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
var URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
navigator.saveBlob = navigator.saveBlob || navigator.msSaveBlob || navigator.mozSaveBlob || navigator.webkitSaveBlob;
window.saveAs = window.saveAs || window.webkitSaveAs || window.mozSaveAs || window.msSaveAs;
// Because highlight.js is a bit awkward at times
var languageOverrides = {
js: 'javascript',
html: 'xml'
};
var livestyles;
emojify.setConfig({
img_dir: 'emoji'
});
var md = markdownit({
html: true,
highlight: function(code, lang) {
if (languageOverrides[lang]) lang = languageOverrides[lang];
if (lang && hljs.getLanguage(lang)) {
try {
return hljs.highlight(lang, code).value;
} catch (e) {}
}
return '';
}
})
.use(markdownitFootnote);
var hashto;
function update(e) {
setOutput(e.getValue());
//If a title is added to the document it will be the new document.title, otherwise use default
var headerElements = document.querySelectorAll('h1');
if (headerElements.length > 0 && headerElements[0].textContent.length > 0) {
title = headerElements[0].textContent;
} else {
title = 'Markdown Editor'
}
//To avoid to much title changing we check if is not the same as before
oldTitle = document.title;
if (oldTitle != title) {
oldTitle = title;
document.title = title;
}
//clearTimeout(hashto);
//hashto = setTimeout(updateHash, 1000);
}
/*
This function is used to check for task list notation.
If regex matches the string to task-list markdown format,
then the task-list is rendered to its correct form.
User: @austinmm
*/
var render_tasklist = function(str){
// Checked task-list box match
if(str.match(/<li>\[x\]\s+\w+/gi)){
str = str.replace(/(<li)(>\[x\]\s+)(\w+)/gi,
`$1 style="list-style-type: none;"><input type="checkbox"
checked style="list-style-type: none;
margin: 0 0.2em 0 -1.3em;" disabled> $3`);
}
// Unchecked task-list box match
if (str.match(/<li>\[ \]\s+\w+/gi)){
str = str.replace(/(<li)(>\[ \]\s+)(\w+)/gi,
`$1 style="list-style-type: none;"><input type="checkbox"
style="list-style-type: none;
margin: 0 0.2em 0 -1.3em;" disabled> $3`);
}
return str
}
function setOutput(val) {
val = val.replace(/<equation>((.*?\n)*?.*?)<\/equation>/ig, function(a, b) {
return '<img src="http://latex.codecogs.com/png.latex?' + encodeURIComponent(b) + '" />';
});
var out = document.getElementById('out');
var old = out.cloneNode(true);
out.innerHTML = md.render(val);
emojify.run(out);
console.log(out.innerHTML);
// Checks if there are any task-list present in out.innerHTML
out.innerHTML = render_tasklist(out.innerHTML);
var allold = old.getElementsByTagName("*");
if (allold === undefined) return;
var allnew = out.getElementsByTagName("*");
if (allnew === undefined) return;
for (var i = 0, max = Math.min(allold.length, allnew.length); i < max; i++) {
if (!allold[i].isEqualNode(allnew[i])) {
out.scrollTop = allnew[i].offsetTop;
return;
}
}
}
CodeMirrorSpellChecker({
codeMirrorInstance: CodeMirror,
});
var editor = CodeMirror.fromTextArea(document.getElementById('code'), {
mode: "spell-checker",
backdrop: "gfm",
lineNumbers: false,
matchBrackets: true,
lineWrapping: true,
theme: 'base16-light',
extraKeys: {
"Enter": "newlineAndIndentContinueMarkdownList"
}
});
editor.on('change', update);
function selectionChanger(selection,operator,endoperator){
if(selection == ""){
return operator;
}
if(!endoperator){
endoperator = operator
}
var isApplied = selection.slice(0, 2) === operator && selection.slice(-2) === endoperator;
var finaltext = isApplied ? selection.slice(2, -2) : operator + selection + endoperator;
return finaltext;
}
editor.addKeyMap({
// bold
'Ctrl-B': function(cm) {
cm.replaceSelection(selectionChanger(cm.getSelection(),'**'));
},
// italic
'Ctrl-I': function(cm) {
cm.replaceSelection(selectionChanger(cm.getSelection(),'_'));
},
// code
'Ctrl-K': function(cm) {
cm.replaceSelection(selectionChanger(cm.getSelection(),'`'));
},
// keyboard shortcut
'Ctrl-L': function(cm) {
cm.replaceSelection(selectionChanger(cm.getSelection(),'<kbd>','</kbd>'));
}
});
document.addEventListener('drop', function(e) {
e.preventDefault();
e.stopPropagation();
var reader = new FileReader();
reader.onload = function(e) {
editor.setValue(e.target.result);
};
reader.readAsText(e.dataTransfer.files[0]);
}, false);
//Print the document named as the document title encoded to avoid strange chars and spaces
function saveAsMarkdown() {
save(editor.getValue(), document.title.replace(/[`~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/\s]/gi, '') + ".md");
}
//Print the document named as the document title encoded to avoid strange chars and spaces
function saveAsHtml() {
save(document.getElementById('out').innerHTML, document.title.replace(/[`~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/\s]/gi, '') + ".html");
}
document.getElementById('saveas-markdown').addEventListener('click', function() {
saveAsMarkdown();
hideMenu();
});
document.getElementById('saveas-html').addEventListener('click', function() {
saveAsHtml();
hideMenu();
});
function save(code, name) {
var blob = new Blob([code], {
type: 'text/plain'
});
if (window.saveAs) {
window.saveAs(blob, name);
} else if (navigator.saveBlob) {
navigator.saveBlob(blob, name);
} else {
url = URL.createObjectURL(blob);
var link = document.createElement("a");
link.setAttribute("href", url);
link.setAttribute("download", name);
var event = document.createEvent('MouseEvents');
event.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
link.dispatchEvent(event);
}
}
var menuVisible = false;
var menu = document.getElementById('menu');
function showMenu() {
menuVisible = true;
menu.style.display = 'block';
}
function hideMenu() {
menuVisible = false;
menu.style.display = 'none';
}
function openFile(evt) {
if (window.File && window.FileReader && window.FileList && window.Blob) {
var files = evt.target.files;
console.log(files);
var reader = new FileReader();
reader.onload = function(file) {
console.log(file.target.result);
editor.setValue(file.target.result);
return true;
};
reader.readAsText(files[0]);
} else {
alert('The File APIs are not fully supported in this browser.');
}
}
document.getElementById('close-menu').addEventListener('click', function() {
hideMenu();
});
document.addEventListener('keydown', function(e) {
if (e.keyCode == 83 && (e.ctrlKey || e.metaKey)) {
// if ( localStorage.getItem('content') == editor.getValue() ) {
// e.preventDefault();
// return false;
// }
e.shiftKey ? showMenu() : saveInBrowser();
e.preventDefault();
return false;
}
if (e.keyCode === 27 && menuVisible) {
hideMenu();
e.preventDefault();
return false;
}
});
function clearEditor() {
editor.setValue("");
}
function saveInBrowser() {
var text = editor.getValue();
if (localStorage.getItem('content') != editor.getValue()) {
swal({
title: "Existing Data Detected",
text: "You will overwrite the data previously saved!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, overwrite!",
closeOnConfirm: false
},
function() {
localStorage.setItem('content', text);
swal("Saved", "Your Document has been saved.", "success");
});
} else {
localStorage.setItem('content', text);
swal("Saved", "Your Document has been saved.", "success");
}
console.log("Saved");
}
function toggleNightMode(button) {
// button = event.target
button.classList.toggle('selected');
document.getElementById('toplevel').classList.toggle('nightmode');
}
function toggleReadMode(button) {
// button = event.target
button.classList.toggle('selected');
document.getElementById('out').classList.toggle('focused');
document.getElementById('in').classList.toggle('hidden');
}
function toggleSpellCheck(button) {
button.classList.toggle('selected');
document.body.classList.toggle('no-spellcheck');
}
toastr.options.timeOut = 2400;
function updateHash() {
window.location.hash = btoa( // base64 so url-safe
RawDeflate.deflate( // gzip
unescape(encodeURIComponent( // convert to utf8
editor.getValue()
))
)
);
shareUrl = "https://wangfenjin.com/markdown-editor/"+window.location.hash;
copyToClipboard(shareUrl);
toastr.success("Copied to clipboard! Paste to share...");
}
// https://hackernoon.com/copying-text-to-clipboard-with-javascript-df4d4988697f
const copyToClipboard = str => {
const el = document.createElement('textarea');
el.value = str;
el.setAttribute('readonly', '');
el.style.position = 'absolute';
el.style.left = '-9999px';
document.body.appendChild(el);
el.select();
document.execCommand('copy');
document.body.removeChild(el);
};
function processQueryParams() {
var params = window.location.search.split('?')[1];
if (window.location.hash) {
document.getElementById('readbutton').click(); // Show reading view
}
if (params) {
var obj = {};
params.split('&').forEach(function(elem) {
obj[elem.split('=')[0]] = elem.split('=')[1];
});
if (obj.reading === 'false') {
document.getElementById('readbutton').click(); // Hide reading view
}
if (obj.dark === 'true') {
document.getElementById('nightbutton').click(); // Show night view
}
}
}
function start() {
processQueryParams();
if (window.location.hash) {
var h = window.location.hash.replace(/^#/, '');
if (h.slice(0, 5) == 'view:') {
setOutput(decodeURIComponent(escape(RawDeflate.inflate(atob(h.slice(5))))));
document.body.className = 'view';
} else {
editor.setValue(
decodeURIComponent(escape(
RawDeflate.inflate(
atob(
h
)
)
))
);
}
} else if (localStorage.getItem('content')) {
editor.setValue(localStorage.getItem('content'));
}
update(editor);
editor.focus();
document.getElementById('fileInput').addEventListener('change', openFile, false);
}
window.addEventListener("beforeunload", function (e) {
if (!editor.getValue() || editor.getValue() == localStorage.getItem('content')) {
return;
}
var confirmationMessage = 'It looks like you have been editing something. '
+ 'If you leave before saving, your changes will be lost.';
(e || window.event).returnValue = confirmationMessage; //Gecko + IE
return confirmationMessage; //Gecko + Webkit, Safari, Chrome etc.
});
// onclick
// document.getElementById('openbutton').addEventListener('click', function() {
// document.getElementById('fileInput').click()
// });
// document.getElementById('browsersavebutton').addEventListener('click', saveInBrowser);
// document.getElementById('savebutton').addEventListener('click', showMenu);
// document.getElementById('sharebutton').addEventListener('click', updateHash);
// document.getElementById('nightbutton').addEventListener('click', toggleNightMode);
// document.getElementById('readbutton').addEventListener('click', toggleReadMode);
// document.getElementById('spellbutton').addEventListener('click', toggleSpellCheck);
// document.getElementById('newbutton').addEventListener('click', clearEditor);
start();