-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheditor.html
More file actions
280 lines (254 loc) · 10.4 KB
/
editor.html
File metadata and controls
280 lines (254 loc) · 10.4 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Offline Editor — Self-Contained</title>
<style>
:root{
--bg:#1e1e1e; --bg2:#252525; --panel:#2b2b2b; --fg:#d4d4d4; --muted:#9aa0a6;
--accent:#2f71b4; --accent-hi:#3a8bc9; --ok:#2f9e44;
--kw:#569cd6; --str:#ce9178; --com:#6a9955; --num:#b5cea8; --tag:#4fa4ff; --attr:#d7ba7d;
}
*{box-sizing:border-box}
html,body{height:100%}
body{margin:0;background:var(--bg);color:var(--fg);font-family:Segoe UI,system-ui,-apple-system,Arial,sans-serif;display:flex;flex-direction:column}
header{background:var(--bg2);padding:10px;display:flex;gap:8px;align-items:center;flex-wrap:wrap}
header input[type="text"],header select{background:#2d2d2d;border:1px solid #333;color:var(--fg);padding:7px 10px;border-radius:6px}
header button{background:var(--accent);border:0;color:white;padding:8px 12px;border-radius:6px;cursor:pointer}
header button:hover{background:var(--accent-hi)}
.wrap{flex:1;display:flex;overflow:hidden}
.editor{flex:1;position:relative;background:#1b1b1b;border-top:1px solid #2a2a2a}
/* Input layer */
textarea{
position:absolute; inset:0; width:100%; height:100%;
background:transparent; color:transparent; caret-color:#fff;
border:0; resize:none; outline:none; padding:18px; font:14px/1.55 "Fira Code",ui-monospace,Consolas,Menlo,monospace;
white-space:pre; overflow:auto; tab-size:2;
}
/* Highlight layer */
pre{
position:absolute; inset:0; margin:0; padding:18px; pointer-events:none;
font:14px/1.55 "Fira Code",ui-monospace,Consolas,Menlo,monospace;
color:var(--fg); white-space:pre-wrap; word-break:normal; overflow:auto;
}
/* Simple tokens */
.tok-kw{color:var(--kw)}
.tok-str{color:var(--str)}
.tok-com{color:var(--com)}
.tok-num{color:var(--num)}
.tok-tag{color:var(--tag)}
.tok-attr{color:var(--attr)}
.status{background:var(--bg2);padding:6px 10px;color:var(--muted);font-size:12px;border-top:1px solid #2a2a2a}
</style>
</head>
<body>
<header>
<select id="lang">
<option value="javascript">JavaScript</option>
<option value="html">HTML</option>
<option value="css">CSS</option>
<option value="python">Python</option>
<option value="xml">XML</option>
<option value="plaintext">Plain Text</option>
</select>
<input id="filename" type="text" placeholder="filename" style="min-width:220px" />
<button id="importBtn">Import</button>
<button id="download">Export</button>
<span style="flex-grow:1"></span>
<input id="search" type="text" placeholder="Search…" />
<input id="replace" type="text" placeholder="Replace with…" />
<button id="replaceSel">Replace Selection</button>
<button id="replaceAll">Replace All</button>
</header>
<div class="wrap">
<div class="editor">
<textarea id="ta" spellcheck="false">// Welcome! Type here.
// Switch language with the dropdown.
// Use Import to open a file, or Export to save.
function hello(name){
const n = 42;
console.log("Hello, " + name + "!");
}
hello("World");</textarea>
<pre id="hl"></pre>
</div>
</div>
<div class="status" id="status">Ready.</div>
<input type="file" id="fileInput" style="display:none;" />
<script>
/* ---------- Tiny, offline highlighter (no external libs) ---------- */
/* Escaping */
const esc = s => s.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">");
/* Regex-based tokenizers (fast + small, not full parsers) */
function highlightJS(src){
let s = esc(src);
s = s
.replace(/(\/\*[\s\S]*?\*\/|\/\/.*?$)/gm,'<span class="tok-com">$1</span>')
.replace(/(["'`])(?:\\.|(?!\1)[\s\S])*?\1/g,'<span class="tok-str">$&</span>')
.replace(/\b(?:function|return|const|let|var|if|else|for|while|class|extends|new|try|catch|finally|throw|switch|case|break|continue|import|from|export|default|await|async|yield|this|super|typeof|in|instanceof|delete|void)\b/g,'<span class="tok-kw">$&</span>')
.replace(/\b\d(?:_?\d)*(\.\d(?:_?\d)*)?(?:[eE][+-]?\d+)?\b/g,'<span class="tok-num">$&</span>');
return s;
}
function highlightCSS(src){
let s = esc(src);
s = s
.replace(/\/\*[\s\S]*?\*\//g,'<span class="tok-com">$&</span>')
.replace(/(["'])(?:\\.|(?!\1).)*\1/g,'<span class="tok-str">$&</span>')
.replace(/([a-z-]+)\s*:/gi,'<span class="tok-attr">$1</span>:')
.replace(/\b\d+(?:\.\d+)?(px|em|rem|%|vh|vw)?\b/g,'<span class="tok-num">$&</span>');
return s;
}
function highlightHTML(src){
let s = esc(src);
s = s
.replace(/(<!--[\s\S]*?-->)/g,'<span class="tok-com">$1</span>')
.replace(/(<\/?\s*)([a-zA-Z][\w:-]*)([^&]*?>)/g,(m,p1,tag,p3)=>`${p1}<span class="tok-tag">${tag}</span>${p3}`)
.replace(/([a-zA-Z:-]+)(=)("[^"]*"|'[^']*')/g,'<span class="tok-attr">$1</span>$2<span class="tok-str">$3</span>');
return s;
}
function highlightXML(src){
// XML ~= HTML without void tag quirks
return highlightHTML(src);
}
function highlightPY(src){
let s = esc(src);
s = s
.replace(/(#.*?$)/gm,'<span class="tok-com">$1</span>')
.replace(/("""[\s\S]*?"""|'''[\s\S]*?'''|"(?:\\.|[^"\n])*"|'(?:\\.|[^'\n])*')/g,'<span class="tok-str">$1</span>')
.replace(/\b(?:def|return|class|import|from|as|if|elif|else|for|while|try|except|finally|raise|with|lambda|pass|break|continue|yield|global|nonlocal|assert|in|is|not|and|or|True|False|None)\b/g,'<span class="tok-kw">$&</span>')
.replace(/\b\d+(?:\.\d+)?\b/g,'<span class="tok-num">$&</span>');
return s;
}
const highlighters = {
javascript: highlightJS,
html: highlightHTML,
css: highlightCSS,
python: highlightPY,
xml: highlightXML,
// "plaintext" is intentionally omitted to use the fallback
};
/* ---------- Editor wiring (textarea + overlay) ---------- */
const ta = document.getElementById('ta');
const pre = document.getElementById('hl');
const langSel = document.getElementById('lang');
const status = document.getElementById('status');
const filename = document.getElementById('filename');
function extFor(lang){
return {javascript:'.js', html:'.html', css:'.css', python:'.py', xml:'.xml', plaintext:'.txt'}[lang] || '.txt';
}
function ensureFilenameExt(){
const lang = langSel.value;
// If in plaintext mode, don't force an extension.
if (lang === 'plaintext') {
if (!filename.value.trim()) filename.value = 'text.txt';
return;
}
let name = filename.value.trim();
const want = extFor(lang);
if(!name){ filename.value = 'code' + want; return; }
// Check if it already has the correct extension
if (name.toLowerCase().endsWith(want)) return;
// Replace other known extensions or append the new one
const knownExtsRegex = /\.(js|html|css|py|xml|txt)$/i;
if (knownExtsRegex.test(name)) {
filename.value = name.replace(knownExtsRegex, want);
} else {
filename.value = name + want;
}
}
function render(){
const lang = langSel.value;
const src = ta.value;
const fn = highlighters[lang] || (s=>esc(s));
pre.innerHTML = fn(src) + (src.endsWith('\n') ? '' : '\n'); // keep last line height
const langDisplay = lang === 'plaintext' ? 'Plain Text' : lang.toUpperCase();
status.textContent = `Language: ${langDisplay} — ${src.length} chars`;
}
function syncScroll(){
pre.scrollTop = ta.scrollTop;
pre.scrollLeft = ta.scrollLeft;
}
function updateSpellcheckState() {
const isPlainText = langSel.value === 'plaintext';
ta.spellcheck = isPlainText;
}
ta.addEventListener('input', render);
ta.addEventListener('scroll', syncScroll);
langSel.addEventListener('change', ()=>{
ensureFilenameExt();
render();
updateSpellcheckState();
});
filename.addEventListener('blur', ensureFilenameExt); // Also check when user leaves the input
window.addEventListener('resize', syncScroll);
// Initial state
render();
ensureFilenameExt();
updateSpellcheckState();
/* ---------- Search / Replace ---------- */
const q = document.getElementById('search');
const r = document.getElementById('replace');
document.getElementById('replaceSel').addEventListener('click', ()=>{
const start = ta.selectionStart, end = ta.selectionEnd;
const val = ta.value;
ta.value = val.slice(0,start) + (r.value ?? '') + val.slice(end);
ta.selectionStart = ta.selectionEnd = start + (r.value ?? '').length;
ta.focus();
render();
});
document.getElementById('replaceAll').addEventListener('click', ()=>{
if(!q.value) return;
const safe = q.value.replace(/[.*+?^${}()|[\]\\]/g,'\\$&');
const re = new RegExp(safe,'g');
ta.value = ta.value.replace(re, r.value ?? '');
render();
});
/* ---------- Import / Export ---------- */
const importBtn = document.getElementById('importBtn');
const fileInput = document.getElementById('fileInput');
importBtn.addEventListener('click', () => {
fileInput.click(); // Trigger the hidden file input
});
fileInput.addEventListener('change', (event) => {
const file = event.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = (e) => {
// Set the textarea content
ta.value = e.target.result;
// Auto-detect language from file extension
const ext = file.name.split('.').pop().toLowerCase();
const langMap = {
js: 'javascript', html: 'html', htm: 'html', css: 'css',
py: 'python', xml: 'xml', txt: 'plaintext'
};
langSel.value = langMap[ext] || 'plaintext'; // Default to plaintext
// Update filename input
filename.value = file.name;
// Re-render the editor with new content and language
render();
syncScroll();
updateSpellcheckState(); // Update spellcheck based on new language
};
reader.onerror = () => {
status.textContent = "Error reading file.";
}
reader.readAsText(file);
// Reset file input to allow opening the same file again
fileInput.value = '';
});
document.getElementById('download').addEventListener('click', ()=>{
ensureFilenameExt();
const name = filename.value.trim() || ('code' + extFor(langSel.value));
const blob = new Blob([ta.value], {type: 'text/plain;charset=utf-8'});
const a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = name;
document.body.appendChild(a);
a.click();
setTimeout(()=>{ URL.revokeObjectURL(a.href); a.remove(); }, 0);
});
</script>
</body>
</html>