-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathui.js
More file actions
356 lines (315 loc) · 13.8 KB
/
ui.js
File metadata and controls
356 lines (315 loc) · 13.8 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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
/**
* ui.js — Demo Frontend Logic for DataManager
*
* This file connects DOM inputs with the DataManager module
* to demonstrate encryption, decryption, and storage capabilities.
*
* NOTE: This is a demo UI. A real application should manage
* data and errors through app logic, not direct DOM manipulation.
*/
import * as DataManager from './datamanager.js';
import { generateRecoveryKey } from './crypto.js';
export function refresh() {
function localStorageKeys() {
const keys = Object.keys(localStorage);
const datalist = document.getElementById('localStorageKeys');
datalist.textContent = '';
for(const key of keys) {
const option = document.createElement('option');
option.value = key;
datalist.appendChild(option);
}
}
localStorageKeys();
}
export function init() {
document.getElementById('fileConfig').addEventListener('change', (event) => {
const content = `{${event.target.value}}`;
try {
const parsed = JSON.parse(content);
event.target.setCustomValidity('');
}
catch(e) {
event.target.setCustomValidity('No valid JSON');
event.target.reportValidity();
}
});
document.getElementById('setFileConfig').addEventListener('click', () => {
const textArea = document.getElementById('fileConfig');
if(!textArea.checkValidity() || textArea.validity.customError) return;
const parsed = JSON.parse(`{${textArea.value}}`);
DataManager.file.formats = parsed;
const formats = Object.keys(parsed);
setSelectOptions(document.getElementById('fileFormatInput'), formats);
})
document.getElementById('localStorageContent').addEventListener('change', (event) => {
const content = `{${event.target.value}}`;
try {
const parsed = JSON.parse(content);
event.target.setCustomValidity('');
}
catch(e) {
event.target.setCustomValidity('No valid JSON');
event.target.reportValidity();
}
});
document.getElementById('setStorage').addEventListener('click', () => {
const textArea = document.getElementById('localStorageContent');
if(!textArea.checkValidity() || textArea.validity.customError) return;
DataManager.storage.prefix = document.getElementById('localStoragePrefix').value || 'datamanager';
const content = JSON.parse(`{${textArea.value}}`);
for(let key in content) {
DataManager.storage.set(key, content[key]);
}
});
document.getElementById('getStorage').addEventListener('click', () => {
DataManager.storage.prefix = document.getElementById('localStoragePrefix').value || 'datamanager';
renderLocalStorageContent();
})
document.getElementById('downloadButton').addEventListener('click', async () => {
const data = document.getElementById('fileContent').value || 'Hello World!';
const format = document.getElementById('fileFormatInput').value;
const password = document.getElementById('filePasswordInput').value;
const recoveryKey = await generateRecoveryKey();
document.getElementById('recoveryKey').textContent = recoveryKey;
DataManager.file.export({data, format, encryptParameters: { password, recoveryKey }})
.catch(error => {
switch(error.code) {
case 'MISSING_ENCRYPT_PARAM':
alert('Missing encryption Parameters');
break;
default:
console.log(error)
alert(error);
}
});
});
document.getElementById('fileInput').addEventListener('change', function(event) {
const file = event.target.files[0];
if(!file) return;
const fileExtension = file.name.split('.').slice(-1)[0];
// Find the format key matching the extension and if encrypted
const formatEntry = Object.values(DataManager.file.formats).find(format => format.extension === fileExtension);
if (formatEntry && formatEntry.encrypted) {
document.getElementById('fileAccessKey').value = '';
document.documentElement.style.setProperty('--fileAccessDisplay', 'block');
}
else {
document.documentElement.style.setProperty('--fileAccessDisplay', 'none');
handleFile();
}
});
document.getElementById('submitUpload').addEventListener('click', handleFile);
document.getElementById('fileFormatInput').addEventListener('change', (event) => {
if(DataManager.file.formats[event.target.value]?.encrypted === true) document.documentElement.style.setProperty('--encryptedFileDisplay', 'flex');
else document.documentElement.style.setProperty('--encryptedFileDisplay', 'none');
});
document.getElementById('copyRecoveryKey').addEventListener('click', async function () {
await navigator.clipboard.writeText(document.getElementById('recoveryKey').textContent)
})
async function handleFile() {
const file = document.getElementById('fileInput').files[0];
const accessKey = document.getElementById('fileAccessKey')?.value;
DataManager.file.import(file, accessKey)
.then((result) =>{
document.getElementById('resultContent').textContent = result;
document.documentElement.style.setProperty('--fileAccessDisplay', 'none');
})
.catch(error => {
switch(error.code) {
case 'NO_KEY':
alert('You need to input your password or recovery key');
break;
case 'INVALID_FILE_STRUCTURE':
alert(`The uploaded file's file structure is invalid.`);
break;
case 'DEK_DECRYPTION_ERROR':
alert('The provided key is invalid');
break;
case 'DECRYPTION_ERROR':
alert('The decryption failed');
break;
case 'BAD_HMAC':
alert('The file decryption failed, because the content seems to be altered or corrupted.');
break;
default:
alert(error.message);
}
});
}
document.getElementById('fileConfig').addEventListener('keydown', tabReplacer);
document.getElementById('localStorageContent').addEventListener('keydown', tabReplacer);
function tabReplacer(e) {
const textarea = e.target;
const start = textarea.selectionStart;
const end = textarea.selectionEnd;
const value = textarea.value;
switch (e.key) {
case 'Tab':
e.preventDefault();
if (start !== end) {
if (e.shiftKey) {
outdentSelection();
} else {
indentSelection();
}
} else {
if (e.shiftKey) {
outdentLine();
} else {
insertText(' ');
}
}
break;
case '{':
case '[':
e.preventDefault();
const pair = e.key === '{' ? ['{', '}'] : ['[', ']'];
if (start !== end) {
const selected = value.substring(start, end);
insertText(pair[0] + selected + pair[1], selected.length + 1);
}
else {
insertText(pair[0] + pair[1], 1);
}
break;
case 'Quote':
e.preventDefault();
if(start !== end) {
const selected = value.substring(start, end);
insertText(`"${selected}"`, selected.length + 1);
}
else insertText(`""`, 1);
break;
case 'Enter':
e.preventDefault();
const indent = getLineIndent(value, start);
const newline = '\n';
if (value[start - 1] === '{') {
const nextChar = value[start] || '';
const middleIndent = indent + ' ';
if (nextChar === '}') {
const insertedText = newline + middleIndent + newline + indent;
const cursorOffset = newline.length + middleIndent.length;
insertText(insertedText, cursorOffset);
} else {
insertText(newline + middleIndent);
}
} else {
insertText(newline + indent);
}
break;
case 'Delete':
e.preventDefault();
if (start !== end) {
insertText('');
} else if (value.substring(start, start + 4) === ' ') {
deleteRange(start, start + 4);
} else {
deleteRange(start, start + 1);
}
break;
case 'Backspace':
e.preventDefault();
if (start !== end) {
insertText('');
} else if (value.substring(start - 4, start) === ' ') {
deleteRange(start - 4, start);
} else {
deleteRange(start - 1, start);
}
break;
}
function insertText(text, cursorOffset = text.length) {
textarea.value = value.substring(0, start) + text + value.substring(end);
const cursor = start + cursorOffset;
textarea.selectionStart = textarea.selectionEnd = cursor;
}
function deleteRange(from, to) {
textarea.value = value.substring(0, from) + value.substring(to);
textarea.selectionStart = textarea.selectionEnd = from;
}
function getLineIndent(text, index) {
const lineStart = text.lastIndexOf('\n', index - 1) + 1;
const match = text.slice(lineStart, index).match(/^\s*/);
return match ? match[0] : '';
}
function indentSelection() {
const lineStart = value.lastIndexOf('\n', start) + 1;
const lineEnd = value.indexOf('\n', end);
const actualEnd = lineEnd === -1 ? value.length : lineEnd;
const selectedText = value.substring(lineStart, actualEnd);
const lines = selectedText.split('\n');
const indented = lines.map(line => ' ' + line).join('\n');
const addedChars = 4 * lines.length;
textarea.value = value.substring(0, lineStart) + indented + value.substring(actualEnd);
textarea.selectionStart = start + 4;
textarea.selectionEnd = end + addedChars;
}
function outdentSelection() {
const lineStart = value.lastIndexOf('\n', start) + 1;
const lineEnd = value.indexOf('\n', end);
const actualEnd = lineEnd === -1 ? value.length : lineEnd;
const selectedText = value.substring(lineStart, actualEnd);
const lines = selectedText.split('\n');
let removedChars = 0;
const outdented = lines.map(line => {
if (line.startsWith(' ')) {
removedChars += 4;
return line.slice(4);
}
return line;
}).join('\n');
textarea.value = value.substring(0, lineStart) + outdented + value.substring(actualEnd);
textarea.selectionStart = Math.max(start - 4, lineStart);
textarea.selectionEnd = end - removedChars;
}
function outdentLine() {
const lineStart = value.lastIndexOf('\n', start - 1) + 1;
if (value.substring(lineStart, lineStart + 4) === ' ') {
textarea.value = value.substring(0, lineStart) +
value.substring(lineStart + 4);
const newCursor = start - 4;
textarea.selectionStart = textarea.selectionEnd = newCursor;
}
}
}
renderLocalStorageContent();
renderFileConfig();
function renderLocalStorageContent() {
const content = JSON.parse(localStorage.getItem(DataManager.storage.prefix));
const list = Object.keys(content);
const result = [];
for(let key of list) {
result.push(`"${key}": ${JSON.stringify(content[key], null, 4)}`);
}
document.getElementById('localStorageContent').value = result.join(',\n');
}
function renderFileConfig() {
const config = DataManager.file.formats;
const list = Object.keys(config);
const result = [];
for(let key of list) {
result.push(`"${key}": ${JSON.stringify(config[key], null, 4)}`);
}
document.getElementById('fileConfig').value = result.join(',\n');
setSelectOptions(document.getElementById('fileFormatInput'), list);
}
function setSelectOptions(node, options) {
node.innerHTML = '';
for(const option of options) {
const opt = document.createElement('option');
opt.value = option;
opt.textContent = option;
node.appendChild(opt);
}
node.dispatchEvent(new Event('change'))
}
}
export function error(message, errorCode) {
alert(`
An Error occurred:
${message}
${errorCode}
`)
}