feat(editor): run markdown source editing on CodeMirror 5
This commit is contained in:
@@ -61,6 +61,14 @@
|
||||
var ZOOM_WHEEL_THROTTLE_MS = 90;
|
||||
var zoomWheelAt = 0;
|
||||
var zoomPercent = 100;
|
||||
// CodeMirror is loaded on demand (first edit mode), never at startup.
|
||||
var CM_MAX_BYTES = 2 * 1024 * 1024;
|
||||
var CM_MAX_LINES = 20000;
|
||||
var cm = null;
|
||||
var cmLoading = false;
|
||||
var cmDisabled = false;
|
||||
var applyingRemote = false;
|
||||
var pendingScrollRatio = 0;
|
||||
// All source-text access goes through this adapter. The CodeMirror
|
||||
// implementation replaces the returned object; callers never touch ta.
|
||||
var ed = createTextareaEditor(ta);
|
||||
@@ -101,12 +109,18 @@
|
||||
document.documentElement.style.setProperty('--content-scale', String(zoomPercent / 100));
|
||||
btnZoomReset.textContent = zoomPercent + '%';
|
||||
if (persist) queueZoomSave();
|
||||
if (inEdit()) ed.resize();
|
||||
if (cm) updateEditorZoom();
|
||||
else if (inEdit()) ed.resize();
|
||||
}
|
||||
function changeZoom(delta) {
|
||||
applyZoom(zoomPercent + delta, true);
|
||||
}
|
||||
function currentScrollProgress() {
|
||||
if (cm && inEdit()) {
|
||||
var info = cm.getScrollInfo();
|
||||
var cmMax = info.height - info.clientHeight;
|
||||
return cmMax > 0 ? Math.min(1, Math.max(0, info.top / cmMax)) : 0;
|
||||
}
|
||||
var root = document.documentElement;
|
||||
var max = Math.max(root.scrollHeight - window.innerHeight, 0);
|
||||
var y = window.scrollY || root.scrollTop || 0;
|
||||
@@ -115,6 +129,22 @@
|
||||
// A newer restore supersedes any callback the previous one left behind.
|
||||
var scrollRestoreToken = 0;
|
||||
function restoreScrollProgress(progress) {
|
||||
if (cm && inEdit()) {
|
||||
pendingScrollRatio = progress;
|
||||
var applyCm = function() {
|
||||
var info = cm.getScrollInfo();
|
||||
var cmMax = Math.max(info.height - info.clientHeight, 0);
|
||||
cm.scrollTo(null, cmMax * progress);
|
||||
};
|
||||
requestAnimationFrame(function() {
|
||||
cm.refresh();
|
||||
applyCm();
|
||||
requestAnimationFrame(applyCm);
|
||||
});
|
||||
// Late layout inside CodeMirror can change the scroll height too.
|
||||
setTimeout(applyCm, 150);
|
||||
return;
|
||||
}
|
||||
var token = ++scrollRestoreToken;
|
||||
function restore() {
|
||||
if (token !== scrollRestoreToken) return;
|
||||
@@ -589,8 +619,164 @@
|
||||
}
|
||||
};
|
||||
}
|
||||
// ---- CodeMirror implementation -------------------------------------------
|
||||
function updateEditorZoom() {
|
||||
if (!cm) return;
|
||||
cm.getWrapperElement().style.fontSize = (14 * zoomPercent / 100) + 'px';
|
||||
cm.refresh();
|
||||
}
|
||||
function editorTooLarge() {
|
||||
var text = ed.value();
|
||||
if (text.length > CM_MAX_BYTES) return true;
|
||||
return text.split('\n').length > CM_MAX_LINES;
|
||||
}
|
||||
function requestEditorSource() {
|
||||
if (cm || cmLoading || cmDisabled) return;
|
||||
if (editorTooLarge()) { cmDisabled = true; return; }
|
||||
cmLoading = true;
|
||||
if (window.ipc) window.ipc.postMessage('need-editor');
|
||||
}
|
||||
window.__mdpOnEditorSource = function() {
|
||||
cmLoading = false;
|
||||
if (cm || cmDisabled || typeof CodeMirror === 'undefined') return;
|
||||
createCodeMirror();
|
||||
};
|
||||
function createCodeMirror() {
|
||||
var host = document.getElementById('cm-editor');
|
||||
if (!host) return;
|
||||
try {
|
||||
cm = CodeMirror(host, {
|
||||
value: ed.value(),
|
||||
mode: { name: 'markdown', highlightFormatting: true },
|
||||
lineNumbers: true,
|
||||
lineWrapping: true,
|
||||
foldGutter: { rangeFinder: markdownFoldRange, minFoldSize: 1 },
|
||||
gutters: ['CodeMirror-linenumbers', 'CodeMirror-foldgutter'],
|
||||
foldOptions: { rangeFinder: markdownFoldRange, minFoldSize: 1 },
|
||||
indentUnit: 2,
|
||||
tabSize: 2,
|
||||
indentWithTabs: false,
|
||||
viewportMargin: 10,
|
||||
extraKeys: {
|
||||
'Tab': function(instance) {
|
||||
if (instance.somethingSelected()) instance.execCommand('indentMore');
|
||||
else instance.replaceSelection(INDENT, 'end');
|
||||
},
|
||||
'Shift-Tab': function(instance) {
|
||||
if (instance.somethingSelected()) { instance.execCommand('indentLess'); return; }
|
||||
var cursor = instance.getCursor();
|
||||
var line = instance.getLine(cursor.line) || '';
|
||||
var removed = line.charAt(0) === '\t' ? 1 : 0;
|
||||
while (removed < INDENT.length && line.charAt(removed) === ' ') removed += 1;
|
||||
if (removed) instance.replaceRange('', { line: cursor.line, ch: 0 }, { line: cursor.line, ch: removed });
|
||||
},
|
||||
'Enter': function(instance) { instance.execCommand('newlineAndIndent'); },
|
||||
'Ctrl-F': function(instance) { instance.execCommand('find'); },
|
||||
'Cmd-F': function(instance) { instance.execCommand('find'); },
|
||||
'Ctrl-H': function(instance) { instance.execCommand('replace'); },
|
||||
'Cmd-H': function(instance) { instance.execCommand('replace'); },
|
||||
'Ctrl-S': function() { save(); },
|
||||
'Cmd-S': function() { save(); },
|
||||
'Esc': function() { leaveEdit(); }
|
||||
}
|
||||
});
|
||||
} catch (err) {
|
||||
cm = null;
|
||||
cmDisabled = true;
|
||||
return;
|
||||
}
|
||||
ed = createCodeMirrorEditor(cm);
|
||||
cm.on('change', function() {
|
||||
if (applyingRemote) return;
|
||||
setDirty(true);
|
||||
scheduleAutosave();
|
||||
updateDocumentStats(ed.value());
|
||||
});
|
||||
cm.on('scroll', reportScroll);
|
||||
updateEditorZoom();
|
||||
document.body.classList.toggle('cm-active', inEdit());
|
||||
if (inEdit()) {
|
||||
ed.focus();
|
||||
restoreScrollProgress(pendingScrollRatio);
|
||||
}
|
||||
}
|
||||
function createCodeMirrorEditor(instance) {
|
||||
function setValue(text) {
|
||||
applyingRemote = true;
|
||||
try { instance.setValue(text); } finally { applyingRemote = false; }
|
||||
}
|
||||
return {
|
||||
value: function() { return instance.getValue(); },
|
||||
setValue: setValue,
|
||||
focus: function() { instance.focus(); },
|
||||
selection: function() {
|
||||
var ranges = instance.listSelections();
|
||||
var head = ranges && ranges.length ? ranges[0].head : instance.getCursor();
|
||||
var anchor = ranges && ranges.length ? ranges[0].anchor : head;
|
||||
return { start: instance.indexFromPos(anchor), end: instance.indexFromPos(head) };
|
||||
},
|
||||
setSelection: function(start, end) {
|
||||
instance.setSelection(instance.posFromIndex(start), instance.posFromIndex(end));
|
||||
},
|
||||
replaceRange: function(text, start, end) {
|
||||
instance.replaceRange(text, instance.posFromIndex(start), instance.posFromIndex(end));
|
||||
},
|
||||
indent: function() { instance.execCommand('indentMore'); },
|
||||
outdent: function() { instance.execCommand('indentLess'); },
|
||||
newlineWithIndent: function() { instance.execCommand('newlineAndIndent'); },
|
||||
resize: function() { updateEditorZoom(); },
|
||||
isTarget: function(node) { return instance.getWrapperElement().contains(node); },
|
||||
bind: function() {}
|
||||
};
|
||||
}
|
||||
function markdownFoldRange(instance, line) {
|
||||
var text = instance.getLine(line);
|
||||
if (!text) return null;
|
||||
var fence = /^\s*(```+|~~~+)/.exec(text);
|
||||
if (fence) {
|
||||
var marker = fence[1];
|
||||
var fenceEnd = -1;
|
||||
for (var f = line + 1; f <= instance.lastLine(); f += 1) {
|
||||
var fenceLine = instance.getLine(f) || '';
|
||||
if (/^\s*(```+|~~~+)\s*$/.test(fenceLine) && fenceLine.indexOf(marker.charAt(0)) >= 0) {
|
||||
fenceEnd = f;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (fenceEnd > line + 1) {
|
||||
return { from: CodeMirror.Pos(line + 1, 0), to: CodeMirror.Pos(fenceEnd - 1, instance.getLine(fenceEnd - 1).length) };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
var heading = /^(#{1,6})\s/.exec(text);
|
||||
var level = heading ? heading[1].length : 0;
|
||||
if (!heading) {
|
||||
var underline = instance.getLine(line + 1) || '';
|
||||
if (text.trim() && /^(=+|-+)\s*$/.test(underline)) {
|
||||
level = underline.charAt(0) === '=' ? 1 : 2;
|
||||
}
|
||||
}
|
||||
if (!level) return null;
|
||||
var end = line;
|
||||
for (var i = line + 1; i <= instance.lastLine(); i += 1) {
|
||||
var bodyLine = instance.getLine(i) || '';
|
||||
var nextHeading = /^(#{1,6})\s/.exec(bodyLine);
|
||||
var nextLevel = nextHeading ? nextHeading[1].length : 0;
|
||||
if (!nextHeading && bodyLine.trim()) {
|
||||
var nextUnderline = instance.getLine(i + 1) || '';
|
||||
if (/^(=+|-+)\s*$/.test(nextUnderline)) {
|
||||
nextLevel = nextUnderline.charAt(0) === '=' ? 1 : 2;
|
||||
}
|
||||
}
|
||||
if (nextLevel && nextLevel <= level) break;
|
||||
if (bodyLine.trim()) end = i;
|
||||
}
|
||||
if (end <= line) return null;
|
||||
return { from: CodeMirror.Pos(line + 1, 0), to: CodeMirror.Pos(end, instance.getLine(end).length) };
|
||||
}
|
||||
// Edit mode is per tab and owned by Rust; this only paints it.
|
||||
function setEditMode(on) {
|
||||
if (on && !cm && !cmDisabled) requestEditorSource();
|
||||
if (on) {
|
||||
document.body.classList.add('editing');
|
||||
btnToggle.innerHTML = ICON_VIEW;
|
||||
@@ -602,16 +788,22 @@
|
||||
btnToggle.title = L_EDIT;
|
||||
btnToggle.setAttribute('aria-label', L_EDIT);
|
||||
}
|
||||
ed.resize();
|
||||
if (cm) {
|
||||
document.body.classList.toggle('cm-active', on);
|
||||
if (on) cm.refresh();
|
||||
} else {
|
||||
ed.resize();
|
||||
}
|
||||
}
|
||||
function enterEdit() {
|
||||
if (document.body.classList.contains('home')) return;
|
||||
var progress = currentScrollProgress();
|
||||
setEditMode(true);
|
||||
ed.focus();
|
||||
restoreScrollProgress(progress);
|
||||
if (window.ipc) window.ipc.postMessage('edit-mode:' + activeTabId + ':1');
|
||||
}
|
||||
if (document.body.classList.contains('home')) return;
|
||||
var progress = currentScrollProgress();
|
||||
pendingScrollRatio = progress;
|
||||
setEditMode(true);
|
||||
ed.focus();
|
||||
restoreScrollProgress(progress);
|
||||
if (window.ipc) window.ipc.postMessage('edit-mode:' + activeTabId + ':1');
|
||||
}
|
||||
function leaveEdit() {
|
||||
var progress = currentScrollProgress();
|
||||
if (dirty) save();
|
||||
@@ -772,6 +964,7 @@
|
||||
});
|
||||
|
||||
document.addEventListener('keydown', function(e) {
|
||||
if (e.defaultPrevented) return;
|
||||
if (e.key === 'Escape' && tabMenu && !tabMenu.hidden) {
|
||||
hideTabMenu();
|
||||
return;
|
||||
|
||||
Reference in New Issue
Block a user