-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJava.js
More file actions
89 lines (79 loc) · 2.55 KB
/
Copy pathJava.js
File metadata and controls
89 lines (79 loc) · 2.55 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
const editor = document.getElementById("editor");
const saveBtn = document.getElementById("saveBtn");
const loadBtn = document.getElementById("loadBtn");
const fileNameDisplay = document.getElementById("File");
// Global variable to store the file handle
let currentFileHandle = null;
// Auto-save to localStorage
editor.addEventListener("input", () => {
localStorage.setItem("myDraft", editor.value);
});
saveBtn.addEventListener("click", async () => {
try {
// If no file is open, show the picker (Save As)
if (!currentFileHandle) {
currentFileHandle = await window.showSaveFilePicker({
suggestedName: "Draft.txt",
types: [
{
description: "Text Files",
accept: {
"text/plain": [".txt", ".md", ".html", ".css", ".js", ".json"],
},
},
],
});
}
// Write content to the file
const writable = await currentFileHandle.createWritable();
await writable.write(editor.value);
await writable.close();
// Update UI
fileNameDisplay.innerText = currentFileHandle.name;
console.log("File saved!");
} catch (err) {
if (err.name !== "AbortError") console.error(err);
}
});
// Load Function
loadBtn.addEventListener("click", async () => {
try {
const [handle] = await window.showOpenFilePicker({
types: [
{
description: "Documents & Code",
accept: {
"text/plain": [".txt", ".md", ".html", ".css", ".js", ".json"],
},
},
],
multiple: false,
});
// Store the handle!
currentFileHandle = handle;
const file = await handle.getFile();
const content = await file.text();
editor.value = content;
localStorage.setItem("myDraft", content);
fileNameDisplay.innerText = handle.name;
console.log("File loaded!");
} catch (err) {
if (err.name !== "AbortError") console.error(err);
}
});
document.addEventListener("DOMContentLoaded", () => {
if (editor) {
editor.addEventListener("keydown", function (e) {
if (e.key === "Tab") {
e.preventDefault();
const start = this.selectionStart;
const end = this.selectionEnd;
// Using spaces instead of "\t" to ensure zero formatting conflicts
const spaces = " ";
this.value =
this.value.substring(0, start) + spaces + this.value.substring(end);
this.selectionStart = this.selectionEnd = start + spaces.length;
}
});
}
});