-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheditor.js
More file actions
334 lines (292 loc) · 10 KB
/
Copy patheditor.js
File metadata and controls
334 lines (292 loc) · 10 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
// Editing UI for mdview. The page starts in view mode; this only builds the
// editor when the user asks for it, so a plain read never pays for Monaco.
(function () {
var cfg = window.mdviewConfig;
if (!cfg || !cfg.editable) return;
var editor = null;
var monacoPromise = null;
var baseHash = null; // hash of the bytes on disk our buffer is based on
var lastSavedHash = null; // so we can recognise our own write coming back
var dirty = false;
var editing = false;
var previewTimer = null;
// --- toolbar -------------------------------------------------------------
var bar = document.createElement('div');
bar.className = 'mdview-toolbar';
var editBtn = button('Edit', toggle);
var saveBtn = button('Save', save);
var status = document.createElement('span');
status.className = 'mdview-status';
saveBtn.style.display = 'none';
bar.appendChild(status);
bar.appendChild(saveBtn);
bar.appendChild(editBtn);
document.body.appendChild(bar);
function button(label, onClick) {
var b = document.createElement('button');
b.className = 'mdview-btn';
b.type = 'button';
b.textContent = label;
b.addEventListener('click', onClick);
return b;
}
function setStatus(text, kind) {
status.textContent = text || '';
status.className = 'mdview-status' + (kind ? ' mdview-status-' + kind : '');
}
// --- banner (conflicts and external changes) -----------------------------
var banner = null;
function showBanner(message, actions) {
hideBanner();
banner = document.createElement('div');
banner.className = 'mdview-banner';
var text = document.createElement('span');
text.textContent = message;
banner.appendChild(text);
actions.forEach(function (a) {
banner.appendChild(button(a.label, function () {
hideBanner();
a.run();
}));
});
document.body.appendChild(banner);
}
function hideBanner() {
if (banner) {
banner.remove();
banner = null;
}
}
// --- Monaco --------------------------------------------------------------
function loadMonaco() {
if (monacoPromise) return monacoPromise;
monacoPromise = new Promise(function (resolve, reject) {
var s = document.createElement('script');
s.src = '/_mdview/monaco/vs/loader.js';
s.onload = function () {
window.require.config({ paths: { vs: '/_mdview/monaco/vs' } });
window.require(['vs/editor/editor.main'], function () { resolve(window.monaco); }, reject);
};
s.onerror = function () { reject(new Error('could not load the editor')); };
document.head.appendChild(s);
});
return monacoPromise;
}
function monacoTheme() {
var attr = document.documentElement.getAttribute('data-theme');
if (attr === 'dark') return 'vs-dark';
if (attr === 'light') return 'vs';
return window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches ? 'vs-dark' : 'vs';
}
// Follow the page's theme, both the toggle and the OS setting.
new MutationObserver(function () {
if (window.monaco) window.monaco.editor.setTheme(monacoTheme());
}).observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] });
if (window.matchMedia) {
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', function () {
if (window.monaco && !document.documentElement.getAttribute('data-theme')) {
window.monaco.editor.setTheme(monacoTheme());
}
});
}
// --- fetch helpers -------------------------------------------------------
function authHeaders(extra) {
var h = { 'X-Mdview-Token': cfg.token };
if (extra) Object.keys(extra).forEach(function (k) { h[k] = extra[k]; });
return h;
}
function getSource() {
return fetch('/source', { headers: authHeaders() }).then(function (r) {
if (!r.ok) throw new Error('could not read the file (' + r.status + ')');
return r.json();
});
}
// --- edit mode -----------------------------------------------------------
function toggle() {
if (editing) leaveEditing();
else enterEditing();
}
function enterEditing() {
setStatus('Loading editor…');
editBtn.disabled = true;
Promise.all([getSource(), loadMonaco()]).then(function (results) {
var src = results[0];
var monaco = results[1];
baseHash = src.hash;
var container = document.querySelector('.container');
var split = document.createElement('div');
split.className = 'mdview-split';
var pane = document.createElement('div');
pane.className = 'mdview-editor-pane';
container.parentNode.insertBefore(split, container);
split.appendChild(pane);
split.appendChild(container);
document.body.classList.add('mdview-editing');
editor = monaco.editor.create(pane, {
value: src.text,
language: 'markdown',
theme: monacoTheme(),
automaticLayout: true,
wordWrap: 'on',
minimap: { enabled: false },
scrollBeyondLastLine: false,
fontSize: 14,
});
editor.onDidChangeModelContent(function () {
dirty = true;
updateChrome();
schedulePreview();
});
editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyS, save);
editing = true;
dirty = false;
editBtn.disabled = false;
editBtn.textContent = 'Done';
saveBtn.style.display = '';
updateChrome();
editor.focus();
}).catch(function (err) {
editBtn.disabled = false;
setStatus(err.message, 'error');
});
}
function leaveEditing() {
if (dirty && !window.confirm('You have unsaved changes. Discard them?')) return;
var split = document.querySelector('.mdview-split');
var container = document.querySelector('.container');
if (split && container) {
split.parentNode.insertBefore(container, split);
split.remove();
}
if (editor) {
editor.dispose();
editor = null;
}
document.body.classList.remove('mdview-editing');
editing = false;
dirty = false;
hideBanner();
editBtn.textContent = 'Edit';
saveBtn.style.display = 'none';
setStatus('');
// The preview may hold unsaved text; put the file's own rendering back.
refreshPreview();
}
function updateChrome() {
saveBtn.disabled = !dirty;
setStatus(dirty ? 'Unsaved changes' : 'Saved');
}
// --- preview -------------------------------------------------------------
function schedulePreview() {
clearTimeout(previewTimer);
previewTimer = setTimeout(renderPreview, 250);
}
function renderPreview() {
if (!editor) return;
fetch('/preview', {
method: 'POST',
headers: authHeaders({ 'Content-Type': 'application/json' }),
body: JSON.stringify({ text: editor.getValue() }),
}).then(function (r) {
return r.ok ? r.json() : null;
}).then(function (data) {
if (data) document.getElementById('content').innerHTML = data.html;
}).catch(function () { /* preview is best-effort */ });
}
function refreshPreview() {
fetch('/raw').then(function (r) { return r.json(); }).then(function (data) {
document.getElementById('content').innerHTML = data.html;
}).catch(function () {});
}
// --- saving --------------------------------------------------------------
function save() {
if (!editor) return;
var text = editor.getValue();
setStatus('Saving…');
fetch('/save', {
method: 'POST',
headers: authHeaders({ 'Content-Type': 'application/json' }),
body: JSON.stringify({ text: text, baseHash: baseHash }),
}).then(function (r) {
return r.json().then(function (data) { return { status: r.status, data: data }; });
}).then(function (res) {
if (res.status === 409) {
onConflict(res.data);
return;
}
if (res.status !== 200) {
setStatus((res.data && res.data.error) || 'Save failed', 'error');
return;
}
baseHash = res.data.hash;
lastSavedHash = res.data.hash;
dirty = false;
updateChrome();
}).catch(function (err) {
setStatus(err.message, 'error');
});
}
function onConflict(data) {
setStatus('Not saved — the file changed on disk', 'error');
showBanner('This file changed on disk since you started editing.', [
{
label: 'Overwrite',
run: function () {
// Adopt the on-disk hash so the retry passes the freshness check.
baseHash = data.hash;
save();
},
},
{
label: 'Discard mine and reload',
run: function () {
editor.setValue(data.text);
baseHash = data.hash;
dirty = false;
updateChrome();
renderPreview();
},
},
]);
}
// --- coordination with live reload ---------------------------------------
// Called by the inline reload script. Returning true means "leave the DOM
// alone" — while editing, the preview belongs to the editor, and replacing
// it would fight with what the user is typing.
window.mdviewEditor = {
onReload: function () {
if (!editing) return false;
getSource().then(function (src) {
if (src.hash === lastSavedHash || src.hash === baseHash) return; // our own write
if (dirty) {
showBanner('This file changed on disk while you were editing.', [
{
label: 'Load from disk',
run: function () {
editor.setValue(src.text);
baseHash = src.hash;
dirty = false;
updateChrome();
renderPreview();
},
},
{ label: 'Keep mine', run: function () {} },
]);
} else {
editor.setValue(src.text);
baseHash = src.hash;
dirty = false;
updateChrome();
renderPreview();
}
}).catch(function () {});
return true;
},
};
window.addEventListener('beforeunload', function (e) {
if (dirty) {
e.preventDefault();
e.returnValue = '';
}
});
})();