-
Notifications
You must be signed in to change notification settings - Fork 0
/
react-ui.js
522 lines (481 loc) · 14.5 KB
/
react-ui.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
const { useEffect, useState, useCallback, useRef, useMemo } = React;
const rootElement = document.getElementById("root");
const metaElements = document.getElementsByTagName("meta");
const urlRegex =
/(?:\w+:\/\/)?\b(?:(?:[\w_\-@.\p{L}]+\.[\w]{1,6})|(?:\w+:\/\/localhost))\b(?::[\d]{1,5})?[\/#]?(?:[\w@:%_\+.~#?&\/\/=\$\p{L}-]*)?/gim;
const { STORE_KEYS, ACTIONS, META_LIST } = window.APP;
const useLocalStorage = (key, initialvalue, stale) => {
const [staled, setStaled] = stale;
const load = () => {
const savedvalue = JSON.parse(localStorage.getItem(key));
if (savedvalue !== null) return savedvalue;
return initialvalue;
};
const [value, setvalue] = useState(load());
const refresh = () => setvalue(load());
useEffect(() => {
if (staled === key) refresh();
}, [staled]);
useEffect(() => {
if (JSON.parse(sessionStorage.getItem(key))) {
if (staled === "") {
localStorage.setItem(key, JSON.stringify(value));
window.APP.sendMessage({ action: ACTIONS.RELOAD_DATA, key });
} else setStaled("");
} else sessionStorage.setItem(key, true);
}, [value]);
return [value, setvalue, refresh];
};
const Check = () => {
return (
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="white">
<path d="M9 16.2L4.8 12l-1.4 1.4L9 19 21 7l-1.4-1.4L9 16.2z" />
</svg>
);
};
const Note = ({
showLinks,
note,
handleEdit,
handleDelete,
setEditing,
editing,
copyNote,
}) => {
const { id, completed, body } = note;
const highlightedText = useMemo(() => {
let matches = body.match(urlRegex),
content = [],
j = 0,
len = body.length;
if (matches) {
matches.forEach((match) => {
const i = body.indexOf(match);
if (i !== 0 || j !== 0) content.push({ str: body.slice(j ? j : 0, i) });
content.push({
url: match,
href: match.includes("://") ? match : `http://${match}`,
});
j = i + match.length;
});
if (j !== len - 1) content.push({ str: body.slice(j, len - 1) });
} else content.push({ str: body });
return content.map(({ url, str, href }) => {
if (url)
return (
<a
key={crypto.randomUUID()}
href={href ? href : url}
title={url}
target="_blank"
rel="noopener noreferrer"
>
{url}
</a>
);
else return <>{str}</>;
});
}, [body]);
return (
<div
className={`note${note.new ? " enter-anim" : ""}${
note.deleted ? " delete-anim" : ""
}${completed ? " completed" : ""}`}
key={id}
>
<p>{showLinks ? highlightedText : <>{body}</>}</p>
<div className={`actions${editing === id ? " open" : ""}`}>
<button title="Copy" onClick={() => copyNote(id)} class="button">
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
fill="white"
>
<path d="M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z" />
</svg>
</button>
<button
title={completed ? "Mark as not done" : "Mark as done"}
onClick={() => handleEdit(id)}
class={`button mark${completed ? " completed" : ""}`}
>
{completed ? (
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
fill="white"
>
<path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z" />
</svg>
) : (
<Check />
)}
</button>
<button
onClick={
editing === id ? () => setEditing(false) : () => setEditing(id)
}
className={`button edit${editing === id ? " editing" : ""}`}
title={editing === id ? "Stop editing" : "Edit"}
>
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
fill="white"
>
<path d="M3.95 16.7v3.4h3.4l9.8-9.9-3.4-3.4-9.8 9.9zm15.8-9.1c.4-.4.4-.9 0-1.3l-2.1-2.1c-.4-.4-.9-.4-1.3 0l-1.6 1.6 3.4 3.4 1.6-1.6z" />
</svg>
</button>
<button
onClick={(e) => handleDelete(e, id)}
className="button delete"
title="Delete"
>
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
fill="white"
>
<path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z" />
</svg>
</button>
</div>
</div>
);
};
const CheckBox = ({ checked }) => {
return (
<span className={checked ? "checkbox checked" : "checkbox"}>
<Check />
</span>
);
};
``;
const App = () => {
const stale = useState("");
const [, setStaled] = stale;
const [notes, setNotes] = useLocalStorage(STORE_KEYS.NOTES, [], stale);
const [theme, setTheme] = useLocalStorage(STORE_KEYS.THEME, false, stale);
const [newNote, setNewNote] = useLocalStorage(STORE_KEYS.NEWNOTE, "", stale);
const [enterSend, setEnterSend] = useLocalStorage(
STORE_KEYS.ENTERSEND,
false,
stale
);
const [isNote, setIsNote] = useState(false);
const [alert, setAlert] = useState("");
const [undo, setUndo] = useState(false);
const [editing, setEditing] = useState(null);
const [showLinks, setShowLinks] = useState(true);
const [nav, setNav] = useState(false);
const [updateAvailable, setUpdateAvailable] = useState(false);
const [version, setVersion] = useState(0);
const [updating, setUpdating] = useState(false);
const textarea = useRef();
const undoTimeoutRef = useRef();
useEffect(async () => {
window.APP.init()
.then((reg) => {
navigator.serviceWorker.addEventListener("message", (event) => {
switch (event.data.action) {
case ACTIONS.RELOAD_DATA: {
setStaled(event.data.key);
break;
}
case ACTIONS.UPDATE_AVAILABLE: {
if (window.APP.newServiceWorker) setUpdateAvailable(true);
break;
}
case ACTIONS.VERSION: {
setVersion(event.data.version);
break;
}
}
});
return reg;
})
.then(() => {
window.APP.sendMessage({ action: ACTIONS.VERSION });
});
textarea.current.focus();
textarea.current.selectionStart = newNote.length;
}, []);
useEffect(() => {
setIsNote(!/^\s*$/g.test(newNote));
updateInputSize();
textarea.current.focus();
}, [newNote]);
useEffect(() => {
textarea.current.focus();
}, [textarea.current]);
useEffect(() => {
if (undoTimeoutRef.current) clearTimeout(undoTimeoutRef.current);
if (undo === false) undoTimeoutRef.current = false;
else undoTimeoutRef.current = setTimeout(() => setUndo(false), 5000);
}, [undo]);
useEffect(() => {
if (alert !== "") setTimeout(() => setAlert(""), 3000);
}, [alert]);
useEffect(() => {
if (!nav) document.activeElement.blur();
}, [nav]);
useEffect(() => {
const themeColor = theme ? "#1976d2" : "#161b22";
if (theme) rootElement.classList.remove("dark");
else rootElement.classList.add("dark");
for (let i = 0; i < metaElements.length; i++) {
if (META_LIST.includes(metaElements[i].name)) {
metaElements[i].content = themeColor;
}
}
}, [theme]);
useEffect(() => {
setTimeout(() => {
if (notes.some((i) => i.new === true)) {
setNotes(
notes.map((i) => {
if (i.new) return { ...i, new: undefined };
return i;
})
);
}
}, 400);
}, [notes]);
useEffect(() => {
if (editing) {
setNewNote(notes.find((i) => i.id === editing).body);
} else if (editing === false) {
setNewNote("");
}
}, [editing]);
const SetNotes = useCallback(
(newNotes, undoText) => {
const oldNotes = notes;
setUndo({ text: undoText, func: () => setNotes(oldNotes) });
setNotes(newNotes);
},
[notes]
);
const updateInputSize = useCallback(() => {
const el = textarea.current;
if (
el.style.height.slice(0, -2) == el.scrollHeight ||
(el.scrollHeight > 170
? el.style.height.slice(0, -2) === 170
? true
: false
: false)
)
return;
el.style.height = "50px";
el.style.height = el.scrollHeight + "px";
el.style.overflowY = el.scrollHeight < 170 ? "hidden" : "auto";
}, [textarea.current]);
const saveEditedNote = useCallback(() => {
if (isNote) {
setNotes(
notes.map((i) => {
if (i.id === editing) {
return {
...i,
body: newNote,
};
}
return i;
})
);
setEditing(false);
setAlert("Note edited");
} else return;
}, [isNote, newNote, textarea.current, notes]);
const saveNewNote = useCallback(() => {
if (isNote) {
setNotes([
{
id: new Date().getTime(),
body: newNote.trim(),
completed: false,
new: true,
},
...notes,
]);
setNewNote("");
} else return;
}, [isNote, newNote, textarea.current, notes]);
const handleDelete = useCallback(
(e, id) => {
if (editing === id) setEditing(false);
setNotes(
notes.map((i) => {
if (i.id === id) return { ...i, deleted: true };
return i;
})
);
setTimeout(() => {
SetNotes(
notes.filter((note) => note.id !== id),
"Note deleted"
);
}, 400);
},
[notes, editing, undoTimeoutRef.current, SetNotes]
);
const handleEdit = useCallback(
(id) => {
const Newnotes = notes.map((item) => {
if (item.id === id) {
item.completed = !item.completed;
return item;
} else return item;
});
setNotes(Newnotes);
},
[notes]
);
const handleSubmit = useCallback(
(e) => {
if (editing) saveEditedNote();
else saveNewNote();
},
[saveNewNote, saveEditedNote, editing]
);
const removeall = useCallback(() => {
if (confirm("Delete All Notes")) {
SetNotes([], "Deleted all Notes");
setNav(false);
}
}, [SetNotes]);
const copyNote = useCallback(
async (id) => {
await window.APP.copyToClipBoard(notes.find((i) => i.id === id).body);
setAlert("Copied note ✓");
},
[notes]
);
if (updating) return <span class="preloader">Updating</span>;
else {
return (
<div className={theme ? "html" : "html dark"}>
<div className="header-cont">
<div className="header">
<p>Notebook</p>
<button onClick={() => setNav(!nav)} title="Menu">
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
fill="white"
>
<path d="M3 18h18v-2H3v2zm0-5h18v-2H3v2zm0-7v2h18V6H3z" />
</svg>
</button>
</div>
</div>
<div
className={nav ? "nav-cont nav-cont-show" : "nav-cont"}
onClick={(e) => {
if (e.target.id === "nav-cont") setNav(false);
}}
id="nav-cont"
>
<div className={nav ? "nav nav-show" : "nav"}>
<button onClick={() => setEnterSend(!enterSend)}>
'Enter' key is save
<CheckBox checked={enterSend} />
</button>
<button onClick={() => setShowLinks(!showLinks)}>
Show Url's as Links
<CheckBox checked={showLinks} />
</button>
<button onClick={() => setTheme(!theme)}>
Dark theme
<CheckBox checked={!theme} />
</button>
<button onClick={removeall}>Delete All Notes</button>
<p className="about">version : {version}</p>
<p className="about">
Do not delete localStorage data!. Notes are stored in localStorage
and could be lost during an update so keep a backup of your
important information.
</p>
</div>
</div>
<div className="popup-cont">
{alert !== "" && (
<div className="popup">
<span>{alert}</span>
</div>
)}
{undo.func && (
<div className="popup">
<span>{undo.text}</span>
<button
onClick={() => {
undo.func();
setUndo(false);
}}
>
undo
</button>
</div>
)}
{updateAvailable && (
<div className="popup">
<span>Update available for Notebook</span>
<button
onClick={() => {
setUpdating(true);
window.APP.sendMessage(
{ action: ACTIONS.UPDATE },
window.APP.newServiceWorker
);
}}
>
update
</button>
</div>
)}
</div>
<div className="form">
<textarea
title="Type a note"
className={isNote ? "textarea" : "notextarea"}
rows={1}
ref={textarea}
value={newNote}
onChange={(e) => setNewNote(e.target.value)}
onKeyUp={({ keyCode }) =>
keyCode == "13" && enterSend ? handleSubmit() : null
}
></textarea>
<span className="placeholder">Type a note</span>
<button
title="Save Note"
onClick={handleSubmit}
className={isNote ? "save" : "nosave"}
tabIndex={isNote ? 0 : -1}
>
save
</button>
</div>
<div className="container">
{notes && notes.length !== 0 ? (
notes.map((item) => (
<Note
showLinks={showLinks}
note={item}
handleEdit={handleEdit}
handleDelete={handleDelete}
setEditing={setEditing}
editing={editing}
copyNote={copyNote}
/>
))
) : (
<div className="nonotes">No Saved Notes ☹️</div>
)}
</div>
</div>
);
}
};
ReactDOM.render(<App />, rootElement);