offline-tex-editor 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- offline_tex_editor/__init__.py +2 -0
- offline_tex_editor/__main__.py +3 -0
- offline_tex_editor/gitapi.py +250 -0
- offline_tex_editor/index.html +132 -0
- offline_tex_editor/latexlog.py +205 -0
- offline_tex_editor/project.py +403 -0
- offline_tex_editor/server.py +923 -0
- offline_tex_editor/static/app.css +231 -0
- offline_tex_editor/static/app.js +72 -0
- offline_tex_editor/static/compile.js +83 -0
- offline_tex_editor/static/complete.js +159 -0
- offline_tex_editor/static/diffview.js +72 -0
- offline_tex_editor/static/editor.js +230 -0
- offline_tex_editor/static/files.js +181 -0
- offline_tex_editor/static/git.js +120 -0
- offline_tex_editor/static/package.json +5 -0
- offline_tex_editor/static/panels.js +83 -0
- offline_tex_editor/static/pdfview.js +254 -0
- offline_tex_editor/static/textindex.js +45 -0
- offline_tex_editor/static/tools.js +72 -0
- offline_tex_editor/static/util.js +57 -0
- offline_tex_editor/vendor/README.md +29 -0
- offline_tex_editor/vendor/codemirror/LICENSE +21 -0
- offline_tex_editor/vendor/codemirror/addon/dialog/dialog.min.css +1 -0
- offline_tex_editor/vendor/codemirror/addon/dialog/dialog.min.js +1 -0
- offline_tex_editor/vendor/codemirror/addon/edit/matchbrackets.min.js +1 -0
- offline_tex_editor/vendor/codemirror/addon/search/jump-to-line.min.js +1 -0
- offline_tex_editor/vendor/codemirror/addon/search/search.min.js +1 -0
- offline_tex_editor/vendor/codemirror/addon/search/searchcursor.min.js +1 -0
- offline_tex_editor/vendor/codemirror/addon/selection/active-line.min.js +1 -0
- offline_tex_editor/vendor/codemirror/codemirror.min.css +1 -0
- offline_tex_editor/vendor/codemirror/codemirror.min.js +1 -0
- offline_tex_editor/vendor/codemirror/mode/markdown/markdown.min.js +1 -0
- offline_tex_editor/vendor/codemirror/mode/python/python.min.js +1 -0
- offline_tex_editor/vendor/codemirror/mode/stex/stex.min.js +1 -0
- offline_tex_editor/vendor/pdfjs/LICENSE +177 -0
- offline_tex_editor/vendor/pdfjs/pdf.min.mjs +21 -0
- offline_tex_editor/vendor/pdfjs/pdf.worker.min.mjs +21 -0
- offline_tex_editor-0.2.0.dist-info/METADATA +193 -0
- offline_tex_editor-0.2.0.dist-info/RECORD +44 -0
- offline_tex_editor-0.2.0.dist-info/WHEEL +5 -0
- offline_tex_editor-0.2.0.dist-info/entry_points.txt +2 -0
- offline_tex_editor-0.2.0.dist-info/licenses/LICENSE +21 -0
- offline_tex_editor-0.2.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
// The source editor: CodeMirror, open documents and their tabs, saving, error and conflict marks, spell check.
|
|
2
|
+
import { $, el, app, state, store, pkey, api, post, setStatus, baseName, debounce } from './util.js';
|
|
3
|
+
|
|
4
|
+
const TEX = /\.(tex|sty|cls|bib|bst|tikz|bbx|cbx|lbx|dtx|ins|ltx|cfg|def|clo)$/;
|
|
5
|
+
const modeFor = p => p.endsWith('.py') ? 'python' : p.endsWith('.md') ? 'markdown' : TEX.test(p) ? 'stex' : 'text/plain';
|
|
6
|
+
|
|
7
|
+
// contenteditable input is what lets the browser spell-check; spell check itself is a separate, switchable option.
|
|
8
|
+
export const cm = CodeMirror.fromTextArea($('ed'), {
|
|
9
|
+
lineNumbers: true, lineWrapping: true, matchBrackets: true, styleActiveLine: true, indentUnit: 2,
|
|
10
|
+
inputStyle: 'contenteditable', spellcheck: false,
|
|
11
|
+
extraKeys: {
|
|
12
|
+
'Ctrl-S': () => save(), 'Cmd-S': () => save(),
|
|
13
|
+
'Ctrl-Enter': () => app.compile(), 'Cmd-Enter': () => app.compile(),
|
|
14
|
+
'Ctrl-J': () => app.syncToPdf(), 'Cmd-J': () => app.syncToPdf(),
|
|
15
|
+
'Ctrl-/': c => toggleComment(c), 'Cmd-/': c => toggleComment(c),
|
|
16
|
+
'Ctrl-Space': () => app.complete(true),
|
|
17
|
+
'Shift-Ctrl-F': () => app.showSearch(), 'Shift-Cmd-F': () => app.showSearch(),
|
|
18
|
+
},
|
|
19
|
+
});
|
|
20
|
+
app.cm = cm;
|
|
21
|
+
// Grammar-checking browser extensions attach to contenteditable areas and rewrite their DOM, which corrupts a
|
|
22
|
+
// CodeMirror document. These attributes are their documented opt-out.
|
|
23
|
+
for (const [k, v] of [['data-gramm', 'false'], ['data-gramm_editor', 'false'], ['data-enable-grammarly', 'false'], ['data-lt-active', 'false']])
|
|
24
|
+
cm.getInputField().setAttribute(k, v);
|
|
25
|
+
|
|
26
|
+
function toggleComment(c) {
|
|
27
|
+
const from = c.getCursor('from').line, to = c.getCursor('to').line;
|
|
28
|
+
const lines = []; for (let l = from; l <= to; l++) lines.push(c.getLine(l));
|
|
29
|
+
const all = lines.every(s => /^\s*%/.test(s) || !s.trim());
|
|
30
|
+
c.operation(() => { for (let l = from; l <= to; l++) {
|
|
31
|
+
const s = c.getLine(l);
|
|
32
|
+
if (all) { const m = s.match(/^(\s*)% ?/); if (m) c.replaceRange(m[1], { line: l, ch: 0 }, { line: l, ch: m[0].length }); }
|
|
33
|
+
else if (s.trim()) c.replaceRange('% ', { line: l, ch: 0 });
|
|
34
|
+
} });
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// ---------- spell check ----------
|
|
38
|
+
// LaTeX commands, math and brackets are not words: mark them so the browser does not underline them.
|
|
39
|
+
const NO_SPELL = /\bcm-(tag|builtin|keyword|atom|number|bracket|meta|variable-2|variable-3|string-2|qualifier|def)\b/;
|
|
40
|
+
cm.on('renderLine', (_cm, _line, elt) => {
|
|
41
|
+
for (const s of elt.querySelectorAll('span[class*="cm-"]')) if (NO_SPELL.test(s.className)) s.spellcheck = false;
|
|
42
|
+
});
|
|
43
|
+
export function setSpellcheck(on) { cm.setOption('spellcheck', !!on); store.set('spellcheck', !!on); }
|
|
44
|
+
setSpellcheck(store.get('spellcheck', false));
|
|
45
|
+
|
|
46
|
+
// ---------- documents and tabs ----------
|
|
47
|
+
const docs = new Map(); // path -> { doc, mtime, gen, encoding }
|
|
48
|
+
let tabs = [];
|
|
49
|
+
|
|
50
|
+
export const isDirty = p => { const d = docs.get(p); return !!d && !d.doc.isClean(d.gen); };
|
|
51
|
+
const anyDirty = () => [...docs.keys()].some(isDirty);
|
|
52
|
+
const saveTabs = () => store.set(pkey('tabs'), tabs);
|
|
53
|
+
|
|
54
|
+
export function refreshDirty() {
|
|
55
|
+
document.querySelectorAll('#files .f[data-path]').forEach(e => e.classList.toggle('mod', isDirty(e.dataset.path)));
|
|
56
|
+
document.querySelectorAll('#tabs .tab').forEach(e => e.classList.toggle('mod', isDirty(e.dataset.path)));
|
|
57
|
+
document.title = (anyDirty() ? '● ' : '') + 'Offline TeX Editor';
|
|
58
|
+
}
|
|
59
|
+
cm.on('change', debounce(refreshDirty, 120));
|
|
60
|
+
|
|
61
|
+
function renderTabs() {
|
|
62
|
+
$('tabs').replaceChildren(...tabs.map(p => el('div', {
|
|
63
|
+
className: 'tab' + (p === state.current ? ' on' : '') + (isDirty(p) ? ' mod' : ''), title: p, role: 'tab',
|
|
64
|
+
dataset: { path: p }, onclick: () => openFile(p), onauxclick: e => { if (e.button === 1) closeTab(p); },
|
|
65
|
+
}, baseName(p), el('button', { className: 'x', title: 'Close', onclick: e => { e.stopPropagation(); closeTab(p); } },
|
|
66
|
+
el('span', {}, '×')))));
|
|
67
|
+
$('tabs').querySelector('.on')?.scrollIntoView({ block: 'nearest', inline: 'nearest' });
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
async function loadDoc(path) {
|
|
71
|
+
const r = await api('/api/file?path=' + encodeURIComponent(path));
|
|
72
|
+
if (!r.ok) { setStatus(`cannot open ${path}: ${r.error || r.status}`, 'err'); return null; }
|
|
73
|
+
const doc = CodeMirror.Doc(r.content, modeFor(path), 0, r.eol === '\r\n' ? '\r\n' : null);
|
|
74
|
+
const d = { doc, mtime: r.mtime, gen: doc.changeGeneration(), encoding: r.encoding || 'utf-8' };
|
|
75
|
+
docs.set(path, d);
|
|
76
|
+
return d;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// Open a file, optionally at a line; opts.ch/opts.len select a range on that line (a search match).
|
|
80
|
+
export async function openFile(path, line, opts = {}) {
|
|
81
|
+
if (!docs.has(path)) { if (!(await loadDoc(path))) return false; }
|
|
82
|
+
else checkExternalChange(path);
|
|
83
|
+
app.closePreview?.();
|
|
84
|
+
if (state.current !== path) { cm.swapDoc(docs.get(path).doc); state.current = path; store.set(pkey('lastFile'), path); }
|
|
85
|
+
if (!tabs.includes(path)) { tabs.push(path); saveTabs(); }
|
|
86
|
+
renderTabs(); hideBanner(); markErrors(); markConflicts(); refreshDirty();
|
|
87
|
+
document.querySelectorAll('#files .f').forEach(e => e.classList.toggle('active', e.dataset.path === path));
|
|
88
|
+
if (line) {
|
|
89
|
+
const l = Math.min(cm.lineCount() - 1, Math.max(0, line - 1));
|
|
90
|
+
if (opts.ch !== undefined) cm.setSelection({ line: l, ch: opts.ch }, { line: l, ch: opts.ch + (opts.len || 0) });
|
|
91
|
+
else cm.setCursor({ line: l, ch: 0 });
|
|
92
|
+
cm.scrollIntoView({ line: l, ch: 0 }, cm.getScrollInfo().clientHeight / 2);
|
|
93
|
+
if (opts.flash) { const h = cm.addLineClass(l, 'background', 'line-hit'); setTimeout(() => cm.removeLineClass(h, 'background', 'line-hit'), 1600); }
|
|
94
|
+
}
|
|
95
|
+
app.onFileOpened?.(path);
|
|
96
|
+
cm.focus();
|
|
97
|
+
return true;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export function closeTab(path, force = false) {
|
|
101
|
+
if (isDirty(path) && !force) {
|
|
102
|
+
if (path !== state.current) openFile(path);
|
|
103
|
+
showBanner(`${path} has unsaved changes.`, 'Save and close', async () => { if (await save(path, { compile: false })) closeTab(path, true); },
|
|
104
|
+
'Discard changes', () => closeTab(path, true), 'Cancel', hideBanner);
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
const i = tabs.indexOf(path);
|
|
108
|
+
tabs = tabs.filter(t => t !== path); saveTabs(); docs.delete(path); hideBanner();
|
|
109
|
+
if (state.current === path) {
|
|
110
|
+
state.current = null;
|
|
111
|
+
const next = tabs[i] || tabs[i - 1] || app.project?.main;
|
|
112
|
+
if (next) openFile(next); else renderTabs();
|
|
113
|
+
} else renderTabs();
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export async function restoreTabs(main) {
|
|
117
|
+
tabs = store.get(pkey('tabs'), []).filter(p => app.project.files.includes(p));
|
|
118
|
+
const last = store.get(pkey('lastFile'), null);
|
|
119
|
+
await openFile(app.project.files.includes(last) ? last : main);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// After a rename or move on disk: keep open documents and tabs (also those inside a renamed folder).
|
|
123
|
+
export function renameDoc(from, to) {
|
|
124
|
+
const map = p => p === from ? to : p.startsWith(from + '/') ? to + p.slice(from.length) : p;
|
|
125
|
+
for (const [p, d] of [...docs]) { const q = map(p); if (q !== p) { docs.delete(p); docs.set(q, d); } }
|
|
126
|
+
tabs = tabs.map(map); saveTabs();
|
|
127
|
+
if (state.current) state.current = map(state.current);
|
|
128
|
+
renderTabs();
|
|
129
|
+
}
|
|
130
|
+
// After a delete: close the documents without asking (the file is in the trash).
|
|
131
|
+
export function dropDoc(path) {
|
|
132
|
+
for (const p of [...docs.keys()]) if (p === path || p.startsWith(path + '/')) { docs.delete(p); tabs = tabs.filter(t => t !== p); }
|
|
133
|
+
saveTabs();
|
|
134
|
+
if (state.current === path || state.current?.startsWith(path + '/')) { state.current = null; openFile(tabs[0] || app.project.main); }
|
|
135
|
+
else renderTabs();
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// ---------- saving ----------
|
|
139
|
+
export async function save(path = state.current, { force = false, compile = true } = {}) {
|
|
140
|
+
if (!path || !docs.has(path)) return true;
|
|
141
|
+
const d = docs.get(path);
|
|
142
|
+
if (!isDirty(path) && !force) { if (compile && $('auto').checked) app.compile(); return true; }
|
|
143
|
+
const r = await post('/api/file', { path, content: d.doc.getValue(), mtime: d.mtime, force, encoding: d.encoding });
|
|
144
|
+
if (r.status === 409) {
|
|
145
|
+
if (path !== state.current) await openFile(path);
|
|
146
|
+
showBanner(`${path} changed on disk since you opened it.`, 'Overwrite with mine', () => save(path, { force: true }),
|
|
147
|
+
'Load disk version', () => reloadFromDisk(path));
|
|
148
|
+
return false;
|
|
149
|
+
}
|
|
150
|
+
if (!r.ok) { setStatus(`could not save ${path}: ${r.error || r.status}`, 'err'); return false; }
|
|
151
|
+
d.mtime = r.mtime; d.gen = d.doc.changeGeneration(); refreshDirty(); hideBanner();
|
|
152
|
+
setStatus('saved ' + path, 'ok');
|
|
153
|
+
app.onSaved?.(path);
|
|
154
|
+
if (compile && $('auto').checked) app.compile();
|
|
155
|
+
return true;
|
|
156
|
+
}
|
|
157
|
+
export async function saveAll() {
|
|
158
|
+
for (const p of [...docs.keys()]) if (isDirty(p) && !(await save(p, { compile: false }))) return false;
|
|
159
|
+
return true;
|
|
160
|
+
}
|
|
161
|
+
export async function reloadFromDisk(path) {
|
|
162
|
+
const d = docs.get(path); if (!d) return;
|
|
163
|
+
const r = await api('/api/file?path=' + encodeURIComponent(path));
|
|
164
|
+
if (!r.ok) return;
|
|
165
|
+
const cur = path === state.current ? cm.getCursor() : null, top = path === state.current ? cm.getScrollInfo().top : null;
|
|
166
|
+
d.doc.setValue(r.content); d.mtime = r.mtime; d.encoding = r.encoding; d.gen = d.doc.changeGeneration();
|
|
167
|
+
if (cur) { cm.setCursor(cur); cm.scrollTo(null, top); }
|
|
168
|
+
hideBanner(); refreshDirty(); markConflicts();
|
|
169
|
+
}
|
|
170
|
+
// Open documents that are not modified pick up changes made on disk (after a git pull or a replace-all).
|
|
171
|
+
export async function reloadClean() { for (const p of [...docs.keys()]) if (!isDirty(p)) await reloadFromDisk(p); }
|
|
172
|
+
|
|
173
|
+
// Another editor (or git) changed the file: reload it when we have no edits, else ask.
|
|
174
|
+
export async function checkExternalChange(path = state.current) {
|
|
175
|
+
const d = path && docs.get(path); if (!d) return;
|
|
176
|
+
const r = await api('/api/mtime?path=' + encodeURIComponent(path));
|
|
177
|
+
if (r.status === 404 || (r.ok && r.mtime === null)) return;
|
|
178
|
+
if (r.ok && r.mtime && Math.abs(r.mtime - d.mtime) > 1e-6) {
|
|
179
|
+
if (!isDirty(path)) reloadFromDisk(path);
|
|
180
|
+
else if (path === state.current && !$('banner').classList.contains('show'))
|
|
181
|
+
showBanner(`${path} was changed on disk (another editor, git, or a replace).`, 'Load disk version', () => reloadFromDisk(path),
|
|
182
|
+
'Keep mine', () => { d.mtime = r.mtime; hideBanner(); });
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// ---------- banner ----------
|
|
187
|
+
export function showBanner(text, a, fa, b, fb, c, fc) {
|
|
188
|
+
$('bannerText').textContent = text;
|
|
189
|
+
[['bannerA', a, fa], ['bannerB', b, fb], ['bannerC', c, fc]].forEach(([id, label, fn]) => {
|
|
190
|
+
$(id).hidden = !label; $(id).textContent = label || ''; $(id).onclick = fn || null;
|
|
191
|
+
});
|
|
192
|
+
$('banner').classList.add('show');
|
|
193
|
+
}
|
|
194
|
+
export function hideBanner() { $('banner').classList.remove('show'); }
|
|
195
|
+
|
|
196
|
+
// ---------- error and conflict marks ----------
|
|
197
|
+
let errorMarks = [];
|
|
198
|
+
export function markErrors() {
|
|
199
|
+
errorMarks.forEach(h => cm.removeLineClass(h, 'background', 'line-error')); errorMarks = [];
|
|
200
|
+
if (!state.lastResult || !state.current) return;
|
|
201
|
+
(state.lastResult.errors || []).filter(e => e.file === state.current && e.line).forEach(e => {
|
|
202
|
+
const h = cm.getLineHandle(e.line - 1); if (h) { cm.addLineClass(h, 'background', 'line-error'); errorMarks.push(h); }
|
|
203
|
+
});
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
let conflictMarks = [];
|
|
207
|
+
// Highlight git conflict blocks: <<<<<<< ours ======= theirs >>>>>>>
|
|
208
|
+
export function markConflicts() {
|
|
209
|
+
conflictMarks.forEach(([h, cls]) => cm.removeLineClass(h, 'background', cls)); conflictMarks = [];
|
|
210
|
+
if (!cm.getValue().includes('<<<<<<<')) return;
|
|
211
|
+
let mode = null;
|
|
212
|
+
const add = (h, cls) => { cm.addLineClass(h, 'background', cls); conflictMarks.push([h, cls]); };
|
|
213
|
+
cm.eachLine(h => {
|
|
214
|
+
const t = h.text;
|
|
215
|
+
if (t.startsWith('<<<<<<<')) { add(h, 'cf-marker'); mode = 'ours'; }
|
|
216
|
+
else if (mode && t.startsWith('|||||||')) { add(h, 'cf-marker'); mode = 'base'; }
|
|
217
|
+
else if (mode && t.startsWith('=======')) { add(h, 'cf-marker'); mode = 'theirs'; }
|
|
218
|
+
else if (mode && t.startsWith('>>>>>>>')) { add(h, 'cf-marker'); mode = null; }
|
|
219
|
+
else if (mode === 'ours') add(h, 'cf-ours');
|
|
220
|
+
else if (mode === 'theirs') add(h, 'cf-theirs');
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
cm.on('change', debounce(markConflicts, 300));
|
|
224
|
+
cm.on('cursorActivity', debounce(() => app.onCursor?.(), 150));
|
|
225
|
+
|
|
226
|
+
window.addEventListener('beforeunload', e => { if (anyDirty()) { e.preventDefault(); e.returnValue = ''; } });
|
|
227
|
+
|
|
228
|
+
Object.assign(app, { openFile, closeTab, restoreTabs, renameDoc, dropDoc, save, saveAll, reloadFromDisk, reloadClean,
|
|
229
|
+
checkExternalChange, showBanner, hideBanner, markErrors, markConflicts, refreshDirty, isDirty,
|
|
230
|
+
setSpellcheck });
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
// The file list: tree, filter, new/rename/delete, upload (button or drag and drop), image and PDF previews.
|
|
2
|
+
import { $, el, app, state, project, store, pkey, api, post, setStatus, dirOf, baseName } from './util.js';
|
|
3
|
+
|
|
4
|
+
const IMAGE = /\.(png|jpe?g|gif|svg|webp|bmp)$/i;
|
|
5
|
+
|
|
6
|
+
export async function loadFiles() {
|
|
7
|
+
const r = await api('/api/files');
|
|
8
|
+
if (!r.ok) return setStatus('cannot list files: ' + (r.error || r.status), 'err');
|
|
9
|
+
Object.assign(project, { root: r.root, main: r.main, files: r.files || [], assets: r.assets || [], dirs: r.dirs || [] });
|
|
10
|
+
$('mainDoc').textContent = project.main;
|
|
11
|
+
renderFiles();
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function tree() {
|
|
15
|
+
const root = { dirs: new Map(), files: [] };
|
|
16
|
+
const node = d => {
|
|
17
|
+
let n = root;
|
|
18
|
+
if (d) for (const part of d.split('/')) { if (!n.dirs.has(part)) n.dirs.set(part, { dirs: new Map(), files: [] }); n = n.dirs.get(part); }
|
|
19
|
+
return n;
|
|
20
|
+
};
|
|
21
|
+
(project.dirs || []).forEach(d => node(d));
|
|
22
|
+
project.files.forEach(f => node(dirOf(f)).files.push({ path: f, asset: false }));
|
|
23
|
+
project.assets.forEach(f => node(dirOf(f)).files.push({ path: f, asset: true }));
|
|
24
|
+
return root;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function renderFiles() {
|
|
28
|
+
const q = $('filter').value.toLowerCase().trim(), box = $('files');
|
|
29
|
+
const collapsed = new Set(store.get(pkey('collapsed'), []));
|
|
30
|
+
const rows = [];
|
|
31
|
+
const fileRow = (f, depth) => {
|
|
32
|
+
const row = el('div', { className: 'f' + (f.asset ? ' asset' : '') + (f.path === state.current ? ' active' : '') + (app.isDirty?.(f.path) ? ' mod' : ''),
|
|
33
|
+
title: f.path, dataset: { path: f.path }, onclick: () => f.asset ? preview(f.path) : app.openFile(f.path) },
|
|
34
|
+
el('span', { className: 'nm' }, baseName(f.path)),
|
|
35
|
+
f.path === project.main ? el('span', { className: 'badge', title: 'Main document' }, 'main') : null,
|
|
36
|
+
actions(f.path, false));
|
|
37
|
+
row.style.paddingLeft = (18 + depth * 12) + 'px';
|
|
38
|
+
rows.push(row);
|
|
39
|
+
};
|
|
40
|
+
const walk = (n, path, depth) => {
|
|
41
|
+
const files = n.files.filter(f => !q || f.path.toLowerCase().includes(q))
|
|
42
|
+
.sort((a, b) => (a.path === project.main ? -1 : b.path === project.main ? 1 : 0) || a.asset - b.asset || a.path.localeCompare(b.path));
|
|
43
|
+
files.forEach(f => fileRow(f, depth));
|
|
44
|
+
for (const name of [...n.dirs.keys()].sort((a, b) => a.localeCompare(b))) {
|
|
45
|
+
const d = path ? `${path}/${name}` : name, child = n.dirs.get(name);
|
|
46
|
+
if (q && !hasMatch(child, q)) continue;
|
|
47
|
+
const open = q || !collapsed.has(d);
|
|
48
|
+
const head = el('div', { className: 'dir toggle', title: d, dataset: { dir: d }, onclick: () => {
|
|
49
|
+
const s = new Set(store.get(pkey('collapsed'), [])); s.has(d) ? s.delete(d) : s.add(d); store.set(pkey('collapsed'), [...s]); renderFiles();
|
|
50
|
+
} }, el('span', { className: 'nm' }, (open ? '▾ ' : '▸ ') + name), el('span', { className: 'spacer' }), actions(d, true));
|
|
51
|
+
head.style.paddingLeft = (8 + depth * 12) + 'px';
|
|
52
|
+
rows.push(head);
|
|
53
|
+
if (open) walk(child, d, depth + 1);
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
walk(tree(), '', 0);
|
|
57
|
+
box.replaceChildren(...rows);
|
|
58
|
+
}
|
|
59
|
+
const hasMatch = (n, q) => n.files.some(f => f.path.toLowerCase().includes(q)) || [...n.dirs.values()].some(c => hasMatch(c, q));
|
|
60
|
+
$('filter').oninput = renderFiles;
|
|
61
|
+
|
|
62
|
+
function actions(path, isDir) {
|
|
63
|
+
const stop = fn => e => { e.stopPropagation(); fn(e); };
|
|
64
|
+
return el('span', { className: 'acts' },
|
|
65
|
+
isDir ? el('button', { title: 'New file here', onclick: stop(() => openForm('file', path + '/')) }, '+') : null,
|
|
66
|
+
el('button', { title: 'Rename or move', onclick: stop(() => openForm('rename', path)) }, '✎'),
|
|
67
|
+
path === project.main ? null : el('button', { title: 'Delete (moves it to build/.editor-trash)', onclick: stop(e => confirmDelete(e.target.closest('.f, .dir'), path)) }, '×'));
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function confirmDelete(row, path) {
|
|
71
|
+
const acts = row.querySelector('.acts');
|
|
72
|
+
row.classList.add('confirm');
|
|
73
|
+
acts.replaceChildren(el('span', { className: 'muted' }, 'Delete? '),
|
|
74
|
+
el('button', { className: 'danger', onclick: async e => { e.stopPropagation(); await remove(path); } }, 'Yes'),
|
|
75
|
+
el('button', { onclick: e => { e.stopPropagation(); renderFiles(); } }, 'No'));
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
async function remove(path) {
|
|
79
|
+
const r = await post('/api/fs/delete', { path });
|
|
80
|
+
if (!r.ok) { renderFiles(); return setStatus(`could not delete ${path}: ${r.error}`, 'err'); }
|
|
81
|
+
app.dropDoc(path); await loadFiles(); app.filesChanged?.();
|
|
82
|
+
setStatus(`moved ${path} to ${r.trash}`, 'ok');
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// ---------- new / rename form ----------
|
|
86
|
+
let form = null; // { kind: 'file' | 'folder' | 'rename', from }
|
|
87
|
+
function openForm(kind, value) {
|
|
88
|
+
form = { kind, from: kind === 'rename' ? value : null };
|
|
89
|
+
$('fsForm').hidden = false;
|
|
90
|
+
const input = $('fsInput');
|
|
91
|
+
input.value = value || (state.current && dirOf(state.current) ? dirOf(state.current) + '/' : '');
|
|
92
|
+
$('fsHint').textContent = kind === 'rename' ? 'New path (Enter to rename, Esc to cancel)'
|
|
93
|
+
: kind === 'folder' ? 'Folder path (Enter to create, Esc to cancel)' : 'File path, e.g. chapters/intro.tex (Enter to create)';
|
|
94
|
+
input.focus();
|
|
95
|
+
if (kind === 'rename') { const b = value.lastIndexOf('/') + 1, dot = value.lastIndexOf('.'); input.setSelectionRange(b, dot > b ? dot : value.length); }
|
|
96
|
+
else input.setSelectionRange(input.value.length, input.value.length);
|
|
97
|
+
}
|
|
98
|
+
function closeForm() { form = null; $('fsForm').hidden = true; }
|
|
99
|
+
$('fsInput').addEventListener('keydown', async e => {
|
|
100
|
+
if (e.key === 'Escape') return closeForm();
|
|
101
|
+
if (e.key !== 'Enter' || !form) return;
|
|
102
|
+
e.preventDefault();
|
|
103
|
+
const path = $('fsInput').value.trim().replace(/^\/+|\/+$/g, '');
|
|
104
|
+
if (!path) return;
|
|
105
|
+
if (form.kind === 'rename') {
|
|
106
|
+
if (path === form.from) return closeForm();
|
|
107
|
+
if (!(await app.saveAll())) return;
|
|
108
|
+
const r = await post('/api/fs/rename', { from: form.from, to: path });
|
|
109
|
+
if (!r.ok) return ($('fsHint').textContent = r.error);
|
|
110
|
+
app.renameDoc(form.from, r.path);
|
|
111
|
+
if (r.main !== project.main) { project.main = r.main; app.refreshSettings?.(); }
|
|
112
|
+
closeForm(); await loadFiles(); app.filesChanged?.();
|
|
113
|
+
setStatus(`renamed to ${r.path}`, 'ok');
|
|
114
|
+
} else {
|
|
115
|
+
const kind = form.kind;
|
|
116
|
+
const r = await post('/api/fs/new', { path: kind === 'file' && !/\.[A-Za-z0-9]+$/.test(path) ? path + '.tex' : path, kind });
|
|
117
|
+
if (!r.ok) return ($('fsHint').textContent = r.error);
|
|
118
|
+
closeForm(); await loadFiles(); app.filesChanged?.();
|
|
119
|
+
if (kind === 'file') app.openFile(r.path);
|
|
120
|
+
setStatus(`created ${r.path}`, 'ok');
|
|
121
|
+
}
|
|
122
|
+
});
|
|
123
|
+
$('newFileBtn').onclick = () => openForm('file');
|
|
124
|
+
$('newFolderBtn').onclick = () => openForm('folder');
|
|
125
|
+
|
|
126
|
+
// ---------- upload ----------
|
|
127
|
+
const readBase64 = f => new Promise((res, rej) => {
|
|
128
|
+
const r = new FileReader();
|
|
129
|
+
r.onload = () => res(String(r.result).split(',', 2)[1] || '');
|
|
130
|
+
r.onerror = () => rej(r.error);
|
|
131
|
+
r.readAsDataURL(f);
|
|
132
|
+
});
|
|
133
|
+
const ask = text => new Promise(res => app.showBanner(text, 'Replace', () => { app.hideBanner(); res(true); }, 'Skip', () => { app.hideBanner(); res(false); }));
|
|
134
|
+
|
|
135
|
+
async function upload(files, dir) {
|
|
136
|
+
let n = 0;
|
|
137
|
+
for (const f of files) {
|
|
138
|
+
const path = (dir ? dir + '/' : '') + f.name;
|
|
139
|
+
const data = await readBase64(f);
|
|
140
|
+
let r = await post('/api/fs/upload', { path, data });
|
|
141
|
+
if (r.status === 409 && r.exists && await ask(`${path} already exists.`)) r = await post('/api/fs/upload', { path, data, replace: true });
|
|
142
|
+
if (r.ok) n++; else if (r.status !== 409) setStatus(`could not add ${path}: ${r.error}`, 'err');
|
|
143
|
+
}
|
|
144
|
+
if (n) { await loadFiles(); app.filesChanged?.(); setStatus(`added ${n} file${n > 1 ? 's' : ''}${dir ? ' to ' + dir : ''}`, 'ok'); }
|
|
145
|
+
}
|
|
146
|
+
$('uploadBtn').onclick = () => $('uploadInput').click();
|
|
147
|
+
$('uploadInput').onchange = async () => {
|
|
148
|
+
const files = [...$('uploadInput').files]; $('uploadInput').value = '';
|
|
149
|
+
await upload(files, state.current ? dirOf(state.current) : '');
|
|
150
|
+
};
|
|
151
|
+
const hasFiles = e => [...(e.dataTransfer?.types || [])].includes('Files');
|
|
152
|
+
$('files').addEventListener('dragover', e => {
|
|
153
|
+
if (!hasFiles(e)) return;
|
|
154
|
+
e.preventDefault(); $('files').classList.add('drop');
|
|
155
|
+
document.querySelectorAll('#files .dir.drop').forEach(d => d.classList.remove('drop'));
|
|
156
|
+
e.target.closest?.('.dir')?.classList.add('drop');
|
|
157
|
+
});
|
|
158
|
+
$('files').addEventListener('dragleave', e => { if (!$('files').contains(e.relatedTarget)) $('files').classList.remove('drop'); });
|
|
159
|
+
$('files').addEventListener('drop', e => {
|
|
160
|
+
if (!hasFiles(e)) return;
|
|
161
|
+
e.preventDefault(); $('files').classList.remove('drop');
|
|
162
|
+
const t = e.target.closest?.('[data-dir], [data-path]');
|
|
163
|
+
upload([...e.dataTransfer.files], t ? (t.dataset.dir ?? dirOf(t.dataset.path)) : '');
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
// ---------- previews ----------
|
|
167
|
+
export async function preview(path) {
|
|
168
|
+
const body = $('previewBody');
|
|
169
|
+
body.replaceChildren(el('div', { className: 'muted' }, 'Loading…'));
|
|
170
|
+
$('previewTitle').textContent = path; $('preview').hidden = false;
|
|
171
|
+
const url = '/api/raw?path=' + encodeURIComponent(path);
|
|
172
|
+
if (IMAGE.test(path)) body.replaceChildren(el('img', { src: url, alt: path }));
|
|
173
|
+
else if (/\.pdf$/i.test(path)) {
|
|
174
|
+
const canvas = await app.renderPdfPage(url).catch(() => null);
|
|
175
|
+
body.replaceChildren(canvas || el('div', { className: 'muted' }, 'Cannot show this PDF.'));
|
|
176
|
+
} else body.replaceChildren(el('div', { className: 'muted' }, 'No preview for this file type.'));
|
|
177
|
+
}
|
|
178
|
+
export function closePreview() { $('preview').hidden = true; }
|
|
179
|
+
$('previewClose').onclick = closePreview;
|
|
180
|
+
|
|
181
|
+
Object.assign(app, { loadFiles, renderFiles, preview, closePreview });
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
// The Git panel: changes and diffs, stage, commit, push, pull (also when histories diverged), conflicts, history.
|
|
2
|
+
import { $, el, app, api, post } from './util.js';
|
|
3
|
+
|
|
4
|
+
app.git = null;
|
|
5
|
+
export function gitOut(text, cls, ...buttons) {
|
|
6
|
+
$('gitMsgOut').replaceChildren(text || '', ...(buttons.length ? [el('div', { className: 'gitBtns', style: 'margin-top: 4px' }, ...buttons)] : []));
|
|
7
|
+
$('gitMsgOut').className = cls || '';
|
|
8
|
+
}
|
|
9
|
+
// The editor's path for a path relative to the repository top level (null when outside the project).
|
|
10
|
+
const editorPath = p => { const g = app.git; if (!g || !g.prefix) return p; return p.startsWith(g.prefix + '/') ? p.slice(g.prefix.length + 1) : null; };
|
|
11
|
+
|
|
12
|
+
function renderGit(s) {
|
|
13
|
+
if (!s || !s.ok) { gitOut(s && s.error || 'git status failed', 'err'); return; }
|
|
14
|
+
app.git = s;
|
|
15
|
+
if (!s.repo) {
|
|
16
|
+
$('gitBranch').textContent = 'not a git repository'; $('gitSync').textContent = ''; $('gitLists').replaceChildren();
|
|
17
|
+
$('gitBadge').textContent = ''; $('gitState').hidden = true; return;
|
|
18
|
+
}
|
|
19
|
+
$('gitBranch').textContent = '⎇ ' + s.branch;
|
|
20
|
+
$('gitSync').textContent = s.upstream ? `↑${s.ahead} ↓${s.behind}` : (s.remotes.length ? 'not pushed yet' : 'no remote');
|
|
21
|
+
$('gitBadge').textContent = s.files.length ? `(${s.files.length})` : '';
|
|
22
|
+
$('gitPush').textContent = s.ahead ? `Push (${s.ahead})` : 'Push';
|
|
23
|
+
const conflicts = s.files.filter(f => f.conflict), staged = s.files.filter(f => f.staged), changed = s.files.filter(f => f.unstaged);
|
|
24
|
+
|
|
25
|
+
// A rebase or merge in progress: say what to do next.
|
|
26
|
+
$('gitState').hidden = !s.state;
|
|
27
|
+
if (s.state) {
|
|
28
|
+
const what = s.state === 'rebasing' ? 'Rebase' : 'Merge';
|
|
29
|
+
$('gitState').replaceChildren(
|
|
30
|
+
el('div', {}, conflicts.length
|
|
31
|
+
? `${what} in progress: ${conflicts.length} file${conflicts.length > 1 ? 's have' : ' has'} conflicts. Edit them (keep the right side of each <<<<<<< … >>>>>>> block), then mark them resolved.`
|
|
32
|
+
: `${what} in progress: all conflicts are resolved.`),
|
|
33
|
+
el('div', { className: 'gitBtns', style: 'margin-top: 4px' },
|
|
34
|
+
el('button', { className: 'primary', disabled: conflicts.length > 0, onclick: () => gitOp('continue') }, s.state === 'rebasing' ? 'Continue rebase' : 'Finish merge'),
|
|
35
|
+
el('button', { onclick: () => gitOp('abort') }, `Abort ${what.toLowerCase()}`)));
|
|
36
|
+
}
|
|
37
|
+
$('gitCommit').disabled = s.state === 'rebasing';
|
|
38
|
+
|
|
39
|
+
const rows = [];
|
|
40
|
+
const section = (title, items, kind) => {
|
|
41
|
+
const h = el('div', { className: 'gsec' }, `${title} (${items.length})`);
|
|
42
|
+
if (items.length && kind !== 'conflict')
|
|
43
|
+
h.append(el('button', { onclick: () => gitOp(kind === 'staged' ? 'unstage' : 'stage', { paths: items.map(f => f.path) }) }, kind === 'staged' ? 'Unstage all' : 'Stage all'));
|
|
44
|
+
rows.push(h);
|
|
45
|
+
items.forEach(f => {
|
|
46
|
+
const code = kind === 'conflict' ? 'C' : kind === 'staged' ? f.x : (f.untracked ? 'U' : f.y);
|
|
47
|
+
const name = f.path.slice(f.path.lastIndexOf('/') + 1), dir = f.path.includes('/') ? f.path.slice(0, f.path.lastIndexOf('/')) : '';
|
|
48
|
+
const btn = kind === 'conflict'
|
|
49
|
+
? el('button', { title: 'Mark resolved (stage it)', onclick: e => { e.stopPropagation(); gitOp('stage', { paths: [f.path] }); } }, 'Resolved')
|
|
50
|
+
: el('button', { title: kind === 'staged' ? 'Unstage' : 'Stage', onclick: e => { e.stopPropagation(); gitOp(kind === 'staged' ? 'unstage' : 'stage', { paths: [f.path] }); } }, kind === 'staged' ? '−' : '+');
|
|
51
|
+
const open = () => { const p = editorPath(f.path); if (kind === 'conflict' && p) app.openFile(p); else app.showDiff(f.path, kind === 'staged'); };
|
|
52
|
+
rows.push(el('div', { className: 'gf', title: f.path + (f.orig ? ` (from ${f.orig})` : ''), onclick: open },
|
|
53
|
+
el('span', { className: `st ${code}` }, code), el('span', { className: 'nm' }, name + ' ', el('small', {}, dir)), btn));
|
|
54
|
+
});
|
|
55
|
+
};
|
|
56
|
+
if (conflicts.length) section('Conflicts', conflicts, 'conflict');
|
|
57
|
+
section('Staged', staged, 'staged'); section('Changes', changed, 'changed');
|
|
58
|
+
if (!s.files.length) rows.push(el('div', { className: 'gsec' }, 'Working tree clean'));
|
|
59
|
+
$('gitLists').replaceChildren(...rows);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export async function gitRefresh(fetchRemote) {
|
|
63
|
+
renderGit(fetchRemote ? await post('/api/git/fetch') : await api('/api/git/status'));
|
|
64
|
+
if (!$('gitPane').hidden && app.git && app.git.repo) {
|
|
65
|
+
const l = await api('/api/git/log');
|
|
66
|
+
$('gitLog').replaceChildren(...(l.commits || []).map(c => el('div', { className: 'gl', title: `${c.author}, ${c.when}`, onclick: () => app.showCommit(c.hash, c.subject) },
|
|
67
|
+
el('code', {}, c.hash), ' ', el('span', {}, c.subject), ' ', el('small', {}, c.when))));
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
let gitT;
|
|
71
|
+
export const gitSoon = () => { clearTimeout(gitT); gitT = setTimeout(() => gitRefresh(false), 400); };
|
|
72
|
+
|
|
73
|
+
async function gitOp(op, body) {
|
|
74
|
+
const r = await post('/api/git/' + op, body);
|
|
75
|
+
if (!r.ok) { gitOut(r.error, 'err'); return gitRefresh(false); }
|
|
76
|
+
renderGit(r);
|
|
77
|
+
if (op === 'continue' || op === 'abort') { gitOut(r.output || (op === 'abort' ? 'Aborted.' : 'Done.'), 'ok'); await app.reloadClean(); gitRefresh(false); }
|
|
78
|
+
app.closeDiff();
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
async function gitCommit() {
|
|
82
|
+
if (!(await app.saveAll())) return;
|
|
83
|
+
const msg = $('gitMsg').value.trim();
|
|
84
|
+
if (!msg && app.git?.state !== 'merging') return gitOut('Write a commit message first.', 'err');
|
|
85
|
+
const r = await post('/api/git/commit', { message: msg });
|
|
86
|
+
if (!r.ok) return gitOut(r.error, 'err');
|
|
87
|
+
$('gitMsg').value = ''; gitOut('Committed ' + r.commit, 'ok'); renderGit(r); gitRefresh(false);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
async function pull(mode = 'ff') {
|
|
91
|
+
$('gitPull').disabled = true; gitOut(mode === 'ff' ? 'Pulling…' : mode === 'rebase' ? 'Rebasing…' : 'Merging…');
|
|
92
|
+
const r = await post('/api/git/pull', { mode });
|
|
93
|
+
$('gitPull').disabled = false;
|
|
94
|
+
if (!r.ok) return gitOut(r.error, 'err');
|
|
95
|
+
renderGit(r);
|
|
96
|
+
if (r.diverged) return gitOut('Your branch and the remote both have new commits. How should they be combined?', '',
|
|
97
|
+
el('button', { className: 'primary', title: 'Replay your commits on top of the remote ones (linear history)', onclick: () => pull('rebase') }, 'Rebase my commits'),
|
|
98
|
+
el('button', { title: 'Create a merge commit', onclick: () => pull('merge') }, 'Merge'));
|
|
99
|
+
if (r.conflict) gitOut('Some files conflict. Open them from the Conflicts list, fix them, and mark them resolved.', 'err');
|
|
100
|
+
else gitOut(r.output || 'Up to date.', 'ok');
|
|
101
|
+
await app.reloadClean(); gitRefresh(false); app.filesChanged?.();
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
async function push() {
|
|
105
|
+
$('gitPush').disabled = true; gitOut('Pushing…');
|
|
106
|
+
const r = await post('/api/git/push');
|
|
107
|
+
$('gitPush').disabled = false;
|
|
108
|
+
if (!r.ok) return gitOut(r.error, 'err');
|
|
109
|
+
gitOut(r.output || 'Done.', 'ok'); renderGit(r); gitRefresh(false);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
$('gitCommit').onclick = gitCommit;
|
|
113
|
+
$('gitStageAll').onclick = () => app.git && gitOp('stage', { paths: app.git.files.filter(f => f.unstaged).map(f => f.path) });
|
|
114
|
+
$('gitPush').onclick = push;
|
|
115
|
+
$('gitPull').onclick = () => pull('ff');
|
|
116
|
+
$('gitRefresh').onclick = () => gitRefresh(true);
|
|
117
|
+
$('gitMsg').addEventListener('keydown', e => { if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) { e.preventDefault(); gitCommit(); } });
|
|
118
|
+
setInterval(() => { if (!document.hidden) gitRefresh(false); }, 10000);
|
|
119
|
+
|
|
120
|
+
Object.assign(app, { gitRefresh, gitSoon, gitOut });
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
// Side panels: search (and replace) in all files, and the document outline.
|
|
2
|
+
import { $, el, app, state, api, post, setStatus, confirmClick, debounce } from './util.js';
|
|
3
|
+
|
|
4
|
+
// ---------- search all files ----------
|
|
5
|
+
let lastSearch = null;
|
|
6
|
+
const params = () => ({ q: $('searchInput').value, case: $('sCase').checked ? 1 : 0, word: $('sWord').checked ? 1 : 0,
|
|
7
|
+
regex: $('sRegex').checked ? 1 : 0 });
|
|
8
|
+
|
|
9
|
+
export async function runSearch() {
|
|
10
|
+
const p = params();
|
|
11
|
+
lastSearch = p;
|
|
12
|
+
if (!p.q) { $('searchResults').replaceChildren(); $('searchCount').textContent = ''; $('replaceAllBtn').disabled = true; return; }
|
|
13
|
+
const r = await api('/api/search?' + new URLSearchParams(p));
|
|
14
|
+
if (lastSearch !== p) return; // a newer search is under way
|
|
15
|
+
if (!r.ok) { $('searchCount').textContent = r.error; $('replaceAllBtn').disabled = true; return; }
|
|
16
|
+
const byFile = new Map();
|
|
17
|
+
r.matches.forEach(m => { if (!byFile.has(m.path)) byFile.set(m.path, []); byFile.get(m.path).push(m); });
|
|
18
|
+
const rows = [];
|
|
19
|
+
for (const [path, ms] of byFile) {
|
|
20
|
+
rows.push(el('div', { className: 'sf', title: path }, path, el('small', {}, String(ms.length))));
|
|
21
|
+
for (const m of ms) {
|
|
22
|
+
const start = Math.max(0, m.col - 30), pre = (start ? '…' : '') + m.text.slice(start, m.col).trimStart();
|
|
23
|
+
rows.push(el('div', { className: 'sm', title: m.text.trim(), onclick: () => app.openFile(m.path, m.line, { ch: m.col, len: m.len }) },
|
|
24
|
+
el('i', {}, String(m.line)), pre, el('b', {}, m.text.slice(m.col, m.col + m.len)), m.text.slice(m.col + m.len, m.col + m.len + 120)));
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
$('searchResults').replaceChildren(...rows);
|
|
28
|
+
const n = r.matches.length;
|
|
29
|
+
$('searchCount').textContent = n ? `${n}${r.truncated ? '+' : ''} in ${byFile.size} file${byFile.size === 1 ? '' : 's'}` : 'No results';
|
|
30
|
+
$('replaceAllBtn').disabled = !n;
|
|
31
|
+
}
|
|
32
|
+
const searchSoon = debounce(runSearch, 250);
|
|
33
|
+
['searchInput'].forEach(id => $(id).addEventListener('input', searchSoon));
|
|
34
|
+
['sCase', 'sWord', 'sRegex'].forEach(id => $(id).addEventListener('change', runSearch));
|
|
35
|
+
$('searchInput').addEventListener('keydown', e => { if (e.key === 'Enter') runSearch(); });
|
|
36
|
+
|
|
37
|
+
$('replaceAllBtn').onclick = () => {
|
|
38
|
+
const n = $('searchCount').textContent.split(' ')[0];
|
|
39
|
+
confirmClick($('replaceAllBtn'), `Replace ${n}?`, async () => {
|
|
40
|
+
if (!(await app.saveAll())) return;
|
|
41
|
+
const p = params();
|
|
42
|
+
const r = await post('/api/replace', { q: p.q, regex: !!p.regex, case: !!p.case, word: !!p.word, replacement: $('replaceInput').value });
|
|
43
|
+
if (!r.ok) return setStatus('replace failed: ' + r.error, 'err');
|
|
44
|
+
await app.reloadClean();
|
|
45
|
+
setStatus(`replaced ${r.replaced} in ${Object.keys(r.files).length} file(s)`, 'ok');
|
|
46
|
+
runSearch(); app.filesChanged?.();
|
|
47
|
+
if ($('auto').checked) app.compile();
|
|
48
|
+
});
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
export function showSearch() {
|
|
52
|
+
app.showTab('search');
|
|
53
|
+
const sel = app.cm.getSelection();
|
|
54
|
+
if (sel && !sel.includes('\n')) $('searchInput').value = sel;
|
|
55
|
+
$('searchInput').focus(); $('searchInput').select();
|
|
56
|
+
runSearch();
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// ---------- outline ----------
|
|
60
|
+
let outline = [];
|
|
61
|
+
export async function refreshOutline() {
|
|
62
|
+
const r = await api('/api/outline');
|
|
63
|
+
if (!r.ok) return;
|
|
64
|
+
outline = r.entries;
|
|
65
|
+
const min = Math.min(...outline.map(e => e.level), 9);
|
|
66
|
+
$('outline').replaceChildren(...(outline.length ? outline.map((e, i) => {
|
|
67
|
+
const row = el('div', { className: `o l${e.level}`, title: `${e.file}:${e.line}`, dataset: { i },
|
|
68
|
+
onclick: () => app.openFile(e.file, e.line, { flash: true }) }, e.title || '(untitled)');
|
|
69
|
+
row.style.paddingLeft = (8 + (e.level - min) * 12) + 'px';
|
|
70
|
+
return row;
|
|
71
|
+
}) : [el('div', { className: 'muted', style: 'padding: 8px' }, 'No \\section commands found in the main document.')]));
|
|
72
|
+
markCurrentSection();
|
|
73
|
+
}
|
|
74
|
+
// Highlight the section the cursor is in.
|
|
75
|
+
export function markCurrentSection() {
|
|
76
|
+
if ($('outlinePane').hidden || !state.current) return;
|
|
77
|
+
const line = app.cm.getCursor().line + 1;
|
|
78
|
+
let cur = -1;
|
|
79
|
+
outline.forEach((e, i) => { if (e.file === state.current && e.line <= line) cur = i; });
|
|
80
|
+
document.querySelectorAll('#outline .o').forEach(r => r.classList.toggle('cur', +r.dataset.i === cur));
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
Object.assign(app, { runSearch, showSearch, refreshOutline, markCurrentSection });
|