-
Notifications
You must be signed in to change notification settings - Fork 30
/
writty.js
359 lines (284 loc) · 10.4 KB
/
writty.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
window.onload = function () {
trigger();
setupEventListenerForThemeSwitch();
setupEventListenerForFileImport();
setupEventListenerForCounter();
initialCheckForTheme();
initialCheckForCounter();
};
// Styling: Headings, Bold, Italic, Underline, Quotes, Lists //
document.querySelectorAll('[data-edit]').forEach(btn =>
btn.addEventListener('click', edit)
);
function edit(ev) {
ev.preventDefault();
const cmd_val = this.getAttribute('data-edit').split(':');
document.execCommand(cmd_val[0], false, cmd_val[1]);
}
// Functions: Links and Images //
const btns = document.querySelectorAll('[data-edt]');
function Space(aID) {
return document.getElementById(aID);
}
function trigger() {
let space = document.getElementById('content');
space.designMode = 'on';
space.addEventListener('mouseup', agent);
space.addEventListener('keyup', agent);
//Buttons Commands //
for (let b of btns) {
b.addEventListener('click', () => {
run(b.dataset.edt, b, b.dataset.param);
document.getElementById('content').focus();
document.getElementById('content').focus();
});
}
}
// Insert Link //
function run(cmd, ele, value = null) {
let status = document.execCommand(cmd, false, value);
if (!status) {
switch (cmd) {
case 'insertLink':
value = prompt('Enter url');
if (value.slice(0, 4) != 'http') {
value = 'http://' + value;
}
document.execCommand('createLink', false, value);
// Overrides inherited attribute "contenteditable" from parent
// which would otherwise prevent anchor tag from being interacted with.
atag = document.getSelection().focusNode.parentNode;
atag.setAttribute("contenteditable", "false");
break;
}
}
}
// Insert Image //
if (window.File && window.FileList && window.FileReader) {
const filesInput = document.getElementById("imageUpload");
filesInput.addEventListener("change", function (event) {
const files = event.target.files; //FileList object
const output = document.getElementById("content");
for (let i = 0; i < files.length; i++) {
const file = files[i];
//Only pics
if (!file.type.match('image'))
continue;
const picReader = new FileReader();
picReader.addEventListener("load", (event) => {
const picSrc = event.target.result;
const imgThumbnailElem = "<div class='imgView'><img src='" + picSrc + "'" +
"title='" + file.name + "'/><h5 style=text-align:center;>Caption</h5></div>";
output.innerHTML = output.innerHTML + imgThumbnailElem;
});
//Read the image
picReader.readAsDataURL(file);
}
});
} else {
alert("Your browser does not support File API");
}
// Word Counter //
function agent() {
let currentCounterPreference = localStorage.getItem("counter-preference");
var counterTotal;
switch(currentCounterPreference) {
case "character-count":
counterTotal = characterCount(document.getElementById('content').innerText);
break;
case "word-count":
counterTotal = wordCount(document.getElementById('content').innerText);
break;
}
document.getElementById('counter').innerText = counterTotal;
}
// Count All Characters //
function characterCount(str) {
return str.length;
}
// Count Words //
function wordCount(str) {
return str.match(/\b[-?(\w+)?]+\b/gi).length;
}
// Check For Counter //
function initialCheckForCounter() {
let counterPreference = "character-count";
// Local storage is used to override OS theme settings
if(localStorage.getItem("counter-preference")){
if(localStorage.getItem("counter-preference") === "word-count"){
counterPreference = "word-count";
}
}
localStorage.setItem("counter-preference", counterPreference);
}
// Toggle Current Counter //
function toggleCounterPreference() {
let currentCounterPreference = localStorage.getItem("counter-preference");
switch(currentCounterPreference) {
case "character-count":
localStorage.setItem("counter-preference", "word-count");
break;
case "word-count":
localStorage.setItem("counter-preference", "character-count");
break;
}
agent();
}
// Counter Switch //
function setupEventListenerForCounter() {
const counter = document.getElementById("counter");
counter.addEventListener("click", function() {
toggleCounterPreference();
});
}
// Theme Switch //
function setupEventListenerForThemeSwitch() {
const themeSwitch = document.getElementById("theme-switch");
themeSwitch.addEventListener("click", function() {
toggleThemePreference();
});
}
// File Import //
function triggerImportFile() {
const fileInput = document.getElementById("import-file")
fileInput.click()
}
function setupEventListenerForFileImport() {
const fileInput = document.getElementById("import-file")
fileInput.addEventListener("change", (event) => {
const file = event.currentTarget.files[0]
if(!file){ return }
const extension = file.name.split(".").pop()
if(extension === "html" || "md"){
const reader = new FileReader()
reader.onload = function(){
importContent(extension, reader.result)
}
reader.readAsText(file)
} else {
alert("File type is not supported for import")
}
})
}
function downloadContent(type) {
let editorContent = ''
if (type === 'txt') {
editorContent = document.getElementById('content').textContent;
} else if(type === 'md') {
const turndownService = new TurndownService({ headingStyle: 'atx', codeBlockStyle: 'fenced', emDelimiter: '*' });
editorContent = turndownService.turndown(document.getElementById('content').innerHTML);
} else {
editorContent =`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Writty</title>
</head>
<body>
${document.getElementById('content').innerHTML}
</body>
</html>
`
}
const linkElement = document.createElement("a")
linkElement.setAttribute("download", `writty.${type}`)
linkElement.setAttribute("href", 'data:text/plain;charset=utf-8,' + encodeURIComponent(editorContent))
linkElement.click()
document.body.removeChild(linkElement);
}
function importContent(fileExtension, content) {
const editorElement = document.getElementById('content')
if(fileExtension === 'html'){
const sanitizedContent = HtmlSanitizer.SanitizeHtml(content)
const tempElement = document.createElement("html")
tempElement.innerHTML = sanitizedContent
editorElement.innerHTML = tempElement.querySelector("body").innerHTML
} else if(fileExtension === "md") {
const converter = new showdown.Converter()
const html = converter.makeHtml(content)
editorElement.innerHTML = html
} else {
alert("Import only supports Markdown & HTML File")
}
agent()
}
// Toggle RTL //
function toggleRTL() {
const editorElement = document.querySelector("#editor")
const currentDir = editorElement.getAttribute("dir")
if (!currentDir || currentDir === "ltr") {
editorElement.setAttribute("dir", "rtl")
} else {
editorElement.setAttribute("dir", "ltr")
} {
var nav = document.querySelector('.topbar-button');
nav.classList.toggle('active');
e.preventDefault();
}
}
// Check for theme //
function initialCheckForTheme() {
// Default to light-theme
let themePreference = "light-theme";
// Local storage is used to override OS theme settings
if(localStorage.getItem("theme-preference")){
if(localStorage.getItem("theme-preference") === "dark-theme"){
themePreference = "dark-theme";
}
} else if(!window.matchMedia) {
// matchMedia method not supported
return false;
} else if(window.matchMedia("(prefers-color-scheme: dark)").matches) {
// OS theme setting detected as dark
themePreference = "dark-theme";
}
if (themePreference === "dark-theme") {
const themeSwitch = document.getElementById("theme-switch");
themeSwitch.checked = true;
}
localStorage.setItem("theme-preference", themePreference);
document.body.classList.add(themePreference);
}
// Toggle current theme //
function toggleThemePreference() {
let currentThemePreference = localStorage.getItem("theme-preference");
switch(currentThemePreference) {
case "light-theme":
localStorage.setItem("theme-preference", "dark-theme");
document.body.classList.remove("light-theme");
document.body.classList.add("dark-theme");
break;
case "dark-theme":
localStorage.setItem("theme-preference", "light-theme");
document.body.classList.remove("dark-theme");
document.body.classList.add("light-theme");
break;
}
}
// Paste plain text //
const ce = document.querySelector('[contenteditable]');
ce.addEventListener('paste', function (e) {
e.preventDefault();
const text = e.clipboardData.getData('text/plain');
document.execCommand('insertText', false, text);
});
// Paste image //
document.getElementById('content').addEventListener("paste", (event) => {
var clipboardData = event.clipboardData;
clipboardData.types.forEach((type, i) => {
const fileType = clipboardData.items[i].type;
if (fileType.match(/image.*/)) {
const file = clipboardData.items[i].getAsFile();
const reader = new FileReader();
reader.onload = function (evt) {
const dataURL = evt.target.result;
const img = document.createElement("img");
img.src = dataURL;
document.execCommand('insertHTML', true, img.outerHTML);
};
reader.readAsDataURL(file);
}
})
});