-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
342 lines (306 loc) · 11.2 KB
/
script.js
File metadata and controls
342 lines (306 loc) · 11.2 KB
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
var quill = "placeholder";
var lastset = "none"
var output
//Sleep
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
//Copy to clipboard
function clipCopy(stuff) {
try {
navigator.clipboard.writeText(stuff);
} catch(error){
console.log("Copy of text failed " + error);
}
}
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + exdays * 24 * 60 * 60 * 1000);
var expires = "expires=" + d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(";");
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == " ") {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
//Make HTML out of quill
function quilltoHTML(debug=false){
try {
console.log("Converting quill to HTML..");
ogcontent = quillGetHTML();
if(debug){
console.log(ogcontent);
}
let substrings = ogcontent.split(/(?=<)/);
if(debug){
console.log(substrings);
}
for (let i = 0; i < substrings.length; i++) {
substrings[i] += '\n';
}
if(debug){
console.log(substrings);
}
let brrr = substrings.join('')
//hella replace things (split up so it's not readable but not as bad as if it were one long line)
brrr = brrr.replace(/class="[^"]*"/g, '');
brrr = brrr.replace(/ >/g, '>');
brrr = brrr.replace(/\n<\//g, '</');
brrr = brrr.replace(/<p>\n<br><\/p>/g, '<br>');
brrr = brrr.replace(/<p>\n<strong>/g, '<p><strong>');
brrr = brrr.replace(/ rel="noopener noreferrer" target="_blank"/, '')
for (let confusion=0; confusion < 11323; confusion++){ //idk why this is necessary but i cba to find a better solution
brrr = brrr.replace(/<div data-language="plain">(.*?)<\/div>/, '<code>$1</code>');
}
//I FUCKING HATE HOW QUILL DOES EQUATIONS LIKE THIS, THIS DOES LIKE NOTHING (I moved on because I have better things to do)
brrr = brrr.replace(/<span[^>]*aria-hidden="true"[^>]*>[\s\S]*?<\/span>/g, '');
if(debug){
console.log(brrr);
}
var firstOp = quill.getContents().ops.find(op => op.insert !== '\n'); // Find the first non-empty text segment
var font = firstOp.attributes && firstOp.attributes.font ? firstOp.attributes.font : 'Sans-Serif';
var size = firstOp.attributes && firstOp.attributes.size ? firstOp.attributes.size : '8px';
strappedstyle="<style>\nbody{\nbackground-color:#1e1e2e;\ncolor:#cdd6f4;\nfont-family:"+font+";\n}\n</style>\n";
console.log("Style to strap: "+strappedstyle);
output=strappedstyle+brrr;
const encodedString = btoa(unescape(encodeURIComponent(output)));
hostlink="https://cstext.pages.dev/host/?note="+encodedString;
const copyButton = document.createElement("button");
copyButton.textContent = "Share this note with a friend? (currently read only)";
copyButton.className = "normalbutton"
copyButton.onclick = function() {
clipCopy(hostlink);
alert('link copied')
};
document.getElementById('host').appendChild(copyButton)
document.getElementById('convertedhtml').innerText = output;
document.getElementById('htmlout').style.display = 'block';
console.log("..success!")
} catch(error){
console.log("error "+error);
}
}
//Save and saveload functions
function save(quill) {
console.log('Saving changes');
const data = JSON.stringify(quill.getContents());
return data;
}
function saveLocal(){
var usin = prompt("write to save name:")
if (localStorage.getItem(usin) == null) {
localStorage.setItem(usin, save(quill));
if (localStorage.getItem("itemlist")==null){
localStorage.setItem("itemlist", "- " + usin + "\n")
} else {
let ls=localStorage.getItem("itemlist")
localStorage.setItem("itemlist", ls + "- " + usin + "\n")
}
} else if (confirm("overwrite save?")) {
localStorage.setItem(usin, save(quill));
}
}
function loadLocal(){
if (localStorage.getItem("itemlist")!=null){
usin = prompt("Here is a list of all of your saves, choose one: \n \n" + localStorage.getItem("itemlist"))
} else {
alert("Sorry, you don't have any saves yet, if this is due to a bug in an update, we apologise")
}
if(confirm("load save "+usin+"?")){
data = JSON.parse(localStorage.getItem(usin));
quill.setContents(data);
console.log("..success!");
console.log(data);
} else {
console.log("loadsave cancelled successfully")
}
}
function dropdown(){
if (lastset == "block"){
document.getElementById("dropdown-content").style.display="none"
lastset = "none"
} else {
document.getElementById("dropdown-content").style.display="block"
lastset = "block"
}
}
function dlSave(){
console.log("dlSave requested");
let textFile = null;
const makeTextFile = (text) => {
const data = new Blob ([text], { type: 'text/plain', });
if (textFile !== null) {
window.URL.revokeObjectURL (textFile);
}
textFile = window.URL.createObjectURL (data);
return textFile;
};
const link = document.createElement ('a');
var nam = prompt("File name:")
if (nam != null){
link.setAttribute ('download', nam + ".cst");
}
link.href = makeTextFile(save(quill));
try {
link.click();
console.log("successfully downloaded text file");
} catch(error) {
console.log("Small problem: " + error);
}
}
function upSave(){
console.log("upSave requested");
var input = document.createElement('input');
input.type = 'file';
input.onchange = (e) => {
var file = e.target.files[0];
var reader = new FileReader();
reader.readAsText(file, 'UTF-8');
reader.onload = (readerEvent) => {
var content = readerEvent.target.result;
var data = JSON.parse(content);
console.log(data);
quill.setContents(data);
}
}
try {
input.click();
console.log("load success!");
} catch(error) {
console.log("fuck you :D " + error);
}
}
//Function to get HTML from a quill delta
function quillGetHTML(inputDelta=quill.getContents()) {
console.log("Get Quill HTML");
try {
var tempCont = document.createElement("div");
(new Quill(tempCont)).setContents(inputDelta);
convhtml = tempCont.getElementsByClassName("ql-editor")[0].innerHTML;
console.log("..success!");
} catch(error){
console.log("Quill HTML get failed. " + error);
}
return convhtml;
}
//Set quill to an empty string. Just disables all quill functions. Not sure why you need this.
function killQuill(){
quill = "";
console.log("quill killed. saving and loading is broken but it probably still works");
}
//Custom handler functions for the video link input (turns it into embedded links)
function getVideoUrl(url) {
let match =
url.match(/^(?:(https?):\/\/)?(?:(?:www|m)\.)?youtube\.com\/watch.*v=([a-zA-Z0-9_-]+)/) || //Yes this is a pain to decipher, I had bing do it
url.match(/^(?:(https?):\/\/)?(?:(?:www|m)\.)?youtu\.be\/([a-zA-Z0-9_-]+)/);
if (match && match.length === 3) {
return `https://www.youtube.com/embed/${match[2]}?showinfo=0`;
}
match = url.match(/^(?:(https?):\/\/)?(?:www\.)?vimeo\.com\/(\d+)/);
if (match) {
return `https://player.vimeo.com/video/${match[1]}/`;
}
return "invalid";
}
function videoHandler() {
console.log("Video embed button triggered");
let url = prompt("Enter Video URL:"); // Prompt the user for the video URL
if (url) {
url = getVideoUrl(url); // Convert the URL to an embeddable format
if (url == "invalid") {
alert("invalid url provided (needs youtube or vimeo)");
url=False;
}
let range = quill.getSelection();
if (url) {
quill.insertEmbed(range, "video", url); // Insert the video embed
}
} else {
console.log("Invalid video URL provided.");
}
}
//Essentially the main function, cuz quill needs the page to be loaded first (ik it's not a function)
document.addEventListener('DOMContentLoaded', (event) => {
console.log("CStext 0.3.0, powered by wTextitor v0.2.1c")
//Only init quill after everything has loaded because otherwise it throws an error :shrug:
console.log("initalise quill");
const fontSizeArr = ['8px','9px','10px','12px','14px','16px','20px','24px','32px','42px','54px','68px','84px','98px'];
try {
var Delta = Quill.import('delta');
var Size = Quill.import('attributors/style/size');
Size.whitelist = fontSizeArr;
Quill.register(Size, true);
var toolbarOptions = {
container: [ //All the toolbar shit
[{ 'font': [] }, { 'size': fontSizeArr }],
['bold', 'italic', 'underline', 'strike'],
['link', 'image', 'video'],
[{ 'list': 'ordered'}, { 'list': 'bullet' }, { 'list': 'check' }, { 'align': [] }],
['blockquote', 'code-block', 'formula'],
[{ 'background': [] }],
[{ 'script': 'sub'}, { 'script': 'super' }],
[{'header': 1}, {'header': 2}]
],
handlers: {
video: videoHandler
}
};
quill = new Quill('#editor', {
modules: {
toolbar: toolbarOptions
},
theme: 'snow'
});
} catch(error) {
console.log("quill broke with " + error);
document.getElementById('infoh1').innerHTML = "quill failed to load.";
document.getElementById('infop1').innerHTML = "Please refresh the page. If this this issue persists, please create an issue on https://github.com/ThisCatLikesCrypto/Website (not a link)";
document.getElementById('infop2').innerHTML = "Error is " + error;
document.getElementById('infop3').innerHTML = "Please remember that this is still in alpha, and all feedback is welcome!";
}
var change = new Delta();
quill.on('text-change', function(delta) {
change = change.compose(delta);
});
var toContinue=getQueryVariable("continue")
if (toContinue != "no"){
loadLocal()
}
if (getCookie("theme") != ""){
document.getElementById("theme").href="css/"+getCookie("theme")+".css"
}
});
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
return "no";
}
function showSettings(){
document.getElementById("notSettings").style.display="none"
document.getElementById("settings").style.display="block"
}
function hideSettings(){
document.getElementById("settings").style.display="none"
document.getElementById("notSettings").style.display="block"
}
function changeTheme(theme){
setCookie("theme", theme, 365)
alert("theme set, save your work and reload cstext when you are ready")
}